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
+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,