forked from Yara724/api
Compare commits
36 Commits
70160543a2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
61684156c6 | ||
|
|
588a92c4b4 | ||
|
|
c94dd27a96 | ||
|
|
e4c3b7a16a | ||
|
|
4b9d946bfd | ||
|
|
9828aee8af | ||
| 778544c321 | |||
|
|
3afff67336 | ||
| 793ff639ba | |||
|
|
ec15cff557 | ||
| fd42adf9d6 | |||
|
|
4272790fad | ||
| ac65cdb77b | |||
| 8430c68e3a | |||
| 49fe548215 | |||
|
|
777eae1028 | ||
| b67dd733cd | |||
|
|
4818f73252 | ||
| cc8a5354c7 | |||
|
|
2d5ade33d2 | ||
| b73c92c21f | |||
| f9f462d47b | |||
| c3eb36dc41 | |||
|
|
f75ecf5c2c | ||
| 75c4cb6a05 | |||
|
|
7a4277f8b2 | ||
| e50bc78344 | |||
|
|
2c1cd93dd0 | ||
| ffd44df718 | |||
|
|
64865b70f2 | ||
| c207c30be9 | |||
|
|
fcb169e9ac | ||
| 1867292499 | |||
|
|
2cc96f6132 | ||
| 4d5b91d4fe | |||
| 8ba97537a4 |
21
.env.example
21
.env.example
@@ -5,6 +5,10 @@ NODE_ENV =
|
|||||||
PORT =
|
PORT =
|
||||||
CLIENT_ID =
|
CLIENT_ID =
|
||||||
CLIENT_NAME =
|
CLIENT_NAME =
|
||||||
|
FANAVARAN_CLIENT=parsian
|
||||||
|
INSURANCE_CORP_ID='شرکت بيمه پارسيان(بيمه گر)'
|
||||||
|
CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED=false
|
||||||
|
CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN=53000000
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
# 🌐 Application URLs
|
# 🌐 Application URLs
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
@@ -63,6 +67,23 @@ AUTH_SMS_TEMPLATE =
|
|||||||
EXP_OTP_TIME =
|
EXP_OTP_TIME =
|
||||||
FAKE_OTP =
|
FAKE_OTP =
|
||||||
|
|
||||||
|
# ---------------------------------------------
|
||||||
|
# 🌐 Proxy Configuration (Local Development Only)
|
||||||
|
# ---------------------------------------------
|
||||||
|
# NOTE: These proxy settings are for local development only.
|
||||||
|
# When deploying to the server, comment out or remove these lines
|
||||||
|
# as the server IP is already whitelisted by Fanavaran.
|
||||||
|
# SOCKS_PROXY_HOST = localhost
|
||||||
|
# SOCKS_PROXY_PORT = 6565
|
||||||
|
|
||||||
|
# ---------------------------------------------
|
||||||
|
# 🏢 Fanavaran Insurance Corp
|
||||||
|
# ---------------------------------------------
|
||||||
|
# Caption from Fanavaran insurance-corp lookup used to resolve InsuranceCorpId
|
||||||
|
# for damage-case payloads. Must match a Caption in the insurance-corp code-list.
|
||||||
|
# Example: "شرکت بيمه تجارت نو"
|
||||||
|
INSURANCE_CORP_ID =
|
||||||
|
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
# ⚙️ Application Features / Flags
|
# ⚙️ Application Features / Flags
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
|
|||||||
@@ -274,6 +274,20 @@ curl -X GET "$FANAVARAN_BIME_URL/car/code-list/accident-culprit-type" \
|
|||||||
-H "ContractId: $CONTRACT_ID" \
|
-H "ContractId: $CONTRACT_ID" \
|
||||||
-H "Location: $LOCATION" \
|
-H "Location: $LOCATION" \
|
||||||
-H "Content-Type: application/json"
|
-H "Content-Type: application/json"
|
||||||
|
|
||||||
|
curl -X GET "$FANAVARAN_BIME_URL/car/base-info/vehicle-kinds" \
|
||||||
|
-H "authenticationToken: $AUTHENTICATION_TOKEN" \
|
||||||
|
-H "CorpId: $CORP_ID" \
|
||||||
|
-H "ContractId: $CONTRACT_ID" \
|
||||||
|
-H "Location: $LOCATION" \
|
||||||
|
-H "Content-Type: application/json"
|
||||||
|
|
||||||
|
curl -X GET "$FANAVARAN_BIME_URL/car/vehicles/inquiry-by-vin?vin=IRNKAEK4150012345" \
|
||||||
|
-H "authenticationToken: $AUTHENTICATION_TOKEN" \
|
||||||
|
-H "CorpId: $CORP_ID" \
|
||||||
|
-H "ContractId: $CONTRACT_ID" \
|
||||||
|
-H "Location: $LOCATION" \
|
||||||
|
-H "Content-Type: application/json"
|
||||||
```
|
```
|
||||||
|
|
||||||
### 3B. Policy Inquiry By National Code
|
### 3B. Policy Inquiry By National Code
|
||||||
|
|||||||
@@ -45,6 +45,7 @@
|
|||||||
"pdfkit": "^0.19.1",
|
"pdfkit": "^0.19.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
|
"socks-proxy-agent": "^8.0.4",
|
||||||
"svg-captcha": "^1.4.0"
|
"svg-captcha": "^1.4.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
@@ -9,4 +9,5 @@ export enum RoleEnum {
|
|||||||
FILE_MAKER = "file_maker",
|
FILE_MAKER = "file_maker",
|
||||||
FILE_REVIEWER = "file_reviewer",
|
FILE_REVIEWER = "file_reviewer",
|
||||||
SUPER_ADMIN = "super_admin",
|
SUPER_ADMIN = "super_admin",
|
||||||
|
CALL_CENTER = "call_center",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { HttpModule } from "@nestjs/axios";
|
|
||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { AiService } from "./ai.service";
|
import { AiService } from "./ai.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [HttpModule],
|
imports: [],
|
||||||
providers: [AiService],
|
providers: [AiService],
|
||||||
exports: [AiService],
|
exports: [AiService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
|
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
|
||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { ConfigService } from "@nestjs/config";
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { HttpModule } from "@nestjs/axios";
|
||||||
import { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor";
|
import { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor";
|
||||||
import { MongooseModule } from "@nestjs/mongoose";
|
import { MongooseModule } from "@nestjs/mongoose";
|
||||||
import { ServeStaticModule } from "@nestjs/serve-static";
|
import { ServeStaticModule } from "@nestjs/serve-static";
|
||||||
@@ -28,9 +29,15 @@ import { WorkflowStepManagementModule } from "./workflow-step-management/workflo
|
|||||||
import { DatabaseModule } from "./core/database/database.module";
|
import { DatabaseModule } from "./core/database/database.module";
|
||||||
import { AppConfigModule } from "./core/config/config.module";
|
import { AppConfigModule } from "./core/config/config.module";
|
||||||
import { SuperAdminModule } from "./super-admin/super-admin.module";
|
import { SuperAdminModule } from "./super-admin/super-admin.module";
|
||||||
|
import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
DatabaseModule,
|
DatabaseModule,
|
||||||
CronModule,
|
CronModule,
|
||||||
|
|||||||
@@ -29,6 +29,7 @@ import { FieldExpertDbService } from "src/users/entities/db-service/field-expert
|
|||||||
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
||||||
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
|
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
|
||||||
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
|
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
|
||||||
|
import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service";
|
||||||
import { HashService } from "src/utils/hash/hash.service";
|
import { HashService } from "src/utils/hash/hash.service";
|
||||||
import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service";
|
import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service";
|
||||||
import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service";
|
import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service";
|
||||||
@@ -58,6 +59,7 @@ export class ActorAuthService {
|
|||||||
private readonly fileMakerDbService: FileMakerDbService,
|
private readonly fileMakerDbService: FileMakerDbService,
|
||||||
private readonly fileReviewerDbService: FileReviewerDbService,
|
private readonly fileReviewerDbService: FileReviewerDbService,
|
||||||
private readonly superAdminDbService: SuperAdminDbService,
|
private readonly superAdminDbService: SuperAdminDbService,
|
||||||
|
private readonly callCenterAgentDbService: CallCenterAgentDbService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// TODO convrt to class for dynamic controller
|
// TODO convrt to class for dynamic controller
|
||||||
@@ -123,6 +125,14 @@ export class ActorAuthService {
|
|||||||
});
|
});
|
||||||
else res = await this.superAdminDbService.findByLoginIdentifier(username);
|
else res = await this.superAdminDbService.findByLoginIdentifier(username);
|
||||||
break;
|
break;
|
||||||
|
case RoleEnum.CALL_CENTER:
|
||||||
|
if (username == null && userId)
|
||||||
|
res = await this.callCenterAgentDbService.findOne({
|
||||||
|
_id: new Types.ObjectId(userId),
|
||||||
|
});
|
||||||
|
else
|
||||||
|
res = await this.callCenterAgentDbService.findByLoginIdentifier(username);
|
||||||
|
break;
|
||||||
default:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { MongooseModule } from "@nestjs/mongoose";
|
import { MongooseModule } from "@nestjs/mongoose";
|
||||||
|
import { HttpModule } from "@nestjs/axios";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
import { AiModule } from "src/ai/ai.module";
|
import { AiModule } from "src/ai/ai.module";
|
||||||
import { SandHubModule } from "src/sand-hub/sand-hub.module";
|
import { SandHubModule } from "src/sand-hub/sand-hub.module";
|
||||||
import { RequestManagementModule } from "src/request-management/request-management.module";
|
import { RequestManagementModule } from "src/request-management/request-management.module";
|
||||||
@@ -52,13 +55,16 @@ import { ClientModule } from "src/client/client.module";
|
|||||||
import { ClaimAccessGuard } from "src/auth/guards/claim-access.guard";
|
import { ClaimAccessGuard } from "src/auth/guards/claim-access.guard";
|
||||||
import { JwtModule } from "@nestjs/jwt";
|
import { JwtModule } from "@nestjs/jwt";
|
||||||
import { MediaPolicyModule } from "src/media-policy/media-policy.module";
|
import { MediaPolicyModule } from "src/media-policy/media-policy.module";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
|
||||||
import { FanavaranAuditModule } from "src/fanavaran/fanavaran-audit.module";
|
import { FanavaranAuditModule } from "src/fanavaran/fanavaran-audit.module";
|
||||||
import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module";
|
import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
FanavaranAuditModule,
|
FanavaranAuditModule,
|
||||||
FanavaranLookupModule,
|
FanavaranLookupModule,
|
||||||
PublicIdModule,
|
PublicIdModule,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -106,14 +106,16 @@ export class SelectOtherPartsV2ResponseDto {
|
|||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Sheba number (masked for security)',
|
description: 'Sheba number (masked for security)',
|
||||||
example: 'IR12************1234',
|
example: 'IR12************1234',
|
||||||
|
required: false,
|
||||||
})
|
})
|
||||||
shebaNumber: string;
|
shebaNumber?: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'National code of owner (masked)',
|
description: 'National code of owner (masked)',
|
||||||
example: '12******90',
|
example: '12******90',
|
||||||
|
required: false,
|
||||||
})
|
})
|
||||||
nationalCodeOfOwner: string;
|
nationalCodeOfOwner?: string;
|
||||||
|
|
||||||
@ApiProperty({
|
@ApiProperty({
|
||||||
description: 'Current workflow step',
|
description: 'Current workflow step',
|
||||||
|
|||||||
@@ -86,6 +86,15 @@ export class FanavaranSyncStage {
|
|||||||
|
|
||||||
@Prop({ type: MongooseSchema.Types.Mixed })
|
@Prop({ type: MongooseSchema.Types.Mixed })
|
||||||
response?: unknown;
|
response?: unknown;
|
||||||
|
|
||||||
|
@Prop({ type: Number, default: 0 })
|
||||||
|
retryCount?: number;
|
||||||
|
|
||||||
|
@Prop({ type: Number, default: 2 })
|
||||||
|
maxRetries?: number;
|
||||||
|
|
||||||
|
@Prop({ type: Date })
|
||||||
|
nextRetryAt?: Date;
|
||||||
}
|
}
|
||||||
export const FanavaranSyncStageSchema =
|
export const FanavaranSyncStageSchema =
|
||||||
SchemaFactory.createForClass(FanavaranSyncStage);
|
SchemaFactory.createForClass(FanavaranSyncStage);
|
||||||
|
|||||||
@@ -4,9 +4,12 @@ import {
|
|||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
|
HttpException,
|
||||||
|
InternalServerErrorException,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
Query,
|
Query,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
@@ -516,6 +519,73 @@ Returns status of each item (uploaded/captured or not).
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Owner signature on expert pricing ───────────────────────────────────────
|
||||||
|
|
||||||
|
@Put("claim-sign/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@ApiBody({
|
||||||
|
description: "Signature file, agreement, and branch",
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["sign", "agree", "branchId"],
|
||||||
|
properties: {
|
||||||
|
sign: { type: "string", format: "binary", description: "Signature image" },
|
||||||
|
agree: { type: "boolean", description: "true to accept, false to reject" },
|
||||||
|
branchId: { type: "string", description: "Insurer branch ID" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Owner signature on expert pricing (Flow 3 — expert acts on behalf of user)",
|
||||||
|
description:
|
||||||
|
"Field expert submits the damaged party's signature during the final approval stage. " +
|
||||||
|
"Delegates to the same service method as the user sign endpoint; the expert's " +
|
||||||
|
"identity is resolved to the claim owner via `resolveClaimEffectiveUserId`.",
|
||||||
|
})
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("sign", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-sign",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
|
||||||
|
callback(null, `${base}-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
async submitOwnerSign(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body("agree") agree: string | boolean,
|
||||||
|
@Body("branchId") branchId: string,
|
||||||
|
@CurrentUser() expert: any,
|
||||||
|
@UploadedFile() sign: Express.Multer.File,
|
||||||
|
) {
|
||||||
|
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
|
||||||
|
const agreed =
|
||||||
|
typeof agree === "string"
|
||||||
|
? agree === "true" || agree === "1"
|
||||||
|
: Boolean(agree);
|
||||||
|
try {
|
||||||
|
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
|
||||||
|
claimRequestId,
|
||||||
|
agreed,
|
||||||
|
typeof branchId === "string" ? branchId : "",
|
||||||
|
sign,
|
||||||
|
expert.sub,
|
||||||
|
expert,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof HttpException) throw error;
|
||||||
|
throw new InternalServerErrorException(
|
||||||
|
error instanceof Error ? error.message : "Failed to submit signature",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Patch("car-capture/:claimRequestId")
|
@Patch("car-capture/:claimRequestId")
|
||||||
@ApiConsumes("multipart/form-data")
|
@ApiConsumes("multipart/form-data")
|
||||||
@UseInterceptors(
|
@UseInterceptors(
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ export class AuthGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const payload: JwtPayload =
|
const payload: JwtPayload =
|
||||||
await this.jwtService.verifyAsync<JwtPayload>(token);
|
await this.jwtService.verifyAsync<JwtPayload>(token, {
|
||||||
|
secret: `${process.env.JWT_SECRET}`,
|
||||||
|
});
|
||||||
request["user"] = payload;
|
request["user"] = payload;
|
||||||
} catch {
|
} catch {
|
||||||
throw new UnauthorizedException("Invalid or expired token");
|
throw new UnauthorizedException("Invalid or expired token");
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ export interface FanavaranPayloadDefaults {
|
|||||||
AccidentReportTypeId: number;
|
AccidentReportTypeId: number;
|
||||||
AccidentVehicleUsedId: number;
|
AccidentVehicleUsedId: number;
|
||||||
ClaimExpertId: number;
|
ClaimExpertId: number;
|
||||||
|
ExpertiseClaimExpertId: number;
|
||||||
CompensationReferenceId: number;
|
CompensationReferenceId: number;
|
||||||
CulpritLicenceTypeId: number;
|
CulpritLicenceTypeId: number;
|
||||||
CulpritTypeId: number;
|
CulpritTypeId: number;
|
||||||
@@ -74,7 +75,8 @@ const FANAVARAN_CLIENT_PROFILES: Record<
|
|||||||
AccidentCityId: 701,
|
AccidentCityId: 701,
|
||||||
AccidentReportTypeId: 155,
|
AccidentReportTypeId: 155,
|
||||||
AccidentVehicleUsedId: 1,
|
AccidentVehicleUsedId: 1,
|
||||||
ClaimExpertId: 1589,
|
ClaimExpertId: 4543092,
|
||||||
|
ExpertiseClaimExpertId: 4543092,
|
||||||
CompensationReferenceId: 167,
|
CompensationReferenceId: 167,
|
||||||
CulpritLicenceTypeId: 2,
|
CulpritLicenceTypeId: 2,
|
||||||
CulpritTypeId: 337,
|
CulpritTypeId: 337,
|
||||||
@@ -84,7 +86,7 @@ const FANAVARAN_CLIENT_PROFILES: Record<
|
|||||||
PlaqueSampleId: 10,
|
PlaqueSampleId: 10,
|
||||||
DriverIsOwner: 0,
|
DriverIsOwner: 0,
|
||||||
FaultPercent: 100,
|
FaultPercent: 100,
|
||||||
ClaimFileTypeId: 70,
|
ClaimFileTypeId: 23,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
parsian: {
|
parsian: {
|
||||||
@@ -103,6 +105,7 @@ const FANAVARAN_CLIENT_PROFILES: Record<
|
|||||||
AccidentReportTypeId: 155,
|
AccidentReportTypeId: 155,
|
||||||
AccidentVehicleUsedId: 1,
|
AccidentVehicleUsedId: 1,
|
||||||
ClaimExpertId: 154,
|
ClaimExpertId: 154,
|
||||||
|
ExpertiseClaimExpertId: 29,
|
||||||
CompensationReferenceId: 167,
|
CompensationReferenceId: 167,
|
||||||
CulpritLicenceTypeId: 2,
|
CulpritLicenceTypeId: 2,
|
||||||
CulpritTypeId: 337,
|
CulpritTypeId: 337,
|
||||||
|
|||||||
26
src/core/config/http-proxy.factory.ts
Normal file
26
src/core/config/http-proxy.factory.ts
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
import { ConfigService } from "@nestjs/config";
|
||||||
|
import { HttpModuleOptions } from "@nestjs/axios";
|
||||||
|
import { SocksProxyAgent } from "socks-proxy-agent";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Shared HttpModule.registerAsync factory that applies the SOCKS proxy
|
||||||
|
* when SOCKS_PROXY_HOST + SOCKS_PROXY_PORT env vars are set.
|
||||||
|
* Used by every module that imports HttpModule.
|
||||||
|
*/
|
||||||
|
export function createHttpModuleOptions(
|
||||||
|
configService: ConfigService,
|
||||||
|
): HttpModuleOptions | Promise<HttpModuleOptions> {
|
||||||
|
const socksHost = configService.get<string>("SOCKS_PROXY_HOST");
|
||||||
|
const socksPort = configService.get<string>("SOCKS_PROXY_PORT");
|
||||||
|
|
||||||
|
if (socksHost && socksPort) {
|
||||||
|
const proxyUrl = `socks5://${socksHost}:${socksPort}`;
|
||||||
|
const agent = new SocksProxyAgent(proxyUrl);
|
||||||
|
return {
|
||||||
|
httpsAgent: agent,
|
||||||
|
httpAgent: agent,
|
||||||
|
proxy: false,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {};
|
||||||
|
}
|
||||||
@@ -1871,6 +1871,7 @@ export class ExpertBlameService {
|
|||||||
link: this.smsOrchestrationService.buildBlamePartyLink(
|
link: this.smsOrchestrationService.buildBlamePartyLink(
|
||||||
requestIdToken,
|
requestIdToken,
|
||||||
role,
|
role,
|
||||||
|
"v1",
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -2065,6 +2066,7 @@ export class ExpertBlameService {
|
|||||||
link: this.smsOrchestrationService.buildBlamePartyLink(
|
link: this.smsOrchestrationService.buildBlamePartyLink(
|
||||||
requestIdToken,
|
requestIdToken,
|
||||||
linkRole,
|
linkRole,
|
||||||
|
"v1",
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
import { MongooseModule } from "@nestjs/mongoose";
|
import { MongooseModule } from "@nestjs/mongoose";
|
||||||
import { AiModule } from "src/ai/ai.module";
|
import { AiModule } from "src/ai/ai.module";
|
||||||
import { AuthModule } from "src/auth/auth.module";
|
import { AuthModule } from "src/auth/auth.module";
|
||||||
@@ -21,7 +23,11 @@ import { ExpertClaimService } from "./expert-claim.service";
|
|||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
SandHubModule,
|
SandHubModule,
|
||||||
MongooseModule.forFeature([
|
MongooseModule.forFeature([
|
||||||
{ name: ClaimFactorsImage.name, schema: ClaimFactorsImageSchema },
|
{ name: ClaimFactorsImage.name, schema: ClaimFactorsImageSchema },
|
||||||
|
|||||||
@@ -3164,7 +3164,7 @@ export class ExpertClaimService {
|
|||||||
receptor: ownerPhoneResend,
|
receptor: ownerPhoneResend,
|
||||||
fileKind: "claim",
|
fileKind: "claim",
|
||||||
publicId: claim.publicId,
|
publicId: claim.publicId,
|
||||||
link: this.smsOrchestrationService.buildClaimLink(String(claim._id)),
|
link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3462,21 +3462,11 @@ export class ExpertClaimService {
|
|||||||
fileKind: "claim",
|
fileKind: "claim",
|
||||||
publicId: claim.publicId,
|
publicId: claim.publicId,
|
||||||
expertLastName,
|
expertLastName,
|
||||||
link: this.smsOrchestrationService.buildClaimLink(String(claim._id)),
|
link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const fanavaranExpertise = !needsFactorUpload
|
// Fanavaran expertise is now triggered on owner final sign, not here.
|
||||||
? await this.claimRequestManagementService.autoSubmitFanavaranExpertiseOnExpertReply(
|
|
||||||
claimRequestId,
|
|
||||||
)
|
|
||||||
: {
|
|
||||||
attempted: false,
|
|
||||||
submitted: false,
|
|
||||||
skipped: true,
|
|
||||||
skipReason:
|
|
||||||
"Expertise submit waits until factor-needed repair lines are validated.",
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
claimRequestId,
|
claimRequestId,
|
||||||
@@ -3490,7 +3480,6 @@ export class ExpertClaimService {
|
|||||||
mixedPricingAndFactors: mixedFactorAndPrice,
|
mixedPricingAndFactors: mixedFactorAndPrice,
|
||||||
allPartsFactorNeeded: !!needsFactorUpload && !!allFactorLines,
|
allPartsFactorNeeded: !!needsFactorUpload && !!allFactorLines,
|
||||||
isFinalReplyAfterObjection,
|
isFinalReplyAfterObjection,
|
||||||
fanavaranExpertise,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3727,14 +3716,19 @@ export class ExpertClaimService {
|
|||||||
let claims: any[] = [];
|
let claims: any[] = [];
|
||||||
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
||||||
const expertOid = new Types.ObjectId(actor.sub);
|
const expertOid = new Types.ObjectId(actor.sub);
|
||||||
|
// Exclude V4/V5 blame files — same rule as getFieldExpertClaimListV2.
|
||||||
const expertBlameIds = await this.blameRequestDbService
|
const expertBlameIds = await this.blameRequestDbService
|
||||||
.find(
|
.find(
|
||||||
{ expertInitiated: true, initiatedByFieldExpertId: expertOid },
|
{
|
||||||
|
expertInitiated: true,
|
||||||
|
initiatedByFieldExpertId: expertOid,
|
||||||
|
isMadeByFileMaker: { $ne: true },
|
||||||
|
},
|
||||||
{ select: "_id", lean: true },
|
{ select: "_id", lean: true },
|
||||||
)
|
)
|
||||||
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
||||||
const claimOr: Record<string, unknown>[] = [
|
const claimOr: Record<string, unknown>[] = [
|
||||||
{ initiatedByFieldExpertId: expertOid },
|
{ initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } },
|
||||||
];
|
];
|
||||||
if (expertBlameIds.length > 0) {
|
if (expertBlameIds.length > 0) {
|
||||||
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
||||||
@@ -4063,15 +4057,22 @@ export class ExpertClaimService {
|
|||||||
query: ListQueryV2Dto = {},
|
query: ListQueryV2Dto = {},
|
||||||
): Promise<GetClaimListV2ResponseDto> {
|
): Promise<GetClaimListV2ResponseDto> {
|
||||||
const expertOid = new Types.ObjectId(actor.sub);
|
const expertOid = new Types.ObjectId(actor.sub);
|
||||||
|
// Exclude V4/V5 blame files (isMadeByFileMaker=true) — those belong to
|
||||||
|
// the FILE_MAKER/FILE_REVIEWER flows, not the V3 field-expert flow.
|
||||||
const expertBlameIds = await this.blameRequestDbService
|
const expertBlameIds = await this.blameRequestDbService
|
||||||
.find(
|
.find(
|
||||||
{ expertInitiated: true, initiatedByFieldExpertId: expertOid },
|
{
|
||||||
|
expertInitiated: true,
|
||||||
|
initiatedByFieldExpertId: expertOid,
|
||||||
|
isMadeByFileMaker: { $ne: true },
|
||||||
|
},
|
||||||
{ select: "_id", lean: true },
|
{ select: "_id", lean: true },
|
||||||
)
|
)
|
||||||
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
||||||
|
|
||||||
const claimOr: Record<string, unknown>[] = [
|
const claimOr: Record<string, unknown>[] = [
|
||||||
{ initiatedByFieldExpertId: expertOid },
|
// Direct claim link: exclude V5 claims that require FileMaker approval
|
||||||
|
{ initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } },
|
||||||
];
|
];
|
||||||
if (expertBlameIds.length > 0) {
|
if (expertBlameIds.length > 0) {
|
||||||
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
||||||
@@ -4749,8 +4750,19 @@ export class ExpertClaimService {
|
|||||||
"This file has been taken by another reviewer.",
|
"This file has been taken by another reviewer.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (!claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame)) {
|
} else {
|
||||||
throw new ForbiddenException("This claim is not accessible to you.");
|
// FIELD_EXPERT: V3 flow only. Reject V4/V5 files (isMadeByFileMaker)
|
||||||
|
// even if their ID matches initiatedByFieldExpertId on the blame —
|
||||||
|
// those are FILE_MAKER files, accessible via the FILE_MAKER role only.
|
||||||
|
const isV4V5Blame = !!(linkedBlame as any)?.isMadeByFileMaker;
|
||||||
|
if (isV4V5Blame) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
"Field experts can only access V3 expert-initiated files.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame)) {
|
||||||
|
throw new ForbiddenException("This claim is not accessible to you.");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// Fall through to the detail build below (skip the damage-expert gate)
|
// Fall through to the detail build below (skip the damage-expert gate)
|
||||||
} else if (actor.role !== RoleEnum.FILE_MAKER) {
|
} else if (actor.role !== RoleEnum.FILE_MAKER) {
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { readFile } from "node:fs/promises";
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
@@ -117,6 +118,21 @@ export class ExpertClaimV2Controller {
|
|||||||
return this.claimRequestManagementService.getOuterPartsCatalogV2(carType);
|
return this.claimRequestManagementService.getOuterPartsCatalogV2(carType);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get("inner-parts-catalog")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Get inner parts catalog",
|
||||||
|
description: "Returns the full list of inner car parts from the static catalog.",
|
||||||
|
})
|
||||||
|
@ApiResponse({ status: 200, description: "Inner parts catalog (object keyed by part name)" })
|
||||||
|
async getInnerPartsCatalog() {
|
||||||
|
const raw = await readFile(`${process.cwd()}/src/static/car-part.json`, "utf-8");
|
||||||
|
try {
|
||||||
|
return JSON.parse(raw);
|
||||||
|
} catch {
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Get("branches")
|
@Get("branches")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "List insurer branches for this damage expert (V2)",
|
summary: "List insurer branches for this damage expert (V2)",
|
||||||
|
|||||||
@@ -76,6 +76,37 @@ export const FANAVARAN_REMOTE_LOOKUPS: FanavaranRemoteLookupDefinition[] = [
|
|||||||
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/person-role`,
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/person-role`,
|
||||||
cacheFile: "person-role.json",
|
cacheFile: "person-role.json",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "insurance-corp",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/insurance-corp`,
|
||||||
|
cacheFile: "insurance-corp.json",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "file-types",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/base-info/file-types`,
|
||||||
|
cacheFile: "file-types.json",
|
||||||
|
},
|
||||||
|
// NEW LOOKUPS ADDED
|
||||||
|
{
|
||||||
|
name: "cities",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/base-info/cities`,
|
||||||
|
cacheFile: "cities.json",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dmg-case-type",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/code-list/dmg-case-type`,
|
||||||
|
cacheFile: "dmg-case-type.json",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dmg-history-status",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/code-list/dmg-case-history-status`,
|
||||||
|
cacheFile: "dmg-history-status.json",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "provinces",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/base-info/Provinces`,
|
||||||
|
cacheFile: "provinces.json",
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
export const TEJARAT_STATIC_ACCIDENT_FILES = {
|
export const TEJARAT_STATIC_ACCIDENT_FILES = {
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
import { FanavaranLookupService } from "./fanavaran-lookup.service";
|
import { FanavaranLookupService } from "./fanavaran-lookup.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [HttpModule],
|
imports: [
|
||||||
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
|
],
|
||||||
providers: [FanavaranLookupService],
|
providers: [FanavaranLookupService],
|
||||||
exports: [FanavaranLookupService],
|
exports: [FanavaranLookupService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -183,24 +183,6 @@ export class FanavaranLookupService {
|
|||||||
this.logger.log(
|
this.logger.log(
|
||||||
`[${clientKey}] Fanavaran lookup response status=${response.status} dataCount=${dataCount}`,
|
`[${clientKey}] Fanavaran lookup response status=${response.status} dataCount=${dataCount}`,
|
||||||
);
|
);
|
||||||
this.logger.log(
|
|
||||||
`[${clientKey}] Fanavaran lookup raw response: ${JSON.stringify(
|
|
||||||
response.data,
|
|
||||||
null,
|
|
||||||
2,
|
|
||||||
)}`,
|
|
||||||
);
|
|
||||||
|
|
||||||
if (Array.isArray(response.data) && response.data.length > 0) {
|
|
||||||
const firstItem = response.data[0];
|
|
||||||
if (firstItem && typeof firstItem === "object") {
|
|
||||||
this.logger.log(
|
|
||||||
`[${clientKey}] Fanavaran lookup first item keys: ${Object.keys(
|
|
||||||
firstItem,
|
|
||||||
).join(", ")}`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return response.data;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -255,6 +237,51 @@ export class FanavaranLookupService {
|
|||||||
return this.fetchFromFanavaran(clientKey, url);
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async myPolicies(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
nationalCode: string,
|
||||||
|
insuranceLineId: number = 5,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url =
|
||||||
|
`${FANAVARAN_LOOKUP_BASE_URL}/common/Policies/inquiry-my-policies` +
|
||||||
|
`?InsuranceLineId=${insuranceLineId}` +
|
||||||
|
`&NationalCode=${encodeURIComponent(nationalCode)}`;
|
||||||
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
async thirdPartyPolicyById(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
policyId: number,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/third-party-car-policies/${policyId}`;
|
||||||
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bodyPolicyById(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
policyId: number,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicle-hull-policies/${policyId}`;
|
||||||
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
async vehicleById(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
vehicleId: number,
|
||||||
|
versionNo: number = 1,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicles/${vehicleId}?versionno=${versionNo}`;
|
||||||
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
|
}
|
||||||
|
|
||||||
|
async customerById(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
customerId: number,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url = `${FANAVARAN_LOOKUP_BASE_URL}/common/customers/${customerId}`;
|
||||||
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
|
}
|
||||||
|
|
||||||
async inquiryByUniqueIdentifier(
|
async inquiryByUniqueIdentifier(
|
||||||
clientKey: FanavaranClientKey,
|
clientKey: FanavaranClientKey,
|
||||||
params: {
|
params: {
|
||||||
@@ -273,6 +300,91 @@ export class FanavaranLookupService {
|
|||||||
return this.fetchFromFanavaran(clientKey, url);
|
return this.fetchFromFanavaran(clientKey, url);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async resolveInsuranceCorpId(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
): Promise<number | null> {
|
||||||
|
const caption = process.env.INSURANCE_CORP_ID?.trim();
|
||||||
|
if (!caption) {
|
||||||
|
this.logger.warn("resolveInsuranceCorpId: INSURANCE_CORP_ID env not set");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check resolved cache first
|
||||||
|
const cachedId = await this.readCacheFile<number>(clientKey, "insurance-corp-id-resolved.json");
|
||||||
|
if (cachedId !== null) {
|
||||||
|
this.logger.log(`resolveInsuranceCorpId: using cached id=${cachedId} for "${caption}"`);
|
||||||
|
return cachedId;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try fetching the full list directly from Fanavaran
|
||||||
|
let companies: unknown;
|
||||||
|
const url = `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/insurance-corp`;
|
||||||
|
try {
|
||||||
|
companies = await this.fetchFromFanavaran(clientKey, url);
|
||||||
|
} catch (error) {
|
||||||
|
this.logger.warn(
|
||||||
|
`resolveInsuranceCorpId: Fanavaran fetch failed, trying local lookup endpoint`,
|
||||||
|
);
|
||||||
|
// Fallback: call our own local lookup endpoint
|
||||||
|
try {
|
||||||
|
const localPort = process.env.PORT || 3000;
|
||||||
|
const response = await firstValueFrom(
|
||||||
|
this.httpService.get(`http://localhost:${localPort}/lookups/fanavaran/insurance-corp`, {
|
||||||
|
timeout: 10000,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
companies = response.data;
|
||||||
|
} catch (localError) {
|
||||||
|
this.logger.error(
|
||||||
|
`resolveInsuranceCorpId: both Fanavaran and local lookup failed`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(companies)) {
|
||||||
|
this.logger.warn(
|
||||||
|
`resolveInsuranceCorpId: insurance-corp response is not an array, type=${typeof companies}`,
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.log(
|
||||||
|
`resolveInsuranceCorpId: got ${companies.length} companies, searching for "${caption}"`,
|
||||||
|
);
|
||||||
|
|
||||||
|
const normalizedCaption = caption
|
||||||
|
.replace(/\s+/g, " ")
|
||||||
|
.toLowerCase()
|
||||||
|
.trim();
|
||||||
|
|
||||||
|
const match = companies.find((c: any) => {
|
||||||
|
if (c?.IsActive !== 1) return false;
|
||||||
|
if (typeof c?.Id !== "number") return false;
|
||||||
|
const cCaption = typeof c?.Caption === "string" ? c.Caption : "";
|
||||||
|
const normalized = cCaption.replace(/\s+/g, " ").toLowerCase().trim();
|
||||||
|
return normalized.includes(normalizedCaption) || normalizedCaption.includes(normalized);
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!match) {
|
||||||
|
this.logger.warn(
|
||||||
|
`resolveInsuranceCorpId: no active company matching "${caption}". Available: ` +
|
||||||
|
companies
|
||||||
|
.filter((c: any) => c?.IsActive === 1)
|
||||||
|
.map((c: any) => `${c.Caption} (${c.Id})`)
|
||||||
|
.join(", "),
|
||||||
|
);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const corpId = match.Id as number;
|
||||||
|
// Cache both the resolved id and the full list for future use
|
||||||
|
await this.writeCacheFile(clientKey, "insurance-corp-id-resolved.json", corpId);
|
||||||
|
await this.writeCacheFile(clientKey, "insurance-corp.json", companies);
|
||||||
|
this.logger.log(`resolveInsuranceCorpId: resolved id=${corpId} for "${caption}"`);
|
||||||
|
return corpId;
|
||||||
|
}
|
||||||
|
|
||||||
mapFanavaranAccidentCausesToReasonOptions(
|
mapFanavaranAccidentCausesToReasonOptions(
|
||||||
causes: unknown,
|
causes: unknown,
|
||||||
): { id: number; label: string; fanavaran: number }[] {
|
): { id: number; label: string; fanavaran: number }[] {
|
||||||
@@ -297,4 +409,5 @@ export class FanavaranLookupService {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,18 @@
|
|||||||
import { Controller, Get, Param, Query } from "@nestjs/common";
|
import { Controller, Get, Param, ParseIntPipe, Query, UseGuards } from "@nestjs/common";
|
||||||
import {
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
ApiOkResponse,
|
ApiOkResponse,
|
||||||
ApiOperation,
|
ApiOperation,
|
||||||
ApiParam,
|
ApiParam,
|
||||||
ApiQuery,
|
ApiQuery,
|
||||||
ApiTags,
|
ApiTags,
|
||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
|
import { AuthGuard } from "src/common/auth/guards";
|
||||||
import { LookupsService } from "./lookups.service";
|
import { LookupsService } from "./lookups.service";
|
||||||
|
|
||||||
@ApiTags("lookups")
|
@ApiTags("lookups")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
@Controller("lookups")
|
@Controller("lookups")
|
||||||
export class LookupsController {
|
export class LookupsController {
|
||||||
constructor(private readonly lookupsService: LookupsService) {}
|
constructor(private readonly lookupsService: LookupsService) {}
|
||||||
@@ -210,6 +214,83 @@ export class LookupsController {
|
|||||||
return await this.lookupsService.getPersonRole();
|
return await this.lookupsService.getPersonRole();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get("file-types")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran file types lookup",
|
||||||
|
description:
|
||||||
|
"Returns file type codes from common/base-info/file-types. Use FileTypeId in attachment uploads.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran file types lookup data",
|
||||||
|
schema: {
|
||||||
|
type: "array",
|
||||||
|
items: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
Caption: { type: "string" },
|
||||||
|
Id: { type: "number" },
|
||||||
|
IsActive: { type: "number" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async getFileTypes() {
|
||||||
|
return await this.lookupsService.getFileTypes();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("cities")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran cities lookup",
|
||||||
|
description: "Returns city codes from common/base-info/cities.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran cities lookup data",
|
||||||
|
schema: { type: "array", items: { type: "object" } },
|
||||||
|
})
|
||||||
|
async cities() {
|
||||||
|
return await this.lookupsService.getCities();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("provinces")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran provinces lookup",
|
||||||
|
description: "Returns province codes from common/base-info/provinces.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran provinces lookup data",
|
||||||
|
schema: { type: "array", items: { type: "object" } },
|
||||||
|
})
|
||||||
|
async provinces() {
|
||||||
|
return await this.lookupsService.getProvinces();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("dmg-case-type")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran damage case type lookup",
|
||||||
|
description: "Returns damage case type codes from car/code-list/dmg-case-type.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran damage case type lookup data",
|
||||||
|
schema: { type: "array", items: { type: "object" } },
|
||||||
|
})
|
||||||
|
async dmgCaseType() {
|
||||||
|
return await this.lookupsService.getDmgCaseType();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("dmg-history-status")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran damage history status lookup",
|
||||||
|
description:
|
||||||
|
"Returns damage history status codes from car/code-list/dmg-case-history-status.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran damage history status lookup data",
|
||||||
|
schema: { type: "array", items: { type: "object" } },
|
||||||
|
})
|
||||||
|
async dmgHistoryStatus() {
|
||||||
|
return await this.lookupsService.getDmgHistoryStatus();
|
||||||
|
}
|
||||||
|
|
||||||
@Get("inquiry-by-vin")
|
@Get("inquiry-by-vin")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Fanavaran vehicle inquiry by VIN",
|
summary: "Fanavaran vehicle inquiry by VIN",
|
||||||
@@ -371,4 +452,75 @@ export class LookupsController {
|
|||||||
async getAccidentFields() {
|
async getAccidentFields() {
|
||||||
return await this.lookupsService.getAccidentFields();
|
return await this.lookupsService.getAccidentFields();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get("my-policies")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "My policies inquiry",
|
||||||
|
description:
|
||||||
|
"Returns the list of policies for the given national code via common/Policies/inquiry-my-policies.",
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: "nationalCode",
|
||||||
|
description: "National code of the insured person",
|
||||||
|
example: "0012345678",
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: "insuranceLineId",
|
||||||
|
description: "Insurance line ID (default: 5 for car)",
|
||||||
|
required: false,
|
||||||
|
example: 5,
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns list of policies",
|
||||||
|
schema: { type: "array", items: { type: "object" } },
|
||||||
|
})
|
||||||
|
async myPolicies(
|
||||||
|
@Query("nationalCode") nationalCode: string,
|
||||||
|
@Query("insuranceLineId") insuranceLineId?: number,
|
||||||
|
) {
|
||||||
|
return await this.lookupsService.myPolicies(
|
||||||
|
nationalCode,
|
||||||
|
insuranceLineId ?? 5,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("third-party-policy/:policyId")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Third-party car policy inquiry by policy ID",
|
||||||
|
description:
|
||||||
|
"Returns third-party car insurance policy details for the given policy ID via car/third-party-car-policies/{policyId}.",
|
||||||
|
})
|
||||||
|
@ApiParam({
|
||||||
|
name: "policyId",
|
||||||
|
description: "Fanavaran policy ID",
|
||||||
|
example: 12345,
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns third-party policy details",
|
||||||
|
schema: { type: "object" },
|
||||||
|
})
|
||||||
|
async thirdPartyPolicyById(
|
||||||
|
@Param("policyId", ParseIntPipe) policyId: number,
|
||||||
|
) {
|
||||||
|
return await this.lookupsService.thirdPartyPolicyById(policyId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("body-policy/:policyId")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Vehicle hull (body) policy inquiry by policy ID",
|
||||||
|
description:
|
||||||
|
"Returns vehicle hull (body) insurance policy details for the given policy ID via car/vehicle-hull-policies/{policyId}.",
|
||||||
|
})
|
||||||
|
@ApiParam({
|
||||||
|
name: "policyId",
|
||||||
|
description: "Fanavaran policy ID",
|
||||||
|
example: 12345,
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns body policy details",
|
||||||
|
schema: { type: "object" },
|
||||||
|
})
|
||||||
|
async bodyPolicyById(@Param("policyId", ParseIntPipe) policyId: number) {
|
||||||
|
return await this.lookupsService.bodyPolicyById(policyId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -123,11 +123,109 @@ export class LookupsService {
|
|||||||
return await this.getClientRemoteLookup("person-role");
|
return await this.getClientRemoteLookup("person-role");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getFileTypes(): Promise<any> {
|
||||||
|
return await this.getClientRemoteLookup("file-types");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getCities(): Promise<any> {
|
||||||
|
return await this.getClientRemoteLookup("cities");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getProvinces(): Promise<any> {
|
||||||
|
return await this.getClientRemoteLookup("provinces");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getDmgCaseType(): Promise<any> {
|
||||||
|
return await this.getClientRemoteLookup("dmg-case-type");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getDmgHistoryStatus(): Promise<any> {
|
||||||
|
return await this.getClientRemoteLookup("dmg-history-status");
|
||||||
|
}
|
||||||
|
|
||||||
async inquiryByVin(vin: string): Promise<unknown> {
|
async inquiryByVin(vin: string): Promise<unknown> {
|
||||||
const clientKey = this.activeClientKey();
|
const clientKey = this.activeClientKey();
|
||||||
return this.fanavaranLookupService.inquiryByVin(clientKey, vin);
|
return this.fanavaranLookupService.inquiryByVin(clientKey, vin);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async myPolicies(
|
||||||
|
nationalCode: string,
|
||||||
|
insuranceLineId: number = 5,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const clientKey = this.activeClientKey();
|
||||||
|
return this.fanavaranLookupService.myPolicies(
|
||||||
|
clientKey,
|
||||||
|
nationalCode,
|
||||||
|
insuranceLineId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async mapPolicyDetails(policy: any): Promise<any> {
|
||||||
|
if (!policy || typeof policy !== "object") {
|
||||||
|
return policy;
|
||||||
|
}
|
||||||
|
|
||||||
|
const mappedPolicy = { ...policy };
|
||||||
|
|
||||||
|
// 1. Map PreviousInsuranceCorpId and TransferorInsuranceCorpId
|
||||||
|
try {
|
||||||
|
const companies = (await this.getClientRemoteLookup("insurance-corp")) as any[];
|
||||||
|
if (Array.isArray(companies)) {
|
||||||
|
if (typeof policy.PreviousInsuranceCorpId === "number") {
|
||||||
|
const match = companies.find((c) => c.Id === policy.PreviousInsuranceCorpId);
|
||||||
|
if (match) {
|
||||||
|
mappedPolicy.PreviousInsuranceCorpName = match.Caption;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (typeof policy.TransferorInsuranceCorpId === "number") {
|
||||||
|
const match = companies.find((c) => c.Id === policy.TransferorInsuranceCorpId);
|
||||||
|
if (match) {
|
||||||
|
mappedPolicy.TransferorInsuranceCorpName = match.Caption;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(`Failed to map insurance-corp lookups: ${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Map PolicyUsageTypeId
|
||||||
|
try {
|
||||||
|
const useTypes = (await this.getClientRemoteLookup("vehicle-use-types")) as any[];
|
||||||
|
if (Array.isArray(useTypes) && typeof policy.PolicyUsageTypeId === "number") {
|
||||||
|
const match = useTypes.find((t) => t.Id === policy.PolicyUsageTypeId);
|
||||||
|
if (match) {
|
||||||
|
mappedPolicy.PolicyUsageTypeName = match.Caption;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
this.logger.warn(`Failed to map vehicle-use-types lookups: ${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return mappedPolicy;
|
||||||
|
}
|
||||||
|
|
||||||
|
async thirdPartyPolicyById(policyId: number): Promise<unknown> {
|
||||||
|
const clientKey = this.activeClientKey();
|
||||||
|
const policy = await this.fanavaranLookupService.thirdPartyPolicyById(clientKey, policyId);
|
||||||
|
return this.mapPolicyDetails(policy);
|
||||||
|
}
|
||||||
|
|
||||||
|
async bodyPolicyById(policyId: number): Promise<unknown> {
|
||||||
|
const clientKey = this.activeClientKey();
|
||||||
|
const policy = await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId);
|
||||||
|
return this.mapPolicyDetails(policy);
|
||||||
|
}
|
||||||
|
|
||||||
|
async vehicleById(vehicleId: number, versionNo: number = 1): Promise<unknown> {
|
||||||
|
const clientKey = this.activeClientKey();
|
||||||
|
return this.fanavaranLookupService.vehicleById(clientKey, vehicleId, versionNo);
|
||||||
|
}
|
||||||
|
|
||||||
|
async customerById(customerId: number): Promise<unknown> {
|
||||||
|
const clientKey = this.activeClientKey();
|
||||||
|
return this.fanavaranLookupService.customerById(clientKey, customerId);
|
||||||
|
}
|
||||||
|
|
||||||
async getAccidentWay(): Promise<{ id: number; label: string }[]> {
|
async getAccidentWay(): Promise<{ id: number; label: string }[]> {
|
||||||
const clientKey = this.activeClientKey();
|
const clientKey = this.activeClientKey();
|
||||||
const fileName = TEJARAT_STATIC_ACCIDENT_FILES.accidentWay;
|
const fileName = TEJARAT_STATIC_ACCIDENT_FILES.accidentWay;
|
||||||
|
|||||||
154
src/request-management/call-center-blame-v6.controller.ts
Normal file
154
src/request-management/call-center-blame-v6.controller.ts
Normal file
@@ -0,0 +1,154 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
UseGuards,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiResponse,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
|
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||||
|
import { RolesGuard } from "src/auth/guards/role.guard";
|
||||||
|
import { Roles } from "src/decorators/roles.decorator";
|
||||||
|
import { CurrentUser } from "src/decorators/user.decorator";
|
||||||
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
|
import { RequestManagementService } from "./request-management.service";
|
||||||
|
import { RunCallCenterInquiryV6Dto } from "./dto/run-call-center-inquiry-v6.dto";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6 call-center blame API.
|
||||||
|
*
|
||||||
|
* A call-center agent takes the guilty party's details over the phone
|
||||||
|
* (plate, national code, birthday), runs the insurance inquiry, then sends
|
||||||
|
* the blame link via SMS. The user (guilty party) opens the link and
|
||||||
|
* completes the form through the standard v2 user flow — except the
|
||||||
|
* initial-form / inquiry step is skipped (`skipInitialFormStep=true`) because
|
||||||
|
* the agent already did it.
|
||||||
|
*
|
||||||
|
* For THIRD_PARTY files: only the guilty party's data is collected here.
|
||||||
|
* The damaged party sees their own portion of the page and fills their info
|
||||||
|
* as normal after the blame link is opened.
|
||||||
|
*/
|
||||||
|
@ApiTags("call-center-blame (v6)")
|
||||||
|
@Controller("v6/call-center-blame")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||||
|
@Roles(RoleEnum.CALL_CENTER)
|
||||||
|
export class CallCenterBlameV6Controller {
|
||||||
|
constructor(
|
||||||
|
private readonly requestManagementService: RequestManagementService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Get("my-files")
|
||||||
|
@ApiOperation({ summary: "[V6] List blame files created by this call-center agent" })
|
||||||
|
@ApiResponse({ status: 200, description: "List of blame files started by this agent" })
|
||||||
|
getMyFiles(@CurrentUser() agent: any) {
|
||||||
|
return this.requestManagementService.getMyCallCenterFilesV6(agent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("create")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "[V6] Create a call-center–initiated blame file",
|
||||||
|
description:
|
||||||
|
"Creates a LINK blame file. The call-center agent collects the guilty " +
|
||||||
|
"party's plate + national-code over the phone, calls run-inquiry to store " +
|
||||||
|
"the results, then calls send-link to SMS the blame URL to the user. " +
|
||||||
|
"The user opens the link and fills the form via the normal v2 flow; the " +
|
||||||
|
"initial-form/inquiry step is automatically skipped because the agent " +
|
||||||
|
"already ran it.",
|
||||||
|
})
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["type"],
|
||||||
|
properties: {
|
||||||
|
type: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["THIRD_PARTY", "CAR_BODY"],
|
||||||
|
example: "THIRD_PARTY",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
createFile(
|
||||||
|
@CurrentUser() agent: any,
|
||||||
|
@Body("type") type: "THIRD_PARTY" | "CAR_BODY",
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.createCallCenterInitiatedBlameV6(agent, { type });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("run-inquiry/:requestId")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "[V6] Run plate + insurance inquiry for the guilty party",
|
||||||
|
description:
|
||||||
|
"Call after `create`. The agent supplies the plate and national-code data " +
|
||||||
|
"collected from the caller. Plate + third-party block inquiry is executed " +
|
||||||
|
"and the results are stored on the blame document. " +
|
||||||
|
"For THIRD_PARTY files only the guilty party (first party) is inquired here; " +
|
||||||
|
"the damaged party's inquiry is handled later by the user via the link. " +
|
||||||
|
"Sheba (IBAN) is not collected here — the user adds it themselves.",
|
||||||
|
})
|
||||||
|
@ApiParam({ name: "requestId", description: "Blame request ID from `create`" })
|
||||||
|
@ApiBody({ type: RunCallCenterInquiryV6Dto })
|
||||||
|
runInquiry(
|
||||||
|
@CurrentUser() agent: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: RunCallCenterInquiryV6Dto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.runCallCenterInquiryV6(agent, requestId, dto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("send-link/:requestId")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "[V6] Send blame link to the guilty party via SMS",
|
||||||
|
description:
|
||||||
|
"Call after `run-inquiry`. Provide the guilty party's phone number; " +
|
||||||
|
"the service registers the user if needed, stores them as the first party, " +
|
||||||
|
"and sends the blame invite link via SMS. The user opens the link and " +
|
||||||
|
"completes the blame form via the standard v2 user flow (initial-form step skipped).",
|
||||||
|
})
|
||||||
|
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["phoneNumber"],
|
||||||
|
properties: {
|
||||||
|
phoneNumber: {
|
||||||
|
type: "string",
|
||||||
|
example: "09121234567",
|
||||||
|
description: "Mobile number of the guilty party",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
sendLink(
|
||||||
|
@CurrentUser() agent: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body("phoneNumber") phoneNumber: string,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.sendCallCenterLinkV6(agent, requestId, { phoneNumber });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("blame/:requestId")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "[V6] Get a single blame file created by this agent",
|
||||||
|
description:
|
||||||
|
"Returns the current status, workflow step, and party data for one blame " +
|
||||||
|
"file started by this call-center agent. Useful for checking whether the " +
|
||||||
|
"user has opened the link and progressed through the form.",
|
||||||
|
})
|
||||||
|
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||||
|
getBlame(
|
||||||
|
@CurrentUser() agent: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.getCallCenterBlameDetailV6(agent, requestId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||||
import { IsEnum, IsOptional, IsString } from "class-validator";
|
import { IsBoolean, IsEnum, IsOptional } from "class-validator";
|
||||||
import { CreationMethod } from "../entities/schema/request-management.schema";
|
import { CreationMethod } from "../entities/schema/request-management.schema";
|
||||||
|
|
||||||
export class CreateExpertInitiatedFileDto {
|
export class CreateExpertInitiatedFileDto {
|
||||||
@@ -18,4 +18,17 @@ export class CreateExpertInitiatedFileDto {
|
|||||||
})
|
})
|
||||||
@IsEnum(CreationMethod)
|
@IsEnum(CreationMethod)
|
||||||
creationMethod: CreationMethod;
|
creationMethod: CreationMethod;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 only. When true the resulting claim will require FileMaker approval
|
||||||
|
* before fanavaran submission. V4 files must leave this unset (or false).
|
||||||
|
*/
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
"V5 only — when true the claim requires FileMaker approval before fanavaran submission.",
|
||||||
|
example: false,
|
||||||
|
})
|
||||||
|
@IsBoolean()
|
||||||
|
@IsOptional()
|
||||||
|
requiresFileMakerApproval?: boolean;
|
||||||
}
|
}
|
||||||
|
|||||||
85
src/request-management/dto/run-call-center-inquiry-v6.dto.ts
Normal file
85
src/request-management/dto/run-call-center-inquiry-v6.dto.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||||
|
import {
|
||||||
|
IsBoolean,
|
||||||
|
IsNotEmpty,
|
||||||
|
IsOptional,
|
||||||
|
IsString,
|
||||||
|
ValidateNested,
|
||||||
|
} from "class-validator";
|
||||||
|
import { Type } from "class-transformer";
|
||||||
|
|
||||||
|
class PlateV6Dto {
|
||||||
|
@ApiProperty({ example: "44", description: "Left two digits" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
leftDigits: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "ب", description: "Center alphabet letter" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
centerAlphabet: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "111", description: "Center three digits" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
centerDigits: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "22", description: "Right two digits (Iran region code)" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
ir: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inquiry body for the V6 call-center flow.
|
||||||
|
* Same as V3 but without `sheba` — the user adds their own IBAN later via the link.
|
||||||
|
*/
|
||||||
|
export class RunCallCenterInquiryV6Dto {
|
||||||
|
@ApiProperty({
|
||||||
|
type: PlateV6Dto,
|
||||||
|
description: "Plate segments — Tejarat block / third-party inquiry.",
|
||||||
|
})
|
||||||
|
@ValidateNested()
|
||||||
|
@Type(() => PlateV6Dto)
|
||||||
|
plate: PlateV6Dto;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nationalCodeOfInsurer: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nationalCodeOfDriver: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
|
||||||
|
@IsBoolean()
|
||||||
|
driverIsInsurer: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
|
||||||
|
insurerBirthday: number | string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: 13780624,
|
||||||
|
description: "Driver birth date (Jalali). Required when driverIsInsurer is false.",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
driverBirthday?: number | string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: "123456789",
|
||||||
|
description: "Driver license (required when driverIsInsurer is false).",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
driverLicense?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: "123456789",
|
||||||
|
description: "Insurer license (required when driverIsInsurer is true).",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
insurerLicense?: string;
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import {
|
|||||||
IsNotEmpty,
|
IsNotEmpty,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
|
MaxLength,
|
||||||
ValidateNested,
|
ValidateNested,
|
||||||
} from "class-validator";
|
} from "class-validator";
|
||||||
import { Type } from "class-transformer";
|
import { Type } from "class-transformer";
|
||||||
@@ -89,3 +90,66 @@ export class RunInquiriesV3Dto {
|
|||||||
@IsString()
|
@IsString()
|
||||||
insurerLicense?: string;
|
insurerLicense?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Body for `POST run-inquiries-vin/:requestId`.
|
||||||
|
* Identical to RunInquiriesV3Dto but uses `vin` (17-char chassis number) instead of `plate`.
|
||||||
|
* First call = guilty party (+ auto claim). Second call = damaged party (THIRD_PARTY only).
|
||||||
|
*/
|
||||||
|
export class RunInquiriesVinV3Dto {
|
||||||
|
@ApiProperty({
|
||||||
|
example: "NAAM01E15HK123456",
|
||||||
|
description: "17-character VIN / chassis number (شماره شاسی)",
|
||||||
|
maxLength: 17,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
@MaxLength(17)
|
||||||
|
vin: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nationalCodeOfInsurer: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
nationalCodeOfDriver: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
|
||||||
|
@IsBoolean()
|
||||||
|
driverIsInsurer: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
|
||||||
|
insurerBirthday: number | string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: 13780624, description: "Driver birth date (Jalali). Required when driverIsInsurer is false." })
|
||||||
|
@IsOptional()
|
||||||
|
driverBirthday?: number | string | null;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: "IR123456789012345678901234",
|
||||||
|
description:
|
||||||
|
"Sheba (IBAN). Required on the damaged party call (CAR_BODY first call; THIRD_PARTY second call).",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
sheba?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: "123456789",
|
||||||
|
description: "Driver license (required when driverIsInsurer is false).",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
driverLicense?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
example: "123456789",
|
||||||
|
description: "Insurer license (required when driverIsInsurer is true).",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
insurerLicense?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -117,12 +117,40 @@ export class BlameRequest {
|
|||||||
@Prop({ default: false })
|
@Prop({ default: false })
|
||||||
isMadeByFileMaker?: boolean;
|
isMadeByFileMaker?: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 only. When true the resulting claim requires FileMaker approval before
|
||||||
|
* fanavaran submission. V4 files never set this; it is written at creation
|
||||||
|
* time by the V5 controller and propagated to the linked claim.
|
||||||
|
*/
|
||||||
|
@Prop({ default: false })
|
||||||
|
requiresFileMakerApproval?: boolean;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The FileReviewer who claimed this file for completion (V4 flow only).
|
* The FileReviewer who claimed this file for completion (V4 flow only).
|
||||||
* Set when a FileReviewer calls assign on this file; enforces one-reviewer-per-file.
|
* Set when a FileReviewer calls assign on this file; enforces one-reviewer-per-file.
|
||||||
*/
|
*/
|
||||||
@Prop({ type: Types.ObjectId })
|
@Prop({ type: Types.ObjectId })
|
||||||
assignedFileReviewerId?: Types.ObjectId;
|
assignedFileReviewerId?: Types.ObjectId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6 call-center flow: true when this blame was started by a call-center agent
|
||||||
|
* on behalf of the guilty party who called in.
|
||||||
|
*/
|
||||||
|
@Prop({ default: false })
|
||||||
|
callCenterInitiated?: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6 call-center flow: the call-center agent who created this file.
|
||||||
|
*/
|
||||||
|
@Prop({ type: Types.ObjectId })
|
||||||
|
initiatedByCallCenterId?: Types.ObjectId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6 call-center flow: when true the user-side blame page should skip the
|
||||||
|
* inquiry / initial-form step (the call-center agent already ran the inquiry).
|
||||||
|
*/
|
||||||
|
@Prop({ default: false })
|
||||||
|
skipInitialFormStep?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type BlameRequestDocument = HydratedDocument<BlameRequest>;
|
export type BlameRequestDocument = HydratedDocument<BlameRequest>;
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ export class Person {
|
|||||||
|
|
||||||
@Prop({ type: String })
|
@Prop({ type: String })
|
||||||
driverBirthday?: string | null;
|
driverBirthday?: string | null;
|
||||||
|
|
||||||
|
/** Cached Fanavaran party ID resolved from nationalCodeOfDriver + driverBirthday + driverIsInsurer */
|
||||||
|
@Prop({ type: Number })
|
||||||
|
fanavaranDriverId?: number;
|
||||||
}
|
}
|
||||||
export const PersonSchema = SchemaFactory.createForClass(Person);
|
export const PersonSchema = SchemaFactory.createForClass(Person);
|
||||||
|
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
|||||||
import { CreationMethod } from "./entities/schema/request-management.schema";
|
import { CreationMethod } from "./entities/schema/request-management.schema";
|
||||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
||||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||||
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
|
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
|
||||||
import {
|
import {
|
||||||
CarBodyFormDto,
|
CarBodyFormDto,
|
||||||
DescriptionDto,
|
DescriptionDto,
|
||||||
@@ -181,6 +181,23 @@ export class ExpertInitiatedBlameV3MirrorController {
|
|||||||
return this.requestManagementService.runInquiriesV3(requestId, expert, dto);
|
return this.requestManagementService.runInquiriesV3(requestId, expert, dto);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("run-inquiries-vin/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: RunInquiriesVinV3Dto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Run VIN/chassis inquiries for the current party (V3)",
|
||||||
|
description:
|
||||||
|
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
|
||||||
|
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
|
||||||
|
})
|
||||||
|
async runInquiriesVin(
|
||||||
|
@CurrentUser() expert: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: RunInquiriesVinV3Dto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.runInquiriesVinV3(requestId, expert, dto);
|
||||||
|
}
|
||||||
|
|
||||||
@Post("add-detail-location/:requestId")
|
@Post("add-detail-location/:requestId")
|
||||||
@ApiParam({ name: "requestId" })
|
@ApiParam({ name: "requestId" })
|
||||||
@ApiBody({ type: LocationDto })
|
@ApiBody({ type: LocationDto })
|
||||||
|
|||||||
@@ -27,6 +27,7 @@ import { MediaPolicyService } from "src/media-policy/media-policy.service";
|
|||||||
import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service";
|
import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service";
|
||||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
||||||
|
import { InitialFormVinDto } from "./dto/create-request-management.dto";
|
||||||
import {
|
import {
|
||||||
BlameConfessionDtoV2,
|
BlameConfessionDtoV2,
|
||||||
CarBodyFormDto,
|
CarBodyFormDto,
|
||||||
@@ -34,6 +35,7 @@ import {
|
|||||||
LocationDto,
|
LocationDto,
|
||||||
} from "./dto/create-request-management.dto";
|
} from "./dto/create-request-management.dto";
|
||||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
||||||
|
import { CreationMethod } from "./entities/schema/request-management.schema";
|
||||||
import { SendPartyOtpsDto } from "./dto/send-party-otps.dto";
|
import { SendPartyOtpsDto } from "./dto/send-party-otps.dto";
|
||||||
import { VerifyPartyOtpsDto } from "./dto/verify-party-otps.dto";
|
import { VerifyPartyOtpsDto } from "./dto/verify-party-otps.dto";
|
||||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||||
@@ -75,17 +77,17 @@ export class ExpertInitiatedBlameMirrorController {
|
|||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "[Expert mirror] Create expert-initiated blame file",
|
summary: "[Expert mirror] Create expert-initiated blame file",
|
||||||
description:
|
description:
|
||||||
"Use creationMethod=IN_PERSON for the on-site flow. Creates a BlameRequest owned by the parties but filled by the expert.",
|
"Creates an IN_PERSON blame file filled by the expert on behalf of both parties. creationMethod is always forced to IN_PERSON regardless of what is sent.",
|
||||||
})
|
})
|
||||||
@ApiBody({ type: CreateExpertInitiatedFileDto })
|
@ApiBody({ type: CreateExpertInitiatedFileDto })
|
||||||
async create(
|
async create(
|
||||||
@CurrentUser() expert: any,
|
@CurrentUser() expert: any,
|
||||||
@Body() dto: CreateExpertInitiatedFileDto,
|
@Body() dto: CreateExpertInitiatedFileDto,
|
||||||
) {
|
) {
|
||||||
return this.requestManagementService.createExpertInitiatedBlameV2(
|
return this.requestManagementService.createExpertInitiatedBlameV2(expert, {
|
||||||
expert,
|
...dto,
|
||||||
dto,
|
creationMethod: CreationMethod.IN_PERSON,
|
||||||
);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("send-link/:requestId")
|
@Post("send-link/:requestId")
|
||||||
@@ -180,6 +182,29 @@ export class ExpertInitiatedBlameMirrorController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("/run-inquiries-vin/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: InitialFormVinDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "[Expert mirror] Initial form via VIN/chassis inquiry for current party",
|
||||||
|
description:
|
||||||
|
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
|
||||||
|
"Fills the FIRST or SECOND party insurance/vehicle data depending on the current workflow step.",
|
||||||
|
})
|
||||||
|
async initialFormVin(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: InitialFormVinDto,
|
||||||
|
@CurrentUser() expert: any,
|
||||||
|
@Body("partyRole") partyRole?: string,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.initialFormVinV2(
|
||||||
|
requestId,
|
||||||
|
body,
|
||||||
|
expert,
|
||||||
|
partyRole,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@ApiBody({
|
@ApiBody({
|
||||||
schema: {
|
schema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
|||||||
import { CreationMethod } from "./entities/schema/request-management.schema";
|
import { CreationMethod } from "./entities/schema/request-management.schema";
|
||||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
||||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||||
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
|
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
|
||||||
import {
|
import {
|
||||||
CarBodyFormDto,
|
CarBodyFormDto,
|
||||||
DescriptionDto,
|
DescriptionDto,
|
||||||
@@ -87,7 +87,9 @@ export class FileMakerBlameV4Controller {
|
|||||||
) {
|
) {
|
||||||
return this.requestManagementService.createExpertInitiatedBlameV2(
|
return this.requestManagementService.createExpertInitiatedBlameV2(
|
||||||
fileMaker,
|
fileMaker,
|
||||||
{ ...dto, creationMethod: CreationMethod.IN_PERSON },
|
// requiresFileMakerApproval is V5-only; explicitly exclude it from V4 so
|
||||||
|
// a client that accidentally sends the field cannot poison the blame record.
|
||||||
|
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: false },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,6 +193,27 @@ export class FileMakerBlameV4Controller {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("run-inquiries-vin/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: RunInquiriesVinV3Dto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Run VIN/chassis inquiries for the current party (V4)",
|
||||||
|
description:
|
||||||
|
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
|
||||||
|
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
|
||||||
|
})
|
||||||
|
async runInquiriesVin(
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: RunInquiriesVinV3Dto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.runInquiriesVinV3(
|
||||||
|
requestId,
|
||||||
|
fileMaker,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Party details ────────────────────────────────────────────────────────────
|
// ─── Party details ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@Post("add-detail-location/:requestId")
|
@Post("add-detail-location/:requestId")
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
|||||||
import { CreationMethod } from "./entities/schema/request-management.schema";
|
import { CreationMethod } from "./entities/schema/request-management.schema";
|
||||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
|
||||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||||
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
|
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
|
||||||
import {
|
import {
|
||||||
CarBodyFormDto,
|
CarBodyFormDto,
|
||||||
DescriptionDto,
|
DescriptionDto,
|
||||||
@@ -88,7 +88,7 @@ export class FileMakerBlameV5Controller {
|
|||||||
) {
|
) {
|
||||||
return this.requestManagementService.createExpertInitiatedBlameV2(
|
return this.requestManagementService.createExpertInitiatedBlameV2(
|
||||||
fileMaker,
|
fileMaker,
|
||||||
{ ...dto, creationMethod: CreationMethod.IN_PERSON },
|
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: true },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -192,6 +192,27 @@ export class FileMakerBlameV5Controller {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("run-inquiries-vin/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: RunInquiriesVinV3Dto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Run VIN/chassis inquiries for the current party (V5)",
|
||||||
|
description:
|
||||||
|
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
|
||||||
|
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
|
||||||
|
})
|
||||||
|
async runInquiriesVin(
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: RunInquiriesVinV3Dto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.runInquiriesVinV3(
|
||||||
|
requestId,
|
||||||
|
fileMaker,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Party details ────────────────────────────────────────────────────────────
|
// ─── Party details ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@Post("add-detail-location/:requestId")
|
@Post("add-detail-location/:requestId")
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
import { extname } from "node:path";
|
import { extname } from "node:path";
|
||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
|
HttpException,
|
||||||
|
InternalServerErrorException,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
@@ -316,6 +320,73 @@ export class FileReviewerBlameV4Controller {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Owner signature on expert pricing ───────────────────────────────────────
|
||||||
|
|
||||||
|
@Put("claim-sign/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@ApiBody({
|
||||||
|
description: "Signature file, agreement, and branch",
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["sign", "agree", "branchId"],
|
||||||
|
properties: {
|
||||||
|
sign: { type: "string", format: "binary", description: "Signature image" },
|
||||||
|
agree: { type: "boolean", description: "true to accept, false to reject" },
|
||||||
|
branchId: { type: "string", description: "Insurer branch ID" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Owner signature on expert pricing (V4 — FileReviewer acts on behalf of user)",
|
||||||
|
description:
|
||||||
|
"FileReviewer submits the damaged party's signature during the final approval stage. " +
|
||||||
|
"Delegates to the same service method as the user sign endpoint; the FileReviewer's " +
|
||||||
|
"identity is resolved to the claim owner via `resolveClaimEffectiveUserId`.",
|
||||||
|
})
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("sign", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-sign",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
|
||||||
|
callback(null, `${base}-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
async submitOwnerSign(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body("agree") agree: string | boolean,
|
||||||
|
@Body("branchId") branchId: string,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
@UploadedFile() sign: Express.Multer.File,
|
||||||
|
) {
|
||||||
|
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
|
||||||
|
const agreed =
|
||||||
|
typeof agree === "string"
|
||||||
|
? agree === "true" || agree === "1"
|
||||||
|
: Boolean(agree);
|
||||||
|
try {
|
||||||
|
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
|
||||||
|
claimRequestId,
|
||||||
|
agreed,
|
||||||
|
typeof branchId === "string" ? branchId : "",
|
||||||
|
sign,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof HttpException) throw error;
|
||||||
|
throw new InternalServerErrorException(
|
||||||
|
error instanceof Error ? error.message : "Failed to submit signature",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Walk-around video ────────────────────────────────────────────────────────
|
// ─── Walk-around video ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@Patch("car-capture/:claimRequestId")
|
@Patch("car-capture/:claimRequestId")
|
||||||
|
|||||||
@@ -3,9 +3,12 @@ import {
|
|||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
|
HttpException,
|
||||||
|
InternalServerErrorException,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
@@ -315,6 +318,73 @@ export class FileReviewerBlameV5Controller {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Owner signature on expert pricing ───────────────────────────────────────
|
||||||
|
|
||||||
|
@Put("claim-sign/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@ApiBody({
|
||||||
|
description: "Signature file, agreement, and branch",
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["sign", "agree", "branchId"],
|
||||||
|
properties: {
|
||||||
|
sign: { type: "string", format: "binary", description: "Signature image" },
|
||||||
|
agree: { type: "boolean", description: "true to accept, false to reject" },
|
||||||
|
branchId: { type: "string", description: "Insurer branch ID" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Owner signature on expert pricing (V5 — FileReviewer acts on behalf of user)",
|
||||||
|
description:
|
||||||
|
"FileReviewer submits the damaged party's signature during the final approval stage. " +
|
||||||
|
"Delegates to the same service method as the user sign endpoint; the FileReviewer's " +
|
||||||
|
"identity is resolved to the claim owner via `resolveClaimEffectiveUserId`.",
|
||||||
|
})
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("sign", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-sign",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
|
||||||
|
callback(null, `${base}-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
async submitOwnerSign(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body("agree") agree: string | boolean,
|
||||||
|
@Body("branchId") branchId: string,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
@UploadedFile() sign: Express.Multer.File,
|
||||||
|
) {
|
||||||
|
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
|
||||||
|
const agreed =
|
||||||
|
typeof agree === "string"
|
||||||
|
? agree === "true" || agree === "1"
|
||||||
|
: Boolean(agree);
|
||||||
|
try {
|
||||||
|
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
|
||||||
|
claimRequestId,
|
||||||
|
agreed,
|
||||||
|
typeof branchId === "string" ? branchId : "",
|
||||||
|
sign,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof HttpException) throw error;
|
||||||
|
throw new InternalServerErrorException(
|
||||||
|
error instanceof Error ? error.message : "Failed to submit signature",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Walk-around video ────────────────────────────────────────────────────────
|
// ─── Walk-around video ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@Patch("car-capture/:claimRequestId")
|
@Patch("car-capture/:claimRequestId")
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import { MediaPolicyService } from "src/media-policy/media-policy.service";
|
|||||||
import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service";
|
import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service";
|
||||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
||||||
|
import { InitialFormVinDto } from "./dto/create-request-management.dto";
|
||||||
import {
|
import {
|
||||||
CarBodyFormDto,
|
CarBodyFormDto,
|
||||||
DescriptionDto,
|
DescriptionDto,
|
||||||
@@ -165,6 +166,29 @@ export class RegistrarBlameMirrorController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("/initial-form-vin/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: InitialFormVinDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "[Registrar mirror] Initial form via VIN/chassis inquiry for current party",
|
||||||
|
description:
|
||||||
|
"VIN alternative to initial-form. Uses ESG chassis lookup instead of plate-based inquiry. " +
|
||||||
|
"Fills the FIRST or SECOND party insurance/vehicle data depending on the current workflow step.",
|
||||||
|
})
|
||||||
|
async initialFormVin(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: InitialFormVinDto,
|
||||||
|
@CurrentUser() registrar: any,
|
||||||
|
@Body("partyRole") partyRole?: string,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.initialFormVinV2(
|
||||||
|
requestId,
|
||||||
|
body,
|
||||||
|
registrar,
|
||||||
|
partyRole,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@ApiBody({
|
@ApiBody({
|
||||||
schema: {
|
schema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
|
|||||||
@@ -50,6 +50,7 @@ import { FileReviewerBlameV5Controller } from "./file-reviewer-blame-v5.controll
|
|||||||
import { FileMakerClaimApprovalV5Controller } from "./file-maker-claim-approval-v5.controller";
|
import { FileMakerClaimApprovalV5Controller } from "./file-maker-claim-approval-v5.controller";
|
||||||
import { InquiryRefreshController } from "./inquiry-refresh.controller";
|
import { InquiryRefreshController } from "./inquiry-refresh.controller";
|
||||||
import { InquiryRefreshService } from "./inquiry-refresh.service";
|
import { InquiryRefreshService } from "./inquiry-refresh.service";
|
||||||
|
import { CallCenterBlameV6Controller } from "./call-center-blame-v6.controller";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -92,6 +93,7 @@ import { InquiryRefreshService } from "./inquiry-refresh.service";
|
|||||||
FileReviewerBlameV5Controller,
|
FileReviewerBlameV5Controller,
|
||||||
FileMakerClaimApprovalV5Controller,
|
FileMakerClaimApprovalV5Controller,
|
||||||
InquiryRefreshController,
|
InquiryRefreshController,
|
||||||
|
CallCenterBlameV6Controller,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
RequestManagementService,
|
RequestManagementService,
|
||||||
|
|||||||
@@ -42,7 +42,7 @@ import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatu
|
|||||||
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
||||||
import { resolveClaimOwnerFieldsFromBlame } from "src/helpers/blame-damaged-party";
|
import { resolveClaimOwnerFieldsFromBlame } from "src/helpers/blame-damaged-party";
|
||||||
import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto";
|
import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto";
|
||||||
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
|
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
|
||||||
import { SandHubService } from "src/sand-hub/sand-hub.service";
|
import { SandHubService } from "src/sand-hub/sand-hub.service";
|
||||||
import { ReqBlameStatus } from "src/Types&Enums/blame-request-management/status.enum";
|
import { ReqBlameStatus } from "src/Types&Enums/blame-request-management/status.enum";
|
||||||
import { StepsEnum } from "src/Types&Enums/blame-request-management/steps.enum";
|
import { StepsEnum } from "src/Types&Enums/blame-request-management/steps.enum";
|
||||||
@@ -278,6 +278,32 @@ export class RequestManagementService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// IN_PERSON THIRD_PARTY (expert/registrar-initiated): after first-party description
|
||||||
|
// the expert collects the first party's signature before moving to the second party.
|
||||||
|
// Skip FIRST_INVITE_SECOND and hold at WAITING_FOR_SIGNATURES so the sign endpoint
|
||||||
|
// can be called for the first party. The workflow advances to FIRST_INVITE_SECOND
|
||||||
|
// only after expertUploadPartySignatureV2/V3 records the first-party confirmation.
|
||||||
|
if (
|
||||||
|
req.type === BlameRequestType.THIRD_PARTY &&
|
||||||
|
req.creationMethod === CreationMethod.IN_PERSON &&
|
||||||
|
(req.expertInitiated || req.registrarInitiated) &&
|
||||||
|
submittedStepKey === WorkflowStep.FIRST_DESCRIPTION
|
||||||
|
) {
|
||||||
|
const completed = Array.isArray(req.workflow.completedSteps)
|
||||||
|
? req.workflow.completedSteps
|
||||||
|
: [];
|
||||||
|
if (!completed.includes(submittedStepKey))
|
||||||
|
completed.push(submittedStepKey);
|
||||||
|
req.workflow.completedSteps = completed;
|
||||||
|
req.workflow.currentStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
||||||
|
req.workflow.nextStep = undefined;
|
||||||
|
req.status = CaseStatus.WAITING_FOR_SIGNATURES;
|
||||||
|
this.logger.debug(
|
||||||
|
"[WORKFLOW] IN_PERSON THIRD_PARTY: advanced to WAITING_FOR_SIGNATURES after FIRST_DESCRIPTION (first-party sign before second-party invite)",
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// IN_PERSON THIRD_PARTY: guilt is decided on-site by the expert — there is
|
// IN_PERSON THIRD_PARTY: guilt is decided on-site by the expert — there is
|
||||||
// no waiting-for-field-expert phase. Replace WAITING_FOR_GUILT_DECISION
|
// no waiting-for-field-expert phase. Replace WAITING_FOR_GUILT_DECISION
|
||||||
// with WAITING_FOR_SIGNATURES wherever it would surface as current/next step.
|
// with WAITING_FOR_SIGNATURES wherever it would surface as current/next step.
|
||||||
@@ -2087,13 +2113,9 @@ export class RequestManagementService {
|
|||||||
? req.workflow.completedSteps
|
? req.workflow.completedSteps
|
||||||
: [];
|
: [];
|
||||||
if (!completed.includes(stepKey)) completed.push(stepKey);
|
if (!completed.includes(stepKey)) completed.push(stepKey);
|
||||||
// Same as post–field-expert reply: guilt phase is satisfied without an expert; parties must still sign.
|
|
||||||
if (!completed.includes(WorkflowStep.WAITING_FOR_GUILT_DECISION)) {
|
|
||||||
completed.push(WorkflowStep.WAITING_FOR_GUILT_DECISION);
|
|
||||||
}
|
|
||||||
req.workflow.completedSteps = completed;
|
req.workflow.completedSteps = completed;
|
||||||
req.workflow.currentStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
req.workflow.currentStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
||||||
req.workflow.nextStep = undefined;
|
req.workflow.nextStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
||||||
req.status = CaseStatus.WAITING_FOR_SIGNATURES;
|
req.status = CaseStatus.WAITING_FOR_SIGNATURES;
|
||||||
closedByMutualAgreement = true;
|
closedByMutualAgreement = true;
|
||||||
|
|
||||||
@@ -2174,12 +2196,9 @@ export class RequestManagementService {
|
|||||||
? req.workflow.completedSteps
|
? req.workflow.completedSteps
|
||||||
: [];
|
: [];
|
||||||
if (!completed.includes(stepKey)) completed.push(stepKey);
|
if (!completed.includes(stepKey)) completed.push(stepKey);
|
||||||
if (!completed.includes(WorkflowStep.WAITING_FOR_GUILT_DECISION)) {
|
|
||||||
completed.push(WorkflowStep.WAITING_FOR_GUILT_DECISION);
|
|
||||||
}
|
|
||||||
req.workflow.completedSteps = completed;
|
req.workflow.completedSteps = completed;
|
||||||
req.workflow.currentStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
req.workflow.currentStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
||||||
req.workflow.nextStep = undefined;
|
req.workflow.nextStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
||||||
req.status = CaseStatus.WAITING_FOR_SIGNATURES;
|
req.status = CaseStatus.WAITING_FOR_SIGNATURES;
|
||||||
} else if (!closedByMutualAgreement) {
|
} else if (!closedByMutualAgreement) {
|
||||||
if (stepKey === WorkflowStep.SECOND_DESCRIPTION) {
|
if (stepKey === WorkflowStep.SECOND_DESCRIPTION) {
|
||||||
@@ -2300,6 +2319,7 @@ export class RequestManagementService {
|
|||||||
const url = this.smsOrchestrationService.buildInviteLink(
|
const url = this.smsOrchestrationService.buildInviteLink(
|
||||||
frontendRoute,
|
frontendRoute,
|
||||||
requestId,
|
requestId,
|
||||||
|
"v1",
|
||||||
);
|
);
|
||||||
await this.smsOrchestrationService.sendInviteLink(
|
await this.smsOrchestrationService.sendInviteLink(
|
||||||
secondPartyPhone,
|
secondPartyPhone,
|
||||||
@@ -2353,6 +2373,7 @@ export class RequestManagementService {
|
|||||||
const url = this.smsOrchestrationService.buildInviteLink(
|
const url = this.smsOrchestrationService.buildInviteLink(
|
||||||
frontendRoute,
|
frontendRoute,
|
||||||
requestId,
|
requestId,
|
||||||
|
"v1",
|
||||||
);
|
);
|
||||||
await this.smsOrchestrationService.sendInviteLink(
|
await this.smsOrchestrationService.sendInviteLink(
|
||||||
phoneNumber,
|
phoneNumber,
|
||||||
@@ -3466,6 +3487,7 @@ export class RequestManagementService {
|
|||||||
const URL = this.smsOrchestrationService.buildInviteLink(
|
const URL = this.smsOrchestrationService.buildInviteLink(
|
||||||
frontendRoutes,
|
frontendRoutes,
|
||||||
requestId,
|
requestId,
|
||||||
|
"v1",
|
||||||
);
|
);
|
||||||
await this.smsOrchestrationService.sendInviteLink(
|
await this.smsOrchestrationService.sendInviteLink(
|
||||||
phoneNumber,
|
phoneNumber,
|
||||||
@@ -4816,6 +4838,9 @@ export class RequestManagementService {
|
|||||||
? FilledBy.EXPERT
|
? FilledBy.EXPERT
|
||||||
: FilledBy.CUSTOMER,
|
: FilledBy.CUSTOMER,
|
||||||
...(isFileMakerRole ? { isMadeByFileMaker: true } : {}),
|
...(isFileMakerRole ? { isMadeByFileMaker: true } : {}),
|
||||||
|
// V5 only: flag that causes the resulting claim to require FileMaker
|
||||||
|
// approval before fanavaran submission. V4 files never set this.
|
||||||
|
...(dto.requiresFileMakerApproval ? { requiresFileMakerApproval: true } : {}),
|
||||||
});
|
});
|
||||||
|
|
||||||
const requestId = String((created as any)._id);
|
const requestId = String((created as any)._id);
|
||||||
@@ -4905,6 +4930,7 @@ export class RequestManagementService {
|
|||||||
const firstLink = this.smsOrchestrationService.buildBlamePartyLink(
|
const firstLink = this.smsOrchestrationService.buildBlamePartyLink(
|
||||||
requestId,
|
requestId,
|
||||||
"FIRST",
|
"FIRST",
|
||||||
|
"v2",
|
||||||
);
|
);
|
||||||
const smsSent = await this.smsOrchestrationService.sendFieldExpertLink({
|
const smsSent = await this.smsOrchestrationService.sendFieldExpertLink({
|
||||||
receptor: phone,
|
receptor: phone,
|
||||||
@@ -6637,11 +6663,11 @@ export class RequestManagementService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
await this.verifyExpertAccessForBlameV2(req, expert);
|
await this.verifyExpertAccessForBlameV2(req, expert);
|
||||||
// if (req.status !== CaseStatus.WAITING_FOR_SIGNATURES) {
|
if (req.status !== CaseStatus.WAITING_FOR_SIGNATURES) {
|
||||||
// throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
// "Request is not waiting for signatures. Current status: " + req.status,
|
"Request is not waiting for signatures. Current status: " + req.status,
|
||||||
// );
|
);
|
||||||
// }
|
}
|
||||||
const partyIndex = this.getPartyIndex(req, partyRole);
|
const partyIndex = this.getPartyIndex(req, partyRole);
|
||||||
if (partyIndex === -1) {
|
if (partyIndex === -1) {
|
||||||
throw new BadRequestException(
|
throw new BadRequestException(
|
||||||
@@ -6728,6 +6754,23 @@ export class RequestManagementService {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
} else if (
|
||||||
|
// THIRD_PARTY IN_PERSON: first party just signed — advance workflow to
|
||||||
|
// FIRST_INVITE_SECOND so the frontend knows to proceed to the second-party
|
||||||
|
// registration step. Status stays WAITING_FOR_SIGNATURES.
|
||||||
|
req.type === BlameRequestType.THIRD_PARTY &&
|
||||||
|
req.creationMethod === CreationMethod.IN_PERSON &&
|
||||||
|
(req.expertInitiated || req.registrarInitiated) &&
|
||||||
|
partyRole === PartyRole.FIRST
|
||||||
|
) {
|
||||||
|
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
|
||||||
|
$set: {
|
||||||
|
"workflow.currentStep": WorkflowStep.FIRST_INVITE_SECOND as any,
|
||||||
|
"workflow.nextStep": WorkflowStep.SECOND_INITIAL_FORM as any,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
message =
|
||||||
|
"First party signature recorded. Proceed to register the second party.";
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
requestId: String(req._id),
|
requestId: String(req._id),
|
||||||
@@ -6753,6 +6796,18 @@ export class RequestManagementService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
await this.verifyExpertAccessForBlameV2(req, expert);
|
await this.verifyExpertAccessForBlameV2(req, expert);
|
||||||
|
// In the V2 IN_PERSON mirror flow guilt is resolved automatically after both
|
||||||
|
// parties complete their narrative steps (addDescriptionV2). The sign step for
|
||||||
|
// both parties must happen BEFORE accident-fields is called — calling it earlier
|
||||||
|
// would overwrite the workflow and cause the frontend to skip the sign page.
|
||||||
|
if (
|
||||||
|
req.creationMethod === CreationMethod.IN_PERSON &&
|
||||||
|
req.status !== CaseStatus.COMPLETED
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`accident-fields can only be submitted after both parties have signed (current status: ${req.status}). Complete both signatures first.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if (!req.expert) req.expert = {} as any;
|
if (!req.expert) req.expert = {} as any;
|
||||||
if (!req.expert.decision) req.expert.decision = {} as any;
|
if (!req.expert.decision) req.expert.decision = {} as any;
|
||||||
@@ -6781,29 +6836,24 @@ export class RequestManagementService {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// For IN_PERSON expert files: after accident fields are filled, guilt is
|
// IN_PERSON V2 mirror: accident-fields is a post-sign supplemental step called
|
||||||
// decided and we can go straight to signatures (no separate review needed).
|
// only after COMPLETED (both parties have signed). Record WAITING_FOR_GUILT_DECISION
|
||||||
|
// in completedSteps here — it was intentionally omitted from description so the
|
||||||
|
// frontend does not route to this page before signatures are collected.
|
||||||
if (req.creationMethod === CreationMethod.IN_PERSON) {
|
if (req.creationMethod === CreationMethod.IN_PERSON) {
|
||||||
const completed = Array.isArray(req.workflow?.completedSteps)
|
const completed = Array.isArray(req.workflow?.completedSteps)
|
||||||
? req.workflow.completedSteps
|
? req.workflow.completedSteps
|
||||||
: [];
|
: [];
|
||||||
const currentStep = req.workflow?.currentStep as WorkflowStep | undefined;
|
|
||||||
if (currentStep && !completed.includes(currentStep)) {
|
|
||||||
completed.push(currentStep);
|
|
||||||
}
|
|
||||||
if (!completed.includes(WorkflowStep.WAITING_FOR_GUILT_DECISION)) {
|
if (!completed.includes(WorkflowStep.WAITING_FOR_GUILT_DECISION)) {
|
||||||
completed.push(WorkflowStep.WAITING_FOR_GUILT_DECISION);
|
completed.push(WorkflowStep.WAITING_FOR_GUILT_DECISION);
|
||||||
}
|
}
|
||||||
if (req.workflow) {
|
if (req.workflow) {
|
||||||
req.workflow.completedSteps = completed;
|
req.workflow.completedSteps = completed;
|
||||||
req.workflow.currentStep = WorkflowStep.WAITING_FOR_SIGNATURES;
|
|
||||||
req.workflow.nextStep = undefined;
|
|
||||||
}
|
}
|
||||||
req.status = CaseStatus.WAITING_FOR_SIGNATURES;
|
|
||||||
|
|
||||||
if (!Array.isArray(req.history)) req.history = [];
|
if (!Array.isArray(req.history)) req.history = [];
|
||||||
req.history.push({
|
req.history.push({
|
||||||
type: "ACCIDENT_FIELDS_SAVED_ADVANCED_TO_SIGNATURES",
|
type: "ACCIDENT_FIELDS_SAVED",
|
||||||
actor: {
|
actor: {
|
||||||
actorId: new Types.ObjectId(String(expert.sub)),
|
actorId: new Types.ObjectId(String(expert.sub)),
|
||||||
actorName:
|
actorName:
|
||||||
@@ -6812,7 +6862,6 @@ export class RequestManagementService {
|
|||||||
},
|
},
|
||||||
metadata: {
|
metadata: {
|
||||||
accidentWay: fields.accidentWay,
|
accidentWay: fields.accidentWay,
|
||||||
advancedTo: WorkflowStep.WAITING_FOR_SIGNATURES,
|
|
||||||
},
|
},
|
||||||
} as any);
|
} as any);
|
||||||
}
|
}
|
||||||
@@ -8320,6 +8369,7 @@ export class RequestManagementService {
|
|||||||
targetPhone === request?.parties[0]?.person.phoneNumber
|
targetPhone === request?.parties[0]?.person.phoneNumber
|
||||||
? "FIRST"
|
? "FIRST"
|
||||||
: "SECOND",
|
: "SECOND",
|
||||||
|
"v1",
|
||||||
);
|
);
|
||||||
await this.smsOrchestrationService.sendThirdPartyDamagedPartyClaimLinkNotice(
|
await this.smsOrchestrationService.sendThirdPartyDamagedPartyClaimLinkNotice(
|
||||||
{
|
{
|
||||||
@@ -8834,9 +8884,10 @@ export class RequestManagementService {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
: {}),
|
: {}),
|
||||||
// V5 (isMadeByFileMaker): mark approval gate at claim creation so the flag
|
// V5 only: propagate the approval gate from the blame record to the claim.
|
||||||
// is always present regardless of whether upload-video is called.
|
// isMadeByFileMaker is true for both V4 and V5; only V5 blame records also
|
||||||
...((req as any).isMadeByFileMaker
|
// carry requiresFileMakerApproval=true (set at create time by the V5 controller).
|
||||||
|
...((req as any).requiresFileMakerApproval
|
||||||
? {
|
? {
|
||||||
requiresFileMakerApproval: true,
|
requiresFileMakerApproval: true,
|
||||||
fileMakerApprovalActorId: new Types.ObjectId(actor.sub),
|
fileMakerApprovalActorId: new Types.ObjectId(actor.sub),
|
||||||
@@ -9102,6 +9153,399 @@ export class RequestManagementService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* VIN variant of `runInquiriesV3`.
|
||||||
|
* Identical flow, but calls `getPolicyByChassisInquiry` instead of
|
||||||
|
* `getTejaratBlockInquiry` for the primary policy lookup.
|
||||||
|
*/
|
||||||
|
async runInquiriesVinV3(
|
||||||
|
requestId: string,
|
||||||
|
actor: any,
|
||||||
|
dto: RunInquiriesVinV3Dto,
|
||||||
|
): Promise<{
|
||||||
|
blameRequestId: string;
|
||||||
|
partyRole: PartyRole;
|
||||||
|
claimRequestId?: string;
|
||||||
|
claimPublicId?: string;
|
||||||
|
message: string;
|
||||||
|
}> {
|
||||||
|
const req = await this.blameRequestDbService.findById(requestId);
|
||||||
|
if (!req) throw new NotFoundException("Blame request not found");
|
||||||
|
this.assertBlameV3ExpertInPerson(req);
|
||||||
|
await this.verifyExpertAccessForBlameV2(req, actor);
|
||||||
|
|
||||||
|
const partyRole = this.resolveV3InquiryPartyRole(req);
|
||||||
|
if (!partyRole) {
|
||||||
|
throw new ConflictException("All party inquiries are already complete.");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (partyRole === PartyRole.FIRST) {
|
||||||
|
const firstIdx = this.getPartyIndex(req, PartyRole.FIRST);
|
||||||
|
if (firstIdx === -1)
|
||||||
|
throw new BadRequestException("First party not found");
|
||||||
|
const firstParty = req.parties[firstIdx];
|
||||||
|
if (!firstParty?.person?.userId) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"Guilty party OTP must be verified before running inquiries.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (req.type === BlameRequestType.CAR_BODY) {
|
||||||
|
const form = firstParty.carBodyFirstForm as any;
|
||||||
|
if (form?.car == null && form?.object == null) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"Submit car-body-form before running inquiries (CAR_BODY).",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.runPartyInquiriesVinV3Internal(
|
||||||
|
req,
|
||||||
|
dto,
|
||||||
|
PartyRole.FIRST,
|
||||||
|
firstParty,
|
||||||
|
);
|
||||||
|
if (req.type === BlameRequestType.CAR_BODY) {
|
||||||
|
await this.validateShebaV3(
|
||||||
|
dto as any,
|
||||||
|
firstParty.person?.clientId?.toString(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.markPartyInquiriesCompleteOnBlame(req, PartyRole.FIRST, actor);
|
||||||
|
await (req as any).save();
|
||||||
|
|
||||||
|
const nationalCode =
|
||||||
|
dto.nationalCodeOfInsurer || dto.nationalCodeOfDriver || "";
|
||||||
|
const newClaim = await this.createV3ClaimFromBlame(req, actor, {
|
||||||
|
sheba: req.type === BlameRequestType.CAR_BODY ? dto.sheba : undefined,
|
||||||
|
nationalCode:
|
||||||
|
req.type === BlameRequestType.CAR_BODY ? nationalCode : undefined,
|
||||||
|
interimThirdParty: req.type === BlameRequestType.THIRD_PARTY,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
blameRequestId: requestId,
|
||||||
|
partyRole: PartyRole.FIRST,
|
||||||
|
claimRequestId: String(newClaim._id),
|
||||||
|
claimPublicId: req.publicId,
|
||||||
|
message:
|
||||||
|
"Guilty-party inquiries complete and claim created. Proceed with location, description, voice, and signature.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Damaged party (THIRD_PARTY only)
|
||||||
|
if (!this.partyHasSigned(req, PartyRole.FIRST)) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"Guilty party must sign before running damaged-party inquiries.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const secondIdx = this.getPartyIndex(req, PartyRole.SECOND);
|
||||||
|
if (secondIdx === -1 || !req.parties[secondIdx]?.person?.userId) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"Damaged party OTP must be verified before running inquiries.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const secondParty = req.parties[secondIdx];
|
||||||
|
const firstIdx = this.getPartyIndex(req, PartyRole.FIRST);
|
||||||
|
const firstUserId =
|
||||||
|
firstIdx !== -1 ? req.parties[firstIdx]?.person?.userId : null;
|
||||||
|
const secondUserId = secondParty.person?.userId;
|
||||||
|
if (
|
||||||
|
firstUserId &&
|
||||||
|
secondUserId &&
|
||||||
|
String(firstUserId) === String(secondUserId)
|
||||||
|
) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
"Guilty and damaged parties are bound to the same user account. " +
|
||||||
|
"Re-verify the second party OTP using a different phone number.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.runPartyInquiriesVinV3Internal(
|
||||||
|
req,
|
||||||
|
dto,
|
||||||
|
PartyRole.SECOND,
|
||||||
|
secondParty,
|
||||||
|
);
|
||||||
|
await this.validateShebaV3(
|
||||||
|
dto as any,
|
||||||
|
secondParty.person?.clientId?.toString(),
|
||||||
|
);
|
||||||
|
|
||||||
|
this.ensureV3GuiltyPartyDecision(req);
|
||||||
|
if (typeof (req as any).markModified === "function") {
|
||||||
|
(req as any).markModified("parties");
|
||||||
|
}
|
||||||
|
await (req as any).save();
|
||||||
|
|
||||||
|
await this.syncV3ClaimDamagedPartyFromBlame(req, dto as any);
|
||||||
|
|
||||||
|
this.markPartyInquiriesCompleteOnBlame(req, PartyRole.SECOND, actor);
|
||||||
|
await (req as any).save();
|
||||||
|
|
||||||
|
return {
|
||||||
|
blameRequestId: requestId,
|
||||||
|
partyRole: PartyRole.SECOND,
|
||||||
|
message:
|
||||||
|
"Damaged-party inquiries complete. Proceed with location, description, voice, and signature.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* VIN variant of `runPartyInquiriesV3Internal`.
|
||||||
|
* Calls `getPolicyByChassisInquiry` (ESG chassis lookup) instead of
|
||||||
|
* `getTejaratBlockInquiry` (plate-based). All other inquiries (personal,
|
||||||
|
* driving licence, car-body for CAR_BODY) are unchanged.
|
||||||
|
*/
|
||||||
|
private async runPartyInquiriesVinV3Internal(
|
||||||
|
req: any,
|
||||||
|
partyData: RunInquiriesVinV3Dto,
|
||||||
|
partyRole: PartyRole,
|
||||||
|
party: any,
|
||||||
|
): Promise<{ clientId?: string }> {
|
||||||
|
const roleLabel = partyRole === PartyRole.FIRST ? "FIRST" : "SECOND";
|
||||||
|
let clientId: string | undefined;
|
||||||
|
const inquiryOptions = (cid?: string) =>
|
||||||
|
cid ? { clientId: cid } : undefined;
|
||||||
|
|
||||||
|
let inquiryRaw: any;
|
||||||
|
let inquiryMapped: any;
|
||||||
|
try {
|
||||||
|
const inquiry = await this.sandHubService.getPolicyByChassisInquiry(
|
||||||
|
partyData.vin,
|
||||||
|
inquiryOptions(party?.person?.clientId?.toString()),
|
||||||
|
);
|
||||||
|
inquiryRaw = inquiry.raw;
|
||||||
|
inquiryMapped = inquiry.mapped;
|
||||||
|
this.recordPartyCaseInquiryStatus(req, "thirdParty", partyRole, true, {
|
||||||
|
source: "ESG_VIN_INQUIRY",
|
||||||
|
raw: inquiryRaw,
|
||||||
|
mapped: inquiryMapped,
|
||||||
|
});
|
||||||
|
} catch (err: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[V3-VIN] vin inquiry failed for ${roleLabel} party (request=${req._id}): ${err?.message || err}`,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"thirdParty",
|
||||||
|
partyRole,
|
||||||
|
false,
|
||||||
|
{},
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
throw new BadRequestException(
|
||||||
|
`${roleLabel} party VIN inquiry failed: ${err?.message || "استعلام در دسترس نیست"}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (inquiryMapped?.Error) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
inquiryMapped.Error.Message ||
|
||||||
|
`${roleLabel} party VIN inquiry returned an error`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const clientName = inquiryMapped?.CompanyName;
|
||||||
|
const companyCode = inquiryMapped?.CompanyCode;
|
||||||
|
if (!clientName) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`CompanyName missing from ${roleLabel} party VIN inquiry response`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const client = await this.clientService.findOrCreateClientByCompanyCode(
|
||||||
|
companyCode,
|
||||||
|
clientName,
|
||||||
|
);
|
||||||
|
if (!client) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`CompanyCode missing or invalid in ${roleLabel} party VIN inquiry response`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const resolvedClientId = (client as any)?._id ?? (client as any)?._doc?._id;
|
||||||
|
clientId = resolvedClientId ? String(resolvedClientId) : undefined;
|
||||||
|
|
||||||
|
if (!party.person) party.person = {} as any;
|
||||||
|
party.person.clientId = resolvedClientId;
|
||||||
|
party.person.nationalCodeOfInsurer = partyData.nationalCodeOfInsurer;
|
||||||
|
party.person.nationalCodeOfDriver = partyData.nationalCodeOfDriver;
|
||||||
|
party.person.driverIsInsurer = partyData.driverIsInsurer;
|
||||||
|
party.person.insurerBirthday = partyData.insurerBirthday;
|
||||||
|
party.person.driverBirthday =
|
||||||
|
partyData.driverBirthday ??
|
||||||
|
(partyData.driverIsInsurer ? String(partyData.insurerBirthday) : null);
|
||||||
|
if (partyData.insurerLicense)
|
||||||
|
party.person.insurerLicense = partyData.insurerLicense;
|
||||||
|
if (partyData.driverLicense)
|
||||||
|
party.person.driverLicense = partyData.driverLicense;
|
||||||
|
|
||||||
|
if (!party.vehicle) party.vehicle = {} as any;
|
||||||
|
party.vehicle.plateId = partyData.vin; // store VIN as vehicle identifier
|
||||||
|
party.vehicle.name = inquiryMapped?.MapTypNam;
|
||||||
|
party.vehicle.type = `${inquiryMapped?.UsageField ?? ""} / ${inquiryMapped?.UsageName ?? inquiryMapped?.MapUsageName ?? "-"}`;
|
||||||
|
party.vehicle.inquiry = {
|
||||||
|
source: "ESG_VIN_INQUIRY",
|
||||||
|
raw: inquiryRaw,
|
||||||
|
mapped: inquiryMapped,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!party.insurance) party.insurance = {} as any;
|
||||||
|
party.insurance.policyNumber = inquiryMapped?.PrntPlcyCmpDocNo;
|
||||||
|
party.insurance.company = clientName;
|
||||||
|
party.insurance.financialCeiling = inquiryMapped?.FinancialCvrCptl;
|
||||||
|
party.insurance.startDate = inquiryMapped?.IssueDate;
|
||||||
|
party.insurance.endDate = inquiryMapped?.EndDate;
|
||||||
|
|
||||||
|
if (
|
||||||
|
req.type === BlameRequestType.CAR_BODY &&
|
||||||
|
partyRole === PartyRole.FIRST
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const carBodyInfo = await this.sandHubService.getTejaratCarBodyInquiry(
|
||||||
|
{
|
||||||
|
nationalCodeOfInsurer: partyData.nationalCodeOfInsurer,
|
||||||
|
plate: partyData.vin as any, // VIN used as identifier for CAR_BODY
|
||||||
|
},
|
||||||
|
clientId ? { clientId } : undefined,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, {
|
||||||
|
source: "TEJARAT_CAR_BODY_VIN_INQUIRY",
|
||||||
|
raw: carBodyInfo.raw,
|
||||||
|
mapped: carBodyInfo.mapped,
|
||||||
|
});
|
||||||
|
party.vehicle.inquiry = {
|
||||||
|
...party.vehicle.inquiry,
|
||||||
|
carBody: {
|
||||||
|
source: "TEJARAT_CAR_BODY_VIN_INQUIRY",
|
||||||
|
raw: carBodyInfo.raw,
|
||||||
|
mapped: carBodyInfo.mapped,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const m = carBodyInfo.mapped;
|
||||||
|
(party.insurance as any).carBodyInsurance = {
|
||||||
|
policyNumber: m.policyNumber ?? null,
|
||||||
|
companyId: m.companyId ?? null,
|
||||||
|
companyName: m.CompanyName ?? null,
|
||||||
|
};
|
||||||
|
const cbCompanyCode = m.companyId ?? m.CompanyCode;
|
||||||
|
const cbCompanyName = m.CompanyName ?? m.companyPersianName;
|
||||||
|
if (cbCompanyCode && cbCompanyName) {
|
||||||
|
const cbClient =
|
||||||
|
await this.clientService.findOrCreateClientByCompanyCode(
|
||||||
|
Number(cbCompanyCode),
|
||||||
|
String(cbCompanyName),
|
||||||
|
);
|
||||||
|
const cbClientId =
|
||||||
|
(cbClient as any)?._id ?? (cbClient as any)?._doc?._id;
|
||||||
|
if (cbClientId) {
|
||||||
|
party.person.clientId = cbClientId;
|
||||||
|
clientId = String(cbClientId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (err: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[V3-VIN] car body inquiry failed for request=${req._id}: ${err?.message || err}`,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"carBody",
|
||||||
|
partyRole,
|
||||||
|
false,
|
||||||
|
{},
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
throw new BadRequestException(
|
||||||
|
`CAR_BODY VIN inquiry failed: ${err?.message || "استعلام در دسترس نیست"}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const nationalCode =
|
||||||
|
partyData.nationalCodeOfInsurer || partyData.nationalCodeOfDriver;
|
||||||
|
const birthDate = partyData.insurerBirthday ?? partyData.driverBirthday;
|
||||||
|
if (nationalCode && birthDate != null) {
|
||||||
|
try {
|
||||||
|
const personalInquiry = await this.sandHubService.getPersonalInquiry(
|
||||||
|
nationalCode,
|
||||||
|
birthDate as string | number,
|
||||||
|
clientId ? { clientId } : undefined,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"person",
|
||||||
|
partyRole,
|
||||||
|
true,
|
||||||
|
personalInquiry,
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[V3-VIN] personal inquiry failed for ${roleLabel} party request=${req._id}: ${err?.message || err}`,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"person",
|
||||||
|
partyRole,
|
||||||
|
false,
|
||||||
|
{},
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
throw new BadRequestException(
|
||||||
|
`${roleLabel} party personal identity inquiry failed: ${err?.message || "استعلام در دسترس نیست"}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const licenseNationalCode = partyData.driverIsInsurer
|
||||||
|
? partyData.nationalCodeOfInsurer
|
||||||
|
: partyData.nationalCodeOfDriver;
|
||||||
|
const licenseNumber = partyData.driverIsInsurer
|
||||||
|
? partyData.insurerLicense
|
||||||
|
: partyData.driverLicense;
|
||||||
|
|
||||||
|
if (!licenseNumber) {
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"drivingLicence",
|
||||||
|
partyRole,
|
||||||
|
false,
|
||||||
|
{ skipped: true, reason: "No license number provided" },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
const licenseInquiry = await this.sandHubService.getDrivingLicenseInfo(
|
||||||
|
licenseNationalCode,
|
||||||
|
licenseNumber,
|
||||||
|
clientId ? { clientId } : undefined,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"drivingLicence",
|
||||||
|
partyRole,
|
||||||
|
true,
|
||||||
|
licenseInquiry,
|
||||||
|
);
|
||||||
|
} catch (err: any) {
|
||||||
|
this.logger.error(
|
||||||
|
`[V3-VIN] driving license inquiry failed for ${roleLabel} party request=${req._id}: ${err?.message || err}`,
|
||||||
|
);
|
||||||
|
this.recordPartyCaseInquiryStatus(
|
||||||
|
req,
|
||||||
|
"drivingLicence",
|
||||||
|
partyRole,
|
||||||
|
false,
|
||||||
|
{},
|
||||||
|
err,
|
||||||
|
);
|
||||||
|
throw new BadRequestException(
|
||||||
|
`${roleLabel} party driving license inquiry failed: ${err?.message || "استعلام در دسترس نیست"}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { clientId };
|
||||||
|
}
|
||||||
|
|
||||||
private assertBlameV3PartyDetailPhase(req: any, partyRole: PartyRole): void {
|
private assertBlameV3PartyDetailPhase(req: any, partyRole: PartyRole): void {
|
||||||
this.assertBlameV3ExpertInPerson(req);
|
this.assertBlameV3ExpertInPerson(req);
|
||||||
if (partyRole === PartyRole.FIRST) {
|
if (partyRole === PartyRole.FIRST) {
|
||||||
@@ -9242,12 +9686,11 @@ export class RequestManagementService {
|
|||||||
fresh.workflow.currentStep = WorkflowStep.FIRST_INVITE_SECOND;
|
fresh.workflow.currentStep = WorkflowStep.FIRST_INVITE_SECOND;
|
||||||
fresh.workflow.nextStep = WorkflowStep.SECOND_INITIAL_FORM;
|
fresh.workflow.nextStep = WorkflowStep.SECOND_INITIAL_FORM;
|
||||||
} else {
|
} else {
|
||||||
// CAR_BODY: FileMaker is done — seal the file for FileReviewer pickup
|
// CAR_BODY: FileMaker's narrative is done — move to document-upload step.
|
||||||
|
// blame.status transitions to WAITING_FOR_FILE_REVIEWER only after the
|
||||||
|
// FileMaker completes all document uploads, not here at sign time.
|
||||||
fresh.workflow.currentStep = WorkflowStep.FIRST_COMPLETED;
|
fresh.workflow.currentStep = WorkflowStep.FIRST_COMPLETED;
|
||||||
fresh.workflow.nextStep = WorkflowStep.WAITING_FOR_GUILT_DECISION;
|
fresh.workflow.nextStep = WorkflowStep.WAITING_FOR_GUILT_DECISION;
|
||||||
if (isFileMakerActor) {
|
|
||||||
fresh.status = CaseStatus.WAITING_FOR_FILE_REVIEWER;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
this.pushWorkflowSteps(fresh, [
|
this.pushWorkflowSteps(fresh, [
|
||||||
@@ -9259,10 +9702,8 @@ export class RequestManagementService {
|
|||||||
]);
|
]);
|
||||||
fresh.workflow.currentStep = WorkflowStep.SECOND_COMPLETED;
|
fresh.workflow.currentStep = WorkflowStep.SECOND_COMPLETED;
|
||||||
fresh.workflow.nextStep = WorkflowStep.WAITING_FOR_GUILT_DECISION;
|
fresh.workflow.nextStep = WorkflowStep.WAITING_FOR_GUILT_DECISION;
|
||||||
// THIRD_PARTY: second party sign is FileMaker's last step — seal for FileReviewer
|
// blame.status transitions to WAITING_FOR_FILE_REVIEWER only after the
|
||||||
if (isFileMakerActor) {
|
// FileMaker completes all document uploads, not here at sign time.
|
||||||
fresh.status = CaseStatus.WAITING_FOR_FILE_REVIEWER;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
await (fresh as any).save();
|
await (fresh as any).save();
|
||||||
}
|
}
|
||||||
@@ -9325,16 +9766,26 @@ export class RequestManagementService {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (typeof (req as any).markModified === "function") {
|
||||||
|
(req as any).markModified("expert");
|
||||||
|
}
|
||||||
|
|
||||||
if (!Array.isArray(req.history)) req.history = [];
|
if (!Array.isArray(req.history)) req.history = [];
|
||||||
req.history.push({
|
// Avoid duplicate history entries on idempotent retries.
|
||||||
type: "V3_ACCIDENT_FIELDS_SAVED",
|
const alreadyRecorded = (req.history as any[]).some(
|
||||||
actor: {
|
(e: any) => e?.type === "V3_ACCIDENT_FIELDS_SAVED",
|
||||||
actorId: new Types.ObjectId(String(expert.sub)),
|
);
|
||||||
actorName: `${expert.firstName || ""} ${expert.lastName || ""}`.trim(),
|
if (!alreadyRecorded) {
|
||||||
actorType: "field_expert",
|
req.history.push({
|
||||||
},
|
type: "V3_ACCIDENT_FIELDS_SAVED",
|
||||||
metadata: { accidentWay: fields.accidentWay },
|
actor: {
|
||||||
} as any);
|
actorId: new Types.ObjectId(String(expert.sub)),
|
||||||
|
actorName: `${expert.firstName || ""} ${expert.lastName || ""}`.trim(),
|
||||||
|
actorType: "field_expert",
|
||||||
|
},
|
||||||
|
metadata: { accidentWay: fields.accidentWay },
|
||||||
|
} as any);
|
||||||
|
}
|
||||||
|
|
||||||
await (req as any).save();
|
await (req as any).save();
|
||||||
|
|
||||||
@@ -10032,4 +10483,251 @@ export class RequestManagementService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── V6 call-center flow ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6: Create a LINK blame file initiated by a call-center agent.
|
||||||
|
* Always LINK + CUSTOMER-filled (user fills the form after receiving the SMS).
|
||||||
|
* `skipInitialFormStep` is set so the user-side page skips the inquiry step
|
||||||
|
* (the agent already ran it via runCallCenterInquiryV6).
|
||||||
|
*/
|
||||||
|
async createCallCenterInitiatedBlameV6(
|
||||||
|
agent: any,
|
||||||
|
dto: { type: "THIRD_PARTY" | "CAR_BODY" },
|
||||||
|
): Promise<{ requestId: string; publicId: string }> {
|
||||||
|
if (agent?.role !== RoleEnum.CALL_CENTER) {
|
||||||
|
throw new ForbiddenException("Only call-center agents can use this endpoint.");
|
||||||
|
}
|
||||||
|
const agentId = new Types.ObjectId(agent.sub);
|
||||||
|
const type =
|
||||||
|
dto.type === "CAR_BODY"
|
||||||
|
? BlameRequestType.CAR_BODY
|
||||||
|
: BlameRequestType.THIRD_PARTY;
|
||||||
|
|
||||||
|
const firstStep = await this.getWorkflowStep({ stepNumber: 1 });
|
||||||
|
if (!firstStep?.stepKey) {
|
||||||
|
throw new InternalServerErrorException(
|
||||||
|
"Workflow stepNumber=1 not configured in step manager",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const nextStepFromManager = firstStep.nextPossibleSteps?.[0];
|
||||||
|
const nextStep =
|
||||||
|
type === BlameRequestType.CAR_BODY
|
||||||
|
? (WorkflowStep.CAR_BODY_ACCIDENT_TYPE as WorkflowStep)
|
||||||
|
: (nextStepFromManager as WorkflowStep);
|
||||||
|
if (!nextStep) {
|
||||||
|
throw new InternalServerErrorException(
|
||||||
|
"Workflow stepNumber=1 has no nextPossibleSteps configured",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const publicId = await this.publicIdService.generateRequestPublicId();
|
||||||
|
|
||||||
|
const created = await this.blameRequestDbService.create({
|
||||||
|
publicId,
|
||||||
|
requestNo: publicId,
|
||||||
|
type,
|
||||||
|
parties: [{ role: PartyRole.FIRST, person: {} }],
|
||||||
|
workflow: {
|
||||||
|
currentStep: firstStep.stepKey as WorkflowStep,
|
||||||
|
nextStep,
|
||||||
|
completedSteps: [firstStep.stepKey as WorkflowStep],
|
||||||
|
locked: false,
|
||||||
|
},
|
||||||
|
history: [],
|
||||||
|
callCenterInitiated: true,
|
||||||
|
initiatedByCallCenterId: agentId,
|
||||||
|
creationMethod: CreationMethod.LINK,
|
||||||
|
filledBy: FilledBy.CUSTOMER,
|
||||||
|
// User-side page should skip the inquiry/initial-form step
|
||||||
|
skipInitialFormStep: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const requestId = String((created as any)._id);
|
||||||
|
if (!Array.isArray((created as any).history)) (created as any).history = [];
|
||||||
|
(created as any).history.push({
|
||||||
|
type: "FILE_CREATED_BY_CALL_CENTER",
|
||||||
|
actor: {
|
||||||
|
actorId: agentId,
|
||||||
|
actorName: `${agent.firstName || ""} ${agent.lastName || ""}`.trim(),
|
||||||
|
actorType: RoleEnum.CALL_CENTER,
|
||||||
|
},
|
||||||
|
metadata: { creationMethod: CreationMethod.LINK, type: dto.type },
|
||||||
|
});
|
||||||
|
await (created as any).save();
|
||||||
|
|
||||||
|
return { requestId, publicId: (created as any).publicId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6: Run plate + personal inquiry for the guilty party on behalf of the caller.
|
||||||
|
* Stores the inquiry results on the blame's first party (same as V3 guilty-party path)
|
||||||
|
* but does NOT create a claim — the user will do that after filling the form via the link.
|
||||||
|
* Note: sheba is intentionally absent — the user provides their own IBAN later.
|
||||||
|
*/
|
||||||
|
async runCallCenterInquiryV6(
|
||||||
|
agent: any,
|
||||||
|
requestId: string,
|
||||||
|
dto: Omit<RunInquiriesV3Dto, "sheba">,
|
||||||
|
): Promise<{ blameRequestId: string; message: string }> {
|
||||||
|
if (agent?.role !== RoleEnum.CALL_CENTER) {
|
||||||
|
throw new ForbiddenException("Only call-center agents can use this endpoint.");
|
||||||
|
}
|
||||||
|
const req = await this.blameRequestDbService.findById(requestId);
|
||||||
|
if (!req) throw new NotFoundException("Blame request not found");
|
||||||
|
if (!req.callCenterInitiated || String(req.initiatedByCallCenterId) !== String(agent.sub)) {
|
||||||
|
throw new ForbiddenException("You can only access files that you have initiated.");
|
||||||
|
}
|
||||||
|
|
||||||
|
const firstIdx = this.getPartyIndex(req, PartyRole.FIRST);
|
||||||
|
if (firstIdx === -1) throw new BadRequestException("First party not found");
|
||||||
|
const firstParty = req.parties[firstIdx];
|
||||||
|
|
||||||
|
await this.runPartyInquiriesV3Internal(req, dto, PartyRole.FIRST, firstParty);
|
||||||
|
this.markPartyInquiriesCompleteOnBlame(req, PartyRole.FIRST, agent);
|
||||||
|
if (!Array.isArray((req as any).history)) (req as any).history = [];
|
||||||
|
(req as any).history.push({
|
||||||
|
type: "CALL_CENTER_INQUIRY_COMPLETED",
|
||||||
|
actor: {
|
||||||
|
actorId: new Types.ObjectId(agent.sub),
|
||||||
|
actorName: `${agent.firstName || ""} ${agent.lastName || ""}`.trim(),
|
||||||
|
actorType: RoleEnum.CALL_CENTER,
|
||||||
|
},
|
||||||
|
metadata: { partyRole: PartyRole.FIRST },
|
||||||
|
});
|
||||||
|
await (req as any).save();
|
||||||
|
|
||||||
|
return {
|
||||||
|
blameRequestId: requestId,
|
||||||
|
message: "Guilty-party inquiry complete. You can now send the blame link to the user.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6: Send the blame link to the guilty party's phone number.
|
||||||
|
* Registers/looks up the user by phone and stores them as the first party, then
|
||||||
|
* sends the SMS link so the user can fill in the rest of the form via the v2 flow.
|
||||||
|
*/
|
||||||
|
async sendCallCenterLinkV6(
|
||||||
|
agent: any,
|
||||||
|
requestId: string,
|
||||||
|
dto: { phoneNumber: string },
|
||||||
|
): Promise<{ sent: boolean; sentTo: { role: string; phoneNumber: string; smsSent: boolean; linkUrl: string }[] }> {
|
||||||
|
if (agent?.role !== RoleEnum.CALL_CENTER) {
|
||||||
|
throw new ForbiddenException("Only call-center agents can use this endpoint.");
|
||||||
|
}
|
||||||
|
const req = await this.blameRequestDbService.findById(requestId);
|
||||||
|
if (!req) throw new NotFoundException("Request not found");
|
||||||
|
if (!req.callCenterInitiated || String(req.initiatedByCallCenterId) !== String(agent.sub)) {
|
||||||
|
throw new ForbiddenException("You can only access files that you have initiated.");
|
||||||
|
}
|
||||||
|
if (!process.env.URL) {
|
||||||
|
throw new InternalServerErrorException("URL environment variable is not configured");
|
||||||
|
}
|
||||||
|
|
||||||
|
const phone = (dto?.phoneNumber || "").trim();
|
||||||
|
if (!phone) throw new BadRequestException("phoneNumber is required");
|
||||||
|
|
||||||
|
const firstIdx = this.getPartyIndex(req, PartyRole.FIRST);
|
||||||
|
if (firstIdx === -1) throw new BadRequestException("First party not found on request");
|
||||||
|
const userId = await this.getOrCreateUserByPhoneNumber(phone);
|
||||||
|
if (!req.parties[firstIdx].person) req.parties[firstIdx].person = {} as any;
|
||||||
|
req.parties[firstIdx].person.phoneNumber = normalizeIranMobile(phone) ?? phone;
|
||||||
|
req.parties[firstIdx].person.userId = userId;
|
||||||
|
|
||||||
|
const expertName = `${agent?.lastName || ""}`.trim() || "اپراتور";
|
||||||
|
const firstLink = this.smsOrchestrationService.buildBlamePartyLink(requestId, "FIRST", "v6");
|
||||||
|
const smsSent = await this.smsOrchestrationService.sendFieldExpertLink({
|
||||||
|
receptor: phone,
|
||||||
|
type: req.type,
|
||||||
|
expertLastName: expertName,
|
||||||
|
link: firstLink,
|
||||||
|
});
|
||||||
|
|
||||||
|
const sentTo = [{ role: PartyRole.FIRST, phoneNumber: phone, smsSent, linkUrl: firstLink }];
|
||||||
|
|
||||||
|
if (!Array.isArray((req as any).history)) (req as any).history = [];
|
||||||
|
(req as any).history.push({
|
||||||
|
type: "CALL_CENTER_LINK_SENT",
|
||||||
|
actor: {
|
||||||
|
actorId: new Types.ObjectId(agent.sub),
|
||||||
|
actorName: `${agent.firstName || ""} ${agent.lastName || ""}`.trim(),
|
||||||
|
actorType: RoleEnum.CALL_CENTER,
|
||||||
|
},
|
||||||
|
metadata: { sentTo },
|
||||||
|
});
|
||||||
|
await (req as any).save();
|
||||||
|
|
||||||
|
return { sent: smsSent, sentTo };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6: Get a single blame file detail for the call-center agent who created it.
|
||||||
|
*/
|
||||||
|
async getCallCenterBlameDetailV6(agent: any, requestId: string): Promise<any> {
|
||||||
|
if (agent?.role !== RoleEnum.CALL_CENTER) {
|
||||||
|
throw new ForbiddenException("Only call-center agents can use this endpoint.");
|
||||||
|
}
|
||||||
|
const req = await this.blameRequestDbService.findById(requestId);
|
||||||
|
if (!req) throw new NotFoundException("Blame request not found");
|
||||||
|
if (!req.callCenterInitiated || String(req.initiatedByCallCenterId) !== String(agent.sub)) {
|
||||||
|
throw new ForbiddenException("You can only access files that you have initiated.");
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
_id: (req as any)._id,
|
||||||
|
publicId: (req as any).publicId,
|
||||||
|
requestNo: (req as any).requestNo,
|
||||||
|
type: (req as any).type,
|
||||||
|
status: (req as any).status,
|
||||||
|
blameStatus: (req as any).blameStatus,
|
||||||
|
workflow: (req as any).workflow,
|
||||||
|
skipInitialFormStep: (req as any).skipInitialFormStep,
|
||||||
|
parties: ((req as any).parties ?? []).map((p: any) => ({
|
||||||
|
role: p.role,
|
||||||
|
person: {
|
||||||
|
phoneNumber: p.person?.phoneNumber,
|
||||||
|
nationalCodeOfInsurer: p.person?.nationalCodeOfInsurer,
|
||||||
|
clientId: p.person?.clientId,
|
||||||
|
},
|
||||||
|
insurance: p.insurance
|
||||||
|
? {
|
||||||
|
company: p.insurance.company,
|
||||||
|
policyNumber: p.insurance.policyNumber,
|
||||||
|
startDate: p.insurance.startDate,
|
||||||
|
endDate: p.insurance.endDate,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
vehicle: p.vehicle
|
||||||
|
? { plateId: p.vehicle.plateId, name: p.vehicle.name }
|
||||||
|
: undefined,
|
||||||
|
})),
|
||||||
|
createdAt: (req as any).createdAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V6: List blame files created by this call-center agent.
|
||||||
|
*/
|
||||||
|
async getMyCallCenterFilesV6(agent: any): Promise<any[]> {
|
||||||
|
if (agent?.role !== RoleEnum.CALL_CENTER) {
|
||||||
|
throw new ForbiddenException("Only call-center agents can use this endpoint.");
|
||||||
|
}
|
||||||
|
const agentId = new Types.ObjectId(agent.sub);
|
||||||
|
const files = await this.blameRequestDbService.find({
|
||||||
|
callCenterInitiated: true,
|
||||||
|
initiatedByCallCenterId: agentId,
|
||||||
|
});
|
||||||
|
return (files || []).map((f: any) => ({
|
||||||
|
_id: f._id,
|
||||||
|
publicId: f.publicId,
|
||||||
|
requestNo: f.requestNo,
|
||||||
|
type: f.type,
|
||||||
|
status: f.status,
|
||||||
|
blameStatus: f.blameStatus,
|
||||||
|
workflow: f.workflow,
|
||||||
|
skipInitialFormStep: f.skipInitialFormStep,
|
||||||
|
createdAt: f.createdAt,
|
||||||
|
}));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,7 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
import { MongooseModule } from "@nestjs/mongoose";
|
import { MongooseModule } from "@nestjs/mongoose";
|
||||||
import { ClientModule } from "src/client/client.module";
|
import { ClientModule } from "src/client/client.module";
|
||||||
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
|
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
|
||||||
@@ -9,7 +11,11 @@ import { SandHubService } from "./sand-hub.service";
|
|||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
SystemSettingsModule,
|
SystemSettingsModule,
|
||||||
ClientModule,
|
ClientModule,
|
||||||
MongooseModule.forFeature([
|
MongooseModule.forFeature([
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { ConfigModule } from "@nestjs/config";
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
|
|
||||||
import { KavenegarService } from "./kavenegar.service";
|
import { KavenegarService } from "./kavenegar.service";
|
||||||
import { KavenegarSmsGateway } from "./kavenegar-sms.gateway";
|
import { KavenegarSmsGateway } from "./kavenegar-sms.gateway";
|
||||||
@@ -8,7 +9,14 @@ import { ParsianSmsGateway } from "./parsian-sms.gateway";
|
|||||||
import { SmsGatewayService } from "./sms-gateway.service";
|
import { SmsGatewayService } from "./sms-gateway.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [HttpModule, ConfigModule],
|
imports: [
|
||||||
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
|
ConfigModule,
|
||||||
|
],
|
||||||
providers: [
|
providers: [
|
||||||
KavenegarService,
|
KavenegarService,
|
||||||
KavenegarSmsGateway,
|
KavenegarSmsGateway,
|
||||||
|
|||||||
@@ -6,10 +6,16 @@ import { SmsGatewayModule } from "./provider/sms-gateway.module";
|
|||||||
import { OtpGeneratorService } from "./otp-generator.service";
|
import { OtpGeneratorService } from "./otp-generator.service";
|
||||||
import { SmsOrchestrationService } from "./sms-orchestration.service";
|
import { SmsOrchestrationService } from "./sms-orchestration.service";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
SmsGatewayModule,
|
SmsGatewayModule,
|
||||||
MongooseModule.forFeature([{ name: SmsText.name, schema: SmsTextSchema }]),
|
MongooseModule.forFeature([{ name: SmsText.name, schema: SmsTextSchema }]),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -37,20 +37,25 @@ export class SmsOrchestrationService implements OnModuleInit {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
buildInviteLink(frontendRoute: string, requestId: string): string {
|
buildInviteLink(
|
||||||
return `${process.env.URL}/${process.env.USER_BASE_PATH}/${frontendRoute}?token=${requestId}`;
|
frontendRoute: string,
|
||||||
|
requestId: string,
|
||||||
|
versionPrefix: string,
|
||||||
|
): string {
|
||||||
|
return `${process.env.URL}/${versionPrefix}/${frontendRoute}?token=${requestId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
buildBlamePartyLink(
|
buildBlamePartyLink(
|
||||||
requestId: string,
|
requestId: string,
|
||||||
partyRole: "FIRST" | "SECOND",
|
partyRole: "FIRST" | "SECOND",
|
||||||
|
versionPrefix: string,
|
||||||
): string {
|
): string {
|
||||||
const route = partyRole === "SECOND" ? "user2" : "user";
|
const route = partyRole === "SECOND" ? "user2" : "user";
|
||||||
return `${process.env.URL}/${process.env.USER_BASE_PATH}/${route}?token=${requestId}`;
|
return `${process.env.URL}/${versionPrefix}/${route}?token=${requestId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
buildClaimLink(claimRequestId: string): string {
|
buildClaimLink(claimRequestId: string, versionPrefix: string): string {
|
||||||
return `${process.env.URL}/${process.env.USER_BASE_PATH}/caseClaim?token=${claimRequestId}`;
|
return `${process.env.URL}/${versionPrefix}/caseClaim?token=${claimRequestId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendInviteLink(
|
async sendInviteLink(
|
||||||
|
|||||||
@@ -74,3 +74,37 @@ export class CreateRegistrarAdminDto {
|
|||||||
@IsNotEmpty()
|
@IsNotEmpty()
|
||||||
clientId: string;
|
clientId: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class CreateCallCenterAgentDto {
|
||||||
|
@ApiProperty({ example: "agent@insurer.ir" })
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "CallCenter@724" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Sara" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
firstName: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Hosseini" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
lastName: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: "664a1b2c3d4e5f6789012345",
|
||||||
|
description: "Mongo ObjectId of the insurer client this agent belongs to.",
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
clientId: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: "09121234567" })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
mobile?: string;
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,24 +1,32 @@
|
|||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
|
Query,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import {
|
import {
|
||||||
ApiBearerAuth,
|
ApiBearerAuth,
|
||||||
ApiBody,
|
ApiBody,
|
||||||
ApiOperation,
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiQuery,
|
||||||
ApiResponse,
|
ApiResponse,
|
||||||
ApiTags,
|
ApiTags,
|
||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
|
import { Types } from "mongoose";
|
||||||
import { SuperAdminGuard } from "./guards/super-admin.guard";
|
import { SuperAdminGuard } from "./guards/super-admin.guard";
|
||||||
import { SuperAdminService } from "./super-admin.service";
|
import { SuperAdminService } from "./super-admin.service";
|
||||||
import {
|
import {
|
||||||
CreateSuperAdminDto,
|
CreateSuperAdminDto,
|
||||||
CreateFieldExpertAdminDto,
|
CreateFieldExpertAdminDto,
|
||||||
CreateRegistrarAdminDto,
|
CreateRegistrarAdminDto,
|
||||||
|
CreateCallCenterAgentDto,
|
||||||
} from "./dto/super-admin.dto";
|
} from "./dto/super-admin.dto";
|
||||||
import { ClientDto } from "src/client/dto/create-client.dto";
|
import { ClientDto } from "src/client/dto/create-client.dto";
|
||||||
import {
|
import {
|
||||||
@@ -32,6 +40,20 @@ import {
|
|||||||
UpdateSystemSettingsDto,
|
UpdateSystemSettingsDto,
|
||||||
} from "src/system-settings/dto/system-settings.dto";
|
} from "src/system-settings/dto/system-settings.dto";
|
||||||
import { SetExternalInquiriesLiveDto } from "src/client/dto/external-inquiries-live.dto";
|
import { SetExternalInquiriesLiveDto } from "src/client/dto/external-inquiries-live.dto";
|
||||||
|
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||||
|
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||||
|
import {
|
||||||
|
UnifiedFileStatusReportDto,
|
||||||
|
UnifiedFileStatusReportQueryDto,
|
||||||
|
} from "src/common/dto/unified-file-status-report.dto";
|
||||||
|
import { CreateBranchDto } from "src/client/dto/create-branch.dto";
|
||||||
|
import { FileRating } from "src/request-management/entities/schema/request-management.schema";
|
||||||
|
import {
|
||||||
|
CreateBlameExpertByInsurerDto,
|
||||||
|
CreateClaimExpertByInsurerDto,
|
||||||
|
CreateFileMakerByInsurerDto,
|
||||||
|
CreateFileReviewerByInsurerDto,
|
||||||
|
} from "src/expert-insurer/dto/create-insurer-expert.dto";
|
||||||
|
|
||||||
@ApiTags("super-admin")
|
@ApiTags("super-admin")
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@@ -41,6 +63,7 @@ export class SuperAdminController {
|
|||||||
constructor(
|
constructor(
|
||||||
private readonly superAdminService: SuperAdminService,
|
private readonly superAdminService: SuperAdminService,
|
||||||
private readonly systemSettingsService: SystemSettingsService,
|
private readonly systemSettingsService: SystemSettingsService,
|
||||||
|
private readonly expertInsurerService: ExpertInsurerService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// ── Super-admin account management ───────────────────────────────────────
|
// ── Super-admin account management ───────────────────────────────────────
|
||||||
@@ -129,6 +152,13 @@ export class SuperAdminController {
|
|||||||
return this.superAdminService.createRegistrar(body);
|
return this.superAdminService.createRegistrar(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("create-call-center-agent")
|
||||||
|
@ApiOperation({ summary: "Create a call-center agent for a given client" })
|
||||||
|
@ApiBody({ type: CreateCallCenterAgentDto })
|
||||||
|
createCallCenterAgent(@Body() body: CreateCallCenterAgentDto) {
|
||||||
|
return this.superAdminService.createCallCenterAgent(body);
|
||||||
|
}
|
||||||
|
|
||||||
// ── System settings ──────────────────────────────────────────────────────
|
// ── System settings ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
@Get("system-settings")
|
@Get("system-settings")
|
||||||
@@ -159,4 +189,313 @@ export class SuperAdminController {
|
|||||||
externalApis: { sandHubUseLiveApi: body?.enabled === true },
|
externalApis: { sandHubUseLiveApi: body?.enabled === true },
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Insurer panel (super-admin proxy) ────────────────────────────────────
|
||||||
|
|
||||||
|
@Get("insurer/branches")
|
||||||
|
@ApiOperation({ summary: "List branches for a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
@ApiQuery({ name: "search", required: false, type: String })
|
||||||
|
@ApiQuery({ name: "from", required: false, description: "Optional start datetime (ISO string)" })
|
||||||
|
@ApiQuery({ name: "to", required: false, description: "Optional end datetime (ISO string)" })
|
||||||
|
@ApiQuery({ name: "isActive", required: false, description: "Filter active state (true/false)" })
|
||||||
|
getInsuranceBranches(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Query("search") search?: string,
|
||||||
|
@Query("from") from?: string,
|
||||||
|
@Query("to") to?: string,
|
||||||
|
@Query("isActive") isActive?: string,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.retrieveInsuranceBranches(
|
||||||
|
clientId,
|
||||||
|
{ search, from, to, isActive },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("insurer/branches")
|
||||||
|
@ApiOperation({ summary: "Add a branch for a given client" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
allOf: [
|
||||||
|
{ $ref: "#/components/schemas/CreateBranchDto" },
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
required: ["clientId"],
|
||||||
|
properties: { clientId: { type: "string", description: "Client ObjectId" } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
addBranch(
|
||||||
|
@Body("clientId") clientId: string,
|
||||||
|
@Body() createBranchDto: CreateBranchDto,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.addBranch(clientId, createBranchDto);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Put("insurer/branches/:branchId/status")
|
||||||
|
@ApiOperation({ summary: "Set branch active/inactive for a given client" })
|
||||||
|
@ApiParam({ name: "branchId" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
clientId: { type: "string", description: "Client ObjectId" },
|
||||||
|
isActive: { type: "boolean" },
|
||||||
|
},
|
||||||
|
required: ["clientId", "isActive"],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
setBranchStatus(
|
||||||
|
@Param("branchId") branchId: string,
|
||||||
|
@Body("clientId") clientId: string,
|
||||||
|
@Body("isActive") isActive: unknown,
|
||||||
|
) {
|
||||||
|
let active: boolean;
|
||||||
|
if (typeof isActive === "boolean") {
|
||||||
|
active = isActive;
|
||||||
|
} else {
|
||||||
|
const normalized = String(isActive ?? "").trim().toLowerCase();
|
||||||
|
if (!["true", "false", "1", "0", "yes", "no"].includes(normalized)) {
|
||||||
|
throw new BadRequestException("isActive must be a boolean");
|
||||||
|
}
|
||||||
|
active = ["true", "1", "yes"].includes(normalized);
|
||||||
|
}
|
||||||
|
return this.expertInsurerService.setBranchActive(clientId, branchId, active);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("insurer/experts/blame")
|
||||||
|
@ApiOperation({ summary: "Create a blame expert under a given client" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
allOf: [
|
||||||
|
{ $ref: "#/components/schemas/CreateBlameExpertByInsurerDto" },
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
required: ["clientId"],
|
||||||
|
properties: { clientId: { type: "string", description: "Client ObjectId" } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
addBlameExpert(
|
||||||
|
@Body("clientId") clientId: string,
|
||||||
|
@Body() body: CreateBlameExpertByInsurerDto,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.addBlameExpert(clientId, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("insurer/experts/claim")
|
||||||
|
@ApiOperation({ summary: "Create a claim expert under a given client" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
allOf: [
|
||||||
|
{ $ref: "#/components/schemas/CreateClaimExpertByInsurerDto" },
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
required: ["clientId"],
|
||||||
|
properties: { clientId: { type: "string", description: "Client ObjectId" } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
addClaimExpert(
|
||||||
|
@Body("clientId") clientId: string,
|
||||||
|
@Body() body: CreateClaimExpertByInsurerDto,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.addClaimExpert(clientId, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("insurer/experts/file-maker")
|
||||||
|
@ApiOperation({ summary: "Create a FileMaker account under a given client" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
allOf: [
|
||||||
|
{ $ref: "#/components/schemas/CreateFileMakerByInsurerDto" },
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
required: ["clientId"],
|
||||||
|
properties: { clientId: { type: "string", description: "Client ObjectId" } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
addFileMaker(
|
||||||
|
@Body("clientId") clientId: string,
|
||||||
|
@Body() body: CreateFileMakerByInsurerDto,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.addFileMaker(clientId, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("insurer/experts/file-reviewer")
|
||||||
|
@ApiOperation({ summary: "Create a FileReviewer account under a given client" })
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
allOf: [
|
||||||
|
{ $ref: "#/components/schemas/CreateFileReviewerByInsurerDto" },
|
||||||
|
{
|
||||||
|
type: "object",
|
||||||
|
required: ["clientId"],
|
||||||
|
properties: { clientId: { type: "string", description: "Client ObjectId" } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
addFileReviewer(
|
||||||
|
@Body("clientId") clientId: string,
|
||||||
|
@Body() body: CreateFileReviewerByInsurerDto,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.addFileReviewer(clientId, body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/experts/list")
|
||||||
|
@ApiOperation({ summary: "List all experts of a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
@ApiQuery({ name: "page", type: Number })
|
||||||
|
@ApiQuery({ name: "response_count", type: Number })
|
||||||
|
getAllExperts(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Query("page") page: number,
|
||||||
|
@Query("response_count") count: number,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.retrieveAllExpertsOfClient(
|
||||||
|
{ clientKey: clientId },
|
||||||
|
page,
|
||||||
|
count,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/experts/top")
|
||||||
|
@ApiOperation({ summary: "Top blame vs claim experts for a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getTopExperts(@Query("clientId") clientId: string) {
|
||||||
|
return this.expertInsurerService.getTopExpertsForClient({ clientKey: clientId });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/files")
|
||||||
|
@ApiOperation({ summary: "List files (blame + claim merged) for a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getAllFiles(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Query() query: ListQueryV2Dto,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.retrieveAllFilesOfClient(clientId, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/report/unified-file-statuses")
|
||||||
|
@ApiOperation({ summary: "Unified file status catalog + counts for a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
@ApiResponse({ status: 200, type: UnifiedFileStatusReportDto })
|
||||||
|
getUnifiedFileStatusReport(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Query() query: UnifiedFileStatusReportQueryDto,
|
||||||
|
): Promise<UnifiedFileStatusReportDto> {
|
||||||
|
return this.expertInsurerService.getInsurerUnifiedFileStatusReport(
|
||||||
|
{ clientKey: clientId },
|
||||||
|
query,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/report/status-counts")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Legacy status counts for a given client",
|
||||||
|
deprecated: true,
|
||||||
|
description: "Prefer GET insurer/report/unified-file-statuses.",
|
||||||
|
})
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
@ApiQuery({ name: "from", required: false, description: "Optional start datetime (ISO string)" })
|
||||||
|
@ApiQuery({ name: "to", required: false, description: "Optional end datetime (ISO string)" })
|
||||||
|
getInsurerStatusReport(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Query("from") from?: string,
|
||||||
|
@Query("to") to?: string,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.getInsurerFileStatusCounts(
|
||||||
|
{ clientKey: clientId },
|
||||||
|
from,
|
||||||
|
to,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/files/:publicId/timeline")
|
||||||
|
@ApiOperation({ summary: "Activity timeline for a case of a given client" })
|
||||||
|
@ApiParam({ name: "publicId" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getFileTimeline(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Param("publicId") publicId: string,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.getFileTimeline(clientId, publicId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/files/:publicId")
|
||||||
|
@ApiOperation({ summary: "File details by publicId for a given client" })
|
||||||
|
@ApiParam({ name: "publicId" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getFileDetailsByPublicId(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Param("publicId") publicId: string,
|
||||||
|
) {
|
||||||
|
return this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// @Put("insurer/files/:publicId/rating")
|
||||||
|
// @ApiOperation({ summary: "Rate experts by publicId for a given client" })
|
||||||
|
// @ApiParam({ name: "publicId" })
|
||||||
|
// @ApiBody({
|
||||||
|
// schema: {
|
||||||
|
// type: "object",
|
||||||
|
// required: [
|
||||||
|
// "clientId",
|
||||||
|
// "collisionMethodAccuracy",
|
||||||
|
// "evaluationTimeliness",
|
||||||
|
// "accidentCauseAccuracy",
|
||||||
|
// "guiltyVehicleIdentification",
|
||||||
|
// "botRating",
|
||||||
|
// ],
|
||||||
|
// properties: {
|
||||||
|
// clientId: { type: "string", description: "Client ObjectId" },
|
||||||
|
// collisionMethodAccuracy: { type: "number", minimum: 0, maximum: 5 },
|
||||||
|
// evaluationTimeliness: { type: "number", minimum: 0, maximum: 5 },
|
||||||
|
// accidentCauseAccuracy: { type: "number", minimum: 0, maximum: 5 },
|
||||||
|
// guiltyVehicleIdentification: { type: "number", minimum: 0, maximum: 5 },
|
||||||
|
// botRating: { type: "number", minimum: 0, maximum: 5 },
|
||||||
|
// },
|
||||||
|
// },
|
||||||
|
// })
|
||||||
|
// rateExpertsByPublicId(
|
||||||
|
// @Param("publicId") publicId: string,
|
||||||
|
// @Body() body: FileRating & { clientId: string },
|
||||||
|
// ) {
|
||||||
|
// const { clientId, ...rating } = body;
|
||||||
|
// return this.expertInsurerService.rateExpertByPublicId(publicId, rating as FileRating, clientId);
|
||||||
|
// }
|
||||||
|
|
||||||
|
@Get("insurer/top-files")
|
||||||
|
@ApiOperation({ summary: "Top-rated files for a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getTopFiles(@Query("clientId") clientId: string) {
|
||||||
|
return this.expertInsurerService.getTopFilesForClient(clientId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/statistics")
|
||||||
|
@ApiOperation({ summary: "Expert statistics report for a given client" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getExpertStatistics(@Query("clientId") clientId: string) {
|
||||||
|
return this.expertInsurerService.getExpertStatisticsReport({ clientKey: clientId });
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("insurer/:expertId")
|
||||||
|
@ApiOperation({ summary: "Files handled by one roster expert for a given client" })
|
||||||
|
@ApiParam({ name: "expertId" })
|
||||||
|
@ApiQuery({ name: "clientId", required: true, type: String })
|
||||||
|
getExpertFiles(
|
||||||
|
@Query("clientId") clientId: string,
|
||||||
|
@Param("expertId") expertId: string,
|
||||||
|
) {
|
||||||
|
if (!Types.ObjectId.isValid(expertId)) {
|
||||||
|
throw new BadRequestException("Invalid expert ID");
|
||||||
|
}
|
||||||
|
return this.expertInsurerService.getAllFilesForInsurerExpert(expertId, clientId);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ClientModule } from "src/client/client.module";
|
|||||||
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
|
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
|
||||||
import { HashModule } from "src/utils/hash/hash.module";
|
import { HashModule } from "src/utils/hash/hash.module";
|
||||||
import { UsersModule } from "src/users/users.module";
|
import { UsersModule } from "src/users/users.module";
|
||||||
|
import { ExpertInsurerModule } from "src/expert-insurer/expert-insurer.module";
|
||||||
import { SuperAdminController } from "./super-admin.controller";
|
import { SuperAdminController } from "./super-admin.controller";
|
||||||
import { SuperAdminService } from "./super-admin.service";
|
import { SuperAdminService } from "./super-admin.service";
|
||||||
import { SuperAdminGuard } from "./guards/super-admin.guard";
|
import { SuperAdminGuard } from "./guards/super-admin.guard";
|
||||||
@@ -26,6 +27,7 @@ import { SuperAdminGuard } from "./guards/super-admin.guard";
|
|||||||
SystemSettingsModule,
|
SystemSettingsModule,
|
||||||
HashModule,
|
HashModule,
|
||||||
UsersModule,
|
UsersModule,
|
||||||
|
ExpertInsurerModule,
|
||||||
],
|
],
|
||||||
controllers: [SuperAdminController],
|
controllers: [SuperAdminController],
|
||||||
providers: [SuperAdminService, SuperAdminGuard],
|
providers: [SuperAdminService, SuperAdminGuard],
|
||||||
|
|||||||
@@ -19,10 +19,12 @@ import {
|
|||||||
CreateSuperAdminDto,
|
CreateSuperAdminDto,
|
||||||
CreateFieldExpertAdminDto,
|
CreateFieldExpertAdminDto,
|
||||||
CreateRegistrarAdminDto,
|
CreateRegistrarAdminDto,
|
||||||
|
CreateCallCenterAgentDto,
|
||||||
} from "./dto/super-admin.dto";
|
} from "./dto/super-admin.dto";
|
||||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
|
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
|
||||||
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
||||||
|
import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class SuperAdminService {
|
export class SuperAdminService {
|
||||||
@@ -33,6 +35,7 @@ export class SuperAdminService {
|
|||||||
private readonly actorAuthService: ActorAuthService,
|
private readonly actorAuthService: ActorAuthService,
|
||||||
private readonly fieldExpertDbService: FieldExpertDbService,
|
private readonly fieldExpertDbService: FieldExpertDbService,
|
||||||
private readonly registrarDbService: RegistrarDbService,
|
private readonly registrarDbService: RegistrarDbService,
|
||||||
|
private readonly callCenterAgentDbService: CallCenterAgentDbService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
/** List all super-admin accounts (sans password). */
|
/** List all super-admin accounts (sans password). */
|
||||||
@@ -99,4 +102,28 @@ export class SuperAdminService {
|
|||||||
async createRegistrar(body: CreateRegistrarAdminDto) {
|
async createRegistrar(body: CreateRegistrarAdminDto) {
|
||||||
return this.actorAuthService.createRegistrarMock(body);
|
return this.actorAuthService.createRegistrarMock(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async createCallCenterAgent(body: CreateCallCenterAgentDto) {
|
||||||
|
const email = body.email.toLowerCase().trim();
|
||||||
|
const existing = await this.callCenterAgentDbService.findOne({ email });
|
||||||
|
if (existing) {
|
||||||
|
throw new ConflictException(
|
||||||
|
"A call-center agent with this email already exists.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const password = await this.hashService.hash(body.password);
|
||||||
|
const created = await this.callCenterAgentDbService.create({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
firstName: body.firstName,
|
||||||
|
lastName: body.lastName,
|
||||||
|
clientKey: new Types.ObjectId(body.clientId),
|
||||||
|
mobile: body.mobile,
|
||||||
|
role: RoleEnum.CALL_CENTER,
|
||||||
|
});
|
||||||
|
const { password: _pw, ...rest } = (created as any).toObject
|
||||||
|
? (created as any).toObject()
|
||||||
|
: (created as any);
|
||||||
|
return rest;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { Injectable } from "@nestjs/common";
|
||||||
|
import { InjectModel } from "@nestjs/mongoose";
|
||||||
|
import { FilterQuery, Model, Types } from "mongoose";
|
||||||
|
import { CallCenterAgentModel } from "../schema/call-center-agent.schema";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class CallCenterAgentDbService {
|
||||||
|
constructor(
|
||||||
|
@InjectModel(CallCenterAgentModel.name)
|
||||||
|
private readonly model: Model<CallCenterAgentModel>,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async create(
|
||||||
|
data: Partial<CallCenterAgentModel> & { password: string },
|
||||||
|
): Promise<CallCenterAgentModel> {
|
||||||
|
return this.model.create(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(
|
||||||
|
filter: FilterQuery<CallCenterAgentModel>,
|
||||||
|
): Promise<CallCenterAgentModel | null> {
|
||||||
|
return this.model.findOne(filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findById(id: string): Promise<CallCenterAgentModel | null> {
|
||||||
|
return this.model.findOne({ _id: new Types.ObjectId(id) });
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByLoginIdentifier(
|
||||||
|
identifier: string,
|
||||||
|
): Promise<CallCenterAgentModel | null> {
|
||||||
|
const id = identifier.trim();
|
||||||
|
const or: FilterQuery<CallCenterAgentModel>[] = [
|
||||||
|
{ email: id },
|
||||||
|
{ username: id },
|
||||||
|
];
|
||||||
|
if (/^\d{10}$/.test(id)) {
|
||||||
|
or.push({ nationalCode: id });
|
||||||
|
}
|
||||||
|
return this.model.findOne({ $or: or });
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(
|
||||||
|
filter: FilterQuery<CallCenterAgentModel>,
|
||||||
|
): Promise<(CallCenterAgentModel & { _id: Types.ObjectId })[]> {
|
||||||
|
return this.model.find(filter).lean() as Promise<
|
||||||
|
(CallCenterAgentModel & { _id: Types.ObjectId })[]
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
}
|
||||||
61
src/users/entities/schema/call-center-agent.schema.ts
Normal file
61
src/users/entities/schema/call-center-agent.schema.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
|
||||||
|
import { Types } from "mongoose";
|
||||||
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Call-center agent actor. Works under an insurance company (clientKey) and
|
||||||
|
* can start V6 LINK blame files on behalf of callers.
|
||||||
|
*/
|
||||||
|
@Schema({
|
||||||
|
collection: "call-center-agents",
|
||||||
|
versionKey: false,
|
||||||
|
timestamps: true,
|
||||||
|
})
|
||||||
|
export class CallCenterAgentModel {
|
||||||
|
_id?: Types.ObjectId;
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
firstName: string;
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
lastName: string;
|
||||||
|
|
||||||
|
@Prop({ type: String, unique: true, sparse: true, required: false })
|
||||||
|
email?: string;
|
||||||
|
|
||||||
|
@Prop({ type: String })
|
||||||
|
username?: string;
|
||||||
|
|
||||||
|
@Prop({ type: String, index: true, sparse: true })
|
||||||
|
nationalCode?: string;
|
||||||
|
|
||||||
|
@Prop({ type: Types.ObjectId, index: true })
|
||||||
|
clientKey?: Types.ObjectId;
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@Prop({ required: false })
|
||||||
|
mobile?: string;
|
||||||
|
|
||||||
|
@Prop({ required: false })
|
||||||
|
phone?: string;
|
||||||
|
|
||||||
|
@Prop({ default: RoleEnum.CALL_CENTER })
|
||||||
|
role: RoleEnum;
|
||||||
|
|
||||||
|
@Prop({ type: "string", default: "" })
|
||||||
|
otp: string;
|
||||||
|
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const CallCenterAgentDbSchema =
|
||||||
|
SchemaFactory.createForClass(CallCenterAgentModel);
|
||||||
|
|
||||||
|
CallCenterAgentDbSchema.pre("save", function (next) {
|
||||||
|
if (!this.username) {
|
||||||
|
this.username = (this as any).email || (this as any).nationalCode;
|
||||||
|
}
|
||||||
|
next();
|
||||||
|
});
|
||||||
@@ -11,6 +11,7 @@ import { UserDbService } from "./entities/db-service/user.db.service";
|
|||||||
import { ExpertFileActivityDbService } from "./entities/db-service/expert-file-activity.db.service";
|
import { ExpertFileActivityDbService } from "./entities/db-service/expert-file-activity.db.service";
|
||||||
import { FileMakerDbService } from "./entities/db-service/file-maker.db.service";
|
import { FileMakerDbService } from "./entities/db-service/file-maker.db.service";
|
||||||
import { FileReviewerDbService } from "./entities/db-service/file-reviewer.db.service";
|
import { FileReviewerDbService } from "./entities/db-service/file-reviewer.db.service";
|
||||||
|
import { CallCenterAgentDbService } from "./entities/db-service/call-center-agent.db.service";
|
||||||
import {
|
import {
|
||||||
DamageExpertDbSchema,
|
DamageExpertDbSchema,
|
||||||
DamageExpertModel,
|
DamageExpertModel,
|
||||||
@@ -41,6 +42,10 @@ import {
|
|||||||
FileReviewerDbSchema,
|
FileReviewerDbSchema,
|
||||||
FileReviewerModel,
|
FileReviewerModel,
|
||||||
} from "./entities/schema/file-reviewer.schema";
|
} from "./entities/schema/file-reviewer.schema";
|
||||||
|
import {
|
||||||
|
CallCenterAgentDbSchema,
|
||||||
|
CallCenterAgentModel,
|
||||||
|
} from "./entities/schema/call-center-agent.schema";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -54,6 +59,7 @@ import {
|
|||||||
{ name: ExpertFileActivity.name, schema: ExpertFileActivitySchema },
|
{ name: ExpertFileActivity.name, schema: ExpertFileActivitySchema },
|
||||||
{ name: FileMakerModel.name, schema: FileMakerDbSchema },
|
{ name: FileMakerModel.name, schema: FileMakerDbSchema },
|
||||||
{ name: FileReviewerModel.name, schema: FileReviewerDbSchema },
|
{ name: FileReviewerModel.name, schema: FileReviewerDbSchema },
|
||||||
|
{ name: CallCenterAgentModel.name, schema: CallCenterAgentDbSchema },
|
||||||
]),
|
]),
|
||||||
HashModule,
|
HashModule,
|
||||||
],
|
],
|
||||||
@@ -68,6 +74,7 @@ import {
|
|||||||
ExpertFileActivityDbService,
|
ExpertFileActivityDbService,
|
||||||
FileMakerDbService,
|
FileMakerDbService,
|
||||||
FileReviewerDbService,
|
FileReviewerDbService,
|
||||||
|
CallCenterAgentDbService,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
UserDbService,
|
UserDbService,
|
||||||
@@ -79,6 +86,7 @@ import {
|
|||||||
ExpertFileActivityDbService,
|
ExpertFileActivityDbService,
|
||||||
FileMakerDbService,
|
FileMakerDbService,
|
||||||
FileReviewerDbService,
|
FileReviewerDbService,
|
||||||
|
CallCenterAgentDbService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class UsersModule {}
|
export class UsersModule {}
|
||||||
|
|||||||
Reference in New Issue
Block a user