Compare commits

...

20 Commits

Author SHA1 Message Date
Kallesh B S
36529727a0 api endpoints modified to replace db name to its mapped value 2025-09-05 11:15:17 +05:30
Kallesh B S
c1f03cdf43 28-08-2025 API changes, return specific value in applicationName from login API, payment data persist changes 2025-08-28 17:16:55 +05:30
Kallesh B S
3616b57a73 create login bugs 2025-08-26 17:02:03 +05:30
Kallesh B S
a2c2ed2a68 Added the Payment Data Persistence API 2025-08-25 16:14:25 +05:30
Kallesh B S
45d57cee8d initiate-payment api modified for dynamic amount from UI 2025-08-22 15:16:02 +05:30
Kallesh B S
0e59a652b0 19-08-2025 api modifications 2025-08-19 17:27:14 +05:30
Kallesh B S
75a537aab4 pay 2 2025-08-18 20:34:44 +05:30
Kallesh B S
a61623b0aa The API has been modified as per the instructions provided on 14-08-2025 2025-08-14 12:37:31 +05:30
Kallesh B S
c670266256 new apis 2025-08-13 11:51:24 +05:30
Kallesh B S
f3cbadebd7 pdf generation 2025-08-12 15:27:32 +05:30
Kallesh B S
3646a80800 7Aug Api modifications 2025-08-08 14:59:59 +05:30
Kallesh B S
26bfaeaa0b print carnet api type mismatch for processing 2025-08-06 16:12:24 +05:30
Kallesh B S
49e4f45073 added new api in carnet app 2025-08-05 14:32:54 +05:30
Kallesh B S
c5b5a8e541 register mail added from BE 2025-07-29 19:44:51 +05:30
Kallesh B S
608eafd616 create logins API password field removed and p_userid added to searchHolder API 2025-07-29 17:17:33 +05:30
Kallesh B S
9f2d7f058f transmit application and INACTIVATEPARAMRECORD typo fix and added getAllParamValues 2025-07-28 21:01:57 +05:30
Kallesh B S
5cebcef300 fixed estimated fees and bind mismatch in transmit application and removed comments,logs 2025-07-24 15:03:28 +05:30
Kallesh B S
91208d950d API mod as per 22-07-2025 requested 2025-07-22 20:43:57 +05:30
Kallesh B S
6a68ca024a vulnerabilities resolved 2025-07-21 21:09:33 +05:30
Kallesh B S
1f49012644 added new GET_COUNTRIES_AND_MESSAGES API in param 2025-07-21 17:22:57 +05:30
77 changed files with 5479 additions and 5919 deletions

2
.gitignore vendored
View File

@ -3,6 +3,8 @@
/node_modules
/build
# pdf
# Logs
logs
*.log

View File

@ -1,5 +1,9 @@
GET http://192.168.1.96:3006
###
GET http://localhost:3000/oracle/GetRegions/1
###
GET http://localhost:3000/oracle/SearchHolder/1

View File

@ -3,6 +3,13 @@
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
"deleteOutDir": true,
"assets": [
{
"include": "../public/**/**",
"outDir": "dist/public"
}
],
"watchAssets": true
}
}

7372
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -20,7 +20,6 @@
"test:e2e": "jest --config ./test/jest-e2e.json"
},
"dependencies": {
"@nestjs-modules/mailer": "^2.0.2",
"@nestjs/common": "^11.0.1",
"@nestjs/config": "^4.0.2",
"@nestjs/core": "^11.0.1",
@ -29,6 +28,7 @@
"@nestjs/platform-express": "^11.0.1",
"@nestjs/swagger": "^11.0.6",
"@nestjs/typeorm": "^11.0.0",
"@types/nodemailer": "^6.4.17",
"axios": "^1.10.0",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
@ -37,12 +37,15 @@
"joi": "^17.13.3",
"jsonwebtoken": "^9.0.2",
"jwk-to-pem": "^2.0.7",
"mssql": "^10.0.4",
"mssql": "^11.0.1",
"mysql2": "^3.12.0",
"nodemailer": "^7.0.3",
"oracledb": "^6.7.2",
"passport": "^0.7.0",
"passport-jwt": "^4.0.1",
"pdf-lib": "^1.17.1",
"pdf-merger-js": "^5.1.2",
"pdfkit": "^0.17.1",
"pg": "^8.13.3",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
@ -66,7 +69,7 @@
"@types/oracledb": "^6.5.4",
"@types/supertest": "^6.0.2",
"@types/uuid": "^10.0.0",
"eslint": "^9.18.0",
"eslint": "^9.31.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-prettier": "^5.2.2",
"globals": "^15.14.0",

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -6,11 +6,12 @@ import { OriginCheckMiddleware } from './middleware/OriginCheck.middleware';
import { ReqBodyKeysToUppercaseMiddleware } from './middleware/reqBodyKeysToUppercase.middleware';
import { ConfigModule } from '@nestjs/config';
import { MailModule } from './mail/mail.module';
import { PaypalModule } from './paypal/paypal.module';
@Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
AuthModule, DbModule, OracleModule, MailModule
AuthModule, DbModule, OracleModule, MailModule, PaypalModule
],
controllers: [],
providers: [],

View File

@ -1,7 +1,7 @@
import { Body, Controller, Get, HttpCode, Post, Put, Req, Res, UseGuards, UseInterceptors } from '@nestjs/common';
import { AuthService } from './auth.service';
import { ApiTags } from '@nestjs/swagger';
import { AuthLoginDTO, SendMailDTO } from './auth.dto';
import { AuthLoginDTO, AuthLoginOnlyDTO, SendMailDTO } from './auth.dto';
import { Request, Response } from 'express';
import { LogoutInterceptor } from 'src/interceptors/logout.interceptor';
import { RegisterGuard } from 'src/guards/register.guard';
@ -18,8 +18,9 @@ export class AuthController {
@Post('login')
@HttpCode(200)
async loginClient(@Body() body: AuthLoginDTO, @Res({ passthrough: true }) res: Response, @Req() req: Request) {
let k: any = await this.authService.loginUser(body.P_EMAILADDR.toLowerCase(), body.P_PASSWORD, req);
async loginClient(@Body() body: AuthLoginOnlyDTO, @Res({ passthrough: true }) res: Response, @Req() req: Request) {
let k: any = await this.authService.loginUser(body.P_EMAILADDR.toLowerCase(), body.P_PASSWORD, body.P_APPLICATIONNAME, req);
if (k.access_token) {
res.cookie('access_token', k.access_token, {

View File

@ -1,6 +1,7 @@
import { ApiProperty } from '@nestjs/swagger';
import { ApiProperty, IntersectionType } from '@nestjs/swagger';
import { Transform, Type } from 'class-transformer';
import { IsEmail, IsEnum, IsString, ValidateNested } from 'class-validator';
import { IsEmail, IsEnum, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator';
import { APPLICATIONNAME_DTO } from 'src/dto/property.dto';
export class AuthLoginDTO {
@ApiProperty({ required: true })
@ -12,6 +13,8 @@ export class AuthLoginDTO {
P_PASSWORD: string;
}
export class AuthLoginOnlyDTO extends IntersectionType(AuthLoginDTO, APPLICATIONNAME_DTO) { }
export enum MailTypeDTO {
REGISTER_CLIENT = "REGISTER_CLIENT",
REGISTER_SP = "REGISTER_SP",
@ -51,16 +54,11 @@ export class MailTemplateDTO {
@IsString()
subject: string;
// @ApiProperty({ required: true })
// @IsString()
// text: string;
@ApiProperty({ required: true })
@IsString()
template: string;
templateName: string;
@ApiProperty({ type: () => MailContextDTO, required: true })
@ValidateNested()
@Type(() => MailContextDTO)
context: MailContextDTO;
@IsOptional()
@IsObject()
variables?: Record<string, any>;
}

View File

@ -5,9 +5,10 @@ import { DbModule } from 'src/db/db.module';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';
import { OracleModule } from 'src/oracle/oracle.module';
import { MailModule } from 'src/mail/mail.module';
@Module({
imports: [DbModule, forwardRef(() => OracleModule)],
imports: [DbModule,MailModule, forwardRef(() => OracleModule)],
providers: [
AuthService,
{

View File

@ -10,10 +10,10 @@ import * as jwt from "jsonwebtoken"
import { UnauthorizedException } from 'src/exceptions/unauthorized.exception';
import { ConflictException } from 'src/exceptions/conflict.exception';
import { BadRequestException } from 'src/exceptions/badRequest.exception';
import { MailerService } from '@nestjs-modules/mailer';
import { JwtService } from '@nestjs/jwt';
import { UserMaintenanceService } from 'src/oracle/user-maintenance/user-maintenance.service';
import { v4 as uuidv4 } from 'uuid';
import { MailService } from 'src/mail/mail.service';
interface DecodedToken {
@ -43,7 +43,7 @@ export class AuthService {
constructor(
private readonly oracleDBService: OracleDBService,
private readonly configService: ConfigService,
private readonly mailService: MailerService,
private readonly mailService: MailService,
private readonly userMaintenanceService: UserMaintenanceService,
@Inject("REGISTER_SIGN_JWT") readonly REGISTER_SIGN_JWT: JwtService,
@Inject("REGISTER_VERIFY_JWT") readonly REGISTER_VERIFY_JWT: JwtService
@ -151,14 +151,12 @@ export class AuthService {
// Validate the response shape
if (!data?.keys || !Array.isArray(data.keys)) {
console.log("Invalid JWKS response");
throw new UnauthorizedException('Authentication failed');
}
// Find the key with the matching kid
const key = data.keys.find((k) => k.kid === kid);
if (!key) {
console.log("Authentication failed: Key not found");
throw new UnauthorizedException('Authentication failed');
}
@ -174,7 +172,6 @@ export class AuthService {
// Optionally log error details for debugging
console.error('Failed to retrieve or process JWKS:', error);
// Wrap other errors as InternalServerException
console.log('Failed to retrieve public key');
throw new InternalServerErrorException();
}
}
@ -192,8 +189,6 @@ export class AuthService {
return { active: Array.isArray(sessionData) && sessionData.length > 0 };
} catch (error: any) {
console.log("Error in introspectToken:", error.message || error);
if (error instanceof UnauthorizedException) {
throw error;
}
@ -224,7 +219,6 @@ export class AuthService {
} catch (error) {
if (error instanceof UnauthorizedException) throw error
console.log("Error while getting User session.....");
throw new InternalServerErrorException()
}
}
@ -243,7 +237,6 @@ export class AuthService {
const introspection = await this.introspectToken(token);
if (!introspection.active) {
console.log("Introspect failed for token");
throw new UnauthorizedException("Authentication Failed")
}
@ -252,7 +245,7 @@ export class AuthService {
return verified;
}
async loginUser(username: string, password: string, req: Request): Promise<any> {
async loginUser(username: string, password: string, applicationName: string, req: Request): Promise<any> {
const access_token = req.cookies?.access_token;
const refresh_token = req.cookies?.refresh_token;
@ -267,6 +260,42 @@ export class AuthService {
try {
const userSession = await this.getUserSession(username)
const emailVerifyResponse: any = await this.userMaintenanceService.ValidateEmail({ P_EMAILADDR: username })
if (Array.isArray(emailVerifyResponse) && emailVerifyResponse[0].ERRORMESG) {
throw new BadRequestException();
}
let ROLE = "";
if (Array.isArray(emailVerifyResponse) && !emailVerifyResponse[0].ERRORMESG) {
switch (emailVerifyResponse[0].SOURCE) {
case "USCIB": ROLE = 'ua'; break;
case "SP": ROLE = 'sa'; break;
case "CLIENT": ROLE = 'ca'; break;
}
}
const isValidCombo =
(applicationName === 'policy' && ROLE === 'ua') ||
(applicationName === 'service-provider' && ROLE === 'sa') ||
(applicationName === 'client' && ROLE === 'ca');
if (!isValidCombo) {
throw new UnauthorizedException("Authentication failed")
// console.log(!isValidCombo);
}
// if (ROLE === 'ua' && req.headers.origin !== 'https://policy.alphaomegainfosys.com') {
// throw new BadRequestException("Invalid username or password")
// }
// else if (ROLE === 'sa' && req.headers.origin !== 'https://sp.alphaomegainfosys.com') {
// throw new BadRequestException("Invalid username or password")
// }
// else if (ROLE === 'ca' && req.headers.origin !== 'https://client.alphaomegainfosys.com') {
// throw new BadRequestException("Invalid username or password")
// }
if (access_token && refresh_token && userSession.length > 0) {
const getSub: any = jwt.decode(refresh_token, { complete: true })
@ -280,7 +309,7 @@ export class AuthService {
let tokens = await this.getTokenFromRefreshToken(req);
const decoded = jwt.decode(access_token, { complete: true });
const email: any = (decoded && typeof decoded === 'object') ? (decoded as any).payload?.email : undefined;
return { ...tokens, email }
return { ...tokens, email, ApplicationName: ROLE }
}
@ -292,8 +321,9 @@ export class AuthService {
return k;
} catch (error) {
console.log("error while logging : ", error.message);
if (error instanceof BadRequestException || error instanceof UnauthorizedException) {
throw error
}
throw new BadRequestException('Invalid username or password');
}
}
@ -314,7 +344,6 @@ export class AuthService {
const response = await axios.request(options);
if (response.status !== 200 || !Array.isArray(response.data)) {
console.log("failed to retrieve user-id....");
throw new UnauthorizedException("Authentication failed")
}
@ -326,7 +355,6 @@ export class AuthService {
}
} catch (error) {
console.log("Error in getUserIdByEmail ...........");
if (error instanceof UnauthorizedException) {
throw error
}
@ -353,9 +381,6 @@ export class AuthService {
return userResponse.data;
} catch (error) {
console.log(error.message);
console.log("Error in getUserDetailsById ...........");
if (error instanceof UnauthorizedException) {
throw error;
}
@ -377,9 +402,6 @@ export class AuthService {
});
if (userResponse.status !== 200 || !Array.isArray(userResponse.data)) {
console.log("userResponse : ", userResponse);
console.log("userResponse status : ", userResponse.status);
throw new UnauthorizedException("Authentication failed");
}
@ -406,9 +428,6 @@ export class AuthService {
};
} catch (error) {
console.log(error.message);
console.log("Error in getUserDetailsByEmail ...........");
if (error instanceof UnauthorizedException) {
throw error;
}
@ -454,9 +473,6 @@ export class AuthService {
try {
const { data } = await axios.request(options2);
console.log("forgot password status API request", data.status);
const forgotPasswordStatus = await this.updateForgotPassword(userDetails)
if (!forgotPasswordStatus) {
@ -466,8 +482,6 @@ export class AuthService {
return { statusCode: 200, message: 'password reset successfull' }
} catch (error) {
// console.error(error);
console.log(error.message);
throw new InternalServerErrorException()
}
@ -487,7 +501,6 @@ export class AuthService {
});
if (!data.access_token) {
console.log("failed to retrieve admin access token.....");
throw new UnauthorizedException("Authentication failed")
}
@ -495,7 +508,6 @@ export class AuthService {
} catch (error) {
if (error instanceof UnauthorizedException) throw error
console.log("Error in getAdminAccessToken");
throw new InternalServerErrorException();
}
}
@ -567,30 +579,20 @@ export class AuthService {
if (!ROLE) {
console.log("ERROR while giving access : ");
throw new InternalServerErrorException();
}
const res = await this.assignRoleToUser(uid, ROLE);
console.log("Assigning Role sussessfully ");
console.log(res);
return { statusCode: 201, message: 'User registered successfully' };
}
} catch (error) {
console.log(error.message);
if (error.message === "Request failed with status code 409") {
throw new ConflictException("User already exist");
}
else if (error instanceof BadRequestException) {
console.log("ERROR while registering : ", error.message);
return error;
}
console.log("ERROR while giving access : ", error.message);
throw new InternalServerErrorException('Failed to create user');
}
}
@ -612,7 +614,6 @@ export class AuthService {
});
if (response.status >= 200 && response.status < 300) {
console.log(`✅ Role "${roleName}" successfully assigned to user ${userId}.`);
return { message: "Successfully assigned to user" };
} else {
console.error(`❌ Failed to assign role. Status: ${response.status}, Data:`, response.data);
@ -724,9 +725,6 @@ export class AuthService {
const refreshToken = req.cookies['refresh_token'];
if (!refreshToken) {
console.log("refesh token not present");
throw new UnauthorizedException('Authentication failed');
}
@ -754,52 +752,10 @@ export class AuthService {
} else {
console.error('🔴 Unexpected error:', error.message);
}
console.log("Error while refreshing tokens : ", error.message);
throw new UnauthorizedException('Authentication failed');
}
}
async getMailTemplate(body: SendMailDTO, token: string, source: string): Promise<MailTemplateDTO | null> {
switch (body.P_MAIL_TYPE) {
case MailTypeDTO.REGISTER_CLIENT:
return {
to: body.P_TO,
subject: `🔐 Register Your Account`,
template: 'a',
context: {
to: body.P_TO,
url: `https://client.alphaomegainfosys.com/register`
}
}
case MailTypeDTO.FORGOT_PASSWORD:
return {
to: body.P_TO,
subject: `Reset your password`,
template: 'b',
context: {
to: body.P_TO,
url: `${source === 'ua' ? `https://policy.alphaomegainfosys.com/forgot-password/${token}`
: source === 'sa' ? `https://sp.alphaomegainfosys.com/forgot-password/${token}`
: source === 'ca' ? `https://client.alphaomegainfosys.com/forgot-password/${token}` : ''}`
}
}
// case MailTypeDTO.DEMO_MAIL:
// return {
// to: body.P_TO,
// subject: `Testing`,
// template: 'demo',
// context: {
// to: body.P_TO,
// url: `https://client.alphaomegainfosys.com/register/${token}`
// }
// }
default:
return null;
}
}
async generateUUID() {
try {
const uuid = uuidv4();
@ -824,18 +780,13 @@ export class AuthService {
else {
token = this.REGISTER_SIGN_JWT.sign({ email: payload.P_TO });
}
console.log("Register token : ", token);
if (!token) {
console.log("Register Token Generation failed");
throw new InternalServerErrorException();
}
return token;
}
catch (error) {
console.log(error.message);
throw new InternalServerErrorException("Register Token Generation failed")
}
}
@ -867,23 +818,47 @@ export class AuthService {
const userResponse = await axios.request(options2);
if (userResponse.status !== 204) {
console.log("Error updating forgot-password : ");
throw new InternalServerErrorException();
}
return true;
} catch (error) {
console.log("Error updating forgot password");
console.log("Error : ", error.message);
return false;
}
}
async getMailTemplate(body: SendMailDTO, token: string, source: string): Promise<MailTemplateDTO | null> {
switch (body.P_MAIL_TYPE) {
case MailTypeDTO.REGISTER_CLIENT:
return {
to: body.P_TO,
subject: `🔐 Register Your Account`,
templateName: 'a',
variables: {
to: body.P_TO,
url: `https://client.alphaomegainfosys.com/register`
}
}
case MailTypeDTO.FORGOT_PASSWORD:
return {
to: body.P_TO,
subject: `Reset your password`,
templateName: 'b',
variables: {
to: body.P_TO,
url: `${source === 'ua' ? `https://policy.alphaomegainfosys.com/forgot-password/${token}`
: source === 'sa' ? `https://sp.alphaomegainfosys.com/forgot-password/${token}`
: source === 'ca' ? `https://client.alphaomegainfosys.com/forgot-password/${token}` : ''}`
}
}
default:
return null;
}
}
async sendMail(body: SendMailDTO) {
console.log("mail body : ", body);
let token: string;
let ROLE: string = "";
let uuid: string | undefined = undefined;
@ -916,8 +891,6 @@ export class AuthService {
try {
await this.mailService.sendMail({ ...mailTemplate });
console.log('Email sent successfully');
if (body.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
let forgotPasswordStatus = await this.updateForgotPassword(userDetails, uuid);

View File

@ -1,34 +1,10 @@
// import { MssqlConfig, OracleConfig } from 'ormconfig';
import { createPool, Pool, Connection as cob } from 'oracledb';
import { Connection, ConnectionPool } from 'mssql';
import { createPool, Pool, Connection } from 'oracledb';
import { ConnectionPool } from 'mssql';
import { Injectable, Logger } from '@nestjs/common';
import { InternalServerException } from 'src/exceptions/internalServerError.exception';
import { ConfigService } from '@nestjs/config';
import { getMssqlConfig, getOracleConfig } from './db.config';
// @Injectable()
// export class OracleDBService {
// private pool: Pool;
// constructor() {
// this.initializePool();
// }
// private async initializePool() {
// this.pool = await createPool({
// ...OracleConfig,
// poolMin: 1,
// poolMax: 10,
// poolIncrement: 1,
// });
// }
// async getConnection(): Promise<cob> {
// const connection = await this.pool.getConnection();
// return connection;
// }
// }
@Injectable()
export class OracleDBService {
private pool: Pool | null = null;
@ -114,7 +90,6 @@ export class MssqlDBService {
await this.pool.connect();
this.poolConnected = true;
console.log('Database connection pool initialized.');
}
return this.pool;
} catch (error) {

View File

@ -12,6 +12,16 @@ export enum YON {
NO = "N",
}
export class PRINTGL_DTO {
@ApiProperty({ required: true, enum: YON })
@Transform(({ value }) => typeof value === 'string' ? value.trim().toUpperCase() : value)
@IsEnum(YON, { message: 'P_PRINTGL must be either "Y" or "N"' })
@Length(1, 1, { message: 'P_PRINTGL must be 1 character' })
@IsString()
@IsDefined({ message: "Invalid Request" })
P_PRINTGL: YON;
}
export class CARNETSTATUS_DTO {
@ApiProperty({ required: true })
@Length(0, 20, {
@ -22,6 +32,68 @@ export class CARNETSTATUS_DTO {
P_CARNETSTATUS: string;
}
export class CARNETNO_DTO {
@ApiProperty({ required: true })
@IsString()
@IsDefined({ message: 'Property P_CARNETNO is required' })
P_CARNETNO: string;
}
export class ORDERID_DTO {
@ApiProperty({ required: true, type: String, nullable: true })
@IsString()
@IsDefined({ message: 'Property P_ORDERID is required' })
P_ORDERID: string | null;
}
export class PRICE_DTO {
@ApiProperty({ required: true })
// @Max(999999999, {
// message: 'Property P_PRICE must not exceed 999999999',
// })
@Min(0.01, { message: 'Property P_PRICE must be greater than zero' })
// @IsInt({ message: 'Property P_PRICE allows only whole numbers' })
@IsNumber({}, { message: 'Property P_PRICE must be a number' })
@Transform(({ value }) => Number(value))
@IsDefined({ message: 'Property P_PRICE is required' })
P_PRICE: number;
}
export class PAYMENTAMOUNT_DTO {
@ApiProperty({ required: true })
// @Max(999999999, {
// message: 'Property P_PRICE must not exceed 999999999',
// })
@Min(0.01, { message: 'Property P_PAYMENTAMOUNT must be greater than zero' })
// @IsInt({ message: 'Property P_PRICE allows only whole numbers' })
@IsNumber({}, { message: 'Property P_PAYMENTAMOUNT must be a number' })
@Transform(({ value }) => Number(value))
@IsDefined({ message: 'Property P_PAYMENTAMOUNT is required' })
P_PAYMENTAMOUNT: number;
}
export class PAYMENTSTATUS_DTO {
@ApiProperty({ required: true })
@IsString({ message: 'Property P_STATUS must be a string' })
@IsDefined({ message: 'Property P_STATUS is required' })
P_STATUS: string;
}
export class PAYMENTERROR_DTO {
@ApiProperty({ required: true, type: String, nullable: true })
@IsString({ message: 'Property P_PAYMENTERROR must be a string' })
@IsDefined({ message: 'Property P_PAYMENTERROR is required' })
P_PAYMENTERROR: string | null = null;
}
export class DESCRIPTION_DTO {
@ApiProperty({ required: true })
@IsString()
@IsDefined({ message: 'Property P_DESCRIPTION is required' })
P_DESCRIPTION: string;
}
export class HEADERID_DTO {
@ApiProperty({ required: true })
@Max(999999999, {
@ -42,6 +114,40 @@ export class APPLICATIONNAME_DTO {
P_APPLICATIONNAME: string;
}
export class GOODS_PORT_DTO {
@ApiProperty({ required: true, type: String, nullable: true })
@IsString({ message: 'Property P_GOODSPORT must be a string' })
@IsDefined({ message: 'Property P_GOODSPORT is required' })
P_GOODSPORT: string | null = null;
}
export class GOODS_COUNTRY_DTO {
@ApiProperty({ required: true, type: String, nullable: true })
@IsString({ message: 'Property P_GOODSCOUNTRY must be a string' })
@IsDefined({ message: 'Property P_GOODSCOUNTRY is required' })
P_GOODSCOUNTRY: string | null = null;
}
export class REASON_CODE_DTO {
@ApiProperty({ required: true })
@IsString({ message: 'Property P_REASONCODE must be a string' })
@IsDefined({ message: 'Property P_REASONCODE is required' })
P_REASONCODE: string;
}
export class EXTENSION_PERIOD_DTO {
@ApiProperty({ required: true })
@Max(999999999, {
message: 'Property P_EXTENSIONPERIOD must not exceed 999999999',
})
@Min(0, { message: 'Property P_EXTENSIONPERIOD must be at least 0 or more' })
@IsInt({ message: 'Property P_EXTENSIONPERIOD allows only whole numbers' })
@IsNumber({}, { message: 'Property P_EXTENSIONPERIOD must be a number' })
@Transform(({ value }) => Number(value))
@IsDefined({ message: 'Property P_EXTENSIONPERIOD is required' })
P_EXTENSIONPERIOD: number = 0;
}
export class ORDERTYPE_DTO {
@ApiProperty({ required: true })
@IsString({ message: 'Property P_ORDERTYPE must be a string' })
@ -160,6 +266,63 @@ export class GLTABLE_ROW_DTO {
GOODSORIGINCOUNTRY: string;
}
export class GLTABLE_ROW_ADD_DTO {
@ApiProperty({ required: false })
@Max(99999, { message: 'Property ITEMNO must not exceed 99999' })
@Min(0, { message: 'Property ITEMNO must be at least 0 or more' })
@IsInt({ message: 'Property ITEMNO allows only whole numbers' })
@Transform(({ value }) => {
if (value === undefined || value === null || value === '') return 0;
return Number(value);
})
@IsNumber({}, { message: 'Property ITEMNO must be a number' })
@IsOptional()
ITEMNO: number = 0
@ApiProperty({ required: true })
@MaxLength(200, { message: 'Property ITEMDESCRIPTION must not exceed 200 characters' })
@IsString({ message: 'Property ITEMDESCRIPTION must be a string' })
@IsDefined({ message: 'Property ITEMDESCRIPTION is required' })
ITEMDESCRIPTION: string;
@ApiProperty({ required: true })
@Max(999999999.99, { message: 'Property ITEMVALUE must not exceed 999999999.99' })
@Min(0, { message: 'Property ITEMVALUE must be at least 0 or more' })
@Transform(({ value }) => Number(value))
@IsNumber({ maxDecimalPlaces: 2 }, { message: 'Property ITEMVALUE must be a number' })
@IsDefined({ message: 'Property ITEMVALUE is required' })
ITEMVALUE: number;
@ApiProperty({ required: true })
@Max(99999, { message: 'Property NOOFPIECES must not exceed 99999' })
@Min(0, { message: 'Property NOOFPIECES must be at least 0 or more' })
@IsInt({ message: 'Property NOOFPIECES allows only whole numbers' })
@Transform(({ value }) => Number(value))
@IsNumber({}, { message: 'Property NOOFPIECES must be a number' })
@IsDefined({ message: 'Property NOOFPIECES is required' })
NOOFPIECES: number;
@ApiProperty({ required: true })
@Max(99999.9999, { message: 'Property ITEMVALUE must not exceed 999999999.99' })
@Min(0, { message: 'Property ITEMVALUE must be at least 0 or more' })
@Transform(({ value }) => Number(value))
@IsNumber({ maxDecimalPlaces: 2 }, { message: 'Property ITEMVALUE must be a number' })
@IsDefined({ message: 'Property ITEMVALUE is required' })
ITEMWEIGHT: number;
@ApiProperty({ required: true })
@MaxLength(10, { message: 'Property ITEMWEIGHTUOM must not exceed 10 characters' })
@IsString({ message: 'Property ITEMWEIGHTUOM must be a string' })
@IsDefined({ message: 'Property ITEMWEIGHTUOM is required' })
ITEMWEIGHTUOM: string;
@ApiProperty({ required: true })
@MaxLength(2, { message: 'Property GOODSORIGINCOUNTRY must not exceed 2 characters' })
@IsString({ message: 'Property GOODSORIGINCOUNTRY must be a string' })
@IsDefined({ message: 'Property GOODSORIGINCOUNTRY is required' })
GOODSORIGINCOUNTRY: string;
}
export class GLTABLE_DTO {
@ApiProperty({ required: true, type: () => [GLTABLE_ROW_DTO] })
@Type(() => GLTABLE_ROW_DTO)
@ -169,7 +332,16 @@ export class GLTABLE_DTO {
P_GLTABLE: GLTABLE_ROW_DTO[];
}
export class ITEMNO_DTO{
export class GLTABLE_ITEMNO_OPTIONAL_DTO {
@ApiProperty({ required: true, type: () => [GLTABLE_ROW_ADD_DTO] })
@Type(() => GLTABLE_ROW_ADD_DTO)
@ValidateNested({ each: true })
@IsArray({ message: 'Property P_GLTABLE allows only array type' })
@IsDefined({ message: 'Property P_GLTABLE is required' })
P_GLTABLE: GLTABLE_ROW_ADD_DTO[];
}
export class ITEMNO_DTO {
@ApiProperty({ required: true })
@Max(99999, { message: 'Property ITEMNO must not exceed 99999' })
@Min(0, { message: 'Property ITEMNO must be at least 0 or more' })
@ -180,7 +352,7 @@ export class ITEMNO_DTO{
P_ITEMNO: number;
}
export class SHIPCONTACTID_DTO{
export class SHIPCONTACTID_DTO {
@ApiProperty({ required: true })
@Max(99999, { message: 'Property P_SHIPCONTACTID must not exceed 99999' })
@Min(0, { message: 'Property P_SHIPCONTACTID must be at least 0 or more' })
@ -206,7 +378,7 @@ export class USSETS_DTO {
@Transform(({ value }) => Number(value))
@IsNumber({}, { message: 'Property P_USSETS must be a number' })
@IsDefined({ message: 'Property P_USSETS is required' })
P_USSETS: number;
P_USSETS: number = 0;
}
export enum VOT {

View File

@ -1,11 +1,15 @@
import { IntersectionType, PartialType } from "@nestjs/swagger";
import {
APPLICATIONNAME_DTO, AUTHREP_DTO, AUTO_FLAG_DTO, COMMERCIAL_SAMPLE_FLAG_DTO,
APPLICATIONNAME_DTO, AUTHREP_DTO, AUTO_FLAG_DTO, CARNETNO_DTO, COMMERCIAL_SAMPLE_FLAG_DTO,
COUNTRYTABLE_DTO, CUSTCOURIERNO_DTO, DELIVERYMETHOD_DTO, DELIVERYTYPE_DTO,
EXIBITIONS_FAIR_FLAG_DTO, FORMOFSECURITY_DTO, GLTABLE_DTO, HEADERID_DTO,
HORSE_FLAG_DTO, INSPROTECTION_DTO, ITEMNO_DTO, LDIPROTECTION_DTO, ORDERTYPE_DTO, PAYMENTMETHOD_DTO,
PROF_EQUIPMENT_FLAG_DTO, REFNO_DTO, SHIPADDRID_DTO, SHIPCONTACTID_DTO, SHIPNAME_DTO, SHIPTOTYPE_DTO, USSETS_DTO
DESCRIPTION_DTO,
EXIBITIONS_FAIR_FLAG_DTO, EXTENSION_PERIOD_DTO, FORMOFSECURITY_DTO, GLTABLE_DTO, GLTABLE_ITEMNO_OPTIONAL_DTO, GOODS_COUNTRY_DTO, GOODS_PORT_DTO, HEADERID_DTO,
HORSE_FLAG_DTO, INSPROTECTION_DTO, ITEMNO_DTO, LDIPROTECTION_DTO, ORDERID_DTO, ORDERTYPE_DTO, PAYMENTAMOUNT_DTO, PAYMENTERROR_DTO, PAYMENTMETHOD_DTO,
PAYMENTSTATUS_DTO,
PRICE_DTO,
PRINTGL_DTO,
PROF_EQUIPMENT_FLAG_DTO, REASON_CODE_DTO, REFNO_DTO, SHIPADDRID_DTO, SHIPCONTACTID_DTO, SHIPNAME_DTO, SHIPTOTYPE_DTO, USSETS_DTO
} from "./carnet-application-property.dto";
import { ADDRESS1_DTO, ADDRESS2_DTO, CITY_DTO, COUNTRY_DTO, NOTES_DTO, SPID_DTO, STATE_DTO, USERID_DTO, ZIP_DTO } from "../uscib-managed-sp/sp/sp-property.dto";
@ -51,8 +55,27 @@ export class TransmitApplicationtoProcessDTO extends IntersectionType(
) { }
// processing [ PROCESSINGCENTER_PKG ]
export class CopyCarnetDTO extends (IntersectionType(USERID_DTO, HEADERID_DTO, APPLICATIONNAME_DTO)) { }
export class CarnetProcessingCenterDTO extends (IntersectionType(USERID_DTO, HEADERID_DTO)) { }
export class CarnetProcessingCenterDTO2 extends (IntersectionType(USERID_DTO, CARNETNO_DTO)) { }
export class GetExtendedSectionDTO extends (IntersectionType(SPID_DTO, HEADERID_DTO)) { }
export class SaveExtensionApplicationDTO extends (IntersectionType(
USERID_DTO,
SPID_DTO,
HEADERID_DTO,
PartialType(GOODS_PORT_DTO),
PartialType(GOODS_COUNTRY_DTO),
REASON_CODE_DTO,
PartialType(EXTENSION_PERIOD_DTO)
)) { }
export class PrintCarnetDTO extends (IntersectionType(SPID_DTO, HEADERID_DTO, PRINTGL_DTO)) { }
export class PrintGLDTO extends (IntersectionType(SPID_DTO, HEADERID_DTO)) { }
export class CapturePaymentDTO extends (IntersectionType(ORDERID_DTO, APPLICATIONNAME_DTO, PRICE_DTO, USERID_DTO)) { }
export class InitiatePaymentDTO extends (IntersectionType(APPLICATIONNAME_DTO, PRICE_DTO, DESCRIPTION_DTO, USERID_DTO)) { }
export class GetOrderDetailsDTO extends (IntersectionType(ORDERID_DTO)) { }
export class GetPaymentHistoryDTO extends (IntersectionType(APPLICATIONNAME_DTO, USERID_DTO)) { }
export class SaveHistoryDTO extends (IntersectionType(APPLICATIONNAME_DTO, ORDERID_DTO, PAYMENTAMOUNT_DTO, PAYMENTSTATUS_DTO, USERID_DTO, PartialType(PAYMENTERROR_DTO))) { }
export class CreateApplicationDTO extends IntersectionType(
SPID_DTO, CLIENTID_DTO, LOCATIONID_DTO, USERID_DTO, APPLICATIONNAME_DTO,
@ -70,6 +93,10 @@ export class UpdateExpGoodsAuthRepDTO extends IntersectionType(
) { }
export class AddGenerallistItemsDTO extends IntersectionType(
HEADERID_DTO, GLTABLE_ITEMNO_OPTIONAL_DTO, USERID_DTO
) { }
export class EditGenerallistItemsDTO extends IntersectionType(
HEADERID_DTO, GLTABLE_DTO, USERID_DTO
) { }
@ -78,7 +105,7 @@ export class DeleteGenerallistItemsDTO extends IntersectionType(
) { }
export class AddCountriesDTO extends IntersectionType(
HEADERID_DTO, USSETS_DTO, COUNTRYTABLE_DTO, USERID_DTO
HEADERID_DTO, PartialType(USSETS_DTO), COUNTRYTABLE_DTO, USERID_DTO
) { }
export class UpdateShippingDetailsDTO extends IntersectionType(

View File

@ -60,6 +60,13 @@ export class CLIENTNAME_DTO {
P_CLIENTNAME: string;
}
export class INDUSTRY_TYPE_DTO {
@ApiProperty({ required: true })
@IsString({ message: 'Property P_INDUSTRYTYPE must be a string' })
@IsDefined({ message: 'Property P_INDUSTRYTYPE is required' })
P_INDUSTRYTYPE: string;
}
export class REVENUELOCATION_DTO {
@ApiProperty({ required: true })
@Length(0, 2, {

View File

@ -9,7 +9,7 @@ import {
import {
CLIENT_CONTACTID_DTO, CLIENTID_DTO, CLIENTLOCADDRESSTABLE_DTO, CLIENTLOCATIONID_DTO,
CLIENTNAME_DTO, LOCATIONNAME_DTO, NAMEOF_DTO, PREPARERNAME_DTO, REVENUELOCATION_DTO, STATUS_DTO
CLIENTNAME_DTO, INDUSTRY_TYPE_DTO, LOCATIONNAME_DTO, NAMEOF_DTO, PREPARERNAME_DTO, REVENUELOCATION_DTO, STATUS_DTO
} from "./manage-clients-property.dto";
import {
@ -34,7 +34,8 @@ export class CreateClientDataDTO extends IntersectionType(
PartialType(COUNTRY_DTO),
ISSUING_REGION_DTO,
REVENUELOCATION_DTO,
USERID_DTO
USERID_DTO,
INDUSTRY_TYPE_DTO
) { }
@ -49,7 +50,8 @@ export class UpdateClientDTO extends IntersectionType(
ZIP_DTO,
COUNTRY_DTO,
REVENUELOCATION_DTO,
USERID_DTO
USERID_DTO,
INDUSTRY_TYPE_DTO
) { }
export class UpdateClientContactsDTO extends IntersectionType(

View File

@ -1,6 +1,13 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsNumber, IsString } from "class-validator";
export class PCT_VALUE_DTO {
@ApiProperty({ required: true })
@IsString()
P_PCT_VALUE: string;
}
export class EFFDATE_DTO {
@ApiProperty({ required: true })
@IsString()

View File

@ -6,7 +6,7 @@ import { HOLDERTYPE_DTO, USCIBMEMBERFLAG_DTO } from "../manage-holders/manage-ho
import {
BASICFEESETUPID_DTO, BONDRATESETUPID_DTO, CARGORATESETUPID_DTO, CFFEESETUPID_DTO,
COMMRATE_DTO, CSFEESETUPID_DTO, CUSTOMERTYPE_DTO, EFFDATE_DTO, EFFEESETUPID_DTO, ENDSETS_DTO,
ENDTIME_DTO, FEECOMMID_DTO, FEES_DTO, RATE_DTO, SPCLCOMMODITY_DTO, SPCLCOUNTRY_DTO,
ENDTIME_DTO, FEECOMMID_DTO, FEES_DTO, PCT_VALUE_DTO, RATE_DTO, SPCLCOMMODITY_DTO, SPCLCOUNTRY_DTO,
STARTSETS_DTO, STARTTIME_DTO, TIMEZONE_DTO
} from "./manage-fee-property.dto";
@ -36,7 +36,8 @@ export class CreateBondRateDTO extends IntersectionType(
SPCLCOUNTRY_DTO,
EFFDATE_DTO,
RATE_DTO,
USERID_DTO
USERID_DTO,
PCT_VALUE_DTO
) { }
export class CreateCargoRateDTO extends IntersectionType(
@ -100,7 +101,8 @@ export class UpdateBondRateDTO extends IntersectionType(
BONDRATESETUPID_DTO,
RATE_DTO,
EFFDATE_DTO,
USERID_DTO
USERID_DTO,
PCT_VALUE_DTO
) { }
export class UpdateCargoRateDTO extends IntersectionType(

View File

@ -42,7 +42,6 @@ export class CreateHolderContactsDTO extends IntersectionType(
SPID_DTO, HOLDERID_DTO, CONTACTSTABLE_DTO, USERID_DTO
) { }
export class UpdateHolderDTO extends IntersectionType(
HOLDERID_DTO,
SPID_DTO,
@ -96,5 +95,6 @@ export class HolderContactActivateOrInactivateDTO extends IntersectionType(
export class SearchHolderDTO extends IntersectionType(
SPID_DTO,
PartialType(HOLDERNAME_DTO)
PartialType(HOLDERNAME_DTO),
USERID_DTO
) { }

View File

@ -1,7 +1,7 @@
import { IntersectionType } from '@nestjs/swagger';
import { REGION_CODE_DTO, REGIONID_DTO } from './region-property.dto';
import { NAME_DTO } from '../../property.dto';
import { NAME_DTO, SPID_DTO } from '../../property.dto';
export class InsertRegionsDto extends IntersectionType(REGION_CODE_DTO, NAME_DTO) { }
export class InsertRegionsDto extends IntersectionType(REGION_CODE_DTO, NAME_DTO, SPID_DTO) { }
export class UpdateRegionDto extends IntersectionType(REGIONID_DTO, NAME_DTO) { }

View File

@ -1,7 +1,9 @@
import { IntersectionType } from "@nestjs/swagger";
import { CLIENT_CONTACTID_DTO, CLIENTID_DTO, DOMAIN_DTO,
import {
CLIENT_CONTACTID_DTO, CLIENTID_DTO, DOMAIN_DTO,
EMAIL_DTO, ENABLE_PASSWORD_POLICY_DTO, LOOKUP_CODE_DTO, PASSWORD_DTO,
USERID_DTO } from "src/dto/property.dto";
USERID_DTO
} from "src/dto/property.dto";
import { SPID_DTO } from "../uscib-managed-sp/sp/sp-property.dto";
export class SPID_CLIENTID_DTO extends IntersectionType(SPID_DTO, CLIENTID_DTO) { }
@ -9,13 +11,13 @@ export class SPID_CLIENTID_DTO extends IntersectionType(SPID_DTO, CLIENTID_DTO)
export class SPID_EMAIL_DTO extends IntersectionType(SPID_DTO, EMAIL_DTO) { }
export class CreateUSCIBLoginsDTO extends IntersectionType(
USERID_DTO, EMAIL_DTO, LOOKUP_CODE_DTO, PASSWORD_DTO, ENABLE_PASSWORD_POLICY_DTO
USERID_DTO, EMAIL_DTO, LOOKUP_CODE_DTO, ENABLE_PASSWORD_POLICY_DTO
) { }
export class CreateClientLoginsDTO extends IntersectionType(
SPID_DTO, USERID_DTO, CLIENT_CONTACTID_DTO, PASSWORD_DTO, ENABLE_PASSWORD_POLICY_DTO
SPID_DTO, USERID_DTO, CLIENT_CONTACTID_DTO, ENABLE_PASSWORD_POLICY_DTO
) { }
export class CreateSPLoginsDTO extends IntersectionType(
SPID_DTO, USERID_DTO, DOMAIN_DTO, EMAIL_DTO, LOOKUP_CODE_DTO, PASSWORD_DTO, ENABLE_PASSWORD_POLICY_DTO
SPID_DTO, USERID_DTO, DOMAIN_DTO, EMAIL_DTO, LOOKUP_CODE_DTO, ENABLE_PASSWORD_POLICY_DTO
) { }

View File

@ -0,0 +1,19 @@
import { HttpException, HttpStatus } from '@nestjs/common';
export class NotFoundException extends HttpException {
constructor(
message = 'Not Found',
// errorCode = 'INTERNAL_ERROR',
// data: any = null,
) {
super(
{
statusCode: HttpStatus.NOT_FOUND ,
message,
// errorCode,
// data,
},
HttpStatus.NOT_FOUND,
);
}
}

View File

@ -21,16 +21,11 @@ export class JwtAuthGuard implements CanActivate {
const token = request.cookies?.access_token;
const body = request.body;
console.log("from JWT guard body : ", body);
if (body?.P_MAIL_TYPE && body?.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
return true;
}
if (!token) {
console.log("No token found from Request");
throw new UnauthorizedException('Authentication failed');
}
try {

View File

@ -30,8 +30,6 @@ export class RegisterGuard implements CanActivate {
request['user'] = payload;
return true;
} catch (err) {
console.log("Error in register guard : ", err.message);
throw new UnauthorizedException("Invalid Register Token");
}
}

View File

@ -26,9 +26,6 @@ export class RolesGuard implements CanActivate {
const token = request.cookies?.access_token; // Token is stored as HttpOnly cookie
const body = request.body;
console.log("from JWT guard body : ", body);
if (body?.P_MAIL_TYPE && body?.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
return true;
}
@ -49,8 +46,6 @@ export class RolesGuard implements CanActivate {
return true;
} catch (err: any) {
console.log("from roles guard : ", err.message);
throw new UnauthorizedException('Authentication Failed');
}
}

View File

@ -19,10 +19,6 @@ export class LogoutInterceptor implements NestInterceptor {
// Send a custom 200 response when refresh token is missing
response.clearCookie('access_token');
response.clearCookie('refresh_token');
console.log("No tokens found so logging-out");
response.status(200).json({
statusCode: 200,
message: 'Logged-Out successfully',

View File

@ -1,9 +1,10 @@
import { MailerModule } from '@nestjs-modules/mailer';
import { Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';
import { join } from 'path';
import * as Joi from 'joi';
import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handlebars.adapter';
import { MailService } from './mail.service';
import * as nodemailer from 'nodemailer';
@Module({
imports: [
@ -14,15 +15,15 @@ import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handleba
MAIL_PASS: Joi.string().required(),
}),
}),
],
MailerModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => {
const templatePath = join(__dirname, '../../..', 'public', 'mail-templates');
console.log('Resolved mail template path:', templatePath);
return {
transport: {
providers: [
{
provide: 'MAIL_TRANSPORTER',
useFactory: async (configService: ConfigService) => {
return nodemailer.createTransport(
{
// service: "gmail",
host: 'smtp.gmail.com',
port: 587,
secure: false,
@ -31,21 +32,18 @@ import { HandlebarsAdapter } from '@nestjs-modules/mailer/dist/adapters/handleba
pass: configService.get<string>('MAIL_PASS'),
},
},
defaults: {
{
from: `"Carnet APP" <${configService.get<string>('MAIL_USER')}>`,
},
template: {
dir: templatePath,
adapter: new HandlebarsAdapter(),
options: {
strict: true,
},
},
};
}
);
},
inject: [ConfigService],
}),
},
MailService,
],
exports: [MailService],
})
export class MailModule { }

42
src/mail/mail.service.ts Normal file
View File

@ -0,0 +1,42 @@
// mailer.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { Transporter } from 'nodemailer';
import * as fs from 'fs';
import * as path from 'path';
import * as Handlebars from 'handlebars';
import { MailTemplateDTO } from 'src/auth/auth.dto';
@Injectable()
export class MailService {
private templatesCache = new Map<string, Handlebars.TemplateDelegate>();
constructor(@Inject('MAIL_TRANSPORTER') private readonly transporter: Transporter) {
console.log(path.join(process.cwd(), 'public', 'mail-templates', 'a.hbs'));
}
private loadTemplate(templateName: string): Handlebars.TemplateDelegate {
if (this.templatesCache.has(templateName)) {
return this.templatesCache.get(templateName)!;
}
const templatePath = path.join(process.cwd(), 'public', 'mail-templates', `${templateName}.hbs`);
const source = fs.readFileSync(templatePath, 'utf8');
const compiled = Handlebars.compile(source);
this.templatesCache.set(templateName, compiled);
return compiled;
}
async sendMail(data: MailTemplateDTO) {
const template = this.loadTemplate(data.templateName);
const html = template(data.variables);
const mailOptions = {
to: data.to,
subject: data.subject,
html,
};
return this.transporter.sendMail(mailOptions);
}
}

View File

@ -47,7 +47,7 @@ export class ManageClientsService {
const finalBody: CreateClientDataDTO = { ...newBody, ...reqBody };
let connection: Connection; // Fixed duplicate declaration
let connection: mssql.ConnectionPool; // Fixed duplicate declaration
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -98,7 +98,7 @@ export class ManageClientsService {
};
GetPreparerByClientid = async (body: GetClientDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -142,7 +142,7 @@ export class ManageClientsService {
const finalBody: UpdateClientDTO = { ...newBody, ...reqBody };
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
@ -196,7 +196,7 @@ export class ManageClientsService {
...reqBody,
};
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -272,7 +272,7 @@ export class ManageClientsService {
const finalBody: UpdateClientContactsDTO = { ...newBody, ...reqBody };
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -327,7 +327,7 @@ export class ManageClientsService {
const finalBody: UpdateClientLocationsDTO = { ...newBody, ...reqBody };
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -379,7 +379,7 @@ export class ManageClientsService {
...reqBody,
};
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -452,7 +452,7 @@ export class ManageClientsService {
...reqBody,
};
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -505,7 +505,7 @@ export class ManageClientsService {
...reqBody,
};
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -553,7 +553,7 @@ export class ManageClientsService {
...reqBody,
};
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -20,7 +20,7 @@ export class ManageFeeService {
// Basic Fee Setup
async GETBASICFEERATES(body: GetFeeGeneralDTO): Promise<any[] | Object> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -41,7 +41,7 @@ export class ManageFeeService {
}
async CREATEBASICFEE(body: CreateBasicFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -63,7 +63,7 @@ export class ManageFeeService {
}
async UPDATEBASICFEE(body: UpdateBasicFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -86,7 +86,7 @@ export class ManageFeeService {
async GETBONDRATES(body: GetFeeGeneralDTO): Promise<any[] | object> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -111,7 +111,7 @@ export class ManageFeeService {
async CREATEBONDRATE(body: CreateBondRateDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -138,7 +138,7 @@ export class ManageFeeService {
async UPDATEBONDRATE(body: UpdateBondRateDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -161,7 +161,7 @@ export class ManageFeeService {
// CArgo Rate
async GETCARGORATES(body: GetFeeGeneralDTO): Promise<any[] | object> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -185,7 +185,7 @@ export class ManageFeeService {
}
async CREATECARGORATE(body: CreateCargoRateDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -209,7 +209,7 @@ export class ManageFeeService {
}
async UPDATECARGORATE(body: UpdateCargoRateDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -233,7 +233,7 @@ export class ManageFeeService {
async GETCFFEERATES(body: GetFeeGeneralDTO): Promise<any[]> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -258,7 +258,7 @@ export class ManageFeeService {
async CREATECFFEE(body: CreateCfFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -285,7 +285,7 @@ export class ManageFeeService {
async UPDATECFFEE(body: UpdateCfFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -308,7 +308,7 @@ export class ManageFeeService {
// Continuation sheet
async GETCSFEERATES(body: GetFeeGeneralDTO): Promise<any[]> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -333,7 +333,7 @@ export class ManageFeeService {
}
async CREATECSFEE(body: CreateCsFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -357,7 +357,7 @@ export class ManageFeeService {
}
async UPDATECSFEE(body: UpdateCsFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -381,7 +381,7 @@ export class ManageFeeService {
async GETEFFEERATES(body: GetFeeGeneralDTO): Promise<any[]> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -405,7 +405,7 @@ export class ManageFeeService {
}
async CREATEEFFEE(body: CreateEfFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -432,7 +432,7 @@ export class ManageFeeService {
async UPDATEEFFEE(body: UpdateEfFeeDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -456,7 +456,7 @@ export class ManageFeeService {
async GETFEECOMM(body: GetFeeGeneralDTO): Promise<any[]> {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -483,7 +483,7 @@ export class ManageFeeService {
async CREATEFEECOMM(body: CreateFeeCommDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -507,7 +507,7 @@ export class ManageFeeService {
}
async UPDATEFEECOMM(body: UpdateFeeCommDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -45,7 +45,7 @@ export class ManageHoldersService {
const finalBody: CreateHoldersDTO = { ...newBody, ...reqBody };
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);
@ -103,7 +103,7 @@ export class ManageHoldersService {
};
GetHolderRecord = async (body: GetHolderDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);
@ -119,7 +119,7 @@ export class ManageHoldersService {
};
UpdateHolder = async (body: UpdateHolderDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new mssql.Request(connection);
@ -153,7 +153,7 @@ export class ManageHoldersService {
UpdateHolderContact = async (body: UpdateHolderContactDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new mssql.Request(connection);
@ -181,7 +181,7 @@ export class ManageHoldersService {
GetHolderContacts = async (body: GetHolderDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);
@ -200,7 +200,7 @@ export class ManageHoldersService {
console.log(body);
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);
@ -216,7 +216,7 @@ export class ManageHoldersService {
};
ReactivateHolder = async (body: HolderActivateOrInactivateDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);
@ -233,7 +233,7 @@ export class ManageHoldersService {
};
InactivateHolderContact = async (body: HolderContactActivateOrInactivateDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);
@ -250,7 +250,7 @@ export class ManageHoldersService {
};
ReactivateHolderContact = async (body: HolderContactActivateOrInactivateDTO) => {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request: Request = new Request(connection);

View File

@ -1,6 +1,7 @@
import { Injectable } from '@nestjs/common';
import { Connection, Request } from 'mssql';
import { MssqlDBService } from 'src/db/db.service';
import * as mssql from 'mssql';
@Injectable()
export class MssqlService {
@ -8,7 +9,7 @@ export class MssqlService {
constructor(private readonly mssqlDBService: MssqlDBService) { }
async checkConnection() {
let connection : Connection;
let connection : mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();

View File

@ -20,7 +20,7 @@ export class ParamTableService {
console.log(finalBody);
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -35,7 +35,7 @@ export class ParamTableService {
}
async CREATETABLERECORD(body: CreateTableRecordDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -57,7 +57,11 @@ export class ParamTableService {
}
async CREATEPARAMRECORD(body: CreateParamRecordDTO) {
let connection: Connection;
console.log("rbody : ", body);
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -87,7 +91,7 @@ export class ParamTableService {
}
async UPDATEPARAMRECORD(body: UpdateParamRecordDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -116,7 +120,7 @@ export class ParamTableService {
async INACTIVATEPARAMRECORD(body: ActivateOrInactivateParamRecordDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -136,7 +140,7 @@ export class ParamTableService {
}
async REACTIVATEPARAMRECORD(body: ActivateOrInactivateParamRecordDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -12,7 +12,7 @@ export class CarnetSequenceService {
async getCarnetSequence(body: SPID_DTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -26,7 +26,7 @@ export class CarnetSequenceService {
}
async createCarnetSequence(body: CreateCarnetSequenceDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -11,7 +11,7 @@ export class RegionService {
constructor(private readonly mssqlDBService: MssqlDBService) { }
async getRegions() {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -24,7 +24,7 @@ export class RegionService {
async insetNewRegions(body: InsertRegionsDto) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -39,7 +39,7 @@ export class RegionService {
}
async updateRegions(body: UpdateRegionDto){
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -15,7 +15,7 @@ export class SpContactsService {
async getSpAllContacts(body: SPID_DTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -30,7 +30,7 @@ export class SpContactsService {
async getSPDefaultcontacts(body: SPID_DTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -45,7 +45,7 @@ export class SpContactsService {
async inactivateSPContact(body: SP_CONTACTID_DTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -59,7 +59,7 @@ export class SpContactsService {
}
async insertSPContacts(body: InsertSPContactsDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -83,7 +83,7 @@ export class SpContactsService {
}
async setSPDefaultcontact(body: SP_CONTACTID_DTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -97,7 +97,7 @@ export class SpContactsService {
}
async updateSPContacts(body: UpdateSPContactsDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -12,7 +12,7 @@ export class SpService {
async getAllServiceproviders() {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -26,7 +26,7 @@ export class SpService {
async getSpBySpid(body: SPID_DTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -40,7 +40,7 @@ export class SpService {
}
async insertNewServiceProvider(body: InsertNewServiceProviderDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);
@ -69,7 +69,7 @@ export class SpService {
}
async updateServiceProvider(body: UpdateServiceProviderDTO) {
let connection: Connection;
let connection: mssql.ConnectionPool;
try {
connection = await this.mssqlDBService.getConnection();
const request = new Request(connection);

View File

@ -1,4 +1,4 @@
import { Body, Controller, Delete, Get, Param, Patch, Post, Put, UseGuards } from '@nestjs/common';
import { BadRequestException, Body, Controller, Delete, Get, HttpCode, Param, Patch, Post, Put, Res, StreamableFile, UseGuards } from '@nestjs/common';
import { CarnetApplicationService } from './carnet-application.service';
import { ApiTags } from '@nestjs/swagger';
@ -7,19 +7,26 @@ import {
AddCountriesDTO,
AddGenerallistItemsDTO,
CA_UpdateHolderDTO,
CarnetProcessingCenterDTO, CreateApplicationDTO, DeleteGenerallistItemsDTO, GetCarnetControlCenterDTO, SaveCarnetApplicationDTO, TransmitApplicationtoProcessDTO,
CapturePaymentDTO,
CarnetProcessingCenterDTO, CarnetProcessingCenterDTO2, CopyCarnetDTO, CreateApplicationDTO, DeleteGenerallistItemsDTO, EditGenerallistItemsDTO, GetCarnetControlCenterDTO, GetExtendedSectionDTO, GetOrderDetailsDTO, GetPaymentHistoryDTO, InitiatePaymentDTO, PrintCarnetDTO, PrintGLDTO, SaveCarnetApplicationDTO, SaveExtensionApplicationDTO, SaveHistoryDTO, TransmitApplicationtoProcessDTO,
UpdateExpGoodsAuthRepDTO,
UpdateShippingDetailsDTO
} from 'src/dto/property.dto';
import { Roles } from 'src/decorators/roles.decorator';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { RolesGuard } from 'src/guards/roles.guard';
import { Response } from 'express';
import { join } from 'path';
import { createReadStream } from 'fs';
import { deleteFilesAsync, generateFinalPDF, replaceSlashWithDash } from 'src/utils/helper';
import { BadRequestException as BR } from 'src/exceptions/badRequest.exception';
import { InternalServerException } from 'src/exceptions/internalServerError.exception';
@ApiTags('Carnet Application - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ca', 'sa')
@Controller('oracle')
@Controller('1')
export class CarnetApplicationController {
constructor(private readonly carnetApplicationService: CarnetApplicationService) { }
@ -64,7 +71,7 @@ export class CarnetApplicationController {
}
@Put('EditGenerallistItems')
EditGenerallistItems(@Body() body: AddGenerallistItemsDTO) {
EditGenerallistItems(@Body() body: EditGenerallistItemsDTO) {
return this.carnetApplicationService.EditGenerallistItems(body);
}
@ -101,18 +108,54 @@ export class CarnetApplicationController {
return this.carnetApplicationService.VoidCarnet(body);
}
@Patch('CopyCarnet')
CopyCarnet(@Body() body: CopyCarnetDTO) {
return this.carnetApplicationService.CopyCarnet(body);
}
@Patch('DuplicateCarnet')
@Roles('ca')
DuplicateCarnet(@Body() body: CarnetProcessingCenterDTO) {
DuplicateCarnet(@Body() body: CarnetProcessingCenterDTO2) {
return this.carnetApplicationService.DuplicateCarnet(body);
}
@Patch('AddlSets')
AddlSets(@Body() body: CarnetProcessingCenterDTO2) {
return this.carnetApplicationService.AddlSets(body);
}
@Patch('ExtendCarnet')
ExtendCarnet(@Body() body: CarnetProcessingCenterDTO2) {
return this.carnetApplicationService.ExtendCarnet(body);
}
@Get('GetExtendedSection/:P_SPID/:P_HEADERID')
GetExtendedSection(@Param() body: GetExtendedSectionDTO) {
return this.carnetApplicationService.GetExtendedSection(body);
}
@Post('SaveExtensionApplication')
@HttpCode(200)
SaveExtensionApplication(@Body() body: SaveExtensionApplicationDTO) {
return this.carnetApplicationService.SaveExtensionApplication(body);
}
@Patch('CloseCarnet')
@Roles('sa')
CloseCarnet(@Body() body: CarnetProcessingCenterDTO) {
return this.carnetApplicationService.CloseCarnet(body);
}
@Patch('ResetCarnet')
@Roles('sa')
ResetCarnet(@Body() body: CarnetProcessingCenterDTO) {
return this.carnetApplicationService.ResetCarnet(body);
}
@Delete('DeleteCarnet')
DeleteCarnet(@Body() body: CarnetProcessingCenterDTO) {
return this.carnetApplicationService.DeleteCarnet(body);
}
// [ CARNETCONTROLCENTER_PKG ]
@Get('GetHolderstoEdit/:P_SPID/:P_USERID/:P_HEADERID')
@ -135,12 +178,127 @@ export class CarnetApplicationController {
return this.carnetApplicationService.GetCountryDetailstoEdit(body);
}
@Get('GetShipPaymentDetailstoEdit/:P_SPID/:P_USERID/:P_HEADERID')
GetShipPaymentDetailstoEdit(@Param() body: GetCarnetControlCenterDTO) {
return this.carnetApplicationService.GetShipPaymentDetailstoEdit(body);
}
// [PRINT_PKG]
@Post('PrintCarnet')
@HttpCode(200)
async PrintCarnet(@Body() body: PrintCarnetDTO, @Res({ passthrough: true }) res: Response) {
try {
const { finalArray, carnetData }: any = await this.carnetApplicationService.PrintCarnet(body);
// const filterCarnetData = finalArray.filter(item => item !== '2GeneralList.pdf')
let filesArray = [`${replaceSlashWithDash(carnetData.carnetNo)}p1.pdf`, `${replaceSlashWithDash(carnetData.carnetNo)}p2.pdf`];
// await generateFinalPDF([...filesArray, '2GeneralList.pdf', ...carnetData], 'carnet.pdf');
await generateFinalPDF([...filesArray, ...finalArray, '13LastSheetP3.pdf', '13LastSheetP4.pdf'], `${replaceSlashWithDash(carnetData.carnetNo)}carnet.pdf`);
const fileName = `${replaceSlashWithDash(carnetData.carnetNo)}carnet.pdf`;
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="${fileName}"`,
});
const filePath = join(process.cwd(), 'dist/public/carnet-pdf', fileName); //server
// const filePath = join(process.cwd(), 'public/carnet-pdf', fileName); //local
console.log(filePath);
// console.log(filePath);
const stream = createReadStream(filePath);
// Clean up files after response finishes streaming
res.on('finish', async () => {
await deleteFilesAsync([...filesArray, ...finalArray.filter(x => x !== `${replaceSlashWithDash(carnetData.carnetNo)}p2.pdf`), fileName]);
});
return new StreamableFile(stream);
} catch (error) {
if (error instanceof BadRequestException || error instanceof BR) {
throw new BadRequestException("Download failed please check the details")
}
else {
throw new InternalServerException("Error while downloading");
}
}
}
@Post('PrintGL')
@HttpCode(200)
async PrintGL(@Body() body: PrintGLDTO, @Res({ passthrough: true }) res: Response) {
try {
const { finalArray, carnetData }: any = await this.carnetApplicationService.PrintGL(body);
let filesArray = [`${body.P_HEADERID}p2.pdf`];
// await generateFinalPDF([...filesArray, '2GeneralList.pdf', ...carnetData], 'carnet.pdf');
await generateFinalPDF([...filesArray, ...finalArray], `${body.P_HEADERID}-GL.pdf`);
const fileName = `${body.P_HEADERID}-GL.pdf`;
res.set({
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="${fileName}"`,
});
const filePath = join(process.cwd(), 'dist/public/carnet-pdf', fileName); //server
// const filePath = join(process.cwd(), 'public/carnet-pdf', fileName); //local
// console.log(filePath);
// console.log(filePath);
const stream = createReadStream(filePath);
// Clean up files after response finishes streaming
res.on('finish', async () => {
await deleteFilesAsync([...filesArray, ...finalArray, fileName]);
});
return new StreamableFile(stream);
} catch (error) {
if (error instanceof BadRequestException || error instanceof BR) {
throw new BadRequestException("Download failed please check the details")
}
else {
throw new InternalServerException("Error while downloading");
}
}
}
//[payment]
@Post('InitiatePayment')
async InitiatePayment(@Body() body: InitiatePaymentDTO) {
return this.carnetApplicationService.InitiatePayment(body);
}
@Post('CompletePayment')
@HttpCode(200)
async CapturePayment(@Body() body: CapturePaymentDTO) {
return this.carnetApplicationService.CapturePayment(body);
}
// @Get('OrderDetails/:P_ORDERID')
async OrderDetails(@Param() body: GetOrderDetailsDTO) {
return this.carnetApplicationService.OrderDetails(body);
}
@Get('GetPaymentHistory/:P_APPLICATIONNAME/:P_USERID')
async GetPaymentHistory(@Param() body: GetPaymentHistoryDTO) {
return this.carnetApplicationService.GetPaymentHistory(body);
}
@Post('SaveHistory')
@HttpCode(200)
async SaveHistory(@Body() body: SaveHistoryDTO) {
return this.carnetApplicationService.SaveHistory(body);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -20,7 +20,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('HomePage - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ca', 'sa', 'ua')
@Controller('oracle')
@Controller('1')
export class HomePageController {
constructor(private readonly homePageService: HomePageService) { }

View File

@ -17,7 +17,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('Manage Clients - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa')
@Controller('oracle')
@Controller('1')
export class ManageClientsController {
constructor(private readonly manageClientsService: ManageClientsService) { }

View File

@ -39,6 +39,7 @@ export class ManageClientsService {
P_ISSUINGREGION: null,
P_REVENUELOCATION: null,
P_USERID: null,
P_INDUSTRYTYPE: null
};
const reqBody = JSON.parse(JSON.stringify(body));
@ -58,6 +59,7 @@ export class ManageClientsService {
:P_SPID, :P_CLIENTNAME, :P_LOOKUPCODE, :P_ADDRESS1,
:P_ADDRESS2, :P_CITY, :P_STATE, :P_ZIP,
:P_COUNTRY, :P_ISSUINGREGION, :P_REVENUELOCATION, :P_USERID,
:P_INDUSTRYTYPE,
:P_CLIENTCURSOR
);
END;`,
@ -74,6 +76,7 @@ export class ManageClientsService {
P_ISSUINGREGION: { val: finalBody.P_ISSUINGREGION, type: oracledb.DB_TYPE_NVARCHAR },
P_REVENUELOCATION: { val: finalBody.P_REVENUELOCATION, type: oracledb.DB_TYPE_NVARCHAR },
P_USERID: { val: finalBody.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
P_INDUSTRYTYPE: { val: finalBody.P_INDUSTRYTYPE, type: oracledb.DB_TYPE_NVARCHAR },
P_CLIENTCURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{
@ -118,6 +121,7 @@ export class ManageClientsService {
P_COUNTRY: null,
P_REVENUELOCATION: null,
P_USERID: null,
P_INDUSTRYTYPE: null
};
const reqBody = JSON.parse(JSON.stringify(body));
@ -135,7 +139,8 @@ export class ManageClientsService {
MANAGEPREPARER_PKG.UpdateClient(
:P_SPID, :P_CLIENTID, :P_PREPARERNAME, :P_ADDRESS1,
:P_ADDRESS2, :P_CITY, :P_STATE, :P_ZIP,
:P_COUNTRY, :P_REVENUELOCATION, :P_USERID, :P_CURSOR
:P_COUNTRY, :P_REVENUELOCATION, :P_USERID, :P_INDUSTRYTYPE,
:P_CURSOR
);
END;`,
{
@ -150,6 +155,7 @@ export class ManageClientsService {
P_COUNTRY: { val: finalBody.P_COUNTRY, type: oracledb.DB_TYPE_NVARCHAR },
P_REVENUELOCATION: { val: finalBody.P_REVENUELOCATION, type: oracledb.DB_TYPE_NVARCHAR },
P_USERID: { val: finalBody.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
P_INDUSTRYTYPE: { val: finalBody.P_INDUSTRYTYPE, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{
@ -673,7 +679,9 @@ export class ManageClientsService {
throw new InternalServerException("Incomplete data received from the database.");
}
return await fetchCursor(outBinds.P_CURSOR, ManageClientsService.name);
const fres: any = await fetchCursor(outBinds.P_CURSOR, ManageClientsService.name);
return fres.length > 0 ? fres[0] : [];
} catch (error) {
handleError(error, ManageClientsService.name)

View File

@ -14,7 +14,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('Manage Fee - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa','ua')
@Controller('oracle')
@Controller('1')
export class ManageFeeController {
constructor(private readonly manageFeeService: ManageFeeService) { }

View File

@ -195,6 +195,7 @@ export class ManageFeeService {
MANAGEFEE_SETUP_PKG.CREATEBONDRATE(
:P_SPID, :P_HOLDERTYPE, :P_USCIBMEMBERFLAG, :P_SPCLCOMMODITY,
:P_SPCLCOUNTRY, :P_EFFDATE, :P_RATE, :P_USERID,
:P_PCT_VALUE,
:P_CURSOR
);
END;`,
@ -207,6 +208,7 @@ export class ManageFeeService {
P_EFFDATE: { val: body.P_EFFDATE, type: oracledb.DB_TYPE_VARCHAR },
P_RATE: { val: body.P_RATE, type: oracledb.DB_TYPE_NUMBER },
P_USERID: { val: body.P_USERID, type: oracledb.DB_TYPE_VARCHAR },
P_PCT_VALUE: { val: body.P_PCT_VALUE, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{
@ -238,7 +240,7 @@ export class ManageFeeService {
const result = await connection.execute(
`BEGIN
MANAGEFEE_SETUP_PKG.UPDATEBONDRATE(
:P_BONDRATESETUPID, :P_RATE, :P_EFFDATE, :P_USERID,
:P_BONDRATESETUPID, :P_RATE, :P_EFFDATE, :P_USERID, :P_PCT_VALUE,
:P_CURSOR
);
END;`,
@ -247,6 +249,7 @@ export class ManageFeeService {
P_RATE: { val: body.P_RATE, type: oracledb.DB_TYPE_NUMBER },
P_EFFDATE: { val: body.P_EFFDATE, type: oracledb.DB_TYPE_NVARCHAR },
P_USERID: { val: body.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
P_PCT_VALUE: { val: body.P_PCT_VALUE, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{

View File

@ -1,5 +1,4 @@
import {
BadRequestException,
Body,
Controller,
Get,
@ -22,41 +21,54 @@ import {
import { Roles } from 'src/decorators/roles.decorator';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { RolesGuard } from 'src/guards/roles.guard';
import { BadRequestException } from 'src/exceptions/badRequest.exception';
@ApiTags('Manage Holders - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ca', 'sa')
@Controller('oracle')
@Controller('1')
export class ManageHoldersController {
constructor(private readonly manageHoldersService: ManageHoldersService) { }
@Get('SearchHolder/:P_SPID')
@Get('SearchHolder/:P_SPID/:P_USERID')
@ApiQuery({ name: "P_HOLDERNAME", type: String, required: false, description: "Optional" })
@ApiQuery({ name: "P_HOLDERID", type: Number, required: false, description: "Optional" })
SearchHolder(
@Param('P_SPID') P_SPID: number,
@Param('P_USERID') P_USERID: string,
@Query('P_HOLDERID') P_HOLDERID?: number,
@Query('P_HOLDERNAME') P_HOLDERNAME?: string | null | undefined,
) {
let rawHolderName: string | null | undefined = P_HOLDERNAME;
if (typeof rawHolderName === 'string') {
rawHolderName = rawHolderName.trim();
rawHolderName = rawHolderName.replace(/^['"]|['"]$/g, '');
if (rawHolderName === '' || rawHolderName.toLowerCase() === 'null') {
rawHolderName = null;
} else {
const allowedPattern = /^[A-Za-z0-9 _@&.-]+$/;
// uncomment for strict validation
// if (!allowedPattern.test(rawHolderName)) {
// rawHolderName = null;
// }
}
} else {
rawHolderName = null;
if (!P_USERID) {
throw new BadRequestException('User ID is required');
}
const body = { P_SPID, P_HOLDERNAME: rawHolderName }
// Sanitize holder name
let rawHolderName: string | null = null;
if (typeof P_HOLDERNAME === 'string') {
const trimmed = P_HOLDERNAME.trim().replace(/^['"]|['"]$/g, '');
rawHolderName = trimmed === '' || trimmed.toLowerCase() === 'null' ? null : trimmed;
}
// Validate and coerce P_HOLDERID
let holderId: number | null = null;
if (P_HOLDERID !== undefined && P_HOLDERID !== null) {
const parsed = Number(P_HOLDERID);
if (isNaN(parsed)) {
throw new BadRequestException('Invalid holder ID');
}
holderId = parsed;
}
const body = {
P_SPID,
P_USERID,
P_HOLDERID: holderId,
P_HOLDERNAME: rawHolderName,
};
return this.manageHoldersService.SearchHolder(body)
}

View File

@ -631,7 +631,7 @@ export class ManageHoldersService {
}
};
SearchHolder = async (body: { P_SPID: number, P_HOLDERNAME: string | null }) => {
SearchHolder = async (body: { P_SPID: number, P_USERID: string, P_HOLDERID: number | null, P_HOLDERNAME: string | null }) => {
let connection;
try {
@ -640,12 +640,14 @@ export class ManageHoldersService {
const result: Result<any> = await connection.execute(
`BEGIN
MANAGEHOLDER_PKG.SearchHolder(
:P_SPID, :P_HOLDERNAME, :P_CURSOR
:P_SPID, :P_HOLDERID, :P_HOLDERNAME, :P_USERID, :P_CURSOR
);
END;`,
{
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
P_HOLDERID: { val: body.P_HOLDERID, type: oracledb.DB_TYPE_NUMBER },
P_HOLDERNAME: { val: body.P_HOLDERNAME, type: oracledb.DB_TYPE_NVARCHAR },
P_USERID: { val: body.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{

View File

@ -10,11 +10,13 @@ import { UserMaintenanceModule } from './user-maintenance/user-maintenance.modul
import { CarnetApplicationModule } from './carnet-application/carnet-application.module';
import { OracleService } from './oracle.service';
import { AuthModule } from 'src/auth/auth.module';
import { PaypalModule } from 'src/paypal/paypal.module';
@Global()
@Module({
imports: [
DbModule,
PaypalModule,
CarnetApplicationModule,
UserMaintenanceModule,
HomePageModule,
@ -28,4 +30,4 @@ import { AuthModule } from 'src/auth/auth.module';
controllers: [],
exports: [OracleService, UserMaintenanceModule],
})
export class OracleModule {}
export class OracleModule { }

View File

@ -1,6 +1,6 @@
import { Injectable, Logger } from "@nestjs/common";
import { OracleDBService } from "src/db/db.service";
import { CLIENTLOCADDRESSTABLE_ROW_DTO, CONTACTSTABLE_ROW_DTO, COUNTRYTABLE_DTO, COUNTRYTABLE_ROW_DTO, GLTABLE_DTO, GLTABLE_ROW_DTO } from "src/dto/property.dto";
import { CLIENTLOCADDRESSTABLE_ROW_DTO, CONTACTSTABLE_ROW_DTO, COUNTRYTABLE_DTO, COUNTRYTABLE_ROW_DTO, GLTABLE_DTO, GLTABLE_ITEMNO_OPTIONAL_DTO, GLTABLE_ROW_ADD_DTO, GLTABLE_ROW_DTO } from "src/dto/property.dto";
import { InternalServerException } from "src/exceptions/internalServerError.exception";
import { closeOracleDbConnection, handleError } from "src/utils/helper";
@ -10,6 +10,62 @@ export class OracleService {
constructor(private readonly oracleDBService: OracleDBService) { }
async get_GL_TABLE_OPTIONAL_ITEMNO_INSTANCE(finalBody: any) {
// P_GLTABLE: { val: GLTABLE_INSTANCE, type: 'CARNETSYS.GLTABLE' }
// P_GLTABLE: { val: GLTABLE_INSTANCE, type: oracledb.DB_TYPE_OBJECT }
let connection;
try {
connection = await this.oracleDBService.getConnection();
const GLTABLE = await connection.getDbObjectClass('CARNETSYS.GLTABLE');
if (typeof GLTABLE !== 'function') {
throw new InternalServerException('GLTABLE is not a constructor');
}
async function createGLArrayInstance(
ITEMNO, ITEMDESCRIPTION, ITEMVALUE, NOOFPIECES,
ITEMWEIGHT, ITEMWEIGHTUOM, GOODSORIGINCOUNTRY,
) {
const result = await connection.execute(
`SELECT CARNETSYS.GLARRAY(
:ITEMNO, :ITEMDESCRIPTION, :ITEMVALUE, :NOOFPIECES,
:ITEMWEIGHT, :ITEMWEIGHTUOM, :GOODSORIGINCOUNTRY
) FROM dual`,
{
ITEMNO, ITEMDESCRIPTION, ITEMVALUE, NOOFPIECES,
ITEMWEIGHT, ITEMWEIGHTUOM, GOODSORIGINCOUNTRY,
}
);
return result.rows[0][0];
}
const GLTABLE_ARRAY: GLTABLE_ITEMNO_OPTIONAL_DTO = {
P_GLTABLE: await Promise.all(
(finalBody.P_GLTABLE ?? []).map(async (x: GLTABLE_ROW_ADD_DTO) => {
return await createGLArrayInstance(
x.ITEMNO, x.ITEMDESCRIPTION, x.ITEMVALUE, x.NOOFPIECES,
x.ITEMWEIGHT, x.ITEMWEIGHTUOM, x.GOODSORIGINCOUNTRY,
);
})
)
};
const GLTABLE_INSTANCE = new GLTABLE(GLTABLE_ARRAY.P_GLTABLE ?? []);
return GLTABLE_INSTANCE;
} catch (error) {
console.log("error while creating GL instance : ", error);
throw new Error("Error occured completing this process")
} finally {
await closeOracleDbConnection(connection, OracleService.name)
}
}
async get_GL_TABLE_INSTANCE(finalBody: any) {
// P_GLTABLE: { val: GLTABLE_INSTANCE, type: 'CARNETSYS.GLTABLE' }
@ -40,8 +96,6 @@ export class OracleService {
ITEMWEIGHT, ITEMWEIGHTUOM, GOODSORIGINCOUNTRY,
}
);
console.log(result.rows);
return result.rows[0][0];
}
@ -94,7 +148,6 @@ export class OracleService {
P_VISISTTRANSITIND, COUNTRYCODE, NOOFTIMESENTLEAVE,
},
);
console.log(result.rows);
return result.rows[0][0];
}

View File

@ -1,24 +1,24 @@
import { Body, Controller, Get, Patch, Post, Put, Query, UseGuards } from '@nestjs/common';
import { Body, Controller, Get, Param, Patch, Post, Put, Query, UseGuards } from '@nestjs/common';
import { ApiQuery, ApiTags } from '@nestjs/swagger';
import { ParamTableService } from './param-table.service';
import {
ActivateOrInactivateParamRecordDTO, CreateParamRecordDTO, CreateTableRecordDTO,
getParamValuesDTO, UpdateParamRecordDTO
getParamValuesDTO, SPID_DTO, UpdateParamRecordDTO
} from 'src/dto/property.dto';
import { Roles } from 'src/decorators/roles.decorator';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('Param Table - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa', 'ua')
@Controller('oracle')
@Controller('1')
export class ParamTableController {
constructor(private readonly paramTableService: ParamTableService) { }
@Get('/GetParamValues')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ca', 'sa', 'ua')
@ApiQuery({
name: 'P_SPID',
@ -36,6 +36,29 @@ export class ParamTableController {
return this.paramTableService.GETPARAMVALUES(body);
}
@Get('/GetAllParamValues')
@ApiQuery({
name: 'P_SPID',
required: false,
type: Number,
description: 'The ID of the parameter',
})
@ApiQuery({
name: 'P_PARAMTYPE',
required: false,
type: String,
description: 'The type of the parameter',
})
getAllParamValues(@Query() body: getParamValuesDTO) {
return this.paramTableService.GETALLPARAMVALUES(body);
}
@Get('GetCountriesAndMessages/:P_SPID')
@Roles('ca', 'sa', 'ua')
GET_COUNTRIES_AND_MESSAGES(@Param() body: SPID_DTO) {
return this.paramTableService.GET_COUNTRIES_AND_MESSAGES(body);
}
@Post('/CreateTableRecord')
createTableRecord(@Body() body: CreateTableRecordDTO) {
return this.paramTableService.CREATETABLERECORD(body);

View File

@ -8,7 +8,7 @@ import { closeOracleDbConnection, fetchCursor, handleError } from 'src/utils/hel
import {
ActivateOrInactivateParamRecordDTO, CreateParamRecordDTO, CreateTableRecordDTO,
getParamValuesDTO, UpdateParamRecordDTO
getParamValuesDTO, SPID_DTO, UpdateParamRecordDTO
} from 'src/dto/property.dto';
@Injectable()
@ -63,6 +63,85 @@ export class ParamTableService {
}
}
async GETALLPARAMVALUES(body: getParamValuesDTO) {
const finalBody = {
P_SPID: body.P_SPID === 0 ? body.P_SPID : body.P_SPID ? body.P_SPID : null,
P_PARAMTYPE: body.P_PARAMTYPE ? body.P_PARAMTYPE : null,
};
let connection;
try {
connection = await this.oracleDBService.getConnection();
const result = await connection.execute(
`BEGIN
MANAGEPARAMTABLE_PKG.GetAllParamValues(:P_SPID,:P_PARAMTYPE,:P_CURSOR);
END;`,
{
P_SPID: { val: finalBody.P_SPID, type: oracledb.DB_TYPE_NUMBER },
P_PARAMTYPE: { val: finalBody.P_PARAMTYPE, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{ outFormat: oracledb.OUT_FORMAT_OBJECT }
);
await connection.commit();
const outBinds = result.outBinds;
if (!outBinds?.P_CURSOR) {
this.logger.error('One or more expected cursors are missing from stored procedure output.');
throw new InternalServerException("Incomplete data received from the database.");
}
// const fres: any = await fetchCursor(outBinds.P_CURSOR, ParamTableService.name);
// if (fres.length > 0 && fres[0].ERRORMESG) {
// this.logger.warn(fres[0].ERRORMESG);
// throw new BadRequestException(fres[0].ERRORMESG)
// }
return await fetchCursor(outBinds.P_CURSOR, ParamTableService.name);
} catch (error) {
handleError(error, ParamTableService.name)
} finally {
await closeOracleDbConnection(connection, ParamTableService.name)
}
}
async GET_COUNTRIES_AND_MESSAGES(body: SPID_DTO) {
let connection;
try {
connection = await this.oracleDBService.getConnection();
const result = await connection.execute(
`BEGIN
MANAGEPARAMTABLE_PKG.GetCountriesAndMessages(:P_SPID, :P_CURSOR);
END;`,
{
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{ outFormat: oracledb.OUT_FORMAT_OBJECT }
);
await connection.commit();
const outBinds = result.outBinds;
if (!outBinds?.P_CURSOR) {
this.logger.error('One or more expected cursors are missing from stored procedure output.');
throw new InternalServerException("Incomplete data received from the database.");
}
return await fetchCursor(outBinds.P_CURSOR, ParamTableService.name);
} catch (error) {
handleError(error, ParamTableService.name)
} finally {
await closeOracleDbConnection(connection, ParamTableService.name)
}
}
async CREATETABLERECORD(body: CreateTableRecordDTO) {
let connection;
@ -222,7 +301,7 @@ export class ParamTableService {
const result = await connection.execute(
`BEGIN
MANAGEPARAMTABLE_PKG.REACTIVATEPARAMRECORD(:P_PARAMID,:P_USERID);
MANAGEPARAMTABLE_PKG.INACTIVATEPARAMRECORD(:P_PARAMID,:P_USERID);
END;`,
{
P_PARAMID: { val: body.P_PARAMID, type: oracledb.DB_TYPE_NUMBER },

View File

@ -10,7 +10,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('Carnet Sequence - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa', 'ua')
@Controller('oracle')
@Controller('1')
export class CarnetSequenceController {
constructor(private readonly carnetSequenceService: CarnetSequenceService) { }

View File

@ -1,18 +1,18 @@
import { RegionService } from './region.service';
import { Get, Post, Body, Controller, Patch, UseGuards } from '@nestjs/common';
import { Get, Post, Body, Controller, Patch, UseGuards, Param } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { Roles } from 'src/decorators/roles.decorator';
import { InsertRegionsDto, UpdateRegionDto } from 'src/dto/property.dto';
import { InsertRegionsDto, SPID_DTO, UpdateRegionDto } from 'src/dto/property.dto';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('Regions - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa', 'ua')
@Controller('oracle')
@Controller('1')
export class RegionController {
constructor(private readonly regionService: RegionService) { }
@ -26,9 +26,9 @@ export class RegionController {
return this.regionService.updateRegions(body);
}
@Get('/GetRegions')
getRegions() {
return this.regionService.getRegions();
@Get('/GetRegions/:P_SPID')
getRegions(@Param() param: SPID_DTO) {
return this.regionService.getRegions(param);
}
}

View File

@ -5,7 +5,7 @@ import { BadRequestException } from 'src/exceptions/badRequest.exception';
import { InternalServerException } from 'src/exceptions/internalServerError.exception';
import { closeOracleDbConnection, fetchCursor, handleError } from 'src/utils/helper';
import { InsertRegionsDto, UpdateRegionDto } from 'src/dto/property.dto';
import { InsertRegionsDto, SPID_DTO, UpdateRegionDto } from 'src/dto/property.dto';
@Injectable()
export class RegionService {
@ -21,11 +21,12 @@ export class RegionService {
const result = await connection.execute(
`BEGIN
USCIB_Managed_Pkg.InsertNewRegion(:P_REGION,:P_NAME,:P_CURSOR);
USCIB_Managed_Pkg.InsertNewRegion(:P_REGION, :P_NAME, :P_SPID, :P_CURSOR);
END;`,
{
P_REGION: { val: body.P_REGION, type: oracledb.DB_TYPE_VARCHAR },
P_NAME: { val: body.P_NAME, type: oracledb.DB_TYPE_VARCHAR },
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT },
},
{ outFormat: oracledb.OUT_FORMAT_OBJECT }
@ -95,16 +96,17 @@ export class RegionService {
}
}
async getRegions() {
async getRegions(body: SPID_DTO) {
let connection;
try {
connection = await this.oracleDBService.getConnection();
const result = await connection.execute(
`BEGIN
USCIB_Managed_Pkg.GetRegions(:P_CURSOR);
USCIB_Managed_Pkg.GetRegions(:P_SPID, :P_CURSOR);
END;`,
{
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
{ outFormat: oracledb.OUT_FORMAT_OBJECT }

View File

@ -14,7 +14,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('SPContacts - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa', 'ua')
@Controller('oracle')
@Controller('1')
export class SpContactsController {
constructor(private readonly spContactsService: SpContactsService) { }

View File

@ -13,7 +13,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('SP - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('sa', 'ua')
@Controller('oracle')
@Controller('1')
export class SpController {
constructor(private readonly spService: SpService) { }

View File

@ -241,7 +241,9 @@ export class SpService {
throw new InternalServerException("Incomplete data received from the database.");
}
return await fetchCursor(outBinds.P_CURSOR, SpService.name);
const fres: any = await fetchCursor(outBinds.P_CURSOR, SpService.name);
return fres.length > 0 ? fres[0] : [];
} catch (error) {
handleError(error, SpService.name)

View File

@ -14,7 +14,7 @@ import { RolesGuard } from 'src/guards/roles.guard';
@ApiTags('User Maintenance - Oracle')
@UseGuards(JwtAuthGuard, RolesGuard)
@Roles('ca', 'sa', 'ua')
@Controller('oracle')
@Controller('1')
export class UserMaintenanceController {
constructor(private readonly userMaintenanceService: UserMaintenanceService) { }

View File

@ -1,12 +1,12 @@
import { Module } from '@nestjs/common';
import { forwardRef, Module } from '@nestjs/common';
import { UserMaintenanceController } from './user-maintenance.controller';
import { UserMaintenanceService } from './user-maintenance.service';
import { AuthModule } from 'src/auth/auth.module';
@Module({
imports: [AuthModule],
imports: [forwardRef(() => AuthModule)],
controllers: [UserMaintenanceController],
providers: [UserMaintenanceService],
exports: [UserMaintenanceService]
exports: [UserMaintenanceService, AuthModule]
})
export class UserMaintenanceModule { }

View File

@ -1,4 +1,4 @@
import { Injectable, Logger } from '@nestjs/common';
import { forwardRef, Inject, Injectable, Logger } from '@nestjs/common';
import { OracleDBService } from 'src/db/db.service';
import { InternalServerException } from 'src/exceptions/internalServerError.exception';
import * as oracledb from 'oracledb';
@ -10,6 +10,8 @@ import {
CreateClientLoginsDTO, CreateSPLoginsDTO, CreateUSCIBLoginsDTO, SPID_CLIENTID_DTO, SPID_EMAIL_DTO
} from 'src/dto/property.dto';
import { BadRequestException } from 'src/exceptions/badRequest.exception';
import { AuthService } from 'src/auth/auth.service';
import { MailTypeDTO } from 'src/auth/auth.dto';
interface RoleDetail { [key: string]: any; }
@ -29,7 +31,11 @@ export class UserMaintenanceService {
private readonly logger = new Logger(UserMaintenanceService.name);
constructor(private readonly oracleDBService: OracleDBService) { }
constructor(
private readonly oracleDBService: OracleDBService,
@Inject(forwardRef(() => AuthService))
private readonly authService: AuthService
) { }
async GetSPUserDetails(body: USERID_DTO): Promise<any> {
let connection;
@ -155,14 +161,13 @@ export class UserMaintenanceService {
const result = await connection.execute(
`BEGIN
Userlogin_pkg.CreateUSCIBLogins(
:P_USERID , :P_EMAILADDR , :P_LOOKUPCODE , :P_PASSWORD , :P_ENABLEPASSWORDPOLICY, :P_CURSOR
:P_USERID , :P_EMAILADDR , :P_LOOKUPCODE , :P_ENABLEPASSWORDPOLICY, :P_CURSOR
);
END;`,
{
P_USERID: { val: body.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
P_EMAILADDR: { val: body.P_EMAILADDR, type: oracledb.DB_TYPE_NVARCHAR },
P_LOOKUPCODE: { val: body.P_LOOKUPCODE, type: oracledb.DB_TYPE_NVARCHAR },
P_PASSWORD: { val: body.P_PASSWORD, type: oracledb.DB_TYPE_NVARCHAR },
P_ENABLEPASSWORDPOLICY: { val: body.P_ENABLEPASSWORDPOLICY, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
@ -239,7 +244,7 @@ export class UserMaintenanceService {
const result = await connection.execute(
`BEGIN
Userlogin_pkg.CreateSPLogins(
:P_SPID, :P_USERID, :P_DOMAIN, :P_EMAILADDR, :P_LOOKUPCODE, :P_PASSWORD, :P_ENABLEPASSWORDPOLICY, :P_CURSOR
:P_SPID, :P_USERID, :P_DOMAIN, :P_EMAILADDR, :P_LOOKUPCODE, :P_ENABLEPASSWORDPOLICY, :P_CURSOR
);
END;`,
{
@ -248,7 +253,6 @@ export class UserMaintenanceService {
P_DOMAIN: { val: body.P_DOMAIN, type: oracledb.DB_TYPE_NVARCHAR },
P_EMAILADDR: { val: body.P_EMAILADDR, type: oracledb.DB_TYPE_NVARCHAR },
P_LOOKUPCODE: { val: body.P_LOOKUPCODE, type: oracledb.DB_TYPE_NVARCHAR },
P_PASSWORD: { val: body.P_PASSWORD, type: oracledb.DB_TYPE_NVARCHAR },
P_ENABLEPASSWORDPOLICY: { val: body.P_ENABLEPASSWORDPOLICY, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
@ -360,14 +364,13 @@ export class UserMaintenanceService {
const result = await connection.execute(
`BEGIN
Userlogin_pkg.CreateClientLogins(
:P_SPID, :P_USERID, :P_CLIENTCONTACTID, :P_PASSWORD, :P_ENABLEPASSWORDPOLICY, :P_CURSOR
:P_SPID, :P_USERID, :P_CLIENTCONTACTID, :P_ENABLEPASSWORDPOLICY, :P_CURSOR
);
END;`,
{
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
P_USERID: { val: body.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
P_CLIENTCONTACTID: { val: body.P_CLIENTCONTACTID, type: oracledb.DB_TYPE_NUMBER },
P_PASSWORD: { val: body.P_PASSWORD, type: oracledb.DB_TYPE_NVARCHAR },
P_ENABLEPASSWORDPOLICY: { val: body.P_ENABLEPASSWORDPOLICY, type: oracledb.DB_TYPE_NVARCHAR },
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
},
@ -389,7 +392,13 @@ export class UserMaintenanceService {
throw new BadRequestException(fres[0].ERRORMESG)
}
return { statusCode: 201, message: "Created successfully", ...fres[0] };
const mailRes = await this.authService.sendMail({ P_TO: body.P_USERID, P_MAIL_TYPE: MailTypeDTO.REGISTER_CLIENT })
if (mailRes.statusCode !== 200) {
throw new InternalServerException();
}
return { statusCode: 201, message: "Client registration initiated successfully", ...fres[0] };
} catch (error) {
handleError(error, UserMaintenanceService.name)

View File

@ -0,0 +1,4 @@
import { Controller } from '@nestjs/common';
@Controller('paypal')
export class PaypalController {}

View File

@ -0,0 +1,10 @@
import { Global, Module } from '@nestjs/common';
import { PaypalController } from './paypal.controller';
import { PaypalService } from './paypal.service';
@Global()
@Module({
providers: [PaypalService],
exports: [PaypalService]
})
export class PaypalModule { }

View File

@ -0,0 +1,69 @@
// paypal.service.ts
import { Injectable, Logger } from '@nestjs/common';
import axios from 'axios';
import { InternalServerException } from 'src/exceptions/internalServerError.exception';
@Injectable()
export class PaypalService {
private accessToken: string | null = null;
private tokenExpiresAt: number = 0; // Unix timestamp in milliseconds
private readonly clientId = process.env.PAYPAL_CLIENT_ID;
private readonly clientSecret = process.env.PAYPAL_CLIENT_SECRET;
private readonly baseUrl = process.env.PAYPAL_BASE_URL; // or live URL
private readonly logger = new Logger(PaypalService.name);
async generateAccessToken(): Promise<any> {
// return process.env.PAYPAL_AT
const now = Date.now();
// Check if token is still valid
if (this.accessToken && now < this.tokenExpiresAt - 60_000) {
return this.accessToken;
}
// Fetch new token
const auth = Buffer.from(`${this.clientId}:${this.clientSecret}`).toString('base64');
try {
const tokenUrl = process.env.PAYPAL_BASE_URL + '/v1/oauth2/token';
const params = new URLSearchParams();
params.append('grant_type', 'client_credentials');
const response = await axios.post(
tokenUrl,
params.toString(), // or use `params` directly
{
auth: {
username: process.env.PAYPAL_CLIENT_ID!,
password: process.env.PAYPAL_SECRET!,
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
}
);
const { access_token, expires_in } = response.data;
this.accessToken = access_token;
this.tokenExpiresAt = now + expires_in * 1000; // convert seconds to ms
// this.logger.warn(`Fetched new PayPal access token, expires in ${access_token} seconds`);
// console.log(access_token);
if (this.accessToken) {
return this.accessToken;
}
throw new InternalServerException("Error while getting paypal access token")
} catch (error) {
this.logger.error('Failed to fetch PayPal access token', error);
throw new InternalServerException('PayPal token fetch failed');
}
}
}

File diff suppressed because it is too large Load Diff