add 4 new fields for expert approval

This commit is contained in:
SepehrYahyaee
2026-09-29 15:34:11 +03:30
parent b7a64596dd
commit 05e3e6a4d3
15 changed files with 1271 additions and 74 deletions
+27 -2
View File
@@ -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. " +
@@ -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;
}
+2
View File
@@ -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],
+280 -53
View File
@@ -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<string, unknown> | undefined;
if (objection) {
const invoices = objection.invoices as Array<Record<string, unknown>> | undefined;
const invoices = objection.invoices as
| Array<Record<string, unknown>>
| 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<string, unknown> = {
@@ -4097,7 +4114,10 @@ export class ExpertClaimService {
)
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [
{ 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<string, any>(
@@ -4447,7 +4474,10 @@ export class ExpertClaimService {
const claimOr: Record<string, unknown>[] = [
// 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<string, any>(
@@ -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<Record<string, any>> {
if (Array.isArray(value)) return value as Array<Record<string, any>>;
if (value && typeof value === "object") {
const data = (value as { data?: unknown }).data;
if (Array.isArray(data)) return data as Array<Record<string, any>>;
if (data && typeof data === "object") {
const nested = (data as { data?: unknown }).data;
if (Array.isArray(nested)) return nested as Array<Record<string, any>>;
}
}
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<Record<string, any>>) =>
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<string, any>) => ({
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<string, any>),
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,
@@ -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)",
@@ -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();
});
});
@@ -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);
});
});
@@ -0,0 +1,453 @@
import { normalizeVehicleKindCaptionSearch } from "src/lookups/vehicle-kind-search";
export type InquiryRecord = {
label: string;
raw?: unknown;
mapped?: unknown;
};
export type InquirySignal<T> = {
value: T;
source: string;
};
export type FanavaranVehicleInquirySignals = {
vehicleKindId?: InquirySignal<number>;
vehicleUseTypeId?: InquirySignal<number>;
vehicleGroupCaptions: InquirySignal<string>[];
vehicleUseTypeCaptions: InquirySignal<string>[];
vehicleSystemCaptions: InquirySignal<string>[];
vehicleKindCaptions: InquirySignal<string>[];
legacyCodes: {
usage?: InquirySignal<string>;
vehicleSystem?: InquirySignal<string>;
vehicleGroup?: InquirySignal<string>;
};
};
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<string, unknown>)[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 = <T>(
records: InquiryRecord[],
locations: Array<{ side: "raw" | "mapped"; path: string }>,
parse: (value: unknown) => T | undefined,
): InquirySignal<T> | 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<string>[] => {
const values: InquirySignal<string>[] = [];
const seen = new Set<string>();
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<T extends Record<string, any>>(
rows: T[],
signals: InquirySignal<string>[],
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<Record<string, any>>;
useTypes: Array<Record<string, any>>;
systems: Array<Record<string, any>>;
getVehicleKindById: (
id: number,
) => Promise<Record<string, any> | null | undefined>;
searchVehicleKinds: (input: {
q: string;
limit: number;
vehicleGroupId?: number;
vehicleSystemId?: number;
}) => Promise<{ items: Array<Record<string, any>> }>;
};
export async function buildFanavaranVehicleSuggestion({
records,
groups,
useTypes,
systems,
getVehicleKindById,
searchVehicleKinds,
}: SuggestionBuilderInput) {
const signals = extractFanavaranVehicleInquirySignals(records);
const warnings: string[] = [];
const sources: Record<string, string> = {};
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<string, any> | 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<string, any>; 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,
};
}