Compare commits
32 Commits
9efb9340ad
...
ecbf959ec7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecbf959ec7 | ||
|
|
26bfaeaa0b | ||
|
|
49e4f45073 | ||
|
|
c5b5a8e541 | ||
|
|
608eafd616 | ||
|
|
9f2d7f058f | ||
|
|
5cebcef300 | ||
|
|
91208d950d | ||
|
|
6a68ca024a | ||
|
|
1f49012644 | ||
|
|
d3c943d574 | ||
|
|
f4dd591198 | ||
|
|
d90c79fd67 | ||
|
|
0d4ac3e636 | ||
|
|
b553ff0623 | ||
|
|
cfb09b1f16 | ||
|
|
0cd9b8ca85 | ||
|
|
2259d306b1 | ||
|
|
d1d0c09042 | ||
|
|
c4f9f29208 | ||
|
|
49fe236b30 | ||
|
|
2eb3fe504b | ||
|
|
1f318d0039 | ||
|
|
b41e00959c | ||
|
|
1671eb9bdc | ||
|
|
600a1f7d75 | ||
|
|
7770642b80 | ||
|
|
8b964d2c84 | ||
|
|
fcb8b6e428 | ||
|
|
da0d495894 | ||
|
|
63b08e9883 | ||
|
|
d932953950 |
3
.gitignore
vendored
3
.gitignore
vendored
@ -3,6 +3,9 @@
|
||||
/node_modules
|
||||
/build
|
||||
|
||||
# pdf
|
||||
/public/carnet-pdf/*.pdf
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
|
||||
278
api.http
278
api.http
@ -1,266 +1,72 @@
|
||||
// InsertRegions
|
||||
GET http://192.168.1.96:3006
|
||||
|
||||
POST http://localhost:3000/oracle/InsertRegions
|
||||
###
|
||||
|
||||
GET http://localhost:3000/oracle/SearchHolder/1
|
||||
|
||||
###
|
||||
|
||||
POST http://localhost:3006/sendmail/b@gmail.com
|
||||
|
||||
###
|
||||
|
||||
GET http://localhost:3006/GetUserDetails/d@gmail.com
|
||||
|
||||
###
|
||||
|
||||
GET http://localhost:3006/GetUserDetail/d@gmail.com
|
||||
|
||||
###
|
||||
|
||||
GET http://localhost:3006/GetSP
|
||||
|
||||
###
|
||||
|
||||
GET http://localhost:3006/checkroles
|
||||
|
||||
###
|
||||
|
||||
POST http://localhost:3006/login-client
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"p_region":"p_region",
|
||||
"p_name":"p_name"
|
||||
"P_EMAILADDR":"a@gmail.com",
|
||||
"P_PASSWORD":"A1!bcdef"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
//UpdateRegion
|
||||
POST http://localhost:3006/logout-client
|
||||
|
||||
PATCH http://localhost:3000/oracle/UpdateRegion
|
||||
###
|
||||
|
||||
POST http://localhost:3006/register
|
||||
Content-Type: application/json
|
||||
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImJAZ21haWwuY29tIiwiaWF0IjoxNzUwMTM3NTc4LCJleHAiOjE3NTAxNDExNzh9.ooNhATybtRY_HORWBH0vBLzPODxOWZMi3Q_cvS7kAho
|
||||
|
||||
{
|
||||
"p_regionID": ,
|
||||
"p_name":"p_name"
|
||||
"email":"b@gmail.com",
|
||||
"password":"B1!bcdef"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
// GetRegions
|
||||
|
||||
GET http://localhost:3000/oracle/GetRegions
|
||||
GET http://localhost:3006/getrole/ca
|
||||
|
||||
###
|
||||
|
||||
PUT http://localhost:3006/forgot-password
|
||||
|
||||
//InsertNewServiceProvider
|
||||
|
||||
POST http://localhost:3000/oracle/InsertNewServiceProvider
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"p_name": "Service Provider Name",
|
||||
"p_lookupcode": "SP001",
|
||||
"p_address1": "123 Main St",
|
||||
"p_address2": "Suite 100",
|
||||
"p_city": "Anytown",
|
||||
"p_state": "CA",
|
||||
"p_zip": "90210",
|
||||
"p_country": "USA",
|
||||
"p_issuingregion": "Region A",
|
||||
"p_replacementregion": "Region B",
|
||||
"p_bondsurety": "Surety Co.",
|
||||
"p_cargopolicyno": "CP123456",
|
||||
"p_cargosurety": "Cargo Surety Co.",
|
||||
"p_user_id": "user123"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
|
||||
//UpdateServiceProvider
|
||||
|
||||
PUT http://localhost:3000/oracle/UpdateServiceProvider
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"p_spid": 1,
|
||||
"p_name": "Service Provider Name",
|
||||
"p_lookupcode": "SP001",
|
||||
"p_address1": "123 Main St",
|
||||
"p_address2": "Suite 100",
|
||||
"p_city": "Anytown",
|
||||
"p_state": "CA",
|
||||
"p_zip": "90210",
|
||||
"p_country": "USA",
|
||||
"p_issuingregion": "Region A",
|
||||
"p_replacementregion": "Region B",
|
||||
"p_bondsurety": "Surety Co.",
|
||||
"p_cargopolicyno": "CP123456",
|
||||
"p_cargosurety": "Cargo Surety Co.",
|
||||
"p_user_id": "user123"
|
||||
}
|
||||
POST http://localhost:3006/logout-user
|
||||
|
||||
###
|
||||
|
||||
// GetAllServiceproviders
|
||||
|
||||
GET http://localhost:3000/oracle/GetAllServiceproviders
|
||||
GET http://localhost:3006/ref-tok
|
||||
|
||||
###
|
||||
|
||||
//GetSelectedServiceprovider
|
||||
|
||||
GET http://localhost:3000/oracle/GetSelectedServiceprovider/12
|
||||
|
||||
###
|
||||
|
||||
//InsertSPContacts
|
||||
|
||||
POST http://localhost:3000/oracle/InsertSPContacts
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"p_spid": 12345,
|
||||
"p_defcontactflag":"N",
|
||||
"p_firstname": "John",
|
||||
"p_lastname": "Doe",
|
||||
"p_title": "Mr.",
|
||||
"p_phoneno": "123-456-7890",
|
||||
"p_mobileno": "098-765-4321",
|
||||
"p_faxno": "123-456-7891",
|
||||
"p_emailaddress": "john.doe@example.com",
|
||||
"p_user_id": "jdoe"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
//SetSPDefaultcontact
|
||||
|
||||
POST http://localhost:3000/oracle/SetSPDefaultcontact/12
|
||||
|
||||
###
|
||||
|
||||
//UpdateSPContacts
|
||||
|
||||
PUT http://localhost:3000/oracle/UpdateSPContacts
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"p_spcontactid": 12345,
|
||||
"p_firstname": "Jane",
|
||||
"p_lastname": "Doe",
|
||||
"p_title": "Ms.",
|
||||
"p_phoneno": "123-456-7890",
|
||||
"p_mobileno": "098-765-4321",
|
||||
"p_faxno": "123-456-7891",
|
||||
"p_emailaddress": "jane.doe@example.com",
|
||||
"p_user_id": "jdoe"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
|
||||
//InactivateSPContact
|
||||
|
||||
POST http://localhost:3000/oracle/InactivateSPContact/12
|
||||
|
||||
###
|
||||
|
||||
//GetSPDefaultcontact
|
||||
|
||||
GET http://localhost:3000/oracle/GetSPDefaultcontact/12
|
||||
|
||||
###
|
||||
|
||||
//GetAllSPcontacts
|
||||
|
||||
//GET http://localhost:3000/oracle/GetAllSPcontacts
|
||||
|
||||
###
|
||||
|
||||
//CreateCarnetSequence
|
||||
|
||||
POST http://localhost:3000/oracle/CreateCarnetSequence
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"p_spid": 2,
|
||||
"p_regionid": 81,
|
||||
"p_startnumber": 2000,
|
||||
"p_endnumber": 3000,
|
||||
"p_carnettype": "original"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
//GetCarnetSequence
|
||||
|
||||
GET http://localhost:3000/oracle/GetCarnetSequence/12
|
||||
|
||||
###
|
||||
|
||||
//GetParamValues
|
||||
|
||||
GET http://localhost:3000/oracle/GetParamValues?id=500&type=original
|
||||
|
||||
###
|
||||
|
||||
|
||||
//CreateTableRecord
|
||||
|
||||
POST http://localhost:3000/oracle/CreateTableRecord
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"P_USERID": "6",
|
||||
"P_TABLEFULLDESC": "TypeA desc"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
//CreateParamRecord
|
||||
|
||||
POST http://localhost:3000/oracle/CreateParamRecord
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
# "P_SPID": 4,
|
||||
"P_PARAMTYPE": "TypeA",
|
||||
"P_PARAMDESC": "Description of the parameter",
|
||||
"P_PARAMVALUE": "Value of the parameter",
|
||||
# "P_ADDLPARAMVALUE1": "Additional Value 1",
|
||||
# "P_ADDLPARAMVALUE2": "Additional Value 2",
|
||||
# "P_ADDLPARAMVALUE3": null,
|
||||
# "P_ADDLPARAMVALUE4": "Additional Value 4",
|
||||
# "P_ADDLPARAMVALUE5": null,
|
||||
"P_SORTSEQ": 1,
|
||||
"P_USERID": "12"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
// UpdateParamRecord
|
||||
|
||||
PATCH http://localhost:3000/oracle/UpdateParamRecord
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"P_SPID": 2,
|
||||
"P_PARAMID": 1,
|
||||
"P_PARAMDESC": "abc",
|
||||
"P_ADDLPARAMVALUE1": "asd",
|
||||
"P_ADDLPARAMVALUE2": "ad",
|
||||
"P_ADDLPARAMVALUE3": null,
|
||||
"P_ADDLPARAMVALUE4": "asd",
|
||||
"P_ADDLPARAMVALUE5": null,
|
||||
"P_SORTSEQ": 1,
|
||||
"P_USERID": "12"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
// InActivateParamRecord
|
||||
|
||||
PATCH http://localhost:3000/oracle/InActivateParamRecord?pid=1&uid=2
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"P_PARAMID":2,
|
||||
"P_USERID":"12"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
// ReActivateParamRecord
|
||||
|
||||
PATCH http://localhost:3000/oracle/ReActivateParamRecord?pid=1&uid=2
|
||||
Content-Type: application/json
|
||||
|
||||
{
|
||||
"P_PARAMID":2,
|
||||
"P_USERID":"12"
|
||||
}
|
||||
|
||||
###
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
GET http://localhost:3006/ref
|
||||
|
||||
2694
package-lock.json
generated
2694
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
24
package.json
24
package.json
@ -23,18 +23,33 @@
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/config": "^4.0.2",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"@nestjs/jwt": "^11.0.0",
|
||||
"@nestjs/passport": "^11.0.5",
|
||||
"@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",
|
||||
"mssql": "^10.0.4",
|
||||
"cookie-parser": "^1.4.7",
|
||||
"handlebars": "^4.7.8",
|
||||
"joi": "^17.13.3",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"jwk-to-pem": "^2.0.7",
|
||||
"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-merger-js": "^5.1.2",
|
||||
"pdfkit": "^0.17.1",
|
||||
"pg": "^8.13.3",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"typeorm": "^0.3.20"
|
||||
"typeorm": "^0.3.20",
|
||||
"uuid": "^11.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
@ -44,13 +59,16 @@
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
"@swc/cli": "^0.6.0",
|
||||
"@swc/core": "^1.10.7",
|
||||
"@types/cookie-parser": "^1.4.9",
|
||||
"@types/express": "^5.0.0",
|
||||
"@types/jest": "^29.5.14",
|
||||
"@types/jwk-to-pem": "^2.0.3",
|
||||
"@types/mssql": "^9.1.7",
|
||||
"@types/node": "^22.10.7",
|
||||
"@types/oracledb": "^6.5.4",
|
||||
"@types/supertest": "^6.0.2",
|
||||
"eslint": "^9.18.0",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"eslint": "^9.31.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^15.14.0",
|
||||
|
||||
14
public/mail-templates/a.hbs
Normal file
14
public/mail-templates/a.hbs
Normal file
@ -0,0 +1,14 @@
|
||||
<div style="font-family: Arial, sans-serif; padding: 20px; background-color: #f9f9f9;">
|
||||
<div style="max-width: 600px; margin: auto; background-color: #fff; padding: 30px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
|
||||
<h2 style="color: #4A90E2;">🔐 Registration Initiated</h2>
|
||||
<p style="font-size: 16px;">A Registration has been successfully initiated for the email: <strong>{{to}}</strong></p>
|
||||
<p>Please click below to complete your registration:</p>
|
||||
<a href={{url}} style="display: inline-block; margin-top: 20px; background-color: #007BFF; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-size: 16px;">
|
||||
Register Now
|
||||
</a>
|
||||
<div style="margin-top: 40px;">
|
||||
<p style="color: #888;">Powered by</p>
|
||||
<img src="https://yourapp.com/logo.png" alt="App Logo" style="max-height: 50px;">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
14
public/mail-templates/b.hbs
Normal file
14
public/mail-templates/b.hbs
Normal file
@ -0,0 +1,14 @@
|
||||
<div style="font-family: Arial, sans-serif; padding: 20px; background-color: #f9f9f9;">
|
||||
<div style="max-width: 600px; margin: auto; background-color: #fff; padding: 30px; border-radius: 8px; text-align: center; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
|
||||
<h2 style="color: #4A90E2;">Reset your password</h2>
|
||||
{{!-- <p style="font-size: 16px;">A Registration has been successfully initiated for the email: <strong>{{to}}</strong></p> --}}
|
||||
<p>Please click below to complete your password reset:</p>
|
||||
<a href={{url}} style="display: inline-block; margin-top: 20px; background-color: #007BFF; color: white; padding: 12px 24px; text-decoration: none; border-radius: 4px; font-size: 16px;">
|
||||
Reset Now
|
||||
</a>
|
||||
<div style="margin-top: 40px;">
|
||||
<p style="color: #888;">Powered by</p>
|
||||
<img src="https://yourapp.com/logo.png" alt="App Logo" style="max-height: 50px;">
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
1
public/mail-templates/demo.hbs
Normal file
1
public/mail-templates/demo.hbs
Normal file
@ -0,0 +1 @@
|
||||
<h1>Testing....</h1>
|
||||
@ -2,15 +2,15 @@ import { MiddlewareConsumer, Module } from '@nestjs/common';
|
||||
import { DbModule } from './db/db.module';
|
||||
import { OracleModule } from './oracle/oracle.module';
|
||||
import { AuthModule } from './auth/auth.module';
|
||||
import { MssqlModule } from './mssql/mssql.module';
|
||||
import { OriginCheckMiddleware } from './middleware/OriginCheck.middleware';
|
||||
import { ReqBodyKeysToUppercaseMiddleware } from './middleware/reqBodyKeysToUppercase.middleware';
|
||||
import { ConfigModule } from '@nestjs/config';
|
||||
import { MailModule } from './mail/mail.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
AuthModule, DbModule, OracleModule
|
||||
AuthModule, DbModule, OracleModule, MailModule
|
||||
],
|
||||
controllers: [],
|
||||
providers: [],
|
||||
|
||||
@ -1,15 +1,119 @@
|
||||
import { Body, Controller, Post } from '@nestjs/common';
|
||||
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 } from './auth.dto';
|
||||
import { AuthLoginDTO, SendMailDTO } from './auth.dto';
|
||||
import { Request, Response } from 'express';
|
||||
import { LogoutInterceptor } from 'src/interceptors/logout.interceptor';
|
||||
import { RegisterGuard } from 'src/guards/register.guard';
|
||||
import { RolesGuard } from 'src/guards/roles.guard';
|
||||
import { Roles } from 'src/decorators/roles.decorator';
|
||||
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
|
||||
|
||||
@ApiTags('Auth')
|
||||
@Controller()
|
||||
export class AuthController {
|
||||
constructor(private readonly authService: AuthService) {}
|
||||
constructor(
|
||||
private readonly authService: AuthService,
|
||||
) { }
|
||||
|
||||
@ApiTags('Auth')
|
||||
@Post('/login')
|
||||
login(@Body() body: AuthLoginDTO) {
|
||||
return this.authService.login(body);
|
||||
@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);
|
||||
|
||||
if (k.access_token) {
|
||||
res.cookie('access_token', k.access_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none'
|
||||
});
|
||||
}
|
||||
|
||||
if (k.refresh_token) {
|
||||
res.cookie('refresh_token', k.refresh_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none'
|
||||
});
|
||||
}
|
||||
|
||||
return { statusCode: 200, message: "Logged-In Successfully", email: k.email }
|
||||
}
|
||||
|
||||
// @UseGuards(RegisterGuard)
|
||||
@Post('register')
|
||||
async register(@Body() body: AuthLoginDTO) {
|
||||
return this.authService.registerUser(body);
|
||||
}
|
||||
|
||||
@UseInterceptors(LogoutInterceptor)
|
||||
@HttpCode(200)
|
||||
@Post('logout')
|
||||
async logout(@Req() req: any, @Res() res: Response) {
|
||||
const refreshToken = req.user?.refreshToken;
|
||||
let rst: any = await this.authService.logoutUser(refreshToken);
|
||||
if (rst.statusCode === 200) {
|
||||
res.clearCookie('access_token', {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none'
|
||||
});
|
||||
res.clearCookie('refresh_token', {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none'
|
||||
});
|
||||
}
|
||||
res.json({ ...rst })
|
||||
}
|
||||
|
||||
@UseGuards(RegisterGuard)
|
||||
@Put('forgot-password')
|
||||
async forgotPassword(@Body() body: AuthLoginDTO, @Req() req: Request) {
|
||||
return this.authService.forgotPassword(body, req);
|
||||
}
|
||||
|
||||
@Get('refresh-tokens')
|
||||
async getTokenFromRefreshToken(@Req() req: Request, @Res({ passthrough: true }) res: Response) {
|
||||
let k: any = await this.authService.getTokenFromRefreshToken(req)
|
||||
|
||||
if (k.access_token) {
|
||||
res.cookie('access_token', k.access_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none',
|
||||
maxAge: 8 * 60 * 60 * 1000,
|
||||
path: '/'
|
||||
});
|
||||
}
|
||||
|
||||
if (k.refresh_token) {
|
||||
res.cookie('refresh_token', k.refresh_token, {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none',
|
||||
maxAge: 8 * 60 * 60 * 1000,
|
||||
path: '/'
|
||||
});
|
||||
}
|
||||
|
||||
return { statusCode: 200, message: "Tokens refreshed successfully" }
|
||||
}
|
||||
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('sa')
|
||||
@Post('sendmail')
|
||||
@HttpCode(200)
|
||||
async sendMail(@Body() body: SendMailDTO) {
|
||||
// let token = await this.jwtService.generateToken({ email: mail })
|
||||
return this.authService.sendMail(body);
|
||||
}
|
||||
|
||||
// @Get('checkRoles')
|
||||
// @UseGuards(JwtAuthGuard, RolesGuard)
|
||||
// @Roles('ca')
|
||||
roleChecking() {
|
||||
return { message: "role checking successfull..." }
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
import { IsString } from 'class-validator';
|
||||
import { Transform, Type } from 'class-transformer';
|
||||
import { IsEmail, IsEnum, IsObject, IsOptional, IsString, ValidateNested } from 'class-validator';
|
||||
|
||||
export class AuthLoginDTO {
|
||||
@ApiProperty({ required: true })
|
||||
@ -10,3 +11,51 @@ export class AuthLoginDTO {
|
||||
@IsString()
|
||||
P_PASSWORD: string;
|
||||
}
|
||||
|
||||
export enum MailTypeDTO {
|
||||
REGISTER_CLIENT = "REGISTER_CLIENT",
|
||||
REGISTER_SP = "REGISTER_SP",
|
||||
REGISTER_USCIB = "REGISTER_USCIB",
|
||||
FORGOT_PASSWORD = "FORGOT_PASSWORD"
|
||||
// DEMO_MAIL = "DEMO_MAIL"
|
||||
}
|
||||
|
||||
export class SendMailDTO {
|
||||
@ApiProperty({ required: true, example: 'user@example.com' })
|
||||
@IsEmail({}, { message: 'P_TO must be a valid email address' })
|
||||
P_TO: string;
|
||||
|
||||
@ApiProperty({ enum: MailTypeDTO, required: true })
|
||||
@Transform(({ value }) => value?.toUpperCase())
|
||||
@IsEnum(MailTypeDTO, { message: "Invalid P_MAIL_TYPE" })
|
||||
P_MAIL_TYPE: MailTypeDTO;
|
||||
}
|
||||
|
||||
export class MailContextDTO {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
to: string;
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
url: string;
|
||||
|
||||
}
|
||||
|
||||
export class MailTemplateDTO {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
to: string;
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
subject: string;
|
||||
|
||||
@ApiProperty({ required: true })
|
||||
@IsString()
|
||||
templateName: string;
|
||||
|
||||
@IsOptional()
|
||||
@IsObject()
|
||||
variables?: Record<string, any>;
|
||||
}
|
||||
@ -1,11 +1,61 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { forwardRef, Module } from '@nestjs/common';
|
||||
import { AuthService } from './auth.service';
|
||||
import { AuthController } from './auth.controller';
|
||||
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],
|
||||
providers: [AuthService],
|
||||
imports: [DbModule,MailModule, forwardRef(() => OracleModule)],
|
||||
providers: [
|
||||
AuthService,
|
||||
{
|
||||
provide: "REGISTER_SIGN_JWT",
|
||||
useFactory: (config: ConfigService) => {
|
||||
const base64Key = config.get<string>('JWT_REGISTER_PRIVATE_KEY');
|
||||
if (!base64Key) {
|
||||
throw new Error('JWT_REGISTER_PRIVATE_KEY is not defined in the config');
|
||||
}
|
||||
const secretKey = Buffer.from(base64Key, 'base64').toString('utf-8');
|
||||
|
||||
const expiry = config.get<string>('JWT_REGISTER_EXPIRY');
|
||||
|
||||
if (!expiry) {
|
||||
throw new Error('JWT_REGISTER_PRIVATE_KEY is not defined in the config');
|
||||
}
|
||||
|
||||
return new JwtService({
|
||||
secret: secretKey,
|
||||
signOptions: {
|
||||
expiresIn: expiry,
|
||||
algorithm: 'ES384'
|
||||
},
|
||||
})
|
||||
},
|
||||
inject: [ConfigService],
|
||||
},
|
||||
{
|
||||
provide: "REGISTER_VERIFY_JWT",
|
||||
useFactory: (config: ConfigService) => {
|
||||
const base64Key = config.get<string>('JWT_REGISTER_PUBLIC_KEY');
|
||||
if (!base64Key) {
|
||||
throw new Error('JWT_REGISTER_PRIVATE_KEY is not defined in the config');
|
||||
}
|
||||
const secretKey = Buffer.from(base64Key, 'base64').toString('utf-8');
|
||||
|
||||
return new JwtService({
|
||||
secret: secretKey,
|
||||
verifyOptions: {
|
||||
algorithms: ['ES384']
|
||||
}
|
||||
})
|
||||
},
|
||||
inject: [ConfigService],
|
||||
}
|
||||
],
|
||||
controllers: [AuthController],
|
||||
exports: [AuthService]
|
||||
})
|
||||
export class AuthModule {}
|
||||
export class AuthModule { }
|
||||
|
||||
@ -1,11 +1,81 @@
|
||||
import { BadRequestException, Injectable } from '@nestjs/common';
|
||||
import { Inject, Injectable, InternalServerErrorException } from '@nestjs/common';
|
||||
import { OracleDBService } from 'src/db/db.service';
|
||||
import { AuthLoginDTO } from './auth.dto';
|
||||
import { AuthLoginDTO, MailTemplateDTO, MailTypeDTO, SendMailDTO } from './auth.dto';
|
||||
import * as oracledb from 'oracledb';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
|
||||
import { Request } from 'express';
|
||||
import * as jwkToPem from "jwk-to-pem"
|
||||
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 { 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 {
|
||||
email: string;
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
interface IntrospectResult {
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class AuthService {
|
||||
constructor(private readonly oracleDBService: OracleDBService) { }
|
||||
private keyCache: Record<string, string> = {};
|
||||
|
||||
private readonly KEYCLOAK_URL: string;
|
||||
private readonly KEYCLOAK_REALM: string;
|
||||
private readonly KEYCLOAK_BASE_URL: string;
|
||||
private readonly JWKS_URL: string;
|
||||
private readonly TOKENS_INTROSPECT_URL: string;
|
||||
private readonly CLIENT_ID: string;
|
||||
private readonly CLIENT_SECRET: string;
|
||||
private readonly TOKEN_URL: string;
|
||||
private readonly USERS_URL: string;
|
||||
|
||||
|
||||
constructor(
|
||||
private readonly oracleDBService: OracleDBService,
|
||||
private readonly configService: ConfigService,
|
||||
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
|
||||
) {
|
||||
|
||||
const KEYCLOAK_URL = this.configService.get<string>('KEYCLOAK_URL');
|
||||
if (!KEYCLOAK_URL) throw new Error('Environment variable KEYCLOAK_URL is not set');
|
||||
this.KEYCLOAK_URL = KEYCLOAK_URL;
|
||||
|
||||
const KEYCLOAK_REALM = this.configService.get<string>('KEYCLOAK_REALM');
|
||||
if (!KEYCLOAK_REALM) throw new Error('Environment variable KEYCLOAK_REALM is not set');
|
||||
this.KEYCLOAK_REALM = KEYCLOAK_REALM;
|
||||
|
||||
const CLIENT_ID = this.configService.get<string>('CLIENT_ID');
|
||||
if (!CLIENT_ID) throw new Error('Environment variable KEYCLOAK CLIENT_ID is not set');
|
||||
this.CLIENT_ID = CLIENT_ID;
|
||||
|
||||
const CLIENT_SECRET = this.configService.get<string>('CLIENT_SECRET');
|
||||
if (!CLIENT_SECRET) throw new Error('Environment variable KEYCLOAK CLIENT_SECRET is not set');
|
||||
this.CLIENT_SECRET = CLIENT_SECRET;
|
||||
|
||||
this.KEYCLOAK_BASE_URL = `${this.KEYCLOAK_URL}/realms/${this.KEYCLOAK_REALM}/protocol/openid-connect`;
|
||||
|
||||
this.JWKS_URL = `${this.KEYCLOAK_BASE_URL}/certs`
|
||||
|
||||
this.TOKENS_INTROSPECT_URL = `${this.KEYCLOAK_BASE_URL}/token/introspect`
|
||||
|
||||
this.TOKEN_URL = `${this.KEYCLOAK_BASE_URL}/token`
|
||||
|
||||
this.USERS_URL = `${this.KEYCLOAK_URL}/admin/realms/${this.KEYCLOAK_REALM}/users`;
|
||||
|
||||
}
|
||||
|
||||
async login(body: AuthLoginDTO) {
|
||||
let connection;
|
||||
@ -50,17 +120,15 @@ export class AuthService {
|
||||
|
||||
await cursor.close();
|
||||
} else {
|
||||
throw new BadRequestException({
|
||||
Error: 'Error executing request try after some time!',
|
||||
});
|
||||
throw new BadRequestException('Error executing request try after some time!');
|
||||
}
|
||||
|
||||
if (rows[0]['ERRORMESG']) {
|
||||
throw new BadRequestException({ error: 'Invalid username or password!' });
|
||||
throw new BadRequestException('Invalid username or password!');
|
||||
}
|
||||
return { msg: 'Logged in successfully' };
|
||||
} catch (err) {
|
||||
throw new BadRequestException({ error: 'Invalid username or password' });
|
||||
throw new BadRequestException('Invalid username or password');
|
||||
}
|
||||
finally {
|
||||
if (connection) {
|
||||
@ -72,4 +140,761 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async getPublicKey(kid: string): Promise<string> {
|
||||
try {
|
||||
// Check if the key is already cached
|
||||
if (this.keyCache[kid]) return this.keyCache[kid];
|
||||
|
||||
// Fetch the JWKS (JSON Web Key Set)
|
||||
const { data } = await axios.get(this.JWKS_URL);
|
||||
|
||||
// Validate the response shape
|
||||
if (!data?.keys || !Array.isArray(data.keys)) {
|
||||
throw new UnauthorizedException('Authentication failed');
|
||||
}
|
||||
|
||||
// Find the key with the matching kid
|
||||
const key = data.keys.find((k) => k.kid === kid);
|
||||
if (!key) {
|
||||
throw new UnauthorizedException('Authentication failed');
|
||||
}
|
||||
|
||||
// Convert JWK to PEM format and cache it
|
||||
const pem = jwkToPem(key);
|
||||
this.keyCache[kid] = pem;
|
||||
|
||||
return pem;
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) {
|
||||
throw error; // Let UnauthorizedException bubble up as-is
|
||||
}
|
||||
// Optionally log error details for debugging
|
||||
console.error('Failed to retrieve or process JWKS:', error);
|
||||
// Wrap other errors as InternalServerException
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
async introspectToken(token: string): Promise<IntrospectResult> {
|
||||
try {
|
||||
const decoded = jwt.decode(token) as DecodedToken;
|
||||
|
||||
const { email } = decoded;
|
||||
|
||||
if (!email) throw new UnauthorizedException('Authentication failed');
|
||||
|
||||
const sessionData = await this.getUserSession(email);
|
||||
|
||||
return { active: Array.isArray(sessionData) && sessionData.length > 0 };
|
||||
|
||||
} catch (error: any) {
|
||||
if (error instanceof UnauthorizedException) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new InternalServerErrorException('Failed to introspect token');
|
||||
}
|
||||
}
|
||||
|
||||
async getUserSession(email: string) {
|
||||
try {
|
||||
const uid = await this.getUserIdByEmail(email);
|
||||
|
||||
if (!uid) throw new UnauthorizedException('No user ID found for email.');
|
||||
|
||||
const userInfoUrl = `${this.USERS_URL}/${uid}/sessions`;
|
||||
|
||||
const adminToken = await this.getAdminAccessToken();
|
||||
|
||||
const response = await axios.get(userInfoUrl, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminToken}`,
|
||||
},
|
||||
});
|
||||
|
||||
const sessionData = response.data;
|
||||
|
||||
return sessionData
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error
|
||||
throw new InternalServerErrorException()
|
||||
}
|
||||
}
|
||||
|
||||
async decodeToken(token: string): Promise<any> {
|
||||
const decodedHeader = jwt.decode(token, { complete: true });
|
||||
|
||||
if (!decodedHeader || typeof decodedHeader !== 'object') {
|
||||
throw new UnauthorizedException("Authentication failed")
|
||||
}
|
||||
|
||||
const kid: any = decodedHeader.header.kid;
|
||||
|
||||
const publicKey = await this.getPublicKey(kid);
|
||||
|
||||
const introspection = await this.introspectToken(token);
|
||||
|
||||
if (!introspection.active) {
|
||||
throw new UnauthorizedException("Authentication Failed")
|
||||
}
|
||||
|
||||
const verified = jwt.verify(token, publicKey, { algorithms: ['RS256'] });
|
||||
|
||||
return verified;
|
||||
}
|
||||
|
||||
async loginUser(username: string, password: string, req: Request): Promise<any> {
|
||||
|
||||
const access_token = req.cookies?.access_token;
|
||||
const refresh_token = req.cookies?.refresh_token;
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.append('grant_type', 'password');
|
||||
params.append('client_id', this.CLIENT_ID);
|
||||
params.append('client_secret', this.CLIENT_SECRET);
|
||||
params.append('username', username);
|
||||
params.append('password', password);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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 })
|
||||
|
||||
const user: any = await this.getUserDetailsById(getSub?.payload.sub)
|
||||
|
||||
if (user.email !== username) {
|
||||
throw new UnauthorizedException("Authentication failed")
|
||||
}
|
||||
|
||||
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 }
|
||||
|
||||
}
|
||||
|
||||
const response = await axios.post(this.TOKEN_URL, params, {
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
});
|
||||
|
||||
let k = { ...response.data, email: username };
|
||||
|
||||
return k;
|
||||
} catch (error) {
|
||||
throw new BadRequestException('Invalid username or password');
|
||||
}
|
||||
}
|
||||
|
||||
async getUserIdByEmail(email: string): Promise<string> {
|
||||
try {
|
||||
const adminAccessToken = await this.getAdminAccessToken();
|
||||
const url = `${this.USERS_URL}?email=${encodeURIComponent(email)}`;
|
||||
const options: AxiosRequestConfig = {
|
||||
method: 'GET',
|
||||
url,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
};
|
||||
|
||||
const response = await axios.request(options);
|
||||
|
||||
if (response.status !== 200 || !Array.isArray(response.data)) {
|
||||
throw new UnauthorizedException("Authentication failed")
|
||||
}
|
||||
|
||||
const user = response.data[0];
|
||||
if (user?.id) {
|
||||
return user.id
|
||||
} else {
|
||||
throw new UnauthorizedException("Authentication failed")
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
async getUserDetailsById(id: string) {
|
||||
try {
|
||||
const adminAccessToken = await this.getAdminAccessToken();
|
||||
|
||||
const userResponse = await axios.get(`${this.USERS_URL}/${id}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`
|
||||
},
|
||||
});
|
||||
|
||||
if (userResponse.status !== 200 || !Array.isArray(userResponse.data)) {
|
||||
|
||||
throw new UnauthorizedException("Authentication failed");
|
||||
}
|
||||
|
||||
return userResponse.data;
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) {
|
||||
throw error;
|
||||
}
|
||||
else if (error instanceof BadRequestException) {
|
||||
throw error;
|
||||
}
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
async getUserDetailsByEmail(email: string): Promise<any> {
|
||||
try {
|
||||
const adminAccessToken = await this.getAdminAccessToken();
|
||||
|
||||
const userResponse = await axios.get(`${this.USERS_URL}?email=${encodeURIComponent(email)}`, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`
|
||||
},
|
||||
});
|
||||
|
||||
if (userResponse.status !== 200 || !Array.isArray(userResponse.data)) {
|
||||
throw new UnauthorizedException("Authentication failed");
|
||||
}
|
||||
|
||||
const user = userResponse.data[0];
|
||||
|
||||
if (userResponse.data.length === 0 || !user?.id) {
|
||||
throw new BadRequestException("Invalid User");
|
||||
}
|
||||
const roleUrl = `${this.USERS_URL}/${user.id}/role-mappings`;
|
||||
|
||||
const roleResponse = await axios.get(roleUrl, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`
|
||||
},
|
||||
});
|
||||
|
||||
const clientRoles = roleResponse.data;
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
forgotPassword: user.attributes?.["forgot-password"][0] || null,
|
||||
role: clientRoles.clientMappings?.[this.CLIENT_ID]?.mappings?.map((x) => x.name) || []
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) {
|
||||
throw error;
|
||||
}
|
||||
else if (error instanceof BadRequestException) {
|
||||
throw error;
|
||||
}
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async forgotPassword(body: AuthLoginDTO, req: Request) {
|
||||
|
||||
let det = await req['user'];
|
||||
if (det?.email !== body.P_EMAILADDR) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
const userDetails = await this.getUserDetailsByEmail(body.P_EMAILADDR);
|
||||
|
||||
if (userDetails.forgotPassword !== det.rstID) {
|
||||
throw new UnauthorizedException("Token verification failed");
|
||||
}
|
||||
|
||||
let adminAccessToken = await this.getAdminAccessToken();
|
||||
|
||||
// console.log(`${this.USERS_URL}/${userDetails.id}/reset-password`);
|
||||
|
||||
|
||||
const options2: AxiosRequestConfig = {
|
||||
method: 'PUT',
|
||||
url: `${this.USERS_URL}/${userDetails.id}/reset-password`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
type: 'password',
|
||||
value: body.P_PASSWORD,
|
||||
temporary: false,
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const { data } = await axios.request(options2);
|
||||
const forgotPasswordStatus = await this.updateForgotPassword(userDetails)
|
||||
|
||||
if (!forgotPasswordStatus) {
|
||||
throw new InternalServerErrorException("Update forgot-password failed")
|
||||
}
|
||||
|
||||
return { statusCode: 200, message: 'password reset successfull' }
|
||||
} catch (error) {
|
||||
// console.error(error);
|
||||
throw new InternalServerErrorException()
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
async getAdminAccessToken() {
|
||||
try {
|
||||
const adminParams = new URLSearchParams({
|
||||
grant_type: 'client_credentials',
|
||||
client_id: this.CLIENT_ID,
|
||||
client_secret: this.CLIENT_SECRET,
|
||||
});
|
||||
|
||||
const { data } = await axios.post(this.TOKEN_URL, adminParams, {
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
timeout: 6000, // optional: add a timeout to avoid hanging requests
|
||||
});
|
||||
|
||||
if (!data.access_token) {
|
||||
throw new UnauthorizedException("Authentication failed")
|
||||
}
|
||||
|
||||
return data.access_token;
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
async registerUser(body: AuthLoginDTO) {
|
||||
// let det = await req['user'];
|
||||
// if (det?.email !== body.P_EMAILADDR) {
|
||||
// throw new BadRequestException();
|
||||
// }
|
||||
|
||||
const emailVerifyResponse: any = await this.userMaintenanceService.ValidateEmail({ P_EMAILADDR: body.P_EMAILADDR })
|
||||
|
||||
if (Array.isArray(emailVerifyResponse) && emailVerifyResponse[0].ERRORMESG) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
const userPayload = {
|
||||
username: body.P_EMAILADDR.toLowerCase(),
|
||||
// firstName:"A",
|
||||
// lastName:"B",
|
||||
email: body.P_EMAILADDR.toLowerCase(),
|
||||
emailVerified: true,
|
||||
enabled: true,
|
||||
attributes: {
|
||||
"forgot-password": ["none"]
|
||||
},
|
||||
credentials: [
|
||||
{
|
||||
type: 'password',
|
||||
value: body.P_PASSWORD,
|
||||
temporary: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// console.log(userPayload);
|
||||
|
||||
const adminAccessToken = await this.getAdminAccessToken();
|
||||
|
||||
try {
|
||||
const response = await axios.post(this.USERS_URL, userPayload, {
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (response.status === 201) {
|
||||
|
||||
// console.log("Assigning role : ");
|
||||
|
||||
// console.log("checking validate email response : ", response);
|
||||
|
||||
|
||||
const uid = await this.getUserIdByEmail(body.P_EMAILADDR);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// console.log("Role to assign : ", ROLE);
|
||||
|
||||
|
||||
if (!ROLE) {
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
|
||||
const res = await this.assignRoleToUser(uid, ROLE);
|
||||
return { statusCode: 201, message: 'User registered successfully' };
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (error.message === "Request failed with status code 409") {
|
||||
throw new ConflictException("User already exist");
|
||||
}
|
||||
else if (error instanceof BadRequestException) {
|
||||
return error;
|
||||
}
|
||||
throw new InternalServerErrorException('Failed to create user');
|
||||
}
|
||||
}
|
||||
|
||||
async assignRoleToUser(userId: string, roleName: string): Promise<{ message: string }> {
|
||||
try {
|
||||
const token = await this.getAdminAccessToken();
|
||||
const clientId = await this.getClientUUID();
|
||||
const role = await this.getClientRole(roleName);
|
||||
|
||||
const url = `${this.KEYCLOAK_URL}/admin/realms/${this.KEYCLOAK_REALM}/users/${userId}/role-mappings/clients/${clientId}`;
|
||||
|
||||
const response = await axios.post(url, [role], {
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
validateStatus: () => true, // Let us handle non-2xx statuses manually
|
||||
});
|
||||
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
return { message: "Successfully assigned to user" };
|
||||
} else {
|
||||
console.error(`❌ Failed to assign role. Status: ${response.status}, Data:`, response.data);
|
||||
throw new Error(`Failed to assign role "${roleName}" to user ${userId}. Status: ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
// Handle Axios errors more gracefully
|
||||
if (axios.isAxiosError(error)) {
|
||||
const axiosError = error as AxiosError;
|
||||
console.error(`🔥 Axios error: ${axiosError.message}`);
|
||||
if (axiosError.response) {
|
||||
console.error(`Response status: ${axiosError.response.status}`);
|
||||
console.error(`Response data:`, axiosError.response.data);
|
||||
}
|
||||
} else {
|
||||
console.error(`🔥 Unexpected error:`, error);
|
||||
}
|
||||
|
||||
throw new Error(`Error assigning role "${roleName}" to user ${userId}. See logs for details.`);
|
||||
}
|
||||
}
|
||||
|
||||
async logoutUser(refreshToken: string): Promise<any> {
|
||||
const url = `${this.KEYCLOAK_BASE_URL}/logout`;
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.append('client_id', this.CLIENT_ID);
|
||||
params.append('client_secret', this.CLIENT_SECRET);
|
||||
params.append('refresh_token', refreshToken);
|
||||
|
||||
try {
|
||||
const response = await axios.post(url, params, {
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
});
|
||||
return { statusCode: 200, message: 'Logged-Out successfully' };
|
||||
} catch (error) {
|
||||
throw new InternalServerErrorException('Logout failed');
|
||||
}
|
||||
}
|
||||
|
||||
async getClientUUID(): Promise<string> {
|
||||
try {
|
||||
const token = await this.getAdminAccessToken();
|
||||
|
||||
const realm = this.KEYCLOAK_REALM;
|
||||
const clientId = this.CLIENT_ID;
|
||||
const keycloakUrl = this.KEYCLOAK_URL;
|
||||
|
||||
const response = await axios.get(
|
||||
`${keycloakUrl}/admin/realms/${realm}/clients?clientId=${encodeURIComponent(clientId)}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
validateStatus: () => true, // manually handle status codes
|
||||
}
|
||||
);
|
||||
|
||||
if (response.status !== 200) {
|
||||
throw new Error(`Failed to fetch client list. Status: ${response.status}. Message: ${JSON.stringify(response.data)}`);
|
||||
}
|
||||
|
||||
const clients = response.data;
|
||||
|
||||
if (!Array.isArray(clients) || clients.length === 0) {
|
||||
throw new Error(`Client with ID '${clientId}' not found in realm '${realm}'.`);
|
||||
}
|
||||
|
||||
const clientUUID = clients[0].id;
|
||||
|
||||
if (!clientUUID) {
|
||||
throw new Error(`Client UUID is missing in the response for clientId '${clientId}'.`);
|
||||
}
|
||||
|
||||
return clientUUID;
|
||||
} catch (error) {
|
||||
console.error('❌ Error in getClientUUID:', error.message || error);
|
||||
throw error; // rethrow for upstream handling
|
||||
}
|
||||
}
|
||||
|
||||
async getClientRole(roleName: string): Promise<any> {
|
||||
const token = await this.getAdminAccessToken();
|
||||
|
||||
const clientUUID = await this.getClientUUID();
|
||||
|
||||
try {
|
||||
const response = await axios.get(
|
||||
`${this.KEYCLOAK_URL}/admin/realms/${this.KEYCLOAK_REALM}/clients/${clientUUID}/roles/${roleName}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
console.error(`Error getting client role '${roleName}'`);
|
||||
console.error(error.response?.data || error.message);
|
||||
throw new InternalServerErrorException(`Could not find client role '${roleName}'`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
async getTokenFromRefreshToken(req: Request) {
|
||||
|
||||
const refreshToken = req.cookies['refresh_token'];
|
||||
|
||||
if (!refreshToken) {
|
||||
throw new UnauthorizedException('Authentication failed');
|
||||
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.append('grant_type', 'refresh_token');
|
||||
params.append('client_id', this.CLIENT_ID);
|
||||
params.append('client_secret', this.CLIENT_SECRET);
|
||||
params.append('refresh_token', refreshToken);
|
||||
|
||||
// console.log("url for refresh is : ", `${this.KEYCLOAK_URL}/auth/realms/${this.KEYCLOAK_REALM}/protocol/openid-connect/token`);
|
||||
|
||||
try {
|
||||
const response = await axios.post(this.TOKEN_URL, params, {
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
});
|
||||
|
||||
return response.data;
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response) {
|
||||
console.error('🔴 Axios error:', {
|
||||
status: error.response.status,
|
||||
data: error.response.data,
|
||||
});
|
||||
} else {
|
||||
console.error('🔴 Unexpected error:', error.message);
|
||||
}
|
||||
throw new UnauthorizedException('Authentication failed');
|
||||
}
|
||||
}
|
||||
|
||||
async generateUUID() {
|
||||
try {
|
||||
const uuid = uuidv4();
|
||||
|
||||
if (!uuid || typeof uuid !== 'string') {
|
||||
throw new InternalServerErrorException('Invalid UUID generated');
|
||||
}
|
||||
|
||||
return uuid;
|
||||
} catch (error) {
|
||||
console.error('UUID generation failed:', error.message);
|
||||
throw new InternalServerErrorException('Failed to generate unique ID');
|
||||
}
|
||||
}
|
||||
|
||||
async generateToken(payload: { P_TO: string, uuid?: string }) {
|
||||
let token: string;
|
||||
try {
|
||||
if (payload.uuid) {
|
||||
token = this.REGISTER_SIGN_JWT.sign({ email: payload.P_TO, rstID: payload.uuid });
|
||||
}
|
||||
else {
|
||||
token = this.REGISTER_SIGN_JWT.sign({ email: payload.P_TO });
|
||||
}
|
||||
if (!token) {
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
catch (error) {
|
||||
throw new InternalServerErrorException("Register Token Generation failed")
|
||||
}
|
||||
}
|
||||
|
||||
async updateForgotPassword(user: any, rstID?: string) {
|
||||
try {
|
||||
const adminAccessToken = await this.getAdminAccessToken();
|
||||
|
||||
const options2: AxiosRequestConfig = {
|
||||
method: 'PUT',
|
||||
url: `${this.USERS_URL}/${user.id}`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${adminAccessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
"username": `${user.email}`,
|
||||
// firstName:"A",
|
||||
// lastName:"B",
|
||||
"email": `${user.email}`,
|
||||
"emailVerified": true,
|
||||
"enabled": true,
|
||||
"attributes": {
|
||||
"forgot-password": [`${rstID ? rstID : "none"}`]
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const userResponse = await axios.request(options2);
|
||||
|
||||
if (userResponse.status !== 204) {
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
|
||||
return true;
|
||||
|
||||
} catch (error) {
|
||||
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) {
|
||||
let token: string;
|
||||
let ROLE: string = "";
|
||||
let uuid: string | undefined = undefined;
|
||||
let userDetails: any | null = null;
|
||||
|
||||
if (body.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
|
||||
try {
|
||||
uuid = await this.generateUUID();
|
||||
|
||||
userDetails = await this.getUserDetailsByEmail(body.P_TO);
|
||||
|
||||
ROLE = userDetails.role[0];
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof BadRequestException) {
|
||||
throw error
|
||||
}
|
||||
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
token = await this.generateToken({ P_TO: body.P_TO, uuid: uuid })
|
||||
|
||||
const mailTemplate: MailTemplateDTO | null = await this.getMailTemplate(body, token, ROLE);
|
||||
|
||||
if (!mailTemplate) {
|
||||
throw new BadRequestException();
|
||||
}
|
||||
|
||||
try {
|
||||
await this.mailService.sendMail({ ...mailTemplate });
|
||||
if (body.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
|
||||
let forgotPasswordStatus = await this.updateForgotPassword(userDetails, uuid);
|
||||
|
||||
if (forgotPasswordStatus) {
|
||||
|
||||
return { statusCode: 200, message: 'Email sent successfully' };
|
||||
}
|
||||
|
||||
throw new InternalServerErrorException();
|
||||
|
||||
}
|
||||
return { statusCode: 200, message: 'Email sent successfully' };
|
||||
|
||||
} catch (error) {
|
||||
console.error('Failed to send email:', error.message, error);
|
||||
throw new InternalServerErrorException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -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) {
|
||||
|
||||
5
src/decorators/roles.decorator.ts
Normal file
5
src/decorators/roles.decorator.ts
Normal file
@ -0,0 +1,5 @@
|
||||
// roles.decorator.ts
|
||||
import { SetMetadata } from '@nestjs/common';
|
||||
|
||||
export const ROLES_KEY = 'roles';
|
||||
export const Roles = (...roles: string[]) => SetMetadata(ROLES_KEY, roles);
|
||||
@ -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, {
|
||||
@ -30,6 +40,7 @@ export class HEADERID_DTO {
|
||||
@Min(0, { message: 'Property P_HEADERID must be at least 0 or more' })
|
||||
@IsInt({ message: 'Property P_HEADERID allows only whole numbers' })
|
||||
@IsNumber({}, { message: 'Property P_HEADERID must be a number' })
|
||||
@Transform(({ value }) => Number(value))
|
||||
@IsDefined({ message: 'Property P_HEADERID is required' })
|
||||
P_HEADERID: number;
|
||||
}
|
||||
@ -168,6 +179,35 @@ export class GLTABLE_DTO {
|
||||
P_GLTABLE: GLTABLE_ROW_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' })
|
||||
@IsInt({ message: 'Property ITEMNO allows only whole numbers' })
|
||||
@Transform(({ value }) => Number(value))
|
||||
@IsNumber({}, { message: 'Property ITEMNO must be a number' })
|
||||
@IsDefined({ message: 'Property ITEMNO is required' })
|
||||
P_ITEMNO: number;
|
||||
}
|
||||
|
||||
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' })
|
||||
@IsInt({ message: 'Property P_SHIPCONTACTID allows only whole numbers' })
|
||||
@Transform(({ value }) => Number(value))
|
||||
@IsNumber({}, { message: 'Property P_SHIPCONTACTID must be a number' })
|
||||
@IsDefined({ message: 'Property P_SHIPCONTACTID is required' })
|
||||
P_SHIPCONTACTID: number;
|
||||
}
|
||||
|
||||
export class SHIPNAME_DTO {
|
||||
@ApiProperty({ required: true })
|
||||
@IsString({ message: 'Property P_SHIPNAME must be a string' })
|
||||
@IsDefined({ message: 'Property P_SHIPNAME is required' })
|
||||
P_SHIPNAME: string;
|
||||
}
|
||||
|
||||
export class USSETS_DTO {
|
||||
@ApiProperty({ required: true })
|
||||
// @Max(99999, { message: 'Property P_USSETS must not exceed 99999' })
|
||||
|
||||
@ -4,15 +4,17 @@ import {
|
||||
APPLICATIONNAME_DTO, AUTHREP_DTO, AUTO_FLAG_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, LDIPROTECTION_DTO, ORDERTYPE_DTO, PAYMENTMETHOD_DTO,
|
||||
PROF_EQUIPMENT_FLAG_DTO, REFNO_DTO, SHIPADDRID_DTO, SHIPTOTYPE_DTO, USSETS_DTO
|
||||
HORSE_FLAG_DTO, INSPROTECTION_DTO, ITEMNO_DTO, LDIPROTECTION_DTO, ORDERTYPE_DTO, PAYMENTMETHOD_DTO,
|
||||
PRINTGL_DTO,
|
||||
PROF_EQUIPMENT_FLAG_DTO, REFNO_DTO, SHIPADDRID_DTO, SHIPCONTACTID_DTO, SHIPNAME_DTO, SHIPTOTYPE_DTO, USSETS_DTO
|
||||
} from "./carnet-application-property.dto";
|
||||
|
||||
import { NOTES_DTO, SPID_DTO, USERID_DTO } from "../uscib-managed-sp/sp/sp-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";
|
||||
|
||||
import { CLIENTID_DTO } from "../manage-clients/manage-clients-property.dto";
|
||||
|
||||
import { HOLDERID_DTO, LOCATIONID_DTO } from "../manage-holders/manage-holders-property.dto";
|
||||
import { EMAIL_ADDRESS_DTO, FAX_NO_DTO, FIRSTNAME_DTO, LASTNAME_DTO, MIDDLE_INITIAL_DTO, MOBILE_NO_DTO, PHONE_NO_DTO, TITLE_DTO } from "../property.dto";
|
||||
|
||||
|
||||
export class SaveCarnetApplicationDTO extends IntersectionType(
|
||||
@ -53,6 +55,8 @@ export class TransmitApplicationtoProcessDTO extends IntersectionType(
|
||||
|
||||
export class CarnetProcessingCenterDTO extends (IntersectionType(USERID_DTO, HEADERID_DTO)) { }
|
||||
|
||||
export class PrintCarnetDTO extends (IntersectionType(SPID_DTO, HEADERID_DTO, PRINTGL_DTO)){}
|
||||
|
||||
export class CreateApplicationDTO extends IntersectionType(
|
||||
SPID_DTO, CLIENTID_DTO, LOCATIONID_DTO, USERID_DTO, APPLICATIONNAME_DTO,
|
||||
ORDERTYPE_DTO
|
||||
@ -72,13 +76,26 @@ export class AddGenerallistItemsDTO extends IntersectionType(
|
||||
HEADERID_DTO, GLTABLE_DTO, USERID_DTO
|
||||
) { }
|
||||
|
||||
export class DeleteGenerallistItemsDTO extends IntersectionType(
|
||||
HEADERID_DTO, ITEMNO_DTO, USERID_DTO
|
||||
) { }
|
||||
|
||||
export class AddCountriesDTO extends IntersectionType(
|
||||
HEADERID_DTO, USSETS_DTO, COUNTRYTABLE_DTO, USERID_DTO
|
||||
) { }
|
||||
|
||||
export class UpdateShippingDetailsDTO extends IntersectionType(
|
||||
HEADERID_DTO, SHIPTOTYPE_DTO, SHIPADDRID_DTO, FORMOFSECURITY_DTO,
|
||||
INSPROTECTION_DTO, LDIPROTECTION_DTO, DELIVERYTYPE_DTO, DELIVERYMETHOD_DTO,
|
||||
PAYMENTMETHOD_DTO, CUSTCOURIERNO_DTO, REFNO_DTO, NOTES_DTO, USERID_DTO
|
||||
HEADERID_DTO,
|
||||
PartialType(SHIPTOTYPE_DTO), PartialType(SHIPCONTACTID_DTO), PartialType(SHIPNAME_DTO),
|
||||
PartialType(ADDRESS1_DTO), PartialType(ADDRESS2_DTO), PartialType(CITY_DTO), PartialType(STATE_DTO), PartialType(ZIP_DTO), PartialType(COUNTRY_DTO),
|
||||
PartialType(FIRSTNAME_DTO), PartialType(LASTNAME_DTO), PartialType(TITLE_DTO), PartialType(PHONE_NO_DTO), PartialType(MOBILE_NO_DTO), PartialType(FAX_NO_DTO), PartialType(EMAIL_ADDRESS_DTO), PartialType(MIDDLE_INITIAL_DTO),
|
||||
PartialType(FORMOFSECURITY_DTO), PartialType(INSPROTECTION_DTO), PartialType(LDIPROTECTION_DTO),
|
||||
PartialType(DELIVERYTYPE_DTO), PartialType(DELIVERYMETHOD_DTO), PartialType(PAYMENTMETHOD_DTO),
|
||||
PartialType(CUSTCOURIERNO_DTO), PartialType(REFNO_DTO), PartialType(NOTES_DTO),
|
||||
USERID_DTO
|
||||
) { }
|
||||
|
||||
export class GetCarnetControlCenterDTO extends IntersectionType(
|
||||
SPID_DTO, USERID_DTO, HEADERID_DTO
|
||||
) { }
|
||||
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
import { IntersectionType, PartialType } from "@nestjs/swagger";
|
||||
|
||||
import { CONTACTSTABLE_DTO } from "../manage-holders/manage-holders-property.dto";
|
||||
import { CONTACTSTABLE_DTO, LOCATIONID_DTO } from "../manage-holders/manage-holders-property.dto";
|
||||
|
||||
import {
|
||||
DEFAULT_CONTACT_FLAG_DTO, EMAIL_ADDRESS_DTO, FAX_NO_DTO, FIRSTNAME_DTO, LASTNAME_DTO,
|
||||
@ -102,7 +102,7 @@ export class UpdateClientLocationsDTO extends IntersectionType(
|
||||
|
||||
export class CreateClientContactsDTO extends IntersectionType(
|
||||
SPID_DTO,
|
||||
CLIENTID_DTO,
|
||||
LOCATIONID_DTO,
|
||||
CONTACTSTABLE_DTO,
|
||||
DEFAULT_CONTACT_FLAG_DTO,
|
||||
USERID_DTO
|
||||
@ -120,6 +120,10 @@ export class GetClientDTO extends IntersectionType(
|
||||
CLIENTID_DTO
|
||||
) { }
|
||||
|
||||
export class GetClientContactByLacationIdDTO extends IntersectionType(
|
||||
SPID_DTO, LOCATIONID_DTO
|
||||
){}
|
||||
|
||||
export class ClientContactControlsDTO extends IntersectionType(
|
||||
SPID_DTO,
|
||||
CLIENT_CONTACTID_DTO,
|
||||
|
||||
@ -44,6 +44,7 @@ export class HOLDERID_DTO {
|
||||
@Min(0, { message: 'Property P_HOLDERID must be at least 0 or more' })
|
||||
@IsInt({ message: 'Property P_HOLDERID allows only whole numbers' })
|
||||
@IsNumber({}, { message: 'Property P_HOLDERID must be a number' })
|
||||
@Transform(({ value }) => Number(value))
|
||||
@IsDefined({ message: 'Property P_HOLDERID is required' })
|
||||
P_HOLDERID: number;
|
||||
}
|
||||
@ -58,7 +59,7 @@ export class HOLDERNO_DTO {
|
||||
|
||||
export class HOLDERTYPE_DTO {
|
||||
@ApiProperty({ required: true })
|
||||
@Length(0, 3, { message: 'Property P_HOLDERTYPE must be between 0 to 3 characters' })
|
||||
@Length(0, 4, { message: 'Property P_HOLDERTYPE must be between 0 to 6 characters' })
|
||||
@IsString({ message: 'Property P_HOLDERTYPE must be a string' })
|
||||
@IsDefined({ message: 'Property P_HOLDERTYPE is required' })
|
||||
P_HOLDERTYPE: string;
|
||||
@ -115,6 +116,7 @@ export class HOLDERCONTACTID_DTO {
|
||||
@Min(0, { message: 'Property P_HOLDERCONTACTID must be at least 0 or more' })
|
||||
@IsInt({ message: 'Property P_HOLDERCONTACTID allows only whole numbers' })
|
||||
@IsNumber({}, { message: 'Property P_HOLDERCONTACTID must be a number' })
|
||||
@Transform(({ value }) => Number(value))
|
||||
@IsDefined({ message: 'Property P_HOLDERCONTACTID is required' })
|
||||
P_HOLDERCONTACTID: number;
|
||||
}
|
||||
|
||||
@ -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,
|
||||
HOLDERNAME_DTO
|
||||
PartialType(HOLDERNAME_DTO),
|
||||
USERID_DTO
|
||||
) { }
|
||||
@ -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
|
||||
) { }
|
||||
19
src/exceptions/conflict.exception.ts
Normal file
19
src/exceptions/conflict.exception.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export class ConflictException extends HttpException {
|
||||
constructor(
|
||||
message = 'CONFLICT',
|
||||
errorCode = 'INTERNAL_ERROR',
|
||||
data: any = null,
|
||||
) {
|
||||
super(
|
||||
{
|
||||
statusCode: HttpStatus.CONFLICT,
|
||||
message,
|
||||
// errorCode,
|
||||
// data,
|
||||
},
|
||||
HttpStatus.CONFLICT,
|
||||
);
|
||||
}
|
||||
}
|
||||
19
src/exceptions/unauthorized.exception.ts
Normal file
19
src/exceptions/unauthorized.exception.ts
Normal file
@ -0,0 +1,19 @@
|
||||
import { HttpException, HttpStatus } from '@nestjs/common';
|
||||
|
||||
export class UnauthorizedException extends HttpException {
|
||||
constructor(
|
||||
message = 'Unauthorized',
|
||||
errorCode = 'INTERNAL_ERROR',
|
||||
data: any = null,
|
||||
) {
|
||||
super(
|
||||
{
|
||||
statusCode: HttpStatus.UNAUTHORIZED,
|
||||
message,
|
||||
// errorCode,
|
||||
// data,
|
||||
},
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
);
|
||||
}
|
||||
}
|
||||
46
src/filters/auth-exception.filter.ts
Normal file
46
src/filters/auth-exception.filter.ts
Normal file
@ -0,0 +1,46 @@
|
||||
import {
|
||||
ExceptionFilter,
|
||||
Catch,
|
||||
ArgumentsHost,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { Response } from 'express';
|
||||
|
||||
@Catch(UnauthorizedException)
|
||||
export class AuthExceptionFilter implements ExceptionFilter {
|
||||
catch(exception: UnauthorizedException, host: ArgumentsHost) {
|
||||
const ctx = host.switchToHttp();
|
||||
const response = ctx.getResponse<Response>();
|
||||
|
||||
const status = exception.getStatus();
|
||||
const message = exception.message || 'Unauthorized';
|
||||
|
||||
// Check if message matches specific condition
|
||||
if (message.toLocaleLowerCase() === 'authentication failed') {
|
||||
// Clear cookies
|
||||
response.clearCookie('access_token', {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none',
|
||||
});
|
||||
|
||||
response.clearCookie('refresh_token', {
|
||||
httpOnly: true,
|
||||
secure: true,
|
||||
sameSite: 'none',
|
||||
});
|
||||
|
||||
// Send custom response
|
||||
return response.status(status).json({
|
||||
statusCode: status,
|
||||
message: 'Authentication failed',
|
||||
});
|
||||
}
|
||||
|
||||
// If not a match, fallback to default response
|
||||
return response.status(status).json({
|
||||
statusCode: status,
|
||||
message,
|
||||
});
|
||||
}
|
||||
}
|
||||
48
src/guards/jwt-auth.guard.ts
Normal file
48
src/guards/jwt-auth.guard.ts
Normal file
@ -0,0 +1,48 @@
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
UnauthorizedException,
|
||||
Global,
|
||||
} from '@nestjs/common';
|
||||
import { AuthService } from 'src/auth/auth.service';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import { InternalServerException } from 'src/exceptions/internalServerError.exception';
|
||||
import { UnauthorizedException as UE } from 'src/exceptions/unauthorized.exception';
|
||||
import { MailTypeDTO } from 'src/auth/auth.dto';
|
||||
|
||||
@Global()
|
||||
@Injectable()
|
||||
export class JwtAuthGuard implements CanActivate {
|
||||
constructor(private readonly authService: AuthService) { }
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = request.cookies?.access_token;
|
||||
|
||||
const body = request.body;
|
||||
if (body?.P_MAIL_TYPE && body?.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Authentication failed');
|
||||
}
|
||||
try {
|
||||
const verifiedUser = await this.authService.decodeToken(token);
|
||||
request.user = verifiedUser;
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error instanceof jwt.TokenExpiredError || error instanceof jwt.JsonWebTokenError || error instanceof jwt.NotBeforeError) {
|
||||
throw new UnauthorizedException('Invalid Token');
|
||||
}
|
||||
|
||||
if (error instanceof UnauthorizedException || error instanceof UE) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
throw new InternalServerException();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
36
src/guards/register.guard.ts
Normal file
36
src/guards/register.guard.ts
Normal file
@ -0,0 +1,36 @@
|
||||
// jwt-auth.guard.ts
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Inject,
|
||||
Injectable,
|
||||
UnauthorizedException,
|
||||
} from '@nestjs/common';
|
||||
import { JwtService } from '@nestjs/jwt';
|
||||
import { Request } from 'express';
|
||||
|
||||
@Injectable()
|
||||
export class RegisterGuard implements CanActivate {
|
||||
constructor(
|
||||
@Inject("REGISTER_VERIFY_JWT") readonly REGISTER_VERIFY_JWT: JwtService
|
||||
) { }
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
const authHeader = request.headers['authorization'];
|
||||
|
||||
if (!authHeader || !authHeader.startsWith('Bearer ')) {
|
||||
throw new UnauthorizedException('Invalid Request');
|
||||
}
|
||||
|
||||
const token = authHeader.split(' ')[1];
|
||||
|
||||
try {
|
||||
const payload = this.REGISTER_VERIFY_JWT.verify(token);
|
||||
request['user'] = payload;
|
||||
return true;
|
||||
} catch (err) {
|
||||
throw new UnauthorizedException("Invalid Register Token");
|
||||
}
|
||||
}
|
||||
}
|
||||
52
src/guards/roles.guard.ts
Normal file
52
src/guards/roles.guard.ts
Normal file
@ -0,0 +1,52 @@
|
||||
// roles.guard.ts
|
||||
import {
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { ROLES_KEY } from '../decorators/roles.decorator';
|
||||
import * as jwt from 'jsonwebtoken';
|
||||
import { UnauthorizedException } from 'src/exceptions/unauthorized.exception';
|
||||
import { MailTypeDTO } from 'src/auth/auth.dto';
|
||||
|
||||
@Injectable()
|
||||
export class RolesGuard implements CanActivate {
|
||||
constructor(private reflector: Reflector) { }
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const requiredRoles = this.reflector.getAllAndOverride<string[]>(ROLES_KEY, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (!requiredRoles || requiredRoles.length === 0) return true;
|
||||
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const token = request.cookies?.access_token; // Token is stored as HttpOnly cookie
|
||||
|
||||
const body = request.body;
|
||||
if (body?.P_MAIL_TYPE && body?.P_MAIL_TYPE === MailTypeDTO.FORGOT_PASSWORD) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!token) {
|
||||
throw new UnauthorizedException('Authentication Failed');
|
||||
}
|
||||
|
||||
try {
|
||||
const decoded: any = jwt.decode(token);
|
||||
|
||||
const roles: string[] = decoded?.resource_access?.['carnet-app']?.roles || [];
|
||||
const hasRole = requiredRoles.some(role => roles.includes(role));
|
||||
|
||||
if (!hasRole) {
|
||||
throw new ForbiddenException('Unauthorized : Please Request Access for this Resource');
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
throw new UnauthorizedException('Authentication Failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
39
src/interceptors/logout.interceptor.ts
Normal file
39
src/interceptors/logout.interceptor.ts
Normal file
@ -0,0 +1,39 @@
|
||||
// refresh-token.interceptor.ts
|
||||
import {
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
ExecutionContext,
|
||||
CallHandler,
|
||||
} from '@nestjs/common';
|
||||
import { Observable, of } from 'rxjs';
|
||||
|
||||
@Injectable()
|
||||
export class LogoutInterceptor implements NestInterceptor {
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
const response = context.switchToHttp().getResponse();
|
||||
|
||||
const refreshToken = request.cookies?.refresh_token;
|
||||
|
||||
if (!refreshToken) {
|
||||
// Send a custom 200 response when refresh token is missing
|
||||
response.clearCookie('access_token');
|
||||
response.clearCookie('refresh_token');
|
||||
response.status(200).json({
|
||||
statusCode: 200,
|
||||
message: 'Logged-Out successfully',
|
||||
});
|
||||
|
||||
// Prevent further handling
|
||||
return of(null);
|
||||
}
|
||||
|
||||
// Attach refresh token to request object for later use
|
||||
request.user = {
|
||||
...(request.user || {}),
|
||||
refreshToken,
|
||||
};
|
||||
|
||||
return next.handle();
|
||||
}
|
||||
}
|
||||
49
src/mail/mail.module.ts
Normal file
49
src/mail/mail.module.ts
Normal file
@ -0,0 +1,49 @@
|
||||
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ConfigModule, ConfigService } from '@nestjs/config';
|
||||
import { join } from 'path';
|
||||
import * as Joi from 'joi';
|
||||
import { MailService } from './mail.service';
|
||||
import * as nodemailer from 'nodemailer';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({
|
||||
isGlobal: true,
|
||||
validationSchema: Joi.object({
|
||||
MAIL_USER: Joi.string().required(),
|
||||
MAIL_PASS: Joi.string().required(),
|
||||
}),
|
||||
}),
|
||||
],
|
||||
|
||||
providers: [
|
||||
{
|
||||
provide: 'MAIL_TRANSPORTER',
|
||||
useFactory: async (configService: ConfigService) => {
|
||||
return nodemailer.createTransport(
|
||||
{
|
||||
// service: "gmail",
|
||||
host: 'smtp.gmail.com',
|
||||
port: 587,
|
||||
secure: false,
|
||||
auth: {
|
||||
user: configService.get<string>('MAIL_USER'),
|
||||
pass: configService.get<string>('MAIL_PASS'),
|
||||
},
|
||||
},
|
||||
{
|
||||
from: `"Carnet APP" <${configService.get<string>('MAIL_USER')}>`,
|
||||
}
|
||||
);
|
||||
},
|
||||
inject: [ConfigService],
|
||||
},
|
||||
MailService,
|
||||
],
|
||||
exports: [MailService],
|
||||
|
||||
|
||||
})
|
||||
|
||||
export class MailModule { }
|
||||
42
src/mail/mail.service.ts
Normal file
42
src/mail/mail.service.ts
Normal 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);
|
||||
}
|
||||
}
|
||||
23
src/main.ts
23
src/main.ts
@ -7,36 +7,41 @@ import {
|
||||
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
|
||||
import { SwaggerDocumentOptions } from '@nestjs/swagger';
|
||||
import { BadRequestException } from './exceptions/badRequest.exception';
|
||||
import * as cookieParser from 'cookie-parser';
|
||||
import { AuthExceptionFilter } from './filters/auth-exception.filter';
|
||||
|
||||
async function bootstrap() {
|
||||
const app = await NestFactory.create(AppModule, {
|
||||
logger: ['error', 'warn'],
|
||||
cors: {
|
||||
// origin: 'https://dev.alphaomegainfosys.com/',
|
||||
origin: '*',
|
||||
origin: [
|
||||
'http://localhost:3000',
|
||||
'http://localhost:5173',
|
||||
'https://policy.alphaomegainfosys.com',
|
||||
'https://sp.alphaomegainfosys.com',
|
||||
'https://client.alphaomegainfosys.com'
|
||||
],
|
||||
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE',
|
||||
preflightContinue: false,
|
||||
optionsSuccessStatus: 204,
|
||||
credentials: true,
|
||||
},
|
||||
});
|
||||
|
||||
app.use(cookieParser());
|
||||
|
||||
app.useGlobalFilters(new AuthExceptionFilter());
|
||||
|
||||
|
||||
function extractConstraints(validationErrors: ValidationError[]) {
|
||||
const constraints: { [key: string]: string }[] = [];
|
||||
|
||||
function traverse(errors: ValidationError[]) {
|
||||
// console.log(errors);
|
||||
// console.log("--------------");
|
||||
for (const error of errors) {
|
||||
// If the error has constraints, add them to the list
|
||||
|
||||
// console.log(error);
|
||||
// console.log("--------------");
|
||||
|
||||
if (error.constraints) {
|
||||
constraints.push(error.constraints);
|
||||
}
|
||||
// // If there are children, recursively traverse them
|
||||
if (error.children && error.children.length > 0) {
|
||||
traverse(error.children);
|
||||
}
|
||||
|
||||
@ -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,12 +196,12 @@ export class ManageClientsService {
|
||||
...reqBody,
|
||||
};
|
||||
|
||||
let connection: Connection;
|
||||
let connection: mssql.ConnectionPool;
|
||||
try {
|
||||
connection = await this.mssqlDBService.getConnection();
|
||||
const request = new Request(connection);
|
||||
request.input('P_SPID', mssql.Int, finalBody.P_SPID);
|
||||
request.input('P_CLIENTID', mssql.Int, finalBody.P_CLIENTID);
|
||||
request.input('P_LOCATIONID', mssql.Int, finalBody.P_LOCATIONID);
|
||||
|
||||
const contactTable = new mssql.Table('carnetsys.ContactsTable');
|
||||
contactTable.create = true;
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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();
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -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);
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Patch, Post, Put } from '@nestjs/common';
|
||||
import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Res, StreamableFile, UseGuards } from '@nestjs/common';
|
||||
import { CarnetApplicationService } from './carnet-application.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ -7,13 +7,21 @@ import {
|
||||
AddCountriesDTO,
|
||||
AddGenerallistItemsDTO,
|
||||
CA_UpdateHolderDTO,
|
||||
CarnetProcessingCenterDTO, CreateApplicationDTO, SaveCarnetApplicationDTO, TransmitApplicationtoProcessDTO,
|
||||
CarnetProcessingCenterDTO, CreateApplicationDTO, DeleteGenerallistItemsDTO, GetCarnetControlCenterDTO, PrintCarnetDTO, SaveCarnetApplicationDTO, 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';
|
||||
|
||||
|
||||
@ApiTags('Carnet Application - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('ca', 'sa')
|
||||
@Controller('oracle')
|
||||
export class CarnetApplicationController {
|
||||
|
||||
@ -27,11 +35,13 @@ export class CarnetApplicationController {
|
||||
}
|
||||
|
||||
@Post('TransmitApplicationtoProcess')
|
||||
@Roles('ca')
|
||||
TransmitApplicationtoProcess(@Body() body: TransmitApplicationtoProcessDTO) {
|
||||
return this.carnetApplicationService.TransmitApplicationtoProcess(body);
|
||||
}
|
||||
|
||||
@Post('CreateApplication')
|
||||
@Roles('ca')
|
||||
CreateApplication(@Body() body: CreateApplicationDTO) {
|
||||
return this.carnetApplicationService.CreateApplication(body);
|
||||
}
|
||||
@ -56,31 +66,111 @@ export class CarnetApplicationController {
|
||||
return this.carnetApplicationService.AddCountries(body);
|
||||
}
|
||||
|
||||
@Put('EditGenerallistItems')
|
||||
EditGenerallistItems(@Body() body: AddGenerallistItemsDTO) {
|
||||
return this.carnetApplicationService.EditGenerallistItems(body);
|
||||
}
|
||||
|
||||
@Delete('DeleteGenerallistItems')
|
||||
DeleteGenerallistItems(@Body() body: DeleteGenerallistItemsDTO) {
|
||||
return this.carnetApplicationService.DeleteGenerallistItems(body);
|
||||
}
|
||||
|
||||
@Patch('UpdateShippingDetails')
|
||||
UpdateShippingDetails(@Body() body: UpdateShippingDetailsDTO) {
|
||||
return this.carnetApplicationService.UpdateShippingDetails(body);
|
||||
}
|
||||
|
||||
@Get('EstimatedFees/:P_SPID/:P_USERID/:P_HEADERID')
|
||||
EstimatedFees(@Param() body: GetCarnetControlCenterDTO) {
|
||||
return this.carnetApplicationService.EstimatedFees(body);
|
||||
}
|
||||
|
||||
// processing [ PROCESSINGCENTER_PKG ]
|
||||
|
||||
@Patch('ProcessOriginalCarnet')
|
||||
@Patch('ProcessCarnet')
|
||||
ProcessOriginalCarnet(@Body() body: CarnetProcessingCenterDTO) {
|
||||
return this.carnetApplicationService.ProcessOriginalCarnet(body);
|
||||
return this.carnetApplicationService.ProcessCarnet(body);
|
||||
}
|
||||
|
||||
@Patch('UpdatePrintCarnet')
|
||||
UpdatePrintCarnet(@Body() body: CarnetProcessingCenterDTO) {
|
||||
return this.carnetApplicationService.UpdatePrintCarnet(body);
|
||||
}
|
||||
|
||||
@Patch('VoidCarnet')
|
||||
@Roles('sa')
|
||||
VoidCarnet(@Body() body: CarnetProcessingCenterDTO) {
|
||||
return this.carnetApplicationService.VoidCarnet(body);
|
||||
}
|
||||
|
||||
@Patch('DuplicateCarnet')
|
||||
@Roles('ca')
|
||||
DuplicateCarnet(@Body() body: CarnetProcessingCenterDTO) {
|
||||
return this.carnetApplicationService.DuplicateCarnet(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')
|
||||
GetHolderstoEdit(@Param() body: GetCarnetControlCenterDTO) {
|
||||
return this.carnetApplicationService.GetHolderstoEdit(body);
|
||||
}
|
||||
|
||||
@Get('GetGoodsDetailstoEdit/:P_SPID/:P_USERID/:P_HEADERID')
|
||||
GetGoodsDetailstoEdit(@Param() body: GetCarnetControlCenterDTO) {
|
||||
return this.carnetApplicationService.GetGoodsDetailstoEdit(body);
|
||||
}
|
||||
|
||||
@Get('GetGoodsItemstoEdit/:P_SPID/:P_USERID/:P_HEADERID')
|
||||
GetGoodsItemstoEdit(@Param() body: GetCarnetControlCenterDTO) {
|
||||
return this.carnetApplicationService.GetGoodsItemstoEdit(body);
|
||||
}
|
||||
|
||||
@Get('GetCountryDetailstoEdit/:P_SPID/:P_USERID/:P_HEADERID')
|
||||
GetCountryDetailstoEdit(@Param() body: GetCarnetControlCenterDTO) {
|
||||
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')
|
||||
@Roles('ca', 'sa', 'ua')
|
||||
async PrintCarnet(@Body() body: PrintCarnetDTO, @Res({ passthrough: true }) res: Response) {
|
||||
try {
|
||||
await this.carnetApplicationService.PrintCarnet(body);
|
||||
|
||||
const filePath = join(process.cwd(), 'public/carnet-pdf', 'carnet.pdf');
|
||||
|
||||
res.set({
|
||||
'Content-Type': 'application/pdf',
|
||||
'Content-Disposition': `attachment; filename="${'carnet.pdf'}"`,
|
||||
});
|
||||
const file = createReadStream(filePath);
|
||||
return new StreamableFile(file);
|
||||
} catch (error) {
|
||||
return error.message
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CarnetApplicationController } from './carnet-application.controller';
|
||||
import { CarnetApplicationService } from './carnet-application.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [CarnetApplicationController],
|
||||
providers: [CarnetApplicationService]
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@ -2,6 +2,7 @@ import {
|
||||
Get,
|
||||
Param,
|
||||
Controller,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
|
||||
import { HomePageService } from './home-page.service';
|
||||
@ -12,8 +13,13 @@ import {
|
||||
SPID_DTO,
|
||||
USERID_DTO
|
||||
} 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('HomePage - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('ca', 'sa', 'ua')
|
||||
@Controller('oracle')
|
||||
export class HomePageController {
|
||||
constructor(private readonly homePageService: HomePageService) { }
|
||||
@ -33,18 +39,4 @@ export class HomePageController {
|
||||
GetCarnetDetailsbyCarnetStatus(@Param() params: GetCarnetDetailsbyCarnetStatusDTO) {
|
||||
return this.homePageService.GetCarnetDetailsbyCarnetStatus(params);
|
||||
}
|
||||
|
||||
// NOTE : this has been moved to carent-application module
|
||||
|
||||
// @Post('/oracle/SaveCarnetApplication')
|
||||
// SaveCarnetApplication(@Body() body: SaveCarnetApplicationDTO) {
|
||||
// return this.homePageService.SaveCarnetApplication(body);
|
||||
// }
|
||||
|
||||
// NOTE : this has been moved to carent-application module
|
||||
|
||||
// @Post('/oracle/TransmitApplicationtoProcess')
|
||||
// TransmitApplicationtoProcess(@Body() body: TransmitApplicationtoProcessDTO) {
|
||||
// return this.homePageService.TransmitApplicationtoProcess(body);
|
||||
// }
|
||||
}
|
||||
|
||||
@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
|
||||
import { HomePageService } from './home-page.service';
|
||||
import { HomePageController } from './home-page.controller';
|
||||
import { DbModule } from 'src/db/db.module';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [DbModule],
|
||||
imports: [DbModule,AuthModule],
|
||||
providers: [HomePageService],
|
||||
controllers: [HomePageController],
|
||||
})
|
||||
|
||||
@ -120,7 +120,59 @@ export class HomePageService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return fres;
|
||||
// Step 1: Replace spaces in keys
|
||||
const mappedRows = fres.map((obj) => {
|
||||
const newObj = {};
|
||||
for (const key in obj) {
|
||||
const newKey = key.replace(/ /g, '_');
|
||||
newObj[newKey] = obj[key];
|
||||
}
|
||||
return newObj;
|
||||
});
|
||||
|
||||
// Step 2: Group and aggregate
|
||||
const reducedRows = mappedRows.reduce((acc, curr) => {
|
||||
let existing;
|
||||
|
||||
if (curr.Service_Provider_Name && curr.SPID) {
|
||||
existing = acc.find(
|
||||
(item) =>
|
||||
item.Service_Provider_Name === curr.Service_Provider_Name &&
|
||||
item.SPID === curr.SPID
|
||||
);
|
||||
} else if (curr.Preparer_Name && curr.CLIENTID) {
|
||||
existing = acc.find(
|
||||
(item) =>
|
||||
item.Preparer_Name === curr.Preparer_Name &&
|
||||
item.CLIENTID === curr.CLIENTID
|
||||
);
|
||||
}
|
||||
|
||||
if (existing) {
|
||||
existing.CARNETSTATUS.push(curr.CARNETSTATUS);
|
||||
existing.Carnet_Count.push(curr.Carnet_Count);
|
||||
} else {
|
||||
const newItem = {
|
||||
CARNETSTATUS: [curr.CARNETSTATUS],
|
||||
Carnet_Count: [curr.Carnet_Count],
|
||||
};
|
||||
|
||||
if (curr.Service_Provider_Name && curr.SPID) {
|
||||
newItem['Service_Provider_Name'] = curr.Service_Provider_Name;
|
||||
newItem['SPID'] = curr.SPID;
|
||||
} else if (curr.Preparer_Name && curr.CLIENTID) {
|
||||
newItem['Preparer_Name'] = curr.Preparer_Name;
|
||||
newItem['CLIENTID'] = curr.CLIENTID;
|
||||
}
|
||||
|
||||
acc.push(newItem);
|
||||
}
|
||||
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
|
||||
return reducedRows;
|
||||
} catch (error) {
|
||||
handleError(error, HomePageService.name)
|
||||
} finally {
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Put, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Patch, Post, Put, Query, UseGuards } from '@nestjs/common';
|
||||
import { ManageClientsService } from './manage-clients.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ -6,88 +6,95 @@ import {
|
||||
ClientContactControlsDTO,
|
||||
CreateClientContactsDTO, CreateClientDataDTO,
|
||||
CreateClientLocationsDTO,
|
||||
GetClientContactByLacationIdDTO,
|
||||
GetClientDTO,
|
||||
GetPreparersParamDTO, GetPreparersQueryDTO, UpdateClientContactsDTO, UpdateClientDTO, UpdateClientLocationsDTO
|
||||
} 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('Manage Clients - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('sa')
|
||||
@Controller('oracle')
|
||||
export class ManageClientsController {
|
||||
constructor(private readonly manageClientsService: ManageClientsService) { }
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
|
||||
@Post('CreateNewClients')
|
||||
async CreateClientData(@Body() body: CreateClientDataDTO) {
|
||||
return this.manageClientsService.CreateClientData(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Put('UpdateClient')
|
||||
async UpdateClient(@Body() body: UpdateClientDTO) {
|
||||
return this.manageClientsService.UpdateClient(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Put('UpdateClientContacts')
|
||||
@Roles('ca','sa')
|
||||
UpdateClientContacts(@Body() body: UpdateClientContactsDTO) {
|
||||
return this.manageClientsService.UpdateClientContacts(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Put('UpdateClientLocations')
|
||||
@Roles('ca','sa')
|
||||
UpdateClientLocations(@Body() body: UpdateClientLocationsDTO) {
|
||||
return this.manageClientsService.UpdateClientLocations(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Post('CreateClientContacts')
|
||||
@Roles('ca','sa')
|
||||
CreateClientContact(@Body() body: CreateClientContactsDTO) {
|
||||
return this.manageClientsService.CreateClientContact(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Patch('SetDefaultClientContacts/:P_SPID/:P_CLIENTCONTACTID/:P_USERID')
|
||||
SetDefaultClientContacts(@Param() param: ClientContactControlsDTO) {
|
||||
return this.manageClientsService.SetDefaultClientContacts(param);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Patch('InactivateClientContacts/:P_SPID/:P_CLIENTCONTACTID/:P_USERID')
|
||||
InactivateClientContacts(@Param() param: ClientContactControlsDTO) {
|
||||
return this.manageClientsService.InactivateClientContacts(param);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Patch('ReactivateClientContacts/:P_SPID/:P_CLIENTCONTACTID/:P_USERID')
|
||||
ReactivateClientContacts(@Param() param: ClientContactControlsDTO) {
|
||||
return this.manageClientsService.ReactivateClientContacts(param);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Post('CreateClientLocations')
|
||||
@Roles('ca','sa')
|
||||
CreateClientLocation(@Body() body: CreateClientLocationsDTO) {
|
||||
return this.manageClientsService.CreateClientLocation(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Get('GetPreparers/:P_SPID/:P_STATUS')
|
||||
async GetPreparers(@Param() param: GetPreparersParamDTO, @Query() query: GetPreparersQueryDTO) {
|
||||
return await this.manageClientsService.GetPreparers({ ...param, ...query });
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Get('GetPreparerByClientid/:P_SPID/:P_CLIENTID')
|
||||
GetPreparerByClientid(@Param() body: GetClientDTO) {
|
||||
return this.manageClientsService.GetPreparerByClientid(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Get('GetPreparerContactsByClientid/:P_SPID/:P_CLIENTID')
|
||||
@Roles('ca','sa')
|
||||
GetPreparerContactsByClientid(@Param() body: GetClientDTO) {
|
||||
return this.manageClientsService.GetPreparerContactsByClientid(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Clients - Oracle')
|
||||
@Get('GetPreparerContactsbyClientLocationID/:P_SPID/:P_LOCATIONID')
|
||||
@Roles('ca','sa')
|
||||
GetPreparerContactsbyClientLocationID(@Param() body: GetClientContactByLacationIdDTO) {
|
||||
return this.manageClientsService.GetPreparerContactsbyClientLocationID(body);
|
||||
}
|
||||
|
||||
@Get('GetPreparerLocByClientid/:P_SPID/:P_CLIENTID')
|
||||
@Roles('ca','sa')
|
||||
GetPreparerLocByClientid(@Param() body: GetClientDTO) {
|
||||
return this.manageClientsService.GetPreparerLocByClientid(body);
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ManageClientsController } from './manage-clients.controller';
|
||||
import { ManageClientsService } from './manage-clients.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [ManageClientsController],
|
||||
providers: [ManageClientsService],
|
||||
})
|
||||
|
||||
@ -10,6 +10,7 @@ import {
|
||||
ClientContactControlsDTO,
|
||||
CreateClientContactsDTO, CreateClientDataDTO,
|
||||
CreateClientLocationsDTO,
|
||||
GetClientContactByLacationIdDTO,
|
||||
GetClientDTO,
|
||||
GetPreparersDTO, UpdateClientContactsDTO, UpdateClientDTO, UpdateClientLocationsDTO,
|
||||
} from 'src/dto/property.dto';
|
||||
@ -351,12 +352,12 @@ export class ManageClientsService {
|
||||
const result = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEPREPARER_PKG.CreateClientContact(
|
||||
:P_SPID, :P_CLIENTID, :P_CONTACTSTABLE, :P_DEFCONTACTFLAG, :P_USERID, :P_CURSOR
|
||||
:P_SPID, :P_LOCATIONID, :P_CONTACTSTABLE, :P_DEFCONTACTFLAG, :P_USERID, :P_CURSOR
|
||||
);
|
||||
END;`,
|
||||
{
|
||||
P_SPID: { val: finalBody.P_SPID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_CLIENTID: { val: finalBody.P_CLIENTID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_LOCATIONID: { val: finalBody.P_LOCATIONID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_CONTACTSTABLE: { val: CONTACTSTABLE_INSTANCE, type: oracledb.DB_TYPE_OBJECT },
|
||||
P_DEFCONTACTFLAG: { val: finalBody.P_DEFCONTACTFLAG, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_USERID: { val: finalBody.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
@ -672,7 +673,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)
|
||||
@ -718,6 +721,43 @@ export class ManageClientsService {
|
||||
}
|
||||
};
|
||||
|
||||
GetPreparerContactsbyClientLocationID = async (body: GetClientContactByLacationIdDTO) => {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
connection = await this.oracleDBService.getConnection();
|
||||
|
||||
const result = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEPREPARER_PKG.GetPreparerContactsByClientid(
|
||||
:P_SPID, :P_LOCATIONID, :P_CURSOR
|
||||
);
|
||||
END;`,
|
||||
{
|
||||
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_LOCATIONID: { val: body.P_LOCATIONID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
|
||||
},
|
||||
{
|
||||
outFormat: oracledb.OUT_FORMAT_OBJECT,
|
||||
},
|
||||
);
|
||||
|
||||
const outBinds: any = 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, ManageClientsService.name);
|
||||
|
||||
} catch (error) {
|
||||
handleError(error, ManageClientsService.name)
|
||||
} finally {
|
||||
await closeOracleDbConnection(connection, ManageClientsService.name)
|
||||
}
|
||||
}
|
||||
|
||||
GetPreparerLocByClientid = async (body: GetClientDTO) => {
|
||||
let connection;
|
||||
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { ManageFeeService } from './manage-fee.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ -7,134 +7,120 @@ import {
|
||||
CreateEfFeeDTO, CreateFeeCommDTO, GetFeeGeneralDTO, UpdateBasicFeeDTO, UpdateBondRateDTO,
|
||||
UpdateCargoRateDTO, UpdateCfFeeDTO, UpdateCsFeeDTO, UpdateEfFeeDTO, UpdateFeeCommDTO
|
||||
} 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('Manage Fee - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('sa','ua')
|
||||
@Controller('oracle')
|
||||
export class ManageFeeController {
|
||||
constructor(private readonly manageFeeService: ManageFeeService) { }
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetBasicFeeRates/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetBasicFeeRates(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETBASICFEERATES(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetBondRates/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetBondRates(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETBONDRATES(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetCargoRates/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetCargoRates(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETCARGORATES(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetCfFeeRates/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetCfFeeRates(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETCFFEERATES(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetCsFeeRates/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetCsFeeRates(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETCSFEERATES(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetEfFeeRates/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetEfFeeRates(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETEFFEERATES(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Get('/GetFeeComm/:P_SPID/:P_ACTIVE_INACTIVE')
|
||||
GetFeeComm(@Param() body: GetFeeGeneralDTO) {
|
||||
return this.manageFeeService.GETFEECOMM(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateBasicFee')
|
||||
CreateBasicFee(@Body() body: CreateBasicFeeDTO) {
|
||||
return this.manageFeeService.CREATEBASICFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateBondRate')
|
||||
CreateBondRate(@Body() body: CreateBondRateDTO) {
|
||||
return this.manageFeeService.CREATEBONDRATE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateCargoRate')
|
||||
CreateCargoRate(@Body() body: CreateCargoRateDTO) {
|
||||
return this.manageFeeService.CREATECARGORATE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateCfFee')
|
||||
CreateCfFee(@Body() body: CreateCfFeeDTO) {
|
||||
return this.manageFeeService.CREATECFFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateCsFee')
|
||||
CreateCsFee(@Body() body: CreateCsFeeDTO) {
|
||||
return this.manageFeeService.CREATECSFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateEfFee')
|
||||
CreateEeFee(@Body() body: CreateEfFeeDTO) {
|
||||
return this.manageFeeService.CREATEEFFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Post('/CreateFeeComm')
|
||||
CreateFeeComm(@Body() body: CreateFeeCommDTO) {
|
||||
return this.manageFeeService.CREATEFEECOMM(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateBasicFee')
|
||||
UpdateBasicFee(@Body() body: UpdateBasicFeeDTO) {
|
||||
return this.manageFeeService.UPDATEBASICFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateBondRate')
|
||||
UpdateBondRate(@Body() body: UpdateBondRateDTO) {
|
||||
return this.manageFeeService.UPDATEBONDRATE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateCargoRate')
|
||||
UpdateCargoRate(@Body() body: UpdateCargoRateDTO) {
|
||||
return this.manageFeeService.UPDATECARGORATE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateCfFee')
|
||||
UpdateCfFee(@Body() body: UpdateCfFeeDTO) {
|
||||
return this.manageFeeService.UPDATECFFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateCsFee')
|
||||
UpdateCsFee(@Body() body: UpdateCsFeeDTO) {
|
||||
return this.manageFeeService.UPDATECSFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateEfFee')
|
||||
UpdateEfFee(@Body() body: UpdateEfFeeDTO) {
|
||||
return this.manageFeeService.UPDATEEFFEE(body);
|
||||
}
|
||||
|
||||
@ApiTags('Manage Fee - Oracle')
|
||||
@Patch('/UpdateFeeComm')
|
||||
UpdateFeeComm(@Body() body: UpdateFeeCommDTO) {
|
||||
return this.manageFeeService.UPDATEFEECOMM(body);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ManageFeeController } from './manage-fee.controller';
|
||||
import { ManageFeeService } from './manage-fee.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [ManageFeeController],
|
||||
providers: [ManageFeeService],
|
||||
})
|
||||
|
||||
@ -1,5 +1,4 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
@ -8,31 +7,66 @@ import {
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UseGuards,
|
||||
} from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { ApiQuery, ApiTags } from '@nestjs/swagger';
|
||||
import { ManageHoldersService } from './manage-holders.service';
|
||||
|
||||
import {
|
||||
CreateHolderContactsDTO,
|
||||
CreateHoldersDTO, GetHolderDTO, HolderActivateOrInactivateDTO,
|
||||
HolderContactActivateOrInactivateDTO, SearchHolderDTO, UpdateHolderContactDTO, UpdateHolderDTO
|
||||
HolderContactActivateOrInactivateDTO, SearchHolderDTO, SPID_DTO, UpdateHolderContactDTO, UpdateHolderDTO
|
||||
} 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 { BadRequestException } from 'src/exceptions/badRequest.exception';
|
||||
|
||||
@ApiTags('Manage Holders - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('ca', 'sa')
|
||||
@Controller('oracle')
|
||||
export class ManageHoldersController {
|
||||
constructor(private readonly manageHoldersService: ManageHoldersService) { }
|
||||
|
||||
@Get('SearchHolder/:P_SPID/:P_HOLDERNAME')
|
||||
SearchHolder(@Param() param: SearchHolderDTO) {
|
||||
return this.manageHoldersService.SearchHolder(param)
|
||||
@Get('SearchHolder/:P_SPID/:P_USERID')
|
||||
@ApiQuery({ name: "P_HOLDERNAME", type: String, required: false, description: "Optional" })
|
||||
SearchHolder(
|
||||
@Param('P_SPID') P_SPID: number,
|
||||
@Param('P_USERID') P_USERID: string,
|
||||
@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){
|
||||
return new BadRequestException();
|
||||
}
|
||||
const body = { P_SPID,P_USERID,P_HOLDERNAME: rawHolderName }
|
||||
return this.manageHoldersService.SearchHolder(body)
|
||||
}
|
||||
|
||||
@Post('/CreateHolderData')
|
||||
CreateHolders(@Body() body: CreateHoldersDTO) {
|
||||
return this.manageHoldersService.CreateHolders(body);
|
||||
// return this.manageHoldersService.CreateHoldersX();
|
||||
// return {message:"Request received.."}
|
||||
}
|
||||
|
||||
@Post('CreateHoldercontact')
|
||||
|
||||
@ -2,10 +2,11 @@ import { Module } from '@nestjs/common';
|
||||
import { ManageHoldersService } from './manage-holders.service';
|
||||
import { ManageHoldersController } from './manage-holders.controller';
|
||||
import { DbModule } from 'src/db/db.module';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [DbModule],
|
||||
imports: [DbModule, AuthModule],
|
||||
providers: [ManageHoldersService],
|
||||
controllers: [ManageHoldersController],
|
||||
controllers: [ManageHoldersController]
|
||||
})
|
||||
export class ManageHoldersModule {}
|
||||
export class ManageHoldersModule { }
|
||||
|
||||
@ -8,7 +8,7 @@ import { closeOracleDbConnection, fetchCursor, handleError, setEmptyStringsToNul
|
||||
import {
|
||||
CreateHolderContactsDTO,
|
||||
CreateHoldersDTO, GetHolderDTO, HolderActivateOrInactivateDTO,
|
||||
HolderContactActivateOrInactivateDTO, SearchHolderDTO, UpdateHolderContactDTO, UpdateHolderDTO
|
||||
HolderContactActivateOrInactivateDTO, SearchHolderDTO, SPID_DTO, UpdateHolderContactDTO, UpdateHolderDTO
|
||||
} from 'src/dto/property.dto';
|
||||
import { OracleService } from '../oracle.service';
|
||||
import { BadRequestException } from 'src/exceptions/badRequest.exception';
|
||||
@ -64,7 +64,7 @@ export class ManageHoldersService {
|
||||
:P_USCIBMEMBERFLAG, :P_GOVAGENCYFLAG, :P_HOLDERNAME, :P_NAMEQUALIFIER,
|
||||
:P_ADDLNAME, :P_ADDRESS1, :P_ADDRESS2, :P_CITY,
|
||||
:P_STATE, :P_ZIP, :P_COUNTRY, :P_USERID,
|
||||
:P_CONTACTSTABLE, :P_HOLDERCURSOR, :P_HOLDERCONTACTCURSOR
|
||||
:P_HOLDERCURSOR
|
||||
);
|
||||
END;`,
|
||||
{
|
||||
@ -86,7 +86,7 @@ export class ManageHoldersService {
|
||||
P_USERID: { val: finalBody.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
// P_CONTACTSTABLE: { val: CONTACTSTABLE_INSTANCE, type: oracledb.DB_TYPE_OBJECT },
|
||||
P_HOLDERCURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT },
|
||||
P_HOLDERCONTACTCURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
|
||||
// P_HOLDERCONTACTCURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
|
||||
},
|
||||
{ outFormat: oracledb.OUT_FORMAT_OBJECT }
|
||||
);
|
||||
@ -94,7 +94,7 @@ export class ManageHoldersService {
|
||||
await connection.commit();
|
||||
|
||||
const outBinds: any = result.outBinds;
|
||||
if (!outBinds?.P_HOLDERCURSOR || !outBinds?.P_HOLDERCONTACTCURSOR) {
|
||||
if (!outBinds?.P_HOLDERCURSOR) {
|
||||
this.logger.error('One or more expected cursors are missing from stored procedure output.');
|
||||
throw new InternalServerException("Incomplete data received from the database.");
|
||||
}
|
||||
@ -103,19 +103,21 @@ export class ManageHoldersService {
|
||||
// throw new InternalServerException("Incomplete data received from the database.");
|
||||
// }
|
||||
|
||||
// const fres: any = await fetchCursor(outBinds.P_CURSOR, ParamTableService.name);
|
||||
const fres: any = await fetchCursor(outBinds.P_HOLDERCURSOR, ManageHoldersService.name);
|
||||
|
||||
// if (fres.length > 0 && fres[0].ERRORMESG) {
|
||||
// this.logger.warn(fres[0].ERRORMESG);
|
||||
// throw new BadRequestException(fres[0].ERRORMESG)
|
||||
// }
|
||||
if (fres.length > 0 && fres[0].ERRORMESG) {
|
||||
this.logger.warn(fres[0].ERRORMESG);
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
// return {
|
||||
// holderDetails: await fetchCursor(outBinds.P_HOLDERCURSOR, ManageHoldersService.name),
|
||||
// holderContactDetails: await fetchCursor(outBinds.P_HOLDERCONTACTCURSOR, ManageHoldersService.name),
|
||||
// }
|
||||
|
||||
return await fetchCursor(outBinds.P_HOLDERCURSOR, ManageHoldersService.name);
|
||||
// return await fetchCursor(outBinds.P_HOLDERCURSOR, ManageHoldersService.name);
|
||||
|
||||
return { statusCode: 201, message: "Created Successfully", ...fres[0] };
|
||||
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
@ -149,7 +151,7 @@ export class ManageHoldersService {
|
||||
|
||||
const result = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEPREPARER_PKG.CreateClientContact(
|
||||
MANAGEHOLDER_PKG.CreateHoldercontact(
|
||||
:P_SPID, :P_HOLDERID, :P_CONTACTSTABLE, :P_USERID, :P_CURSOR
|
||||
);
|
||||
END;`,
|
||||
@ -221,7 +223,7 @@ export class ManageHoldersService {
|
||||
|
||||
const result = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEHOLDER_PKG.UPDATEHOLDERS(
|
||||
MANAGEHOLDER_PKG.UPDATEHOLDER(
|
||||
:P_HOLDERID, :P_SPID, :P_LOCATIONID, :P_HOLDERNO,
|
||||
:P_HOLDERTYPE, :P_USCIBMEMBERFLAG, :P_GOVAGENCYFLAG, :P_HOLDERNAME,
|
||||
:P_NAMEQUALIFIER, :P_ADDLNAME, :P_ADDRESS1, :P_ADDRESS2,
|
||||
@ -230,24 +232,24 @@ export class ManageHoldersService {
|
||||
);
|
||||
END;`,
|
||||
{
|
||||
P_HOLDERID: { VAL: finalBody.P_HOLDERID, TYPE: oracledb.DB_TYPE_NUMBER },
|
||||
P_SPID: { VAL: finalBody.P_SPID, TYPE: oracledb.DB_TYPE_NUMBER },
|
||||
P_LOCATIONID: { VAL: finalBody.P_LOCATIONID, TYPE: oracledb.DB_TYPE_NUMBER },
|
||||
P_HOLDERNO: { VAL: finalBody.P_HOLDERNO, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_HOLDERTYPE: { VAL: finalBody.P_HOLDERTYPE, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_USCIBMEMBERFLAG: { VAL: finalBody.P_USCIBMEMBERFLAG, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_GOVAGENCYFLAG: { VAL: finalBody.P_GOVAGENCYFLAG, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_HOLDERNAME: { VAL: finalBody.P_HOLDERNAME, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_NAMEQUALIFIER: { VAL: finalBody.P_NAMEQUALIFIER, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ADDLNAME: { VAL: finalBody.P_ADDLNAME, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ADDRESS1: { VAL: finalBody.P_ADDRESS1, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ADDRESS2: { VAL: finalBody.P_ADDRESS2, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_CITY: { VAL: finalBody.P_CITY, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_STATE: { VAL: finalBody.P_STATE, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ZIP: { VAL: finalBody.P_ZIP, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_COUNTRY: { VAL: finalBody.P_COUNTRY, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_USERID: { VAL: finalBody.P_USERID, TYPE: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_CURSOR: { TYPE: oracledb.CURSOR, DIR: oracledb.BIND_OUT }
|
||||
P_HOLDERID: { val: finalBody.P_HOLDERID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_SPID: { val: finalBody.P_SPID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_LOCATIONID: { val: finalBody.P_LOCATIONID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_HOLDERNO: { val: finalBody.P_HOLDERNO, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_HOLDERTYPE: { val: finalBody.P_HOLDERTYPE, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_USCIBMEMBERFLAG: { val: finalBody.P_USCIBMEMBERFLAG, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_GOVAGENCYFLAG: { val: finalBody.P_GOVAGENCYFLAG, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_HOLDERNAME: { val: finalBody.P_HOLDERNAME, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_NAMEQUALIFIER: { val: finalBody.P_NAMEQUALIFIER, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ADDLNAME: { val: finalBody.P_ADDLNAME, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ADDRESS1: { val: finalBody.P_ADDRESS1, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ADDRESS2: { val: finalBody.P_ADDRESS2, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_CITY: { val: finalBody.P_CITY, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_STATE: { val: finalBody.P_STATE, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_ZIP: { val: finalBody.P_ZIP, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_COUNTRY: { val: finalBody.P_COUNTRY, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_USERID: { val: finalBody.P_USERID, type: oracledb.DB_TYPE_NVARCHAR },
|
||||
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
|
||||
},
|
||||
{
|
||||
outFormat: oracledb.OUT_FORMAT_OBJECT,
|
||||
@ -268,8 +270,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
|
||||
return { P_cursor: fres };
|
||||
return { statusCode: 200, message: "Updated Successfully", ...fres[0] };
|
||||
|
||||
// return fres
|
||||
} catch (error) {
|
||||
@ -292,9 +293,9 @@ export class ManageHoldersService {
|
||||
);
|
||||
END;`,
|
||||
{
|
||||
P_SPID: { VAL: body.P_SPID, TYPE: oracledb.DB_TYPE_NUMBER },
|
||||
P_HOLDERID: { VAL: body.P_HOLDERID, TYPE: oracledb.DB_TYPE_NUMBER },
|
||||
P_CURSOR: { TYPE: oracledb.CURSOR, DIR: oracledb.BIND_OUT }
|
||||
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_HOLDERID: { val: body.P_HOLDERID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_CURSOR: { type: oracledb.CURSOR, dir: oracledb.BIND_OUT }
|
||||
},
|
||||
{
|
||||
outFormat: oracledb.OUT_FORMAT_OBJECT,
|
||||
@ -302,6 +303,7 @@ export class ManageHoldersService {
|
||||
);
|
||||
|
||||
const outBinds: any = 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.");
|
||||
@ -314,7 +316,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_CURSOR: fres };
|
||||
return fres.length > 0 ? fres[0] : fres;
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
} finally {
|
||||
@ -350,7 +352,7 @@ export class ManageHoldersService {
|
||||
|
||||
const result: Result<any> = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEHOLDER_PKG.UPDATEHOLDERS(
|
||||
MANAGEHOLDER_PKG.UpdateHolderContacts(
|
||||
:P_HOLDERCONTACTID, :P_SPID, :P_FIRSTNAME, :P_LASTNAME,
|
||||
:P_MIDDLEINITIAL, :P_TITLE, :P_PHONENO, :P_MOBILENO,
|
||||
:P_FAXNO, :P_EMAILADDRESS, :P_USERID, :P_CURSOR
|
||||
@ -392,7 +394,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_cursor: fres };
|
||||
return { statusCode: 200, message: "Updated Successfully", ...fres[0] };
|
||||
|
||||
// return fres
|
||||
} catch (error) {
|
||||
@ -437,7 +439,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_CURSOR: fres };
|
||||
return fres;
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
} finally {
|
||||
@ -483,7 +485,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_CURSOR: fres };
|
||||
return { statusCode: 200, message: 'Inactivated holder successfully' };
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
} finally {
|
||||
@ -529,7 +531,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_CURSOR: fres };
|
||||
return { statusCode: 200, message: 'Reactivated holder successfully' };
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
} finally {
|
||||
@ -575,7 +577,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_CURSOR: fres };
|
||||
return { statusCode: 200, message: 'Inactivated holder contact successfully' };
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
} finally {
|
||||
@ -621,7 +623,7 @@ export class ManageHoldersService {
|
||||
throw new BadRequestException(fres[0].ERRORMESG)
|
||||
}
|
||||
|
||||
return { P_CURSOR: fres };
|
||||
return { statusCode: 200, message: 'Reactivated holder contact successfully' };
|
||||
} catch (error) {
|
||||
handleError(error, ManageHoldersService.name)
|
||||
} finally {
|
||||
@ -629,7 +631,7 @@ export class ManageHoldersService {
|
||||
}
|
||||
};
|
||||
|
||||
SearchHolder = async (body: SearchHolderDTO) => {
|
||||
SearchHolder = async (body: { P_SPID: number, P_USERID: string, P_HOLDERNAME: string | null }) => {
|
||||
let connection;
|
||||
|
||||
try {
|
||||
@ -638,12 +640,13 @@ export class ManageHoldersService {
|
||||
const result: Result<any> = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEHOLDER_PKG.SearchHolder(
|
||||
:P_SPID, :P_HOLDERNAME, :P_CURSOR
|
||||
:P_SPID, :P_HOLDERNAME, :P_USERID, :P_CURSOR
|
||||
);
|
||||
END;`,
|
||||
{
|
||||
P_SPID: { val: body.P_SPID, type: oracledb.DB_TYPE_NUMBER },
|
||||
P_HOLDERCONTACTID: { val: body.P_HOLDERNAME, 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 }
|
||||
},
|
||||
{
|
||||
|
||||
@ -9,6 +9,7 @@ import { ManageClientsModule } from './manage-clients/manage-clients.module';
|
||||
import { UserMaintenanceModule } from './user-maintenance/user-maintenance.module';
|
||||
import { CarnetApplicationModule } from './carnet-application/carnet-application.module';
|
||||
import { OracleService } from './oracle.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Global()
|
||||
@Module({
|
||||
@ -25,6 +26,6 @@ import { OracleService } from './oracle.service';
|
||||
],
|
||||
providers: [OracleService],
|
||||
controllers: [],
|
||||
exports: [OracleService],
|
||||
exports: [OracleService, UserMaintenanceModule],
|
||||
})
|
||||
export class OracleModule {}
|
||||
|
||||
@ -40,8 +40,6 @@ export class OracleService {
|
||||
ITEMWEIGHT, ITEMWEIGHTUOM, GOODSORIGINCOUNTRY,
|
||||
}
|
||||
);
|
||||
console.log(result.rows);
|
||||
|
||||
return result.rows[0][0];
|
||||
}
|
||||
|
||||
@ -94,7 +92,6 @@ export class OracleService {
|
||||
P_VISISTTRANSITIND, COUNTRYCODE, NOOFTIMESENTLEAVE,
|
||||
},
|
||||
);
|
||||
console.log(result.rows);
|
||||
return result.rows[0][0];
|
||||
}
|
||||
|
||||
|
||||
@ -1,17 +1,25 @@
|
||||
import { Body, Controller, Get, Patch, Post, Put, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, 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 } from 'src/dto/property.dto';
|
||||
import {
|
||||
ActivateOrInactivateParamRecordDTO, CreateParamRecordDTO, CreateTableRecordDTO,
|
||||
getParamValuesDTO, 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')
|
||||
export class ParamTableController {
|
||||
constructor(private readonly paramTableService: ParamTableService) { }
|
||||
|
||||
|
||||
@Get('/GetParamValues')
|
||||
@Roles('ca', 'sa', 'ua')
|
||||
@ApiQuery({
|
||||
name: 'P_SPID',
|
||||
required: false,
|
||||
@ -28,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')
|
||||
@Roles('ca', 'sa', 'ua')
|
||||
GET_COUNTRIES_AND_MESSAGES() {
|
||||
return this.paramTableService.GET_COUNTRIES_AND_MESSAGES();
|
||||
}
|
||||
|
||||
@Post('/CreateTableRecord')
|
||||
createTableRecord(@Body() body: CreateTableRecordDTO) {
|
||||
return this.paramTableService.CREATETABLERECORD(body);
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { ParamTableController } from './param-table.controller';
|
||||
import { ParamTableService } from './param-table.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [ParamTableController],
|
||||
providers: [ParamTableService],
|
||||
})
|
||||
|
||||
@ -63,6 +63,84 @@ 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() {
|
||||
let connection;
|
||||
try {
|
||||
connection = await this.oracleDBService.getConnection();
|
||||
|
||||
const result = await connection.execute(
|
||||
`BEGIN
|
||||
MANAGEPARAMTABLE_PKG.GetCountriesAndMessages(:P_CURSOR);
|
||||
END;`,
|
||||
{
|
||||
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 +300,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 },
|
||||
|
||||
@ -1,10 +1,15 @@
|
||||
import { Body, Controller, Get, Param, Post, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { CarnetSequenceService } from './carnet-sequence.service';
|
||||
|
||||
import { SPID_DTO, CreateCarnetSequenceDTO } 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('Carnet Sequence - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('sa', 'ua')
|
||||
@Controller('oracle')
|
||||
export class CarnetSequenceController {
|
||||
constructor(private readonly carnetSequenceService: CarnetSequenceService) { }
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { CarnetSequenceController } from './carnet-sequence.controller';
|
||||
import { CarnetSequenceService } from './carnet-sequence.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [CarnetSequenceController],
|
||||
providers: [CarnetSequenceService],
|
||||
})
|
||||
|
||||
@ -1,12 +1,17 @@
|
||||
import { RegionService } from './region.service';
|
||||
|
||||
import { Get, Post, Body, Controller, Patch } from '@nestjs/common';
|
||||
import { Get, Post, Body, Controller, Patch, UseGuards } from '@nestjs/common';
|
||||
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Roles } from 'src/decorators/roles.decorator';
|
||||
|
||||
import { InsertRegionsDto, 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')
|
||||
export class RegionController {
|
||||
constructor(private readonly regionService: RegionService) { }
|
||||
|
||||
@ -1,9 +1,11 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RegionController } from './region.controller';
|
||||
import { RegionService } from './region.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [RegionController],
|
||||
providers: [RegionService],
|
||||
})
|
||||
export class RegionModule {}
|
||||
export class RegionModule { }
|
||||
|
||||
@ -1,14 +1,19 @@
|
||||
import { SpContactsService } from './sp-contacts.service';
|
||||
import { Body, Controller, Get, Param, Patch, Post, Put, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Patch, Post, Put, Query, UseGuards } from '@nestjs/common';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
import { Roles } from 'src/decorators/roles.decorator';
|
||||
|
||||
import {
|
||||
SPID_DTO,
|
||||
SP_CONTACTID_DTO,
|
||||
InsertSPContactsDTO, UpdateSPContactsDTO
|
||||
} from 'src/dto/property.dto';
|
||||
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
|
||||
import { RolesGuard } from 'src/guards/roles.guard';
|
||||
|
||||
@ApiTags('SPContacts - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('sa', 'ua')
|
||||
@Controller('oracle')
|
||||
export class SpContactsController {
|
||||
constructor(private readonly spContactsService: SpContactsService) { }
|
||||
@ -20,6 +25,7 @@ export class SpContactsController {
|
||||
}
|
||||
|
||||
@Patch('/SetSPDefaultContact/:P_SPCONTACTID')
|
||||
@Roles('ua')
|
||||
setSPDefaultcontact(@Param() param: SP_CONTACTID_DTO) {
|
||||
return this.spContactsService.setSPDefaultcontact(param);
|
||||
}
|
||||
|
||||
@ -2,9 +2,10 @@ import { Module } from '@nestjs/common';
|
||||
import { SpContactsService } from './sp-contacts.service';
|
||||
import { SpContactsController } from './sp-contacts.controller';
|
||||
import { DbModule } from 'src/db/db.module';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [DbModule],
|
||||
imports: [DbModule,AuthModule],
|
||||
providers: [SpContactsService],
|
||||
controllers: [SpContactsController],
|
||||
})
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Post, Put, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Post, Put, Query, UseGuards } from '@nestjs/common';
|
||||
import { SpService } from './sp.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ -6,14 +6,20 @@ import {
|
||||
SPID_DTO, InsertNewServiceProviderDTO,
|
||||
UpdateServiceProviderDTO,
|
||||
} 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('SP - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('sa', 'ua')
|
||||
@Controller('oracle')
|
||||
export class SpController {
|
||||
constructor(private readonly spService: SpService) { }
|
||||
|
||||
|
||||
@Post('/InsertNewServiceProvider')
|
||||
@Roles('ua')
|
||||
insertNewServiceProvider(@Body() body: InsertNewServiceProviderDTO) {
|
||||
return this.spService.insertNewServiceProvider(body);
|
||||
}
|
||||
@ -24,6 +30,7 @@ export class SpController {
|
||||
}
|
||||
|
||||
@Get('/GetAllServiceproviders')
|
||||
@Roles('ua')
|
||||
getAllServiceproviders() {
|
||||
return this.spService.getAllServiceproviders();
|
||||
}
|
||||
|
||||
@ -1,8 +1,10 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { SpController } from './sp.controller';
|
||||
import { SpService } from './sp.service';
|
||||
import { AuthModule } from 'src/auth/auth.module';
|
||||
|
||||
@Module({
|
||||
imports: [AuthModule],
|
||||
controllers: [SpController],
|
||||
providers: [SpService],
|
||||
})
|
||||
|
||||
@ -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)
|
||||
|
||||
@ -1,4 +1,4 @@
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
|
||||
import { Body, Controller, Get, Param, Patch, Post, Query, UseGuards } from '@nestjs/common';
|
||||
import { UserMaintenanceService } from './user-maintenance.service';
|
||||
import { ApiTags } from '@nestjs/swagger';
|
||||
|
||||
@ -7,8 +7,13 @@ import {
|
||||
EMAIL_DTO, USERID_DTO,
|
||||
CreateClientLoginsDTO, CreateSPLoginsDTO, CreateUSCIBLoginsDTO, SPID_CLIENTID_DTO, SPID_EMAIL_DTO
|
||||
} 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('User Maintenance - Oracle')
|
||||
@UseGuards(JwtAuthGuard, RolesGuard)
|
||||
@Roles('ca', 'sa', 'ua')
|
||||
@Controller('oracle')
|
||||
export class UserMaintenanceController {
|
||||
constructor(private readonly userMaintenanceService: UserMaintenanceService) { }
|
||||
@ -28,11 +33,13 @@ export class UserMaintenanceController {
|
||||
// USCIB_LOGINS
|
||||
|
||||
@Get('GetUSCIBLogins')
|
||||
@Roles('ua')
|
||||
async GetUSCIBLogins() {
|
||||
return await this.userMaintenanceService.GetUSCIBLogins();
|
||||
}
|
||||
|
||||
@Post('CreateUSCIBLogins')
|
||||
@Roles('ua')
|
||||
async CreateUSCIBLogins(@Body() body: CreateUSCIBLoginsDTO) {
|
||||
return await this.userMaintenanceService.CreateUSCIBLogins(body);
|
||||
}
|
||||
@ -40,11 +47,13 @@ export class UserMaintenanceController {
|
||||
// SP LOGINS
|
||||
|
||||
@Get('GetSPLogins/:P_SPID')
|
||||
@Roles('sa')
|
||||
async GetSPLogins(@Param() params: SPID_DTO) {
|
||||
return await this.userMaintenanceService.GetSPLogins(params);
|
||||
}
|
||||
|
||||
@Post('CreateSPLogins')
|
||||
@Roles('sa')
|
||||
async CreateSPLogins(@Body() body: CreateSPLoginsDTO) {
|
||||
return await this.userMaintenanceService.CreateSPLogins(body);
|
||||
}
|
||||
@ -52,16 +61,19 @@ export class UserMaintenanceController {
|
||||
// CLIENT LOGINS
|
||||
|
||||
@Get('GetClientloginsBySPID/:P_SPID')
|
||||
@Roles('sa')
|
||||
async GetClientloginsBySPID(@Param() params: SPID_DTO) {
|
||||
return await this.userMaintenanceService.GetSPLogins(params);
|
||||
}
|
||||
|
||||
@Get('GetClientloginsByClientID/:P_SPID/:P_CLIENTID')
|
||||
@Roles('sa')
|
||||
async GetClientloginsByClientID(@Param() params: SPID_CLIENTID_DTO) {
|
||||
return await this.userMaintenanceService.GetSPLogins(params);
|
||||
}
|
||||
|
||||
@Post('CreateClientLogins')
|
||||
@Roles('sa')
|
||||
async CreateClientLogins(@Body() body: CreateClientLoginsDTO) {
|
||||
return await this.userMaintenanceService.CreateClientLogins(body);
|
||||
}
|
||||
|
||||
@ -1,9 +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: [forwardRef(() => AuthModule)],
|
||||
controllers: [UserMaintenanceController],
|
||||
providers: [UserMaintenanceService]
|
||||
providers: [UserMaintenanceService],
|
||||
exports: [UserMaintenanceService, AuthModule]
|
||||
})
|
||||
export class UserMaintenanceModule {}
|
||||
export class UserMaintenanceModule { }
|
||||
|
||||
@ -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) {
|
||||
return new InternalServerException();
|
||||
}
|
||||
|
||||
return { statusCode: 201, message: "Client registration initiated successfully", ...fres[0] };
|
||||
|
||||
} catch (error) {
|
||||
handleError(error, UserMaintenanceService.name)
|
||||
|
||||
@ -5,6 +5,25 @@ import {
|
||||
} from '@nestjs/common';
|
||||
import * as oracledb from 'oracledb';
|
||||
|
||||
const PDFDocument = require('pdfkit');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
import { PDFDocument as pdfl } from 'pdf-lib';
|
||||
import PDFMerger from 'pdf-merger-js';
|
||||
import * as fsPromises from 'fs/promises';
|
||||
|
||||
const doc = new PDFDocument({
|
||||
size: 'A4',
|
||||
margins: {
|
||||
top: 50,
|
||||
bottom: 50,
|
||||
left: 50,
|
||||
right: 50
|
||||
}
|
||||
});
|
||||
const generalistFilePath = path.join(__dirname, '../../../public/carnet-pdf', 'p2.pdf')
|
||||
doc.pipe(fs.createWriteStream(generalistFilePath));
|
||||
|
||||
const logger = new Logger('Helper');
|
||||
|
||||
export const handleError = (error: any, context: string = 'UnknownService'): never => {
|
||||
@ -57,3 +76,562 @@ export const setEmptyStringsToNull = (obj: any): void => {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export interface pdfGLData {
|
||||
itemNo: number;
|
||||
description: string;
|
||||
noOfPieces: number;
|
||||
weight: string;
|
||||
itemValue: number;
|
||||
countryOfOrigin: string
|
||||
}
|
||||
|
||||
export interface pdfCarnetData {
|
||||
carnetNo: string;
|
||||
contPageNo: number;
|
||||
}
|
||||
|
||||
function formatNumber(num) {
|
||||
if (isNaN(num)) return 'N/A';
|
||||
return num.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
}
|
||||
|
||||
export const generateGeneralistPDF1 = async (jsonData: pdfGLData[], headerData: pdfCarnetData) => {
|
||||
// --- Table Configuration ---
|
||||
const table = {
|
||||
x: doc.x,
|
||||
y: doc.y + 20, // Start a bit below the current cursor
|
||||
cellTopPadding: 5,
|
||||
cellBottomPadding: 2,
|
||||
cellHorizontalPadding: 5,
|
||||
cellSpacing: 0,
|
||||
headerColor: '#FFFFFF',
|
||||
rowColor: '#FFFFFF',
|
||||
alternatingRowColor: '#FFFFFF',
|
||||
lineColor: '#000000',
|
||||
headerFontColor: '#000000',
|
||||
bodyFontColor: '#000000',
|
||||
fontSize: 10,
|
||||
headerFontSize: 10,
|
||||
lineWidth: 0.5,
|
||||
widths: [50, 120, 70, 80, 70, 100], //
|
||||
totalRowPaddingTop: 10 // New padding for the total row
|
||||
};
|
||||
|
||||
// Define the maximum number of lines for the entire page
|
||||
const maxLinesPerPage = 37;
|
||||
const fixedHeaderRowHeight = 22; // You can tweak this value
|
||||
const fixedHeaderFontSize = 10; // Same font size for all rows
|
||||
|
||||
|
||||
// Fixed header rows, which are not part of the dynamic data
|
||||
function getFixedHeaderData(headerValues) {
|
||||
return [
|
||||
{
|
||||
isMergedRow: true,
|
||||
cols: [
|
||||
{ text: 'General List', startCol: 0, endCol: 5, }
|
||||
]
|
||||
},
|
||||
{
|
||||
isMergedRow: true,
|
||||
cols: [
|
||||
{ text: '', startCol: 0, endCol: 2 },
|
||||
{ text: 'Carnet No:', startCol: 3, endCol: 4 },
|
||||
{ text: headerValues.carnetNo, startCol: 5, endCol: 5 },
|
||||
]
|
||||
},
|
||||
{
|
||||
isMergedRow: true,
|
||||
cols: [
|
||||
{ text: '', startCol: 0, endCol: 2 },
|
||||
{ text: 'Contn.Sheet No:', startCol: 3, endCol: 4 },
|
||||
{ text: headerValues.contPageNo, startCol: 5, endCol: 5 },
|
||||
]
|
||||
},
|
||||
{ // This is the new blank row
|
||||
isMergedRow: true,
|
||||
cols: [
|
||||
{ text: '', startCol: 0, endCol: 5 }
|
||||
]
|
||||
},
|
||||
['Item No', 'Description', 'No of Pieces', 'Weight', 'Item Value', 'Country Of Origin']
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
// Helper function to draw a single horizontal line
|
||||
function drawHorizontalLine(doc, x, y, width, lineColor, lineWidth) {
|
||||
doc.strokeColor(lineColor)
|
||||
.lineWidth(lineWidth)
|
||||
.moveTo(x, y)
|
||||
.lineTo(x + width, y)
|
||||
.stroke();
|
||||
}
|
||||
|
||||
// Helper function to draw vertical lines between columns for a specific height range
|
||||
function drawVerticalLines(doc, table, startY, endY) {
|
||||
doc.strokeColor(table.lineColor)
|
||||
.lineWidth(table.lineWidth);
|
||||
|
||||
let verticalX = table.x;
|
||||
for (let i = 0; i < table.widths.length; i++) {
|
||||
doc.moveTo(verticalX, startY)
|
||||
.lineTo(verticalX, endY)
|
||||
.stroke();
|
||||
verticalX += table.widths[i];
|
||||
}
|
||||
// Draw the final right vertical line
|
||||
doc.moveTo(verticalX, startY)
|
||||
.lineTo(verticalX, endY)
|
||||
.stroke();
|
||||
}
|
||||
|
||||
// Helper function to draw the table header
|
||||
function drawHeader(doc, table, headerData, cursorY, initialX, totalTableWidth) {
|
||||
const totalVerticalPadding = table.cellTopPadding + table.cellBottomPadding;
|
||||
const totalHorizontalPadding = table.cellHorizontalPadding * 2;
|
||||
|
||||
let headerHeight = 0;
|
||||
let maxTextHeight = 0;
|
||||
doc.fontSize(table.headerFontSize).font('Helvetica');
|
||||
|
||||
for (let i = 0; i < headerData.length; i++) {
|
||||
const textOptions = {
|
||||
width: table.widths[i] - totalHorizontalPadding,
|
||||
lineGap: 3
|
||||
};
|
||||
const h = doc.heightOfString(headerData[i], textOptions);
|
||||
if (h > maxTextHeight) maxTextHeight = h;
|
||||
}
|
||||
|
||||
headerHeight = maxTextHeight + totalVerticalPadding;
|
||||
const headerLines = Math.ceil(maxTextHeight / doc.heightOfString('a', { lineGap: 3 }));
|
||||
|
||||
let currentX = initialX;
|
||||
for (let i = 0; i < headerData.length; i++) {
|
||||
doc.rect(currentX, cursorY, table.widths[i], headerHeight).fill(table.headerColor);
|
||||
currentX += table.widths[i];
|
||||
}
|
||||
|
||||
currentX = initialX;
|
||||
for (let i = 0; i < headerData.length; i++) {
|
||||
doc.fillColor(table.headerFontColor);
|
||||
doc.text(headerData[i], currentX + table.cellHorizontalPadding, cursorY + table.cellTopPadding, {
|
||||
width: table.widths[i] - totalHorizontalPadding,
|
||||
lineGap: 3
|
||||
});
|
||||
currentX += table.widths[i];
|
||||
}
|
||||
|
||||
return { height: headerHeight, lines: headerLines };
|
||||
}
|
||||
|
||||
// Helper function to draw a merged row
|
||||
function drawMergedRow(doc, table, rowData, cursorY, initialX) {
|
||||
const totalHorizontalPadding = table.cellHorizontalPadding * 2;
|
||||
|
||||
const rowHeight = fixedHeaderRowHeight; // Use fixed height
|
||||
const fontSize = fixedHeaderFontSize;
|
||||
|
||||
let currentX = initialX;
|
||||
|
||||
doc.fontSize(fontSize).font('Helvetica'); // Ensure consistent font
|
||||
|
||||
for (let i = 0; i < table.widths.length; i++) {
|
||||
const cell = rowData.cols.find(c => c.startCol === i);
|
||||
if (cell) {
|
||||
let mergedWidth = 0;
|
||||
for (let j = cell.startCol; j <= cell.endCol; j++) {
|
||||
mergedWidth += table.widths[j];
|
||||
}
|
||||
const fillColor = table.rowColor;
|
||||
doc.rect(currentX, cursorY, mergedWidth, rowHeight).fill(fillColor);
|
||||
|
||||
if (cell.text) {
|
||||
doc.fillColor(table.bodyFontColor);
|
||||
doc.text(cell.text, currentX + table.cellHorizontalPadding, cursorY + table.cellTopPadding, {
|
||||
width: mergedWidth - totalHorizontalPadding,
|
||||
height: rowHeight - table.cellTopPadding - table.cellBottomPadding,
|
||||
lineGap: 3
|
||||
});
|
||||
}
|
||||
currentX += mergedWidth;
|
||||
i = cell.endCol;
|
||||
} else {
|
||||
currentX += table.widths[i];
|
||||
}
|
||||
}
|
||||
|
||||
return { height: rowHeight, lines: 1 };
|
||||
}
|
||||
|
||||
// Helper function to draw the fixed header block
|
||||
function drawFixedHeader(doc, table, fixedHeaderData, cursorY, initialX, totalTableWidth) {
|
||||
let headerBlockHeight = 0;
|
||||
let headerBlockLines = 0;
|
||||
let horizontalLineYCoords: number[] = [];
|
||||
|
||||
horizontalLineYCoords.push(cursorY); // Top of the entire header block
|
||||
|
||||
// Draw merged rows (first 4 rows, including the new blank one)
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const rowData = fixedHeaderData[i];
|
||||
const { height: rowHeight, lines: rowLines } = drawMergedRow(doc, table, rowData, cursorY, initialX);
|
||||
cursorY += rowHeight;
|
||||
headerBlockHeight += rowHeight;
|
||||
headerBlockLines += rowLines;
|
||||
horizontalLineYCoords.push(cursorY);
|
||||
}
|
||||
|
||||
// Draw the main header
|
||||
const headerRow = fixedHeaderData[4];
|
||||
const { height: headerHeight, lines: headerLines } = drawHeader(doc, table, headerRow, cursorY, initialX, totalTableWidth);
|
||||
cursorY += headerHeight;
|
||||
headerBlockHeight += headerHeight;
|
||||
headerBlockLines += headerLines;
|
||||
horizontalLineYCoords.push(cursorY);
|
||||
|
||||
// Now draw the horizontal lines for the entire header block
|
||||
for (const yCoord of horizontalLineYCoords) {
|
||||
drawHorizontalLine(doc, initialX, yCoord, totalTableWidth, table.lineColor, table.lineWidth);
|
||||
}
|
||||
|
||||
// Now, manually draw the vertical lines for each header row based on its merged cells
|
||||
// Outer left border for the entire header block
|
||||
doc.moveTo(initialX, horizontalLineYCoords[0]).lineTo(initialX, cursorY).stroke();
|
||||
// Outer right border for the entire header block
|
||||
doc.moveTo(initialX + totalTableWidth, horizontalLineYCoords[0]).lineTo(initialX + totalTableWidth, cursorY).stroke();
|
||||
|
||||
// Loop through the fixed header rows to draw internal vertical lines
|
||||
for (let i = 0; i < fixedHeaderData.length; i++) {
|
||||
const rowData = fixedHeaderData[i];
|
||||
const topY = horizontalLineYCoords[i];
|
||||
const bottomY = horizontalLineYCoords[i + 1];
|
||||
let currentX = initialX;
|
||||
|
||||
if (Array.isArray(rowData)) {
|
||||
// Draw all vertical lines for the non-merged header row
|
||||
for (let j = 0; j < table.widths.length - 1; j++) {
|
||||
currentX += table.widths[j];
|
||||
doc.moveTo(currentX, topY).lineTo(currentX, bottomY).stroke();
|
||||
}
|
||||
} else if (i === 3) {
|
||||
// Special case for the blank merged row (4th row, index 3)
|
||||
// We want to draw all the vertical lines as if it's a regular row
|
||||
for (let j = 0; j < table.widths.length - 1; j++) {
|
||||
currentX += table.widths[j];
|
||||
doc.moveTo(currentX, topY).lineTo(currentX, bottomY).stroke();
|
||||
}
|
||||
}
|
||||
else {
|
||||
// Draw internal lines for other merged rows
|
||||
for (const cell of rowData.cols) {
|
||||
let mergedWidth = 0;
|
||||
for (let j = cell.startCol; j <= cell.endCol; j++) {
|
||||
mergedWidth += table.widths[j];
|
||||
}
|
||||
currentX += mergedWidth;
|
||||
// Don't draw a vertical line if it's the very last column's right border
|
||||
if (cell.endCol < table.widths.length - 1) {
|
||||
doc.moveTo(currentX, topY).lineTo(currentX, bottomY).stroke();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { height: headerBlockHeight, endY: cursorY, lines: headerBlockLines };
|
||||
}
|
||||
|
||||
// Helper function to draw the total row without borders or vertical lines
|
||||
function drawTotalRow(doc, table, totalValue, cursorY, initialX) {
|
||||
// const totalRowDataArray = ['', '', '', 'Total', totalValue.toFixed(2), ''];
|
||||
const totalRowDataArray = ['', '', '', 'Total', formatNumber(totalValue), ''];
|
||||
const totalVerticalPadding = table.cellTopPadding + table.cellBottomPadding;
|
||||
const totalHorizontalPadding = table.cellHorizontalPadding * 2;
|
||||
const totalTableWidth = table.widths.reduce((a, b) => a + b, 0);
|
||||
|
||||
let totalRowHeight = 0;
|
||||
let maxTotalHeightInRow = 0;
|
||||
for (let j = 0; j < totalRowDataArray.length; j++) {
|
||||
const textOptions = {
|
||||
width: table.widths[j] - totalHorizontalPadding,
|
||||
lineGap: 3
|
||||
};
|
||||
const h = doc.heightOfString(totalRowDataArray[j], textOptions);
|
||||
if (h > maxTotalHeightInRow) {
|
||||
maxTotalHeightInRow = h;
|
||||
}
|
||||
}
|
||||
totalRowHeight = maxTotalHeightInRow + totalVerticalPadding;
|
||||
const linesInTotalRow = Math.ceil(maxTotalHeightInRow / doc.heightOfString('a', { lineGap: 3 }));
|
||||
|
||||
const startY = cursorY + table.totalRowPaddingTop;
|
||||
|
||||
// Draw the text only, without any rectangles or lines
|
||||
let currentX = initialX;
|
||||
doc.fontSize(table.fontSize);
|
||||
for (let j = 0; j < totalRowDataArray.length; j++) {
|
||||
doc.fillColor(table.bodyFontColor);
|
||||
doc.text(totalRowDataArray[j], currentX + table.cellHorizontalPadding, startY + table.cellTopPadding, {
|
||||
width: table.widths[j] - totalHorizontalPadding,
|
||||
lineGap: 3
|
||||
});
|
||||
currentX += table.widths[j];
|
||||
}
|
||||
|
||||
return { height: totalRowHeight + table.totalRowPaddingTop, lines: linesInTotalRow, endY: startY + totalRowHeight };
|
||||
}
|
||||
|
||||
|
||||
// --- Function to manually draw a single data row ---
|
||||
function drawDataRow(doc, table, rowData, cursorY, initialX, isEvenRow) {
|
||||
const totalVerticalPadding = table.cellTopPadding + table.cellBottomPadding;
|
||||
const totalHorizontalPadding = table.cellHorizontalPadding * 2;
|
||||
const totalTableWidth = table.widths.reduce((a, b) => a + b, 0);
|
||||
|
||||
let rowHeight = 0;
|
||||
let maxHeightInRow = 0;
|
||||
|
||||
const rowDataArray = [
|
||||
rowData.itemNo,
|
||||
rowData.description,
|
||||
rowData.noOfPieces,
|
||||
rowData.weight,
|
||||
formatNumber(rowData.itemValue), // formatted Item Value
|
||||
rowData.countryOfOrigin
|
||||
];
|
||||
|
||||
for (let j = 0; j < rowDataArray.length; j++) {
|
||||
const textOptions = { width: table.widths[j] - totalHorizontalPadding, lineGap: 3 };
|
||||
const h = doc.heightOfString(rowDataArray[j] || '', textOptions);
|
||||
if (h > maxHeightInRow) {
|
||||
maxHeightInRow = h;
|
||||
}
|
||||
}
|
||||
|
||||
rowHeight = maxHeightInRow + totalVerticalPadding;
|
||||
const linesInRow = Math.ceil(maxHeightInRow / doc.heightOfString('a', { lineGap: 3 }));
|
||||
|
||||
// Draw the data row
|
||||
const fillColor = isEvenRow ? table.alternatingRowColor : table.rowColor;
|
||||
doc.rect(initialX, cursorY, totalTableWidth, rowHeight).fill(fillColor); // Fill the entire row rectangle
|
||||
let currentX = initialX;
|
||||
doc.fontSize(table.fontSize);
|
||||
// for (let j = 0; j < rowDataArray.length; j++) {
|
||||
// doc.fillColor(table.bodyFontColor);
|
||||
// doc.text(rowDataArray[j], currentX + table.cellHorizontalPadding, cursorY + table.cellTopPadding, {
|
||||
// width: table.widths[j] - totalHorizontalPadding,
|
||||
// lineGap: 3
|
||||
// });
|
||||
// currentX += table.widths[j];
|
||||
// }
|
||||
|
||||
for (let j = 0; j < rowDataArray.length; j++) {
|
||||
doc.fillColor(table.bodyFontColor);
|
||||
|
||||
const alignRight = (j === 2 || j === 4); // right-align No of Pieces and Item Value
|
||||
|
||||
doc.text(rowDataArray[j], currentX + table.cellHorizontalPadding, cursorY + table.cellTopPadding, {
|
||||
width: table.widths[j] - totalHorizontalPadding,
|
||||
lineGap: 3,
|
||||
align: alignRight ? 'right' : 'left'
|
||||
});
|
||||
|
||||
currentX += table.widths[j];
|
||||
}
|
||||
|
||||
return { height: rowHeight, lines: linesInRow, endY: cursorY + rowHeight };
|
||||
}
|
||||
|
||||
// --- Function to manually draw the table from JSON data ---
|
||||
function drawTable(doc, table, jsonData, headerData) {
|
||||
let cursorY = table.y;
|
||||
const initialX = table.x;
|
||||
let continuationPageNo = 0;
|
||||
|
||||
const totalTableWidth = table.widths.reduce((a, b) => a + b, 0);
|
||||
|
||||
let rowStart = 0;
|
||||
|
||||
while (rowStart < jsonData.length) {
|
||||
let linesUsed = 0;
|
||||
let rowsOnPage: any = [];
|
||||
let currentY = cursorY;
|
||||
let currentPageTotal = 0;
|
||||
|
||||
// Draw fixed header block and count its visual lines
|
||||
const fixedHeaderData = getFixedHeaderData({ ...headerData, contPageNo: String(continuationPageNo) });
|
||||
const fixedHeaderInfo = drawFixedHeader(doc, table, fixedHeaderData, currentY, initialX, totalTableWidth);
|
||||
currentY = fixedHeaderInfo.endY;
|
||||
linesUsed += fixedHeaderInfo.lines;
|
||||
|
||||
// Collect data rows that can fit in remaining lines
|
||||
for (let i = rowStart; i < jsonData.length; i++) {
|
||||
const rowData = jsonData[i];
|
||||
const isEvenRow = i % 2 === 0;
|
||||
|
||||
const { height, lines } = drawDataRow(doc, table, rowData, -1000, initialX, isEvenRow); // simulate row height
|
||||
const remainingRows = jsonData.length - i - 1;
|
||||
const willBeLastPage = remainingRows === 0;
|
||||
const extraLines = 1 + (willBeLastPage ? 1 : 0);
|
||||
if (linesUsed + lines + extraLines + 1 > maxLinesPerPage) break; // +1 for total row
|
||||
rowsOnPage.push({ data: rowData, isEven: isEvenRow, height, lines });
|
||||
linesUsed += lines;
|
||||
rowStart++;
|
||||
currentPageTotal += parseFloat(rowData.itemValue);
|
||||
}
|
||||
|
||||
// Render data rows
|
||||
let horizontalLineYCoords: number[] = [currentY];
|
||||
for (const row of rowsOnPage as any) {
|
||||
drawDataRow(doc, table, row.data, currentY, initialX, row.isEven);
|
||||
currentY += row.height;
|
||||
horizontalLineYCoords.push(currentY);
|
||||
}
|
||||
|
||||
// Draw horizontal lines for data rows
|
||||
for (const yCoord of horizontalLineYCoords) {
|
||||
drawHorizontalLine(doc, initialX, yCoord, totalTableWidth, table.lineColor, table.lineWidth);
|
||||
}
|
||||
|
||||
// Draw vertical lines for data block
|
||||
drawVerticalLines(doc, table, horizontalLineYCoords[0], currentY);
|
||||
|
||||
// Draw total row
|
||||
const totalRowInfo = drawTotalRow(doc, table, currentPageTotal, currentY, initialX);
|
||||
currentY = totalRowInfo.endY;
|
||||
|
||||
const isLastDataPage = rowStart >= jsonData.length;
|
||||
if (isLastDataPage) {
|
||||
const endMessage = '***** End of list, No item can be added *****';
|
||||
const fontSize = 10;
|
||||
const verticalGap = 10;
|
||||
|
||||
doc.fontSize(fontSize).font('Helvetica-Bold');
|
||||
|
||||
const textWidth = doc.widthOfString(endMessage);
|
||||
const centerX = (doc.page.width - textWidth) / 2;
|
||||
const endY = currentY + verticalGap;
|
||||
|
||||
doc.text(endMessage, centerX, endY);
|
||||
currentY = endY + doc.heightOfString(endMessage); // update Y if needed
|
||||
}
|
||||
|
||||
|
||||
// Add new page if more data remains
|
||||
if (rowStart < jsonData.length) {
|
||||
doc.addPage();
|
||||
continuationPageNo++;
|
||||
cursorY = doc.page.margins.top;
|
||||
}
|
||||
}
|
||||
|
||||
return continuationPageNo + 1;
|
||||
}
|
||||
|
||||
// Draw the custom table and get the total page count
|
||||
const totalPages = drawTable(doc, table, jsonData, headerData);
|
||||
|
||||
// Check if the total number of pages is even and add a "VOID" page if it is
|
||||
if (totalPages % 2 === 0) {
|
||||
doc.addPage();
|
||||
const voidText = 'VOID';
|
||||
doc.fontSize(14).font('Helvetica');
|
||||
const textWidth = doc.widthOfString(voidText);
|
||||
const centerX = (doc.page.width - textWidth) / 2;
|
||||
doc.text(voidText, centerX, doc.page.margins.top);
|
||||
}
|
||||
|
||||
// Finalize the PDF file
|
||||
doc.end();
|
||||
|
||||
console.log('PDF created successfully!');
|
||||
|
||||
return "p2 done";
|
||||
}
|
||||
|
||||
export const generateGeneralistPDF2 = async (carnetNumber: string) => {
|
||||
const pageWidth = doc.page.width;
|
||||
const seeAttachedText = 'See Attached';
|
||||
const seeAttachedWidth = doc.widthOfString(seeAttachedText);
|
||||
const uniqueNoText = `Carnet No: ${carnetNumber}`;
|
||||
const uniqueNoWidth = doc.widthOfString(uniqueNoText);
|
||||
|
||||
// Center position for "See Attached"
|
||||
const centerX = pageWidth / 2;
|
||||
const seeAttachedX = centerX - (seeAttachedWidth / 2);
|
||||
|
||||
// Position "Unique No" next to "See Attached"
|
||||
const spacing = 90; // gap between texts
|
||||
const uniqueNoX = seeAttachedX + seeAttachedWidth + spacing;
|
||||
|
||||
// Vertically align both (e.g., 100 from top)
|
||||
const y = 100;
|
||||
|
||||
// If unique number will overflow, adjust its X position to stay in same line
|
||||
let adjustedUniqueNoX = uniqueNoX;
|
||||
if (uniqueNoX + uniqueNoWidth > pageWidth - 50) {
|
||||
adjustedUniqueNoX = pageWidth - uniqueNoWidth - 50;
|
||||
}
|
||||
|
||||
doc.text(seeAttachedText, seeAttachedX, y);
|
||||
doc.text(uniqueNoText, adjustedUniqueNoX, y);
|
||||
|
||||
// Finalize PDF
|
||||
doc.end();
|
||||
|
||||
return "p2 done"
|
||||
}
|
||||
|
||||
export const generateGreenCoverPDF = async () => {
|
||||
const templatePath = path.join(__dirname, '../../..', 'public/pdf-templates', '2GeneralList.pdf');
|
||||
const existingPdfBytes = fs.readFileSync(templatePath);
|
||||
|
||||
const pdfDoc = await pdfl.load(existingPdfBytes);
|
||||
const form = pdfDoc.getForm();
|
||||
|
||||
let fields = form.getFields();
|
||||
}
|
||||
|
||||
export const generateFinalPDF = async (inputFiles: string[], outputFile: string) => {
|
||||
const merger = new PDFMerger();
|
||||
|
||||
for (const fileName of inputFiles) {
|
||||
const filePath = path.join(__dirname, '../../../public/carnet-pdf', fileName);
|
||||
console.log(`📄 Adding: ${filePath}`);
|
||||
|
||||
try {
|
||||
await merger.add(filePath);
|
||||
} catch (err) {
|
||||
console.error(`❌ Failed to add PDF: ${fileName}`, err);
|
||||
}
|
||||
}
|
||||
|
||||
const outputPath = path.join(__dirname, '../../../public/carnet-pdf', outputFile);
|
||||
|
||||
try {
|
||||
await merger.save(outputPath);
|
||||
console.log(`✅ Merged PDF saved to ${outputPath}`);
|
||||
} catch (err) {
|
||||
console.error(`❌ Failed to save merged PDF`, err);
|
||||
throw new Error("Failed to save merged PDF");
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteFilesAsync = async (relativeFilePaths: string[]): Promise<void> => {
|
||||
for (const relativeFilePath of relativeFilePaths) {
|
||||
const filePath = path.join(__dirname, '../../../public/carnet-pdf', relativeFilePath);
|
||||
|
||||
if (fs.existsSync(filePath)) {
|
||||
try {
|
||||
await fsPromises.unlink(filePath);
|
||||
console.log(`🗑️ Deleted: ${filePath}`);
|
||||
} catch (err) {
|
||||
console.error(`❌ Error deleting file: ${filePath}`, err);
|
||||
}
|
||||
} else {
|
||||
console.warn(`⚠️ File not found: ${filePath}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
Loading…
x
Reference in New Issue
Block a user