diff --git a/docs/fanavaran-vehicle-review.md b/docs/fanavaran-vehicle-review.md new file mode 100644 index 0000000..c75ba44 --- /dev/null +++ b/docs/fanavaran-vehicle-review.md @@ -0,0 +1,43 @@ +# Fanavaran vehicle review gate + +Fanavaran vehicle values returned by external inquiries are advisory only. No outbound Fanavaran stage may create or upload data until an authorized claim-panel actor has approved all four vehicle values. + +## Reviewed values + +| UI field | Fanavaran source | Stored value | +| ----------- | ------------------------------ | --------------------------------------- | +| نوع خودرو | `vehicle-groups` | `fanavaranVehicleReview.vehicleGroup` | +| نوع استفاده | `vehicle-use-types` | `fanavaranVehicleReview.vehicleUseType` | +| سیستم خودرو | `vehicle-systems` | `fanavaranVehicleReview.vehicleSystem` | +| نام خودرو | filtered `vehicle-kinds` cache | `fanavaranVehicleReview.vehicleKind` | + +The persisted review is an authoritative snapshot containing IDs, captions, relationship IDs, reviewer identity/role, approval time, and a monotonically increasing version. `vehicleUseType.id` is used as GEN.03/GEN.12 `AccidentVehicleUsedId`; `vehicleKind.id` is used as GEN.12 `VehicleKindId`. + +## Inquiry prefill and trust boundary + +The options response also includes an unapproved `suggestion`. It is built from the damaged party's role-specific inquiry snapshot and never writes to `fanavaranVehicleReview` by itself. + +Matching order: + +1. A direct Fanavaran `VehicleKindId`/`vehicle.vehicleKind.Id` is validated against the active `vehicle-kinds` cache. Its `VehicleGroupId` and `VehicleSystemId` relationships provide the group and system. +2. A direct Fanavaran `UsedId`/`vehicle.used.Id` is accepted only when it is active and belongs to the matched vehicle group. +3. Otherwise semantic inquiry captions are normalized (Persian/Arabic yeh and kaf, digits, whitespace) and exactly matched: `vehicleKind`/`MapTypNam`, `vehicleSystemTitle`/`SystemField`, `UsageField`/`usage`, and `vehicleGroupTitle`. +4. Ambiguous or relationship-incompatible results remain empty and produce a warning for manual expert selection. + +Legacy provider codes `UsgCod`, `VehSysCod`, and `CarGrpCod` are returned only under `suggestion.legacyCodes` for audit. They are deliberately **not** used as Fanavaran IDs because their numeric domains differ; for example, inquiry `UsgCod=8` can mean personal use while Fanavaran's personal-use lookup ID is `1`. + +The panel applies the suggestion once, displays its matched-field count and raw legacy codes, leaves consent unchecked, and lets the expert replace any value before approval. + +## Panel endpoints + +- `GET /v2/expert-claim/request/:claimRequestId/fanavaran-vehicle-options?vehicleGroupId=1` returns active groups and only the compatible use types/systems for the selected group. +- `GET /lookups/vehicle-list?q=پراید&limit=30&vehicleGroupId=1&vehicleSystemId=14` performs the bounded async vehicle-kind search. +- `PUT /v2/expert-claim/request/:claimRequestId/fanavaran-vehicle-review` accepts the four IDs plus `confirmed: true`. + +The approval endpoint re-resolves every caption server-side and rejects inactive values or a group/use/system/kind relationship mismatch. Client-supplied captions are never trusted. A successful approval resumes base-claim submission and, when selected damage parts already exist, the damage-case stage. + +## Outbound enforcement + +Base claim, damage case, attachments, and expertise writes enforce the persisted approval. Automatic stages are deferred with a skip reason; manual stages return `409` with code `FANAVARAN_VEHICLE_REVIEW_REQUIRED`. Read-only previews remain available for diagnosis. + +Once Fanavaran has created the base claim, the review is immutable in the panel because changing it would make the local snapshot disagree with data already written remotely. diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index d8291a8..1641e53 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -4815,11 +4815,16 @@ export class ClaimRequestManagementService { parseFanavaranId(apiVehicle?.BuiltYear) ?? builtYearFromInquiry; const carType = input.claimCase?.vehicle?.carType as string | undefined; - let vehicleKindId = this.firstPositiveFanavaranId(apiVehicle?.VehicleKindId); - let vehicleKindSource: "vehicle-inquiry" | "car-type-lookup" | null = - parseFanavaranId(apiVehicle?.VehicleKindId) != null - ? "vehicle-inquiry" - : null; + const approvedVehicleKindId = this.firstPositiveFanavaranId( + input.claimCase?.fanavaranVehicleReview?.vehicleKind?.id, + ); + let vehicleKindId = approvedVehicleKindId ?? this.firstPositiveFanavaranId(apiVehicle?.VehicleKindId); + let vehicleKindSource: "expert-review" | "vehicle-inquiry" | "car-type-lookup" | null = + approvedVehicleKindId != null + ? "expert-review" + : parseFanavaranId(apiVehicle?.VehicleKindId) != null + ? "vehicle-inquiry" + : null; if (vehicleKindId == null) { vehicleKindId = await this.resolveVehicleKindId( input.clientKey, @@ -4944,9 +4949,12 @@ export class ClaimRequestManagementService { input.clientKey, ); - let accidentVehicleUsedId: number | null = null; - let usedSource: "vin-inquiry" | "policy-vehicle" | "vehicle-inquiry" | null = - null; + const approvedVehicleUseTypeId = this.firstPositiveFanavaranId( + input.claimCase?.fanavaranVehicleReview?.vehicleUseType?.id, + ); + let accidentVehicleUsedId: number | null = approvedVehicleUseTypeId; + let usedSource: "expert-review" | "vin-inquiry" | "policy-vehicle" | "vehicle-inquiry" | null = + approvedVehicleUseTypeId != null ? "expert-review" : null; if (accidentVehicleUsedId == null && apiVehicle) { const fromDamagedVehicle = await this.resolveAccidentVehicleUsedFromVehicleRecord( @@ -6372,7 +6380,7 @@ export class ClaimRequestManagementService { cachedUsedSource === "policy-vehicle"); delete payload.AccidentVehicleUsedId; - let usedSource: "vin-inquiry" | "policy-vehicle" | null = null; + let usedSource: "expert-review" | "vin-inquiry" | "policy-vehicle" | null = null; if (canReuseApiUsedId) { payload.AccidentVehicleUsedId = Number(cachedUsedId); usedSource = cachedUsedSource; @@ -6395,6 +6403,14 @@ export class ClaimRequestManagementService { } } + const approvedUseTypeId = Number( + (claimCase as any)?.fanavaranVehicleReview?.vehicleUseType?.id, + ); + if (Number.isInteger(approvedUseTypeId) && approvedUseTypeId > 0) { + payload.AccidentVehicleUsedId = approvedUseTypeId; + usedSource = "expert-review"; + } + if (parseFanavaranId(payload.AccidentVehicleUsedId) == null) { payload.AccidentVehicleUsedId = profile.defaults.AccidentVehicleUsedId; @@ -6497,6 +6513,7 @@ export class ClaimRequestManagementService { FanavaranAuditSource.SUBMIT, ); } catch (error) { + if (error instanceof HttpException) throw error; this.logger.error( `[Fanavaran ${clientKey} V2] Error submitting to Fanavaran`, error, @@ -6594,6 +6611,7 @@ export class ClaimRequestManagementService { bodyOverride, ); } catch (error) { + if (error instanceof HttpException) throw error; this.logger.error( `[Fanavaran ${clientKey} V2] Error submitting damage case to Fanavaran`, error, @@ -6790,6 +6808,7 @@ export class ClaimRequestManagementService { const profile = getFanavaranClientProfile(clientKey); let claimCase = await this.claimCaseDbService.findById(claimCaseId); + if (claimCase) this.assertFanavaranVehicleReviewApproved(claimCase); if (!claimCase?.claimId) { try { await this.ensureFanavaranBaseClaim( @@ -7628,6 +7647,8 @@ export class ClaimRequestManagementService { auditSource: FanavaranAuditSource, ): Promise { let claimCase = await this.claimCaseDbService.findById(claimCaseId); + if (!claimCase) throw new NotFoundException("Claim case not found"); + this.assertFanavaranVehicleReviewApproved(claimCase); const product = await this.resolveFanavaranClaimProduct(claimCaseId); if ( !claimCase?.claimId || @@ -7884,6 +7905,17 @@ export class ClaimRequestManagementService { return baseMessage; } + private assertFanavaranVehicleReviewApproved(claimCase: any): void { + const review = claimCase?.fanavaranVehicleReview; + const ids = [review?.vehicleGroup?.id, review?.vehicleUseType?.id, review?.vehicleSystem?.id, review?.vehicleKind?.id]; + if (review?.approved !== true || ids.some((id) => !Number.isInteger(Number(id)) || Number(id) <= 0)) { + throw new ConflictException({ + code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED", + message: "An expert must review and approve the vehicle group, use type, system, and kind before any data can be sent to Fanavaran.", + }); + } + } + private async getFanavaranAutoSubmitSkipReason( claimCase: any, ): Promise { @@ -7891,6 +7923,10 @@ export class ClaimRequestManagementService { return "Already submitted to Fanavaran"; } + if (!claimCase.fanavaranVehicleReview?.approved) { + return "Expert vehicle review is required before Fanavaran submission"; + } + if (!claimCase.blameRequestId) { return "Blame case not linked to claim case"; } @@ -8199,6 +8235,7 @@ export class ClaimRequestManagementService { if (!claimCase) { throw new NotFoundException("Claim case not found"); } + this.assertFanavaranVehicleReviewApproved(claimCase); if (!claimCase.claimId) { await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource); claimCase = await this.claimCaseDbService.findById(claimCaseId); @@ -8967,6 +9004,8 @@ export class ClaimRequestManagementService { } ); } + if (!existing) throw new NotFoundException("Claim case not found"); + this.assertFanavaranVehicleReviewApproved(existing); const auditSession: FanavaranAuditSession = { trackingCode: this.fanavaranAuditService.generateTrackingCode(), diff --git a/src/claim-request-management/entites/schema/claim-cases.schema.ts b/src/claim-request-management/entites/schema/claim-cases.schema.ts index 2f9fe5f..7e28a49 100644 --- a/src/claim-request-management/entites/schema/claim-cases.schema.ts +++ b/src/claim-request-management/entites/schema/claim-cases.schema.ts @@ -97,7 +97,7 @@ export class FanavaranSyncStage { @Prop({ type: Number }) vehicleKindId?: number; - /** How VehicleKindId was resolved: vehicle-inquiry | car-type-lookup */ + /** How VehicleKindId was resolved: expert-review | vehicle-inquiry | car-type-lookup */ @Prop({ type: String }) vehicleKindSource?: string; @@ -124,7 +124,7 @@ export class FanavaranSyncStage { @Prop({ type: Number }) accidentVehicleUsedId?: number; - /** How AccidentVehicleUsedId was resolved: vin-inquiry | policy-vehicle */ + /** How AccidentVehicleUsedId was resolved: expert-review | vin-inquiry | policy-vehicle | vehicle-inquiry */ @Prop({ type: String }) accidentVehicleUsedSource?: string; @@ -181,6 +181,66 @@ export class FanavaranSyncState { export const FanavaranSyncStateSchema = SchemaFactory.createForClass(FanavaranSyncState); +@Schema({ _id: false }) +export class FanavaranVehicleLookupValue { + @Prop({ type: Number, required: true }) + id: number; + + @Prop({ type: String, required: true }) + caption: string; + + @Prop({ type: String }) + name?: string; + + @Prop({ type: Number }) + vehicleGroupId?: number; + + @Prop({ type: Number }) + vehicleSystemId?: number; + + @Prop({ type: String }) + vehicleSystemCaption?: string; +} +export const FanavaranVehicleLookupValueSchema = SchemaFactory.createForClass( + FanavaranVehicleLookupValue, +); + +@Schema({ _id: false }) +export class FanavaranVehicleReview { + @Prop({ type: FanavaranVehicleLookupValueSchema, required: true }) + vehicleGroup: FanavaranVehicleLookupValue; + + @Prop({ type: FanavaranVehicleLookupValueSchema, required: true }) + vehicleUseType: FanavaranVehicleLookupValue; + + @Prop({ type: FanavaranVehicleLookupValueSchema, required: true }) + vehicleSystem: FanavaranVehicleLookupValue; + + @Prop({ type: FanavaranVehicleLookupValueSchema, required: true }) + vehicleKind: FanavaranVehicleLookupValue; + + @Prop({ type: Boolean, required: true, default: true }) + approved: boolean; + + @Prop({ type: Date, required: true }) + approvedAt: Date; + + @Prop({ type: MongooseSchema.Types.ObjectId, required: true }) + approvedByActorId: Types.ObjectId; + + @Prop({ type: String }) + approvedByActorName?: string; + + @Prop({ type: String, required: true }) + approvedByRole: string; + + @Prop({ type: Number, required: true, default: 1 }) + version: number; +} +export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass( + FanavaranVehicleReview, +); + @Schema({ collection: "claimCases", timestamps: true, @@ -278,6 +338,10 @@ export class ClaimCase { @Prop({ type: FanavaranSyncStateSchema, default: () => ({}) }) fanavaranSync?: FanavaranSyncState; + /** Expert-approved Fanavaran vehicle classification used by outbound stages. */ + @Prop({ type: FanavaranVehicleReviewSchema }) + fanavaranVehicleReview?: FanavaranVehicleReview; + @Prop({ type: ClaimDamageSelectionSchema, default: () => ({}) }) damage?: ClaimDamageSelection; diff --git a/src/expert-claim/dto/claim-detail-v2.dto.ts b/src/expert-claim/dto/claim-detail-v2.dto.ts index 8221ce6..bd10d3f 100644 --- a/src/expert-claim/dto/claim-detail-v2.dto.ts +++ b/src/expert-claim/dto/claim-detail-v2.dto.ts @@ -187,13 +187,15 @@ export class ClaimDetailV2ResponseDto { fileMakerRejectionCount?: number; @ApiPropertyOptional({ - description: "V5 only. Reason text from the most recent FileMaker rejection.", + description: + "V5 only. Reason text from the most recent FileMaker rejection.", example: "قیمت نامعقول", }) fileMakerRejectionReason?: string; @ApiPropertyOptional({ - description: "V5 only. ObjectId of the FileMaker who must approve (or has approved) this claim.", + description: + "V5 only. ObjectId of the FileMaker who must approve (or has approved) this claim.", example: "6a43a2689faee3d20bf24030", }) fileMakerApprovalActorId?: string; @@ -222,6 +224,29 @@ export class ClaimDetailV2ResponseDto { insuranceCorpId?: number; }; + @ApiPropertyOptional({ + description: + "Expert-approved vehicle classification used for Fanavaran submissions.", + }) + fanavaranVehicleReview?: { + vehicleGroup: { id: number; caption: string; name?: string }; + vehicleUseType: { id: number; caption: string; vehicleGroupId?: number }; + vehicleSystem: { id: number; caption: string; vehicleGroupId?: number }; + vehicleKind: { + id: number; + caption: string; + vehicleGroupId?: number; + vehicleSystemId?: number; + vehicleSystemCaption?: string; + }; + approved: boolean; + approvedAt: Date | string; + approvedByActorId: string; + approvedByActorName?: string; + approvedByRole: string; + version: number; + }; + @ApiPropertyOptional({ description: "Slice of `claim.evaluation` exposed to the damage expert. " + diff --git a/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts b/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts new file mode 100644 index 0000000..14ed809 --- /dev/null +++ b/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts @@ -0,0 +1,32 @@ +import { ApiProperty } from "@nestjs/swagger"; +import { Equals, IsInt, Min } from "class-validator"; + +export class ApproveFanavaranVehicleReviewDto { + @ApiProperty({ example: 1, description: "Fanavaran vehicle-groups Id" }) + @IsInt() + @Min(1) + vehicleGroupId: number; + + @ApiProperty({ example: 1, description: "Fanavaran vehicle-use-types Id" }) + @IsInt() + @Min(1) + vehicleUseTypeId: number; + + @ApiProperty({ example: 14, description: "Fanavaran vehicle-systems Id" }) + @IsInt() + @Min(1) + vehicleSystemId: number; + + @ApiProperty({ example: 7456, description: "Fanavaran vehicle-kinds Id" }) + @IsInt() + @Min(1) + vehicleKindId: number; + + @ApiProperty({ + example: true, + description: + "Explicit consent that the expert reviewed these values and authorizes Fanavaran submission", + }) + @Equals(true) + confirmed: true; +} diff --git a/src/expert-claim/expert-claim.module.ts b/src/expert-claim/expert-claim.module.ts index cc267a1..e77b71e 100644 --- a/src/expert-claim/expert-claim.module.ts +++ b/src/expert-claim/expert-claim.module.ts @@ -18,6 +18,7 @@ import { SandHubModule } from "src/sand-hub/sand-hub.module"; import { SmsOrchestrationModule } from "src/sms-orchestration/sms-orchestration.module"; import { UsersModule } from "src/users/users.module"; import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module"; +import { LookupsModule } from "src/lookups/lookups.module"; import { ExpertClaimController } from "./expert-claim.controller"; import { ExpertClaimV2Controller } from "./expert-claim.v2.controller"; import { ExpertClaimService } from "./expert-claim.service"; @@ -43,6 +44,7 @@ import { ExpertClaimService } from "./expert-claim.service"; UsersModule, ClientModule, FanavaranLookupModule, + LookupsModule, ], controllers: [ExpertClaimController, ExpertClaimV2Controller], providers: [ExpertClaimService, ClaimFactorsImageDbService], diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index 602dc93..312ff8f 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -181,6 +181,12 @@ import { parseMoneyAmountToman, } from "src/utils/unicode-digits"; import { claimPriceCapAppliesToBlame } from "src/helpers/claim-price-cap"; +import { LookupsService } from "src/lookups/lookups.service"; +import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto"; +import { + buildFanavaranVehicleSuggestion, + collectFanavaranVehicleInquiryRecords, +} from "./fanavaran-vehicle-suggestion"; @Injectable() export class ExpertClaimService { @@ -306,6 +312,7 @@ export class ExpertClaimService { private readonly claimSignDbService: ClaimSignDbService, private readonly claimRequestManagementService: ClaimRequestManagementService, private readonly fanavaranLocationService: FanavaranLocationService, + private readonly lookupsService: LookupsService, ) {} private appendFanavaranAutoSubmitToMessage( @@ -390,7 +397,9 @@ export class ExpertClaimService { // Resolve objection invoice paths to downloadable URLs. const objection = ev.objection as Record | undefined; if (objection) { - const invoices = objection.invoices as Array> | undefined; + const invoices = objection.invoices as + | Array> + | undefined; if (Array.isArray(invoices) && invoices.length > 0) { ev.objection = { ...objection, @@ -455,9 +464,10 @@ export class ExpertClaimService { } if (actor?.role === RoleEnum.FILE_MAKER) { - const actorBranchId = await this.fanavaranLocationService.fileMakerBranchId( - String(actor.sub), - ); + const actorBranchId = + await this.fanavaranLocationService.fileMakerBranchId( + String(actor.sub), + ); if (!actorBranchId || (caseBranchId && caseBranchId !== actorBranchId)) { throw new ForbiddenException("This file belongs to another branch."); } @@ -516,8 +526,7 @@ export class ExpertClaimService { }, { lean: true, - select: - "_id branchId isMadeByFileMaker initiatedByFieldExpertId", + select: "_id branchId isMadeByFileMaker initiatedByFieldExpertId", }, )) as any[]) : []; @@ -749,8 +758,10 @@ export class ExpertClaimService { let carName: string | undefined = cv.carName; let carModel: string | undefined = cv.carModel; if ( - (!carName || carName === carType) || - (!carModel || carModel === carType) + !carName || + carName === carType || + !carModel || + carModel === carType ) { const fromInquiry = this.vehicleNamesFromClaimInquiries(claim); if (!carName || carName === carType) carName = fromInquiry.carName; @@ -798,10 +809,9 @@ export class ExpertClaimService { nationalCode: party?.person?.nationalCode, nationalCodeOfInsurer: party?.person?.nationalCodeOfInsurer, nationalCodeOfDriver: party?.person?.nationalCodeOfDriver, - participants: ( - Array.isArray(party?.participants) - ? party.participants - : party?.inquiryParticipants + participants: (Array.isArray(party?.participants) + ? party.participants + : party?.inquiryParticipants )?.map((participant: any) => ({ phoneNumber: participant?.phoneNumber, nationalCode: participant?.nationalCode, @@ -2625,14 +2635,15 @@ export class ExpertClaimService { }; if (anyRejected) { - const completionStatus = await this.completeClaimCaseAfterFactorValidationV2( - claimRequestId, - claim, - actor, - "FACTORS_REJECTED_REPRICED_AUTO_COMPLETED", - historyActor, - { replyField }, - ); + const completionStatus = + await this.completeClaimCaseAfterFactorValidationV2( + claimRequestId, + claim, + actor, + "FACTORS_REJECTED_REPRICED_AUTO_COMPLETED", + historyActor, + { replyField }, + ); return { message: completionStatus === ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL @@ -2645,14 +2656,15 @@ export class ExpertClaimService { }; } - const completionStatus = await this.completeClaimCaseAfterFactorValidationV2( - claimRequestId, - claim, - actor, - "FACTORS_VALIDATED_ALL_APPROVED_AUTO_COMPLETED", - historyActor, - { replyField }, - ); + const completionStatus = + await this.completeClaimCaseAfterFactorValidationV2( + claimRequestId, + claim, + actor, + "FACTORS_VALIDATED_ALL_APPROVED_AUTO_COMPLETED", + historyActor, + { replyField }, + ); return { message: @@ -2714,7 +2726,6 @@ export class ExpertClaimService { throw new HttpException(error.response, error.claimStatus); } - /** * FILE_REVIEWER path: atomically assign this reviewer to the linked V4 blame * file. Operates on the blame document (not the claim workflow lock). @@ -2767,7 +2778,8 @@ export class ExpertClaimService { throw new BadRequestException({ success: false, status: "unavailable" satisfies ExpertFileAssignStatus, - message: "Only V4/V5 FileMaker files can be assigned to a FileReviewer.", + message: + "Only V4/V5 FileMaker files can be assigned to a FileReviewer.", }); } if ((blame as any).status !== "WAITING_FOR_FILE_REVIEWER") { @@ -2832,11 +2844,11 @@ export class ExpertClaimService { success: true, status: "assigned", assignedAt: now.toISOString(), - message: "File assigned to you. Proceed with accident fields and field capture.", + message: + "File assigned to you. Proceed with accident fields and field capture.", }; } - /** * Assign the current damage expert to a claim for review (V2). * Free cases are locked atomically; already-assigned-to-self is idempotent. @@ -3409,7 +3421,10 @@ export class ExpertClaimService { receptor: ownerPhoneResend, fileKind: "claim", publicId: claim.publicId, - link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"), + link: this.smsOrchestrationService.buildClaimLink( + String(claim._id), + "v1", + ), }); } @@ -3512,7 +3527,8 @@ export class ExpertClaimService { let parsedCurrentCarPrice: number | undefined; if (blame.type === BlameRequestType.CAR_BODY) { - parsedCurrentCarPrice = parseMoneyAmountToman(reply.carPrice) ?? undefined; + parsedCurrentCarPrice = + parseMoneyAmountToman(reply.carPrice) ?? undefined; if ( parsedCurrentCarPrice == null || !Number.isSafeInteger(parsedCurrentCarPrice) || @@ -3751,7 +3767,8 @@ export class ExpertClaimService { } } - const persistedCaseStatus = isV5Claim && !needsFactorUpload + const persistedCaseStatus = + isV5Claim && !needsFactorUpload ? ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL : nextCaseStatus; const updatePayload: Record = { @@ -4097,7 +4114,10 @@ export class ExpertClaimService { ) .then((docs) => docs.map((d) => (d as { _id: unknown })._id)); const claimOr: Record[] = [ - { initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } }, + { + initiatedByFieldExpertId: expertOid, + requiresFileMakerApproval: { $ne: true }, + }, ]; if (expertBlameIds.length > 0) { claimOr.push({ blameRequestId: { $in: expertBlameIds } }); @@ -4177,7 +4197,10 @@ export class ExpertClaimService { (item) => item.unifiedFileStatus === query.unifiedStatus, ); } - const { fromDate, toDate } = parseListDateRange(query.startDate, query.endDate); + const { fromDate, toDate } = parseListDateRange( + query.startDate, + query.endDate, + ); if (fromDate || toDate) { filtered = filtered.filter((item) => isInListDateRange(item.createdAt, fromDate, toDate), @@ -4366,7 +4389,11 @@ export class ExpertClaimService { blameIds.length > 0 ? ((await this.blameRequestDbService.find( { _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } }, - { lean: true, select: "type creationMethod parties expert.decision blameStatus status isMadeByFileMaker" }, + { + lean: true, + select: + "type creationMethod parties expert.decision blameStatus status isMadeByFileMaker", + }, )) as any[]) : []; const blameById = new Map( @@ -4447,7 +4474,10 @@ export class ExpertClaimService { const claimOr: Record[] = [ // Direct claim link: exclude V5 claims that require FileMaker approval - { initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } }, + { + initiatedByFieldExpertId: expertOid, + requiresFileMakerApproval: { $ne: true }, + }, ]; if (expertBlameIds.length > 0) { claimOr.push({ blameRequestId: { $in: expertBlameIds } }); @@ -4468,7 +4498,11 @@ export class ExpertClaimService { blameIds.length > 0 ? ((await this.blameRequestDbService.find( { _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } }, - { lean: true, select: "type creationMethod parties expert.decision blameStatus status" }, + { + lean: true, + select: + "type creationMethod parties expert.decision blameStatus status", + }, )) as any[]) : []; const blameById = new Map( @@ -4587,9 +4621,7 @@ export class ExpertClaimService { ? String(blame.initiatedByFieldExpertId) : null, fileReviewerId: actor.sub, - caseBranchId: blame.branchId - ? String(blame.branchId) - : null, + caseBranchId: blame.branchId ? String(blame.branchId) : null, }, ); return blame; @@ -4660,7 +4692,8 @@ export class ExpertClaimService { assignedToMe: !!assignedToMe, requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval, fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0, - fileMakerRejectionReason: (c as any).fileMakerRejectionReason ?? undefined, + fileMakerRejectionReason: + (c as any).fileMakerRejectionReason ?? undefined, }; }) as ClaimListItemV2Dto[]; @@ -4680,7 +4713,11 @@ export class ExpertClaimService { const ownMakerBlames = (await this.blameRequestDbService.find( { isMadeByFileMaker: true, initiatedByFieldExpertId: makerOid }, - { lean: true, select: "_id branchId type creationMethod parties blameStatus status expert.decision assignedFileReviewerId requiresFileMakerApproval" }, + { + lean: true, + select: + "_id branchId type creationMethod parties blameStatus status expert.decision assignedFileReviewerId requiresFileMakerApproval", + }, )) as any[]; const hasBranchScopedFiles = ownMakerBlames.some( (blame) => !!blame.branchId, @@ -4694,8 +4731,7 @@ export class ExpertClaimService { ); } const makerBlames = ownMakerBlames.filter( - (blame) => - !blame.branchId || String(blame.branchId) === makerBranchId, + (blame) => !blame.branchId || String(blame.branchId) === makerBranchId, ); if (makerBlames.length === 0) { @@ -4752,7 +4788,8 @@ export class ExpertClaimService { awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c), requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval, fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0, - fileMakerRejectionReason: (c as any).fileMakerRejectionReason ?? undefined, + fileMakerRejectionReason: + (c as any).fileMakerRejectionReason ?? undefined, needsFileReviewerCompletion: String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" || (!!blame?.isMadeByFileMaker && @@ -4956,7 +4993,8 @@ export class ExpertClaimService { (actor as any).role === RoleEnum.FIELD_EXPERT || (actor as any).role === RoleEnum.FILE_REVIEWER || (actor as any).role === RoleEnum.FILE_MAKER - ) return; + ) + return; const clientKey = requireActorClientKey(actor); const lockTtlMs = EXPERT_WORKFLOW_LOCK_TTL_MS; const now = new Date(); @@ -5386,15 +5424,20 @@ export class ExpertClaimService { const carType: string | undefined = vehiclePayload.carType; if ( carType && - ((!vehiclePayload.carName || vehiclePayload.carName === carType) || - (!vehiclePayload.carModel || vehiclePayload.carModel === carType)) + (!vehiclePayload.carName || + vehiclePayload.carName === carType || + !vehiclePayload.carModel || + vehiclePayload.carModel === carType) ) { const fromInquiry = this.vehicleNamesFromClaimInquiries(claim); if (!vehiclePayload.carName || vehiclePayload.carName === carType) { vehiclePayload = { ...vehiclePayload, carName: fromInquiry.carName }; } if (!vehiclePayload.carModel || vehiclePayload.carModel === carType) { - vehiclePayload = { ...vehiclePayload, carModel: fromInquiry.carModel }; + vehiclePayload = { + ...vehiclePayload, + carModel: fromInquiry.carModel, + }; } } } @@ -5531,11 +5574,13 @@ export class ExpertClaimService { awaitingFactorValidation: isFactorValidationPending, requiresFileMakerApproval: !!(claim as any).requiresFileMakerApproval, fileMakerRejectionCount: (claim as any).fileMakerRejectionCount ?? 0, - fileMakerRejectionReason: (claim as any).fileMakerRejectionReason ?? undefined, + fileMakerRejectionReason: + (claim as any).fileMakerRejectionReason ?? undefined, fileMakerApprovalActorId: (claim as any).fileMakerApprovalActorId ? String((claim as any).fileMakerApprovalActorId) : undefined, fanavaran: fanavaranClaimReferences(claim), + fanavaranVehicleReview: (claim as any).fanavaranVehicleReview, evaluation: (evaluationForApi as | ClaimDetailV2ResponseDto["evaluation"] @@ -5548,6 +5593,188 @@ export class ExpertClaimService { }; } + private asFanavaranLookupRows(value: unknown): Array> { + if (Array.isArray(value)) return value as Array>; + if (value && typeof value === "object") { + const data = (value as { data?: unknown }).data; + if (Array.isArray(data)) return data as Array>; + if (data && typeof data === "object") { + const nested = (data as { data?: unknown }).data; + if (Array.isArray(nested)) return nested as Array>; + } + } + return []; + } + + private activeFanavaranLookupRows(value: unknown) { + return this.asFanavaranLookupRows(value) + .filter((row) => row.IsActive !== 0 && Number(row.Id) > 0) + .sort((a, b) => + String(a.Caption ?? "").localeCompare(String(b.Caption ?? ""), "fa"), + ); + } + + async getFanavaranVehicleOptionsV2( + claimRequestId: string, + actor: any, + vehicleGroupId?: number, + ) { + await this.getClaimDetailV2(claimRequestId, actor); + const claim = await this.claimCaseDbService.findById(claimRequestId); + if (!claim) throw new NotFoundException("Claim request not found"); + + const [groupsRaw, useTypesRaw, systemsRaw, blame] = await Promise.all([ + this.lookupsService.getClientRemoteLookup("vehicle-groups"), + this.lookupsService.getClientRemoteLookup("vehicle-use-types"), + this.lookupsService.getClientRemoteLookup("vehicle-systems"), + claim.blameRequestId + ? this.blameRequestDbService.findById(String(claim.blameRequestId)) + : Promise.resolve(null), + ]); + const groups = this.activeFanavaranLookupRows(groupsRaw); + const useTypes = this.activeFanavaranLookupRows(useTypesRaw); + const systems = this.activeFanavaranLookupRows(systemsRaw); + const suggestion = await buildFanavaranVehicleSuggestion({ + records: collectFanavaranVehicleInquiryRecords(claim, blame), + groups, + useTypes, + systems, + getVehicleKindById: (id) => + this.lookupsService.getActiveVehicleKindById(id), + searchVehicleKinds: (input) => + this.lookupsService.searchVehicleKindsList(input), + }); + + const groupId = + vehicleGroupId != null && + Number.isInteger(vehicleGroupId) && + vehicleGroupId > 0 + ? vehicleGroupId + : null; + const filterByGroup = (rows: Array>) => + groupId == null + ? [] + : rows.filter((row) => Number(row.VehicleGroupId) === groupId); + return { + vehicleGroups: groups, + vehicleUseTypes: filterByGroup(useTypes), + vehicleSystems: filterByGroup(systems), + suggestion, + }; + } + + async approveFanavaranVehicleReviewV2( + claimRequestId: string, + body: ApproveFanavaranVehicleReviewDto, + actor: any, + ) { + await this.getClaimDetailV2(claimRequestId, actor); + const claim = await this.claimCaseDbService.findById(claimRequestId); + if (!claim) throw new NotFoundException("Claim request not found"); + if (claim.claimId != null || claim.claimNo != null) { + throw new ConflictException( + "Vehicle classification cannot be changed after the claim was sent to Fanavaran.", + ); + } + const [groupsRaw, useTypesRaw, systemsRaw, vehicleKind] = await Promise.all( + [ + this.lookupsService.getClientRemoteLookup("vehicle-groups"), + this.lookupsService.getClientRemoteLookup("vehicle-use-types"), + this.lookupsService.getClientRemoteLookup("vehicle-systems"), + this.lookupsService.getActiveVehicleKindById(body.vehicleKindId), + ], + ); + const group = this.activeFanavaranLookupRows(groupsRaw).find( + (row) => Number(row.Id) === body.vehicleGroupId, + ); + const useType = this.activeFanavaranLookupRows(useTypesRaw).find( + (row) => Number(row.Id) === body.vehicleUseTypeId, + ); + const system = this.activeFanavaranLookupRows(systemsRaw).find( + (row) => Number(row.Id) === body.vehicleSystemId, + ); + if (!group || !useType || !system || !vehicleKind) { + throw new BadRequestException( + "One or more selected Fanavaran vehicle values are inactive or invalid.", + ); + } + if ( + Number(useType.VehicleGroupId) !== body.vehicleGroupId || + Number(system.VehicleGroupId) !== body.vehicleGroupId || + Number(vehicleKind.VehicleGroupId) !== body.vehicleGroupId || + Number(vehicleKind.VehicleSystemId) !== body.vehicleSystemId + ) { + throw new BadRequestException( + "The selected vehicle group, use type, system, and kind are not compatible.", + ); + } + const value = (row: Record) => ({ + id: Number(row.Id), + caption: String(row.Caption ?? ""), + ...(row.Name != null ? { name: String(row.Name) } : {}), + ...(row.VehicleGroupId != null + ? { vehicleGroupId: Number(row.VehicleGroupId) } + : {}), + ...(row.VehicleSystemId != null + ? { vehicleSystemId: Number(row.VehicleSystemId) } + : {}), + ...(row.VehicleSystemCaption != null + ? { vehicleSystemCaption: String(row.VehicleSystemCaption) } + : {}), + }); + const review = { + vehicleGroup: value(group), + vehicleUseType: value(useType), + vehicleSystem: value(system), + vehicleKind: value(vehicleKind as unknown as Record), + approved: true, + approvedAt: new Date(), + approvedByActorId: new Types.ObjectId(String(actor.sub)), + approvedByActorName: actor.fullName, + approvedByRole: String(actor.role), + version: Number((claim as any).fanavaranVehicleReview?.version ?? 0) + 1, + }; + const updated = await this.claimCaseDbService.findByIdAndUpdate( + claimRequestId, + { + $set: { fanavaranVehicleReview: review }, + $push: { + history: { + type: "FANAVARAN_VEHICLE_REVIEW_APPROVED", + actor: { + actorId: new Types.ObjectId(String(actor.sub)), + actorName: actor.fullName, + actorType: actor.role, + }, + timestamp: review.approvedAt, + metadata: { + version: review.version, + vehicleGroupId: body.vehicleGroupId, + vehicleUseTypeId: body.vehicleUseTypeId, + vehicleSystemId: body.vehicleSystemId, + vehicleKindId: body.vehicleKindId, + }, + }, + }, + }, + ); + const baseClaim = + await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCreated( + claimRequestId, + ); + const selectedParts = updated?.damage?.selectedParts ?? []; + const damageCase = selectedParts.length + ? await this.claimRequestManagementService.autoSubmitFanavaranDamageCaseOnOuterPartsSelected( + claimRequestId, + selectedParts, + ) + : undefined; + return { + review: (updated as any)?.fanavaranVehicleReview ?? review, + fanavaranSync: { baseClaim, damageCase }, + }; + } + /** V2 price-drop: claim locked by this expert during damage assessment. */ private async assertExpertCanEditClaimDuringReviewV2( claim: any, diff --git a/src/expert-claim/expert-claim.v2.controller.ts b/src/expert-claim/expert-claim.v2.controller.ts index 6e41a1c..13b4eb3 100644 --- a/src/expert-claim/expert-claim.v2.controller.ts +++ b/src/expert-claim/expert-claim.v2.controller.ts @@ -52,6 +52,7 @@ import { FactorValidationV2Dto } from "./dto/factor-validation.dto"; import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; import { OuterPartCatalogItemDto } from "src/claim-request-management/dto/select-outer-parts-v2.dto"; import { submitExpertReplyValidationPipe } from "./pipes/submit-expert-reply-validation.pipe"; +import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto"; class InPersonVisitV2Dto { @ApiPropertyOptional({ example: "Paint damage requires physical inspection" }) @@ -181,6 +182,48 @@ export class ExpertClaimV2Controller { ); } + @Get("request/:claimRequestId/fanavaran-vehicle-options") + @ApiOperation({ + summary: "Get compatible Fanavaran vehicle classification options", + description: + "Returns active vehicle groups and, after vehicleGroupId is supplied, only compatible use types and systems.", + }) + @ApiQuery({ name: "vehicleGroupId", required: false, type: Number }) + async getFanavaranVehicleOptionsV2( + @Param("claimRequestId") claimRequestId: string, + @CurrentUser() actor: any, + @Query("vehicleGroupId") vehicleGroupId?: string, + ) { + const parsed = + vehicleGroupId != null && vehicleGroupId !== "" + ? Number(vehicleGroupId) + : undefined; + return this.expertClaimService.getFanavaranVehicleOptionsV2( + claimRequestId, + actor, + parsed, + ); + } + + @Put("request/:claimRequestId/fanavaran-vehicle-review") + @ApiOperation({ + summary: "Validate and approve the vehicle data used for Fanavaran", + description: + "Validates all four IDs against active Fanavaran lookups and their relationships, stores an audit snapshot, and releases deferred Fanavaran stages.", + }) + @ApiBody({ type: ApproveFanavaranVehicleReviewDto }) + async approveFanavaranVehicleReviewV2( + @Param("claimRequestId") claimRequestId: string, + @Body() body: ApproveFanavaranVehicleReviewDto, + @CurrentUser() actor: any, + ) { + return this.expertClaimService.approveFanavaranVehicleReviewV2( + claimRequestId, + body, + actor, + ); + } + @Get("request/:claimRequestId/price-drop") @ApiOperation({ summary: "Price-drop context for manual expert entry (V2)", diff --git a/src/expert-claim/fanavaran-vehicle-review.spec.ts b/src/expert-claim/fanavaran-vehicle-review.spec.ts new file mode 100644 index 0000000..4832177 --- /dev/null +++ b/src/expert-claim/fanavaran-vehicle-review.spec.ts @@ -0,0 +1,128 @@ +import { BadRequestException, ConflictException } from "@nestjs/common"; +import { ExpertClaimService } from "./expert-claim.service"; +import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; + +const actor = { + sub: "507f1f77bcf86cd799439011", + fullName: "کارشناس تست", + role: "damage_expert", +}; + +const groups = [{ Id: 1, Caption: "سواری", IsActive: 1, Name: "Savari" }]; +const useTypes = [{ Id: 3, Caption: "تاکسی", IsActive: 1, VehicleGroupId: 1 }]; +const systems = [{ Id: 14, Caption: "پراید", IsActive: 1, VehicleGroupId: 1 }]; +const kind = { + Id: 7456, + Caption: "پراید", + IsActive: 1, + VehicleGroupId: 1, + VehicleSystemId: 14, + VehicleSystemCaption: "پراید", +}; + +function makeService(overrides?: { kind?: typeof kind }) { + const service = Object.create(ExpertClaimService.prototype) as any; + const claim = { + _id: "507f1f77bcf86cd799439012", + damage: { selectedParts: [] }, + }; + service.getClaimDetailV2 = jest.fn().mockResolvedValue({}); + service.claimCaseDbService = { + findById: jest.fn().mockResolvedValue(claim), + findByIdAndUpdate: jest.fn().mockImplementation((_id, update) => + Promise.resolve({ + ...claim, + fanavaranVehicleReview: update.$set.fanavaranVehicleReview, + }), + ), + }; + service.lookupsService = { + getClientRemoteLookup: jest.fn().mockImplementation((name) => { + if (name === "vehicle-groups") return groups; + if (name === "vehicle-use-types") return useTypes; + if (name === "vehicle-systems") return systems; + return []; + }), + getActiveVehicleKindById: jest + .fn() + .mockResolvedValue(overrides?.kind ?? kind), + }; + service.claimRequestManagementService = { + autoSubmitToFanavaranV2OnClaimCreated: jest + .fn() + .mockResolvedValue({ attempted: false, submitted: false }), + autoSubmitFanavaranDamageCaseOnOuterPartsSelected: jest.fn(), + }; + return service; +} + +describe("Fanavaran vehicle review", () => { + it("persists an authoritative snapshot and releases deferred submission", async () => { + const service = makeService(); + + const result = await service.approveFanavaranVehicleReviewV2( + "507f1f77bcf86cd799439012", + { + vehicleGroupId: 1, + vehicleUseTypeId: 3, + vehicleSystemId: 14, + vehicleKindId: 7456, + confirmed: true, + }, + actor, + ); + + expect(result.review).toMatchObject({ + approved: true, + vehicleGroup: { id: 1, caption: "سواری" }, + vehicleUseType: { id: 3, vehicleGroupId: 1 }, + vehicleSystem: { id: 14, vehicleGroupId: 1 }, + vehicleKind: { id: 7456, vehicleGroupId: 1, vehicleSystemId: 14 }, + approvedByRole: "damage_expert", + version: 1, + }); + expect( + service.claimRequestManagementService + .autoSubmitToFanavaranV2OnClaimCreated, + ).toHaveBeenCalledWith("507f1f77bcf86cd799439012"); + }); + + it("rejects a kind that does not belong to the selected system", async () => { + const service = makeService({ kind: { ...kind, VehicleSystemId: 16 } }); + + await expect( + service.approveFanavaranVehicleReviewV2( + "507f1f77bcf86cd799439012", + { + vehicleGroupId: 1, + vehicleUseTypeId: 3, + vehicleSystemId: 14, + vehicleKindId: 7456, + confirmed: true, + }, + actor, + ), + ).rejects.toBeInstanceOf(BadRequestException); + expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled(); + }); + + it("blocks outbound stages until all four values are approved", () => { + const service = Object.create( + ClaimRequestManagementService.prototype, + ) as any; + expect(() => service.assertFanavaranVehicleReviewApproved({})).toThrow( + ConflictException, + ); + expect(() => + service.assertFanavaranVehicleReviewApproved({ + fanavaranVehicleReview: { + approved: true, + vehicleGroup: { id: 1 }, + vehicleUseType: { id: 3 }, + vehicleSystem: { id: 14 }, + vehicleKind: { id: 7456 }, + }, + }), + ).not.toThrow(); + }); +}); diff --git a/src/expert-claim/fanavaran-vehicle-suggestion.spec.ts b/src/expert-claim/fanavaran-vehicle-suggestion.spec.ts new file mode 100644 index 0000000..8ac4e79 --- /dev/null +++ b/src/expert-claim/fanavaran-vehicle-suggestion.spec.ts @@ -0,0 +1,93 @@ +import { + buildFanavaranVehicleSuggestion, + extractFanavaranVehicleInquirySignals, +} from "./fanavaran-vehicle-suggestion"; + +const groups = [{ Id: 1, Caption: "سواري", IsActive: 1 }]; +const useTypes = [ + { Id: 1, Caption: "شخصي", IsActive: 1, VehicleGroupId: 1 }, + { Id: 3, Caption: "تاکسي", IsActive: 1, VehicleGroupId: 1 }, +]; +const systems = [{ Id: 14, Caption: "پرايد", IsActive: 1, VehicleGroupId: 1 }]; +const kind = { + Id: 7456, + Caption: "پرايد", + IsActive: 1, + VehicleGroupId: 1, + VehicleSystemId: 14, + VehicleSystemCaption: "پرايد", +}; + +describe("Fanavaran vehicle inquiry suggestion", () => { + it("keeps legacy provider codes as audit signals instead of Fanavaran IDs", () => { + const signals = extractFanavaranVehicleInquirySignals([ + { + label: "claim.inquiries.thirdParty.SECOND", + raw: { UsgCod: "8", VehSysCod: "2", CarGrpCod: "2" }, + mapped: { UsageField: "شخصی", MapTypNam: "پراید" }, + }, + ]); + + expect(signals.vehicleUseTypeId).toBeUndefined(); + expect(signals.legacyCodes.usage?.value).toBe("8"); + expect(signals.vehicleUseTypeCaptions[0].value).toBe("شخصی"); + }); + + it("uses direct Fanavaran kind/use IDs and derives group and system", async () => { + const suggestion = await buildFanavaranVehicleSuggestion({ + records: [ + { + label: "claim.inquiries.carBody.FIRST", + raw: { + vehicle: { + VehicleKindId: 7456, + UsedId: 1, + vehicleKind: kind, + used: { Id: 1, Caption: "شخصي" }, + }, + }, + }, + ], + groups, + useTypes, + systems, + getVehicleKindById: jest.fn().mockResolvedValue(kind), + searchVehicleKinds: jest.fn(), + }); + + expect(suggestion).toMatchObject({ + vehicleGroup: { Id: 1 }, + vehicleUseType: { Id: 1 }, + vehicleSystem: { Id: 14 }, + vehicleKind: { Id: 7456 }, + complete: true, + approved: false, + }); + }); + + it("matches legacy captions while preserving UsgCod only for traceability", async () => { + const suggestion = await buildFanavaranVehicleSuggestion({ + records: [ + { + label: "claim.inquiries.thirdParty.SECOND", + raw: { UsgCod: "8", VehSysCod: "2", CarGrpCod: "2" }, + mapped: { + UsageField: "شخصی", + MapTypNam: "پراید", + SystemField: "پراید", + }, + }, + ], + groups, + useTypes, + systems, + getVehicleKindById: jest.fn(), + searchVehicleKinds: jest.fn().mockResolvedValue({ items: [kind] }), + }); + + expect(suggestion.vehicleUseType?.Id).toBe(1); + expect(suggestion.vehicleKind?.Id).toBe(7456); + expect(suggestion.legacyCodes.usage?.value).toBe("8"); + expect(suggestion.complete).toBe(true); + }); +}); diff --git a/src/expert-claim/fanavaran-vehicle-suggestion.ts b/src/expert-claim/fanavaran-vehicle-suggestion.ts new file mode 100644 index 0000000..a87fd4c --- /dev/null +++ b/src/expert-claim/fanavaran-vehicle-suggestion.ts @@ -0,0 +1,453 @@ +import { normalizeVehicleKindCaptionSearch } from "src/lookups/vehicle-kind-search"; + +export type InquiryRecord = { + label: string; + raw?: unknown; + mapped?: unknown; +}; + +export type InquirySignal = { + value: T; + source: string; +}; + +export type FanavaranVehicleInquirySignals = { + vehicleKindId?: InquirySignal; + vehicleUseTypeId?: InquirySignal; + vehicleGroupCaptions: InquirySignal[]; + vehicleUseTypeCaptions: InquirySignal[]; + vehicleSystemCaptions: InquirySignal[]; + vehicleKindCaptions: InquirySignal[]; + legacyCodes: { + usage?: InquirySignal; + vehicleSystem?: InquirySignal; + vehicleGroup?: InquirySignal; + }; +}; + +const readPath = (value: unknown, path: string): unknown => { + let current = value; + for (const key of path.split(".")) { + if (!current || typeof current !== "object") return undefined; + current = (current as Record)[key]; + } + return current; +}; + +const positiveId = (value: unknown): number | undefined => { + const parsed = Number(value); + return Number.isInteger(parsed) && parsed > 0 ? parsed : undefined; +}; + +const nonEmpty = (value: unknown): string | undefined => { + if (value == null) return undefined; + const text = String(value).trim(); + return text || undefined; +}; + +const firstSignal = ( + records: InquiryRecord[], + locations: Array<{ side: "raw" | "mapped"; path: string }>, + parse: (value: unknown) => T | undefined, +): InquirySignal | undefined => { + for (const record of records) { + for (const location of locations) { + const value = parse(readPath(record[location.side], location.path)); + if (value !== undefined) { + return { + value, + source: `${record.label}.${location.side}.${location.path}`, + }; + } + } + } + return undefined; +}; + +const allSignals = ( + records: InquiryRecord[], + locations: Array<{ side: "raw" | "mapped"; path: string }>, +): InquirySignal[] => { + const values: InquirySignal[] = []; + const seen = new Set(); + for (const record of records) { + for (const location of locations) { + const value = nonEmpty(readPath(record[location.side], location.path)); + if (!value) continue; + const normalized = normalizeVehicleKindCaptionSearch(value); + if (!normalized || seen.has(normalized)) continue; + seen.add(normalized); + values.push({ + value, + source: `${record.label}.${location.side}.${location.path}`, + }); + } + } + return values; +}; + +/** + * Extracts semantic vehicle signals from both modern ESG/Fanavaran payloads + * and legacy SandHub/Sanhab aliases. Legacy numeric codes are intentionally + * retained only as audit metadata: their code space is not Fanavaran's lookup + * ID space (for example UsgCod=8 means personal use, whose Fanavaran Id is 1). + */ +export function extractFanavaranVehicleInquirySignals( + records: InquiryRecord[], +): FanavaranVehicleInquirySignals { + const vehicleKindId = firstSignal( + records, + [ + { side: "raw", path: "vehicle.VehicleKindId" }, + { side: "raw", path: "vehicle.vehicleKind.Id" }, + { side: "raw", path: "data.vehicle.VehicleKindId" }, + { side: "raw", path: "data.vehicle.vehicleKind.Id" }, + { side: "raw", path: "data.data.vehicle.VehicleKindId" }, + { side: "raw", path: "data.data.vehicle.vehicleKind.Id" }, + { side: "mapped", path: "VehicleKindId" }, + { side: "mapped", path: "vehicleKindId" }, + ], + positiveId, + ); + + const vehicleUseTypeId = firstSignal( + records, + [ + { side: "raw", path: "vehicle.UsedId" }, + { side: "raw", path: "vehicle.used.Id" }, + { side: "raw", path: "data.vehicle.UsedId" }, + { side: "raw", path: "data.vehicle.used.Id" }, + { side: "raw", path: "data.data.vehicle.UsedId" }, + { side: "raw", path: "data.data.vehicle.used.Id" }, + { side: "mapped", path: "UsedId" }, + { side: "mapped", path: "vehicleUsedId" }, + ], + positiveId, + ); + + return { + vehicleKindId, + vehicleUseTypeId, + vehicleGroupCaptions: allSignals(records, [ + { side: "mapped", path: "vehicleGroupTitle" }, + { side: "mapped", path: "vehicleGroup" }, + { side: "raw", path: "vehicle.vehicleKind.VehicleCategoryCaption" }, + { side: "raw", path: "data.vehicle.vehicleKind.VehicleCategoryCaption" }, + { + side: "raw", + path: "data.data.vehicle.vehicleKind.VehicleCategoryCaption", + }, + ]), + vehicleUseTypeCaptions: allSignals(records, [ + { side: "mapped", path: "usage" }, + { side: "mapped", path: "UsageField" }, + { side: "mapped", path: "MapUsageName" }, + { side: "mapped", path: "UsageNameCii" }, + { side: "raw", path: "vehicle.used.Caption" }, + { side: "raw", path: "data.vehicle.used.Caption" }, + { side: "raw", path: "data.data.vehicle.used.Caption" }, + ]), + vehicleSystemCaptions: allSignals(records, [ + { side: "mapped", path: "vehicleSystemTitle" }, + { side: "mapped", path: "vehicleSystem" }, + { side: "mapped", path: "MapVehicleSystemName" }, + { side: "mapped", path: "SystemField" }, + { side: "mapped", path: "SystemNameCii" }, + { side: "raw", path: "vehicle.vehicleKind.VehicleSystemCaption" }, + { side: "raw", path: "data.vehicle.vehicleKind.VehicleSystemCaption" }, + { + side: "raw", + path: "data.data.vehicle.vehicleKind.VehicleSystemCaption", + }, + ]), + vehicleKindCaptions: allSignals(records, [ + { side: "mapped", path: "vehicleKind" }, + { side: "mapped", path: "MapTypNam" }, + { side: "mapped", path: "TypeNameCii" }, + { side: "mapped", path: "CarName" }, + { side: "raw", path: "vehicle.vehicleKind.Caption" }, + { side: "raw", path: "data.vehicle.vehicleKind.Caption" }, + { side: "raw", path: "data.data.vehicle.vehicleKind.Caption" }, + { side: "raw", path: "vehiclePersianName" }, + { side: "raw", path: "MapTypNam" }, + ]), + legacyCodes: { + usage: firstSignal( + records, + [ + { side: "raw", path: "UsgCod" }, + { side: "raw", path: "data.UsgCod" }, + { side: "mapped", path: "UsgCod" }, + { side: "mapped", path: "usgCod" }, + { side: "mapped", path: "UsageCode" }, + ], + nonEmpty, + ), + vehicleSystem: firstSignal( + records, + [ + { side: "raw", path: "VehSysCod" }, + { side: "raw", path: "data.VehSysCod" }, + { side: "mapped", path: "VehSysCod" }, + { side: "mapped", path: "vehSysCod" }, + { side: "mapped", path: "VehicleSystemCode" }, + ], + nonEmpty, + ), + vehicleGroup: firstSignal( + records, + [ + { side: "raw", path: "CarGrpCod" }, + { side: "raw", path: "data.CarGrpCod" }, + { side: "mapped", path: "CarGrpCod" }, + { side: "mapped", path: "carGrpCod" }, + { side: "mapped", path: "CarGroupCode" }, + ], + nonEmpty, + ), + }, + }; +} + +export function exactLookupCaption>( + rows: T[], + signals: InquirySignal[], + predicate?: (row: T) => boolean, +): { row: T; source: string } | undefined { + for (const signal of signals) { + const needle = normalizeVehicleKindCaptionSearch(signal.value); + const matches = rows.filter( + (row) => + (!predicate || predicate(row)) && + normalizeVehicleKindCaptionSearch(row.Caption) === needle, + ); + if (matches.length === 1) return { row: matches[0], source: signal.source }; + } + return undefined; +} + +export function collectFanavaranVehicleInquiryRecords( + claim: any, + blame: any, +): InquiryRecord[] { + const parties = Array.isArray(blame?.parties) ? blame.parties : []; + const ownerId = claim?.owner?.userId ? String(claim.owner.userId) : ""; + let party = ownerId + ? parties.find( + (item: any) => + item?.person?.userId && String(item.person.userId) === ownerId, + ) + : undefined; + if (!party && blame?.expert?.decision?.guiltyPartyId) { + const guiltyId = String(blame.expert.decision.guiltyPartyId); + party = parties.find( + (item: any) => + item?.person?.userId && String(item.person.userId) !== guiltyId, + ); + } + if (!party && parties.length === 1) party = parties[0]; + + const inferredRole = + party?.role ?? (blame?.type === "THIRD_PARTY" ? "SECOND" : "FIRST"); + const records: InquiryRecord[] = []; + const add = (label: string, value: any) => { + if (!value || typeof value !== "object") return; + records.push({ label, raw: value.raw, mapped: value.mapped }); + }; + + // Prefer the damaged party. FIRST remains a fallback for legacy snapshots + // that predate role-keyed inquiry persistence. + for (const role of Array.from(new Set([inferredRole, "FIRST", "SECOND"]))) { + add( + `claim.inquiries.carBody.${role}`, + claim?.inquiries?.carBody?.data?.[role], + ); + add( + `claim.inquiries.thirdParty.${role}`, + claim?.inquiries?.thirdParty?.data?.[role], + ); + add( + `blame.inquiries.carBody.${role}`, + blame?.inquiries?.carBody?.data?.[role], + ); + add( + `blame.inquiries.thirdParty.${role}`, + blame?.inquiries?.thirdParty?.data?.[role], + ); + } + add("damagedParty.vehicle.inquiry", party?.vehicle?.inquiry); + add("damagedParty.vehicle.inquiry.carBody", party?.vehicle?.inquiry?.carBody); + add( + "damagedParty.vehicle.inquiry.thirdParty", + party?.vehicle?.inquiry?.thirdParty, + ); + + const insurance = party?.insurance?.carBodyInsurance; + if (insurance && typeof insurance === "object") { + records.push({ + label: "damagedParty.insurance.carBodyInsurance", + mapped: { + vehicleGroup: insurance.vehicleGroup, + vehicleSystem: insurance.vehicleSystem, + vehicleKind: insurance.vehicleKind, + usage: insurance.usage, + }, + }); + } + return records; +} + +type SuggestionBuilderInput = { + records: InquiryRecord[]; + groups: Array>; + useTypes: Array>; + systems: Array>; + getVehicleKindById: ( + id: number, + ) => Promise | null | undefined>; + searchVehicleKinds: (input: { + q: string; + limit: number; + vehicleGroupId?: number; + vehicleSystemId?: number; + }) => Promise<{ items: Array> }>; +}; + +export async function buildFanavaranVehicleSuggestion({ + records, + groups, + useTypes, + systems, + getVehicleKindById, + searchVehicleKinds, +}: SuggestionBuilderInput) { + const signals = extractFanavaranVehicleInquirySignals(records); + const warnings: string[] = []; + const sources: Record = {}; + + let groupMatch = exactLookupCaption(groups, signals.vehicleGroupCaptions); + let systemMatch = exactLookupCaption( + systems, + signals.vehicleSystemCaptions, + groupMatch + ? (row) => Number(row.VehicleGroupId) === Number(groupMatch?.row.Id) + : undefined, + ); + if (!groupMatch && systemMatch) { + const row = groups.find( + (item) => Number(item.Id) === Number(systemMatch?.row.VehicleGroupId), + ); + if (row) { + groupMatch = { + row, + source: `VehicleGroupId derived from ${systemMatch.source}`, + }; + } + } + + let vehicleKind: Record | null | undefined; + let vehicleKindSource: string | undefined; + if (signals.vehicleKindId) { + vehicleKind = await getVehicleKindById(signals.vehicleKindId.value); + if (vehicleKind) vehicleKindSource = signals.vehicleKindId.source; + else { + warnings.push( + `VehicleKindId=${signals.vehicleKindId.value} در فهرست فعال فناوران پیدا نشد.`, + ); + } + } + + if (!vehicleKind) { + for (const signal of signals.vehicleKindCaptions) { + const result = await searchVehicleKinds({ + q: signal.value, + limit: 100, + vehicleGroupId: groupMatch ? Number(groupMatch.row.Id) : undefined, + vehicleSystemId: systemMatch ? Number(systemMatch.row.Id) : undefined, + }); + const needle = normalizeVehicleKindCaptionSearch(signal.value); + const exact = result.items.filter( + (row) => normalizeVehicleKindCaptionSearch(row.Caption) === needle, + ); + if (exact.length === 1) { + vehicleKind = exact[0]; + vehicleKindSource = signal.source; + break; + } + if (exact.length > 1) { + warnings.push( + `نام خودروی «${signal.value}» با چند گزینه فناوران تطبیق دارد؛ کارشناس باید یکی را انتخاب کند.`, + ); + } + } + } + + // A matched kind carries Fanavaran's own relationships. These are safer than + // provider code fields and complete the group/system suggestions atomically. + if (vehicleKind) { + const relatedGroup = groups.find( + (row) => Number(row.Id) === Number(vehicleKind?.VehicleGroupId), + ); + const relatedSystem = systems.find( + (row) => Number(row.Id) === Number(vehicleKind?.VehicleSystemId), + ); + if (relatedGroup) { + groupMatch = { + row: relatedGroup, + source: `VehicleGroupId derived from ${vehicleKindSource}`, + }; + } + if (relatedSystem) { + systemMatch = { + row: relatedSystem, + source: `VehicleSystemId derived from ${vehicleKindSource}`, + }; + } + } + + let useTypeMatch: { row: Record; source: string } | undefined; + if (signals.vehicleUseTypeId) { + const direct = useTypes.find( + (row) => + Number(row.Id) === signals.vehicleUseTypeId?.value && + (!groupMatch || + Number(row.VehicleGroupId) === Number(groupMatch.row.Id)), + ); + if (direct) { + useTypeMatch = { row: direct, source: signals.vehicleUseTypeId.source }; + } else { + warnings.push( + `UsedId=${signals.vehicleUseTypeId.value} غیرفعال است یا با گروه خودروی تطبیق‌یافته سازگار نیست.`, + ); + } + } + if (!useTypeMatch) { + useTypeMatch = exactLookupCaption( + useTypes, + signals.vehicleUseTypeCaptions, + groupMatch + ? (row) => Number(row.VehicleGroupId) === Number(groupMatch?.row.Id) + : undefined, + ); + } + + if (groupMatch) sources.vehicleGroup = groupMatch.source; + if (useTypeMatch) sources.vehicleUseType = useTypeMatch.source; + if (systemMatch) sources.vehicleSystem = systemMatch.source; + if (vehicleKindSource) sources.vehicleKind = vehicleKindSource; + + const legacyCodes = Object.fromEntries( + Object.entries(signals.legacyCodes).filter(([, signal]) => signal != null), + ); + return { + vehicleGroup: groupMatch?.row, + vehicleUseType: useTypeMatch?.row, + vehicleSystem: systemMatch?.row, + vehicleKind: vehicleKind ?? undefined, + sources, + legacyCodes, + warnings, + complete: Boolean(groupMatch && useTypeMatch && systemMatch && vehicleKind), + approved: false, + }; +} diff --git a/src/lookups/entities/db-service/vehicle-kind.db.service.ts b/src/lookups/entities/db-service/vehicle-kind.db.service.ts index 877b839..4c6fd13 100644 --- a/src/lookups/entities/db-service/vehicle-kind.db.service.ts +++ b/src/lookups/entities/db-service/vehicle-kind.db.service.ts @@ -114,22 +114,35 @@ export class VehicleKindDbService { async searchActiveByCaption( q: string, limit: number, + filters?: { vehicleGroupId?: number; vehicleSystemId?: number }, ): Promise { const needle = normalizeVehicleKindCaptionSearch(q); if (!needle) return []; const escaped = needle.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + const query: FilterQuery = { + IsActive: 1, + captionSearch: { $regex: escaped }, + }; + if (filters?.vehicleGroupId != null) { + query.VehicleGroupId = filters.vehicleGroupId; + } + if (filters?.vehicleSystemId != null) { + query.VehicleSystemId = filters.vehicleSystemId; + } + return this.model - .find( - { - IsActive: 1, - captionSearch: { $regex: escaped }, - }, - PUBLIC_FIELDS, - ) + .find(query, PUBLIC_FIELDS) .sort({ Caption: 1 }) .limit(limit) .lean() .exec() as Promise; } + + async findActiveById(id: number): Promise { + return this.model + .findOne({ Id: id, IsActive: 1 }, PUBLIC_FIELDS) + .lean() + .exec() as Promise; + } } diff --git a/src/lookups/lookups.controller.ts b/src/lookups/lookups.controller.ts index aca554d..3097c03 100644 --- a/src/lookups/lookups.controller.ts +++ b/src/lookups/lookups.controller.ts @@ -314,6 +314,16 @@ export class LookupsController { description: "Max rows (1–100, default 50)", example: 50, }) + @ApiQuery({ + name: "vehicleGroupId", + required: false, + description: "Only return kinds belonging to this Fanavaran vehicle group", + }) + @ApiQuery({ + name: "vehicleSystemId", + required: false, + description: "Only return kinds belonging to this Fanavaran vehicle system", + }) @ApiOkResponse({ description: "Matched active vehicle kinds with echoed query", schema: { @@ -338,10 +348,20 @@ export class LookupsController { async getVehicleList( @Query("q") q?: string, @Query("limit") limit?: string, + @Query("vehicleGroupId") vehicleGroupId?: string, + @Query("vehicleSystemId") vehicleSystemId?: string, ) { return await this.lookupsService.searchVehicleKindsList({ q, limit: limit != null && limit !== "" ? Number(limit) : undefined, + vehicleGroupId: + vehicleGroupId != null && vehicleGroupId !== "" + ? Number(vehicleGroupId) + : undefined, + vehicleSystemId: + vehicleSystemId != null && vehicleSystemId !== "" + ? Number(vehicleSystemId) + : undefined, }); } diff --git a/src/lookups/lookups.service.ts b/src/lookups/lookups.service.ts index 29a49d1..3fb828c 100644 --- a/src/lookups/lookups.service.ts +++ b/src/lookups/lookups.service.ts @@ -232,6 +232,8 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy { async searchVehicleKindsList(input: { q?: string | null; limit?: number | null; + vehicleGroupId?: number | null; + vehicleSystemId?: number | null; }): Promise<{ q: string; count: number; @@ -252,6 +254,14 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy { const items = await this.vehicleKindDbService.searchActiveByCaption( q, limit, + { + ...(input.vehicleGroupId != null + ? { vehicleGroupId: Number(input.vehicleGroupId) } + : {}), + ...(input.vehicleSystemId != null + ? { vehicleSystemId: Number(input.vehicleSystemId) } + : {}), + }, ); return { q, @@ -260,6 +270,11 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy { }; } + async getActiveVehicleKindById(id: number) { + await this.ensureVehicleKindsSynced(false); + return this.vehicleKindDbService.findActiveById(id); + } + /** * Ensure `vehicle-kinds` Mongo collection is populated and not older than 1 week. * Concurrent callers share one in-flight sync. diff --git a/src/lookups/lookups.service.vehicle-list.spec.ts b/src/lookups/lookups.service.vehicle-list.spec.ts index 3cf36f7..5591e9a 100644 --- a/src/lookups/lookups.service.vehicle-list.spec.ts +++ b/src/lookups/lookups.service.vehicle-list.spec.ts @@ -31,7 +31,7 @@ describe("LookupsService.searchVehicleKindsList", () => { }, ], }); - expect(searchActiveByCaption).toHaveBeenCalledWith("ول", 20); + expect(searchActiveByCaption).toHaveBeenCalledWith("ول", 20, {}); }); it("returns empty items for blank q without searching", async () => {