feat(claims): require optional expert signatures and enrich PDF reports

This commit is contained in:
SepehrYahyaee
2026-11-24 11:23:08 +03:30
parent 297664a9a6
commit 475780f17e
24 changed files with 722 additions and 34 deletions
@@ -570,20 +570,8 @@ describe("buildInsurerFileReport", () => {
);
expect(driver).toContain("گواهینامه دارد: بله");
expect(driver).toContain("نوع گواهینامه: پایه دو");
expect(
getFieldValue(
report,
PR.damagedVehicleSection,
"خودرو / سوابق تلاش استعلام / تلاش ۱ / نوع پلاک استعلام‌شده",
),
).toBe("پلاک فعلی");
expect(
getFieldValue(
report,
PR.damagedVehicleSection,
"خودرو / سوابق تلاش استعلام / تلاش ۱ / خطا",
),
).toBe("موردی یافت نشد");
expect(report.sections.flatMap(section => section.fields)
.some(field => field.label.includes("سوابق تلاش استعلام"))).toBe(false);
const renderedText = report.sections
.flatMap((section) => [
@@ -25,6 +25,7 @@ const SKIP_FLATTEN_KEYS = new Set([
"history",
"workflow",
"evidence",
"attempts",
"confirmation",
"inquiries",
"raw",
@@ -821,6 +822,7 @@ function buildFanavaranCodesSection(
claim?: Record<string, unknown> | null,
): InsurerFileReportSection | undefined {
if (!claim) return undefined;
const refs = (claim.fanavaran ?? {}) as Record<string, unknown>;
const sync =
(claim.fanavaranSync as Record<string, unknown> | undefined) ?? {};
const baseClaim =
@@ -833,31 +835,31 @@ function buildFanavaranCodesSection(
return buildSection(PR.fanavaranSection, [
{
label: PR.fanavaranClaimNo,
value: firstDefined(claim.claimNo, baseClaim.claimNo),
value: firstDefined(refs.claimNo, claim.claimNo, baseClaim.claimNo),
},
{
label: PR.fanavaranClaimId,
value: firstDefined(claim.claimId, baseClaim.claimId),
value: firstDefined(refs.claimId, claim.claimId, baseClaim.claimId),
},
{
label: PR.fanavaranDamageCaseId,
value: firstDefined(
claim.dmgCaseId,
refs.dmgCaseId, claim.dmgCaseId,
damageCase.dmgCaseId,
expertise.dmgCaseId,
),
},
{
label: PR.fanavaranExpertiseId,
value: firstDefined(claim.expertiseId, expertise.expertiseId),
value: firstDefined(refs.expertiseId, claim.expertiseId, expertise.expertiseId),
},
{
label: PR.fanavaranPolicyId,
value: firstDefined(baseClaim.policyId),
value: firstDefined(refs.policyId, baseClaim.policyId),
},
{
label: PR.fanavaranDriverId,
value: firstDefined(baseClaim.driverId),
value: firstDefined(refs.driverId, baseClaim.driverId),
},
{
label: PR.fanavaranVehicleKindId,
@@ -872,6 +874,7 @@ function buildFanavaranCodesSection(
function buildEvaluationSection(
claim?: Record<string, unknown> | null,
isCarBody = false,
): InsurerFileReportSection | undefined {
if (!claim) return undefined;
const reply = resolveEvaluationReply(claim);
@@ -895,6 +898,14 @@ function buildEvaluationSection(
label: PR.evaluationSubmittedAt,
value: formatDateTime(resolveEvaluationSubmittedAt(claim, reply)),
},
{
label: "ارزش روز خودرو",
value: formatRial((claim.vehicle as ReportRecord | undefined)?.carPrice ?? (claim.vehicle as ReportRecord | undefined)?.price),
},
{
label: "افت قیمت",
value: isCarBody ? undefined : formatRial((claim.evaluation as any)?.priceDrop?.total),
},
{
label: PR.evaluationResponse,
value: asString(reply?.description),
@@ -1106,7 +1117,7 @@ export function buildInsurerFileReport(file: {
? (resolveClaimOwnerParty(blameContext as any) as ReportParty | null)
: null;
const isCarBody =
String((blameContext?.type as string | undefined) ?? "") === "CAR_BODY";
(blameContext?.type ?? overview.type ?? claim?.blameRequestType) === "CAR_BODY";
const includeGuiltySections =
!!guiltyParty && !(isCarBody && sameParty(damagedParty, guiltyParty));
@@ -1170,7 +1181,7 @@ export function buildInsurerFileReport(file: {
)
: undefined,
buildFanavaranCodesSection(claim),
buildEvaluationSection(claim),
buildEvaluationSection(claim, isCarBody),
buildEvaluationPartsSection(claim),
buildAccidentReportSection(blameContext, claim, damagedParty),
]);
@@ -1,10 +1,16 @@
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
import { Module } from "@nestjs/common";
import { RequestManagementModule } from "src/request-management/request-management.module";
import { ExpertInsurerModule } from "src/expert-insurer/expert-insurer.module";
import { CaseExpertReportInsurerController } from "./case-expert-report.controller";
import { CaseExpertReportService } from "./case-expert-report.service";
@Module({
imports: [ExpertInsurerModule],
imports: [
ExpertInsurerModule,
RequestManagementModule,
ClaimRequestManagementModule,
],
controllers: [CaseExpertReportInsurerController],
providers: [CaseExpertReportService],
exports: [CaseExpertReportService],
@@ -1,5 +1,9 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.db.service";
import { Types } from "mongoose";
import { BlameDocumentDbService } from "src/request-management/entities/db-service/blame-document.db.service";
import { buildReportAttachments, buildReportSignatures } from "./report-media";
import { buildInsurerFileReport } from "./case-expert-report.builder";
import { InsurerFileReportViewModel } from "./case-expert-report.types";
@@ -7,6 +11,8 @@ import { InsurerFileReportViewModel } from "./case-expert-report.types";
export class CaseExpertReportService {
constructor(
private readonly expertInsurerService: ExpertInsurerService,
private readonly blameDocumentDbService: BlameDocumentDbService,
private readonly factorImageDbService: ClaimFactorsImageDbService,
) {}
async generateForInsurer(
@@ -21,7 +27,28 @@ export class CaseExpertReportService {
const file = await this.expertInsurerService.retrieveFileDetailsByPublicId(
clientKey,
publicId,
true,
);
return buildInsurerFileReport(file);
const blame = file.reportBlame ?? file.blame;
const blameId = String(blame?._id ?? "");
const claimId = String(file.claim?.claimRequestId ?? "");
const [blameDocuments, invoices] = await Promise.all([
Types.ObjectId.isValid(blameId)
? this.blameDocumentDbService.findByRequestId(blameId)
: [],
Types.ObjectId.isValid(claimId)
? this.factorImageDbService.findByClaimId(claimId)
: [],
]);
return {
...buildInsurerFileReport({ ...file, blame }),
attachments: buildReportAttachments(
file.claim,
blame,
blameDocuments,
invoices,
),
signatures: buildReportSignatures(blame, file.claim),
};
}
}
@@ -8,9 +8,13 @@ export type InsurerFileReportSection = {
fields: InsurerFileReportField[];
};
export type ReportAttachment = { label: string; url?: string; image?: string };
export type InsurerFileReportViewModel = {
title: string;
publicId: string;
requestNo?: string;
sections: InsurerFileReportSection[];
signatures?: ReportAttachment[];
attachments?: ReportAttachment[];
};
+132
View File
@@ -0,0 +1,132 @@
import { buildFileLink } from "src/helpers/urlCreator";
import { personDisplayName } from "src/helpers/person-display-name";
import type { ReportAttachment } from "./case-expert-report.types";
const documentLabels: Record<string, string> = {
accident_sketch: "کروکی",
car_green_card: "برگه سبز خودرو",
car_certificate: "سند خودرو",
national_card: "کارت ملی",
damaged_driving_license_front: "روی گواهینامه زیان‌دیده",
damaged_driving_license_back: "پشت گواهینامه زیان‌دیده",
damaged_chassis_number: "شماره شاسی",
damaged_engine_photo: "شماره موتور",
damaged_car_card_front: "روی کارت خودروی زیان‌دیده",
damaged_car_card_back: "پشت کارت خودروی زیان‌دیده",
damaged_metal_plate: "پلاک خودروی زیان‌دیده",
guilty_driving_license_front: "روی گواهینامه مقصر",
guilty_driving_license_back: "پشت گواهینامه مقصر",
guilty_car_card_front: "روی کارت خودروی مقصر",
guilty_car_card_back: "پشت کارت خودروی مقصر",
guilty_metal_plate: "پلاک خودروی مقصر",
guilty_damage_area: "آسیب خودروی مقصر",
drivingLicense: "گواهینامه",
nationalCertificate: "مدرک هویتی",
carCertificate: "سند خودرو",
carGreenCard: "برگه سبز خودرو",
};
const angleLabels: Record<string, string> = {
front: "نمای جلو",
back: "نمای عقب",
left: "نمای چپ",
right: "نمای راست",
};
export function buildReportAttachments(
claim: any,
blame: any,
blameDocuments: { path: string; documentType: string }[],
invoices: { path: string }[],
): ReportAttachment[] {
const attachments = new Map<string, ReportAttachment>();
function add(label: string, url: unknown) {
if (typeof url !== "string" || !/(?:^|\/)files\/[^?#]+/.test(url)) return;
const path =
url
.split(/[?#]/)[0]
.split(/(?:^|\/)files\//)
.at(-1) ?? "";
if (!attachments.has(path)) attachments.set(path, { label, url });
}
for (const [key, value] of Object.entries(claim?.carAngles ?? {})) {
const angle = value as { url?: string };
add(angleLabels[key] ?? "نمای خودرو", angle.url);
}
for (const part of claim?.damagedParts ?? []) {
const name =
typeof part.label_fa === "string" && /[\u0600-\u06ff]/.test(part.label_fa)
? part.label_fa
: "تصویر قطعه آسیب‌دیده";
add(name, part.url);
}
for (const [key, value] of Object.entries(claim?.requiredDocuments ?? {})) {
add(
documentLabels[key] ?? "مدرک خسارت",
(value as { fileUrl?: string }).fileUrl,
);
}
for (const party of blame?.parties ?? []) {
for (const image of party.evidence?.images ?? []) {
if (typeof image === "string" && /(?:^|\/)files\//.test(image)) {
add("تصویر حادثه", buildFileLink(image));
}
}
}
for (const document of blameDocuments) {
if (document.path)
add(
documentLabels[document.documentType] ?? "مدرک حادثه",
buildFileLink(document.path),
);
}
const evaluation = claim?.evaluation;
for (const invoice of invoices) {
if (invoice.path) add("فاکتور قطعه", buildFileLink(invoice.path));
}
for (const invoice of evaluation?.objection?.invoices ?? [])
add("فاکتور اعتراض", invoice.url);
return [...attachments.values()];
}
export function buildReportSignatures(
blame: any,
claim: any,
): ReportAttachment[] {
const parties: any[] = blame?.parties ?? claim?.snapshot?.parties ?? [];
const signatures: ReportAttachment[] = [];
for (const [index, party] of parties.entries()) {
const signature = party.confirmation?.signature;
const url =
signature?.link ||
(signature?.fileUrl ? buildFileLink(signature.fileUrl) : undefined);
if (!url) continue;
const isSecond = party.role ? party.role === "SECOND" : index === 1;
const role = isSecond ? "طرف دوم" : "طرف اول";
const name = personDisplayName(party.person);
signatures.push({
label: name ? `امضای ${role} · ${name}` : `امضای ${role}`,
url,
});
}
const ownerSign =
claim?.evaluation?.ownerInsurerApproval?.signLink ??
claim?.evaluation?.ownerPricedPartsApproval?.signLink;
if (ownerSign)
signatures.push({
label: "امضای زیان‌دیده برای تأیید خسارت",
url: ownerSign,
});
const expert = claim?.fanavaranExpertSignature;
if (expert?.image) {
signatures.push({
label:
expert.name && expert.name !== "کارشناس پرونده"
? `امضای کارشناس · ${expert.name}`
: "امضای کارشناس",
image: expert.image,
});
}
return signatures;
}
@@ -118,6 +118,7 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz
VideoCaptureDbService,
ClaimRequiredDocumentDbService,
ClaimSignDbService,
ClaimFactorsImageDbService,
],
})
export class ClaimRequestManagementModule {}
@@ -1,4 +1,13 @@
import {
assertFanavaranExpertSignature,
fanavaranSignatureRevision,
hasFanavaranExpertSignature,
readFanavaranSignatureImage,
requiresFanavaranExpertSignature,
} from 'src/fanavaran/fanavaran-expert-signature';
import { personDisplayName } from 'src/helpers/person-display-name';
import { resolveClaimPriceDropAge } from "src/helpers/claim-price-drop";
import { randomUUID } from "node:crypto";
import { unlink } from "node:fs/promises";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
@@ -2822,7 +2831,6 @@ export class ClaimRequestManagementService {
parts: any[];
claimExpertId: number;
submittedAt: Date;
priceDropTotal: number;
priceDropCarPrice: unknown;
warnings: string[];
/** Non-blocking notices (factory-bundle fallbacks). Never gates submission. */
@@ -2998,7 +3006,7 @@ export class ClaimRequestManagementService {
dmgAssessmentDate: this.convertToPersianDate(input.submittedAt),
inspectionTime: this.getTime24Hour(input.submittedAt),
wage, componentReplacementCost, wasteValue,
dropAmount: input.priceDropTotal || 0,
dropAmount: 0,
vehicleCurrentValue, vehicle, colorId, repairDuration,
dmgSections: hullSections,
});
@@ -6343,7 +6351,7 @@ export class ClaimRequestManagementService {
return this.buildCarBodyFanavaranExpertisePayload({
clientKey: input.clientKey, claimCase: input.claimCase,
blame: blameForExpertIds, profile, parts, claimExpertId,
submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice,
submittedAt, priceDropCarPrice: priceDrop?.carPrice,
warnings, infoWarnings, replyKey: active?.replyKey,
});
}
@@ -6545,24 +6553,96 @@ export class ClaimRequestManagementService {
});
}
async getFanavaranExpertSignatureStatus(
id: string,
actor: { sub: string; role?: string },
) {
const claim = await this.claimCaseDbService.findWithFanavaranSignature(id);
if (!claim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
return {
required: true,
signed: hasFanavaranExpertSignature(claim, actor),
revision: fanavaranSignatureRevision(claim),
submitted: claim.expertiseId != null,
};
}
async saveFanavaranExpertSignature(
id: string,
actor: { sub: string; role: string; fullName?: string },
body: { revision?: string; image?: string },
) {
const image = readFanavaranSignatureImage(body?.image);
const claim = await this.claimCaseDbService.findWithFanavaranSignature(id);
if (!claim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
if (claim.expertiseId != null) {
throw new ConflictException('ثبت نهایی پرونده در فناوران انجام شده است.');
}
const revision = fanavaranSignatureRevision(claim);
if (revision !== body?.revision) {
throw new ConflictException({
code: 'FANAVARAN_EXPERT_SIGNATURE_REQUIRED',
message: 'اطلاعات پرونده تغییر کرده است. پرونده را دوباره بررسی و امضا کنید.',
});
}
const updated = await this.claimCaseDbService.findOneAndUpdate(
{
_id: claim._id, expertiseId: null, updatedAt: (claim as any).updatedAt,
$or: [
{ 'fanavaranExpertSignature.submissionExpiresAt': null },
{ 'fanavaranExpertSignature.submissionExpiresAt': { $lte: new Date() } },
],
},
{
$set: {
fanavaranExpertSignature: {
image, revision,
actorId: String(actor.sub),
actorRole: actor.role,
name: personDisplayName(actor) || 'کارشناس پرونده',
signedAt: new Date(),
},
},
},
);
if (!updated) throw new ConflictException('پرونده تغییر کرده است. دوباره تلاش کنید.');
return { required: true, signed: true, revision, submitted: false };
}
async submitFanavaranExpertiseV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>,
actor?: { sub: string; role?: string },
): Promise<any> {
try {
const manualSubmission =
bodyOverride != null && Object.keys(bodyOverride).length > 0;
const signatureRequired = requiresFanavaranExpertSignature();
if (signatureRequired) {
if (manualSubmission) {
throw new BadRequestException('با فعال بودن امضای کارشناس، ارسال فقط با اطلاعات ذخیره‌شده پرونده انجام می‌شود.');
}
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(claimCaseId);
if (!signedClaim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
if (signedClaim.expertiseId != null) {
return signedClaim.fanavaranSync?.expertise?.response ?? { Id: signedClaim.expertiseId };
}
assertFanavaranExpertSignature(signedClaim, actor);
}
await this.completeFanavaranExpertisePrerequisites(
claimCaseId,
clientKey,
FanavaranAuditSource.SUBMIT,
);
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
const claimCase = signatureRequired
? await this.claimCaseDbService.findWithFanavaranSignature(claimCaseId)
: await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) throw new NotFoundException('Claim case not found');
if (claimCase.expertiseId != null) {
return claimCase.fanavaranSync?.expertise?.response ?? { Id: claimCase.expertiseId };
}
if (signatureRequired) assertFanavaranExpertSignature(claimCase, actor);
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
const built = await this.buildFanavaranExpertisePayload({
claimCase,
@@ -6573,17 +6653,22 @@ export class ClaimRequestManagementService {
built.payload,
bodyOverride,
);
if (product === 'car-body') payload.DropAmount = 0;
this.assertFanavaranExpertisePayloadReady(
payload,
manualSubmission ? [] : built.warnings,
{ ...hullExpertiseAssertFields(product) },
);
const signatureArgs: [typeof actor?, string?] = signatureRequired
? [actor, fanavaranSignatureRevision(claimCase)]
: [];
const result = await this.executeFanavaranExpertiseSubmit(
claimCaseId,
clientKey,
payload,
FanavaranAuditSource.SUBMIT,
manualSubmission,
...signatureArgs,
);
// Surface infoWarnings (e.g. factory-bundle fallbacks) on the success
// response so callers are informed, without ever blocking the submit.
@@ -6607,6 +6692,8 @@ export class ClaimRequestManagementService {
payload: Record<string, unknown>,
auditSource: FanavaranAuditSource,
preservePayload = false,
signingActor?: { sub: string; role?: string },
signedRevision?: string,
): Promise<any> {
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) throw new NotFoundException('Claim case not found');
@@ -6667,6 +6754,38 @@ export class ClaimRequestManagementService {
requestMeta: { claimId: claimCase.claimId },
});
let submissionId: string | undefined;
if (requiresFanavaranExpertSignature()) {
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(claimCaseId);
if (!signedClaim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
if (signedClaim.expertiseId != null) {
return signedClaim.fanavaranSync?.expertise?.response ?? { Id: signedClaim.expertiseId };
}
assertFanavaranExpertSignature(signedClaim, signingActor);
if (signedClaim.fanavaranExpertSignature?.revision !== signedRevision) {
throw new ConflictException({
code: 'FANAVARAN_EXPERT_SIGNATURE_REQUIRED',
message: 'اطلاعات پرونده تغییر کرده است. پرونده را دوباره بررسی کنید.',
});
}
submissionId = randomUUID();
const locked = await this.claimCaseDbService.findOneAndUpdate(
{
_id: signedClaim._id,
expertiseId: null,
updatedAt: (signedClaim as any).updatedAt,
$or: [
{ 'fanavaranExpertSignature.submissionExpiresAt': null },
{ 'fanavaranExpertSignature.submissionExpiresAt': { $lte: new Date() } },
],
},
{ $set: {
'fanavaranExpertSignature.submissionId': submissionId,
'fanavaranExpertSignature.submissionExpiresAt': new Date(Date.now() + 5 * 60_000),
} },
);
if (!locked) throw new ConflictException('پرونده در حال ارسال است یا تغییر کرده است. دوباره تلاش کنید.');
}
try {
const response = await this.postFanavaranJson(
url,
@@ -6728,6 +6847,16 @@ export class ClaimRequestManagementService {
durationMs: Date.now() - startedAt,
});
throw error;
} finally {
if (submissionId) {
await this.claimCaseDbService.findOneAndUpdate(
{ _id: claimCaseId, 'fanavaranExpertSignature.submissionId': submissionId },
{ $unset: {
'fanavaranExpertSignature.submissionId': '',
'fanavaranExpertSignature.submissionExpiresAt': '',
} },
).catch(() => this.logger.warn('Could not release Fanavaran expertise submission lock.'));
}
}
}
@@ -6758,6 +6887,15 @@ export class ClaimRequestManagementService {
};
}
if (requiresFanavaranExpertSignature()) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: 'در انتظار امضای کارشناس و ارسال نهایی به فناوران',
};
}
// Same ordered soft-ensure as manual expertise submit: base → damage → files.
await this.completeFanavaranExpertisePrerequisites(
claimCaseId,
@@ -20,6 +20,10 @@ export class ClaimCaseDbService {
return this.claimCaseModel.findById(id);
}
async findWithFanavaranSignature(id: string | Types.ObjectId) {
return this.claimCaseModel.findById(id).select("+fanavaranExpertSignature");
}
async findOne(
filter: FilterQuery<ClaimCase>,
): Promise<ClaimCaseDocument | null> {
@@ -1,6 +1,6 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Model, Types } from "mongoose";
import { ClaimFactorsImage } from "src/claim-request-management/entites/schema/factor-image.schema";
@Injectable()
@@ -13,6 +13,10 @@ export class ClaimFactorsImageDbService {
return await this.model.create(image);
}
async findByClaimId(id: string): Promise<ClaimFactorsImage[]> {
return this.model.find({ claimId: new Types.ObjectId(id) }).lean();
}
async findById(id: string): Promise<ClaimFactorsImage | null> {
return this.model.findById(id).lean();
}
@@ -33,6 +33,7 @@ import {
ClaimWorkflowSchema,
} from "./claim-case.workflow.schema";
import { UserClaimRating } from "./claim-request-management.schema";
import type { FanavaranExpertSignature } from "src/fanavaran/fanavaran-expert-signature";
import type { FanavaranFieldReview } from "../../fanavaran-stage-fields";
import {
CaseInquiries,
@@ -350,6 +351,9 @@ export class ClaimCase {
@Prop({ type: FanavaranSyncStateSchema, default: () => ({}) })
fanavaranSync?: FanavaranSyncState;
@Prop({ type: MongooseSchema.Types.Mixed, select: false })
fanavaranExpertSignature?: FanavaranExpertSignature;
/** Expert-approved Fanavaran vehicle classification used by outbound stages. */
@Prop({ type: FanavaranVehicleReviewSchema })
fanavaranVehicleReview?: FanavaranVehicleReview;
@@ -41,7 +41,7 @@ describe("Fanavaran depreciation age eligibility", () => {
.mockResolvedValue(product);
service.getFanavaranLookupRows = jest.fn().mockResolvedValue([]);
service.buildCarBodyFanavaranExpertisePayload = jest.fn(
async (input) => ({ payload: { DropAmount: input.priceDropTotal } }),
async (input) => ({ payload: { DropAmount: input.priceDropTotal ?? 0 } }),
);
const claimCase = {
_id: "claim",
@@ -59,7 +59,7 @@ describe("Fanavaran depreciation age eligibility", () => {
? "DropAmount"
: "DropAmountAdditionsDeductions"
],
).toBe(age > 10 ? 0 : 999);
).toBe(product === "car-body" || age > 10 ? 0 : 999);
expect(claimCase.evaluation.priceDrop.total).toBe(999); // Historical data is preserved.
},
);
+4
View File
@@ -20,6 +20,10 @@ export enum Environment {
}
export class EnvironmentVariables {
@IsOptional()
@IsBooleanString()
FANAVARAN_REQUIRE_EXPERT_SIGNATURE?: string;
@IsEnum(Environment, {
message: "NODE_ENV should be development or production",
})
+11 -1
View File
@@ -28,7 +28,8 @@ function setup() {
evaluation: {},
};
const blame: any = {
type: "CAR_BODY",
type: "THIRD_PARTY",
expert: { decision: { guiltyPartyId: "other-party" } },
parties: [
{
role: "FIRST",
@@ -36,6 +37,7 @@ function setup() {
vehicle: { inquiry: { mapped: { ModelField: "1402" } } },
statement: { accidentDate: "2026-11-23" },
},
{ role: "SECOND", person: { userId: "other-party" } },
],
};
const service = Object.create(ExpertClaimService.prototype) as any;
@@ -66,6 +68,14 @@ function setup() {
}
describe("Fanavaran depreciation review and persistence", () => {
it("does not provide depreciation options or save depreciation for car-body claims", async () => {
const { service, blame, body, id } = setup();
blame.type = "CAR_BODY";
await expect(service.getPriceDropContextV2(id, {})).rejects.toThrow("افت قیمت برای پرونده بیمه بدنه");
await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow("افت قیمت برای پرونده بیمه بدنه");
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("returns the Fanavaran catalog and age at accident without changing the saved assessment", async () => {
const { service, claim, id } = setup();
claim.evaluation.priceDrop = { total: 123, partLines: [] };
+23
View File
@@ -3976,6 +3976,9 @@ export class ExpertClaimService {
let evaluationForApi: Record<string, unknown> | undefined;
if (enrichedEvaluation) {
if (blameFileContext.blameRequestType === BlameRequestType.CAR_BODY) {
delete enrichedEvaluation.priceDrop;
}
evaluationForApi = {};
// damageExpertReply / damageExpertReplyFinal: include whenever present.
// Previously these were gated on isFactorValidationPending, which hid the
@@ -4072,6 +4075,18 @@ export class ExpertClaimService {
};
}
async assertCanSignFanavaranClaim(id: string, actor: any) {
if (!Types.ObjectId.isValid(id)) throw new BadRequestException("شناسه پرونده معتبر نیست.");
const roles = [
RoleEnum.DAMAGE_EXPERT, RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER, RoleEnum.REGISTRAR,
];
if (!actor?.sub || !roles.includes(actor.role)) {
throw new ForbiddenException("فقط کارشناس مجاز پرونده می‌تواند آن را امضا کند.");
}
await this.getClaimDetailV2(id, actor);
}
private asFanavaranLookupRows(value: unknown): Array<Record<string, any>> {
if (Array.isArray(value)) return value as Array<Record<string, any>>;
if (value && typeof value === "object") {
@@ -4488,6 +4503,12 @@ export class ExpertClaimService {
return { version: fields.review.version };
}
private assertPriceDropProduct(type: unknown) {
if (type === BlameRequestType.CAR_BODY) {
throw new BadRequestException("افت قیمت برای پرونده بیمه بدنه قابل ثبت نیست.");
}
}
/** V2 price-drop: claim locked by this expert during damage assessment. */
private async assertExpertCanEditClaimDuringReviewV2(
claim: any,
@@ -4539,6 +4560,7 @@ export class ExpertClaimService {
},
);
const blame = blameRows[0] as Record<string, unknown> | undefined;
this.assertPriceDropProduct(blame?.type);
suggestedCarModelYear = resolveVehicleModelYearFromBlame(
claim,
blame as Parameters<typeof resolveVehicleModelYearFromBlame>[1],
@@ -4618,6 +4640,7 @@ export class ExpertClaimService {
select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate",
},
);
this.assertPriceDropProduct(blameRows[0]?.type);
carModelYear ??=
resolveVehicleModelYearFromBlame(
claim,
+17 -1
View File
@@ -1,3 +1,4 @@
import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature";
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
import {
BadRequestException,
@@ -698,6 +699,9 @@ export class ExpertInsurerService {
const evaluationEnriched =
await this.enrichClaimEvaluationForInsurer(evaluation);
if (blameForContext?.type === BlameRequestType.CAR_BODY && evaluationEnriched) {
delete evaluationEnriched.priceDrop;
}
const vehicleSanitized = claim.vehicle
? this.sanitizeVehicleInquiry(claim.vehicle as any)
: undefined;
@@ -1842,7 +1846,7 @@ export class ExpertInsurerService {
};
}
async retrieveFileDetailsByPublicId(insurerId: string, publicId: string) {
async retrieveFileDetailsByPublicId(insurerId: string, publicId: string, includeReportMedia = false) {
if (!publicId?.trim()) {
throw new BadRequestException("publicId is required");
}
@@ -1917,10 +1921,22 @@ export class ExpertInsurerService {
? await this.buildInsurerClaimDetail(claimFull, blameForClaimContext)
: undefined;
const reportBlame = includeReportMedia
? blameDetails ?? (blameForClaimContext ? await this.buildInsurerBlameDetail(blameForClaimContext) : undefined)
: undefined;
if (includeReportMedia && claimDetails && claimFull?._id) {
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(String(claimFull._id));
const signature = signedClaim?.fanavaranExpertSignature;
if (signature && (signedClaim.expertiseId != null || signature.revision === fanavaranSignatureRevision(signedClaim))) {
claimDetails.fanavaranExpertSignature = { name: signature.name, image: signature.image };
}
}
return {
overview,
blame: blameDetails,
claim: claimDetails,
...(includeReportMedia ? { reportBlame } : {}),
};
}
@@ -0,0 +1,144 @@
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { fanavaranSignatureRevision } from "./fanavaran-expert-signature";
describe("Fanavaran expert signature gate", () => {
const actor = {
sub: "expert-1",
role: "damage_expert",
fullName: "کارشناس نمونه",
};
const image =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j3ZkAAAAASUVORK5CYII=";
let service: any;
let claim: any;
let old: string | undefined;
beforeEach(() => {
old = process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE;
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = "true";
claim = {
_id: "claim-1",
vehicle: { carName: "پژو" },
updatedAt: new Date(),
evaluation: {},
};
service = Object.create(ClaimRequestManagementService.prototype);
service.claimCaseDbService = {
findById: jest.fn(async () => claim),
findWithFanavaranSignature: jest.fn(async () => claim),
findOneAndUpdate: jest.fn(async (_query, update) => {
Object.assign(claim, update.$set);
return claim;
}),
};
service.completeFanavaranExpertisePrerequisites = jest.fn();
service.resolveFanavaranClaimProduct = jest.fn(async () => "third-party");
service.buildFanavaranExpertisePayload = jest.fn(async () => ({
payload: {},
warnings: [],
infoWarnings: [],
}));
service.assertFanavaranExpertisePayloadReady = jest.fn();
service.executeFanavaranExpertiseSubmit = jest.fn(async () => ({
Id: 123,
}));
});
afterEach(() => {
if (old === undefined)
delete process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE;
else process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = old;
});
it("requires a signature before running prerequisites and leaves automatic final submission pending", async () => {
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
undefined,
actor,
),
).rejects.toMatchObject({
response: { code: "FANAVARAN_EXPERT_SIGNATURE_REQUIRED" },
});
await expect(
service.autoSubmitFanavaranExpertiseOnExpertReply("claim-1"),
).resolves.toMatchObject({ skipped: true });
expect(
service.completeFanavaranExpertisePrerequisites,
).not.toHaveBeenCalled();
});
it("stores the authenticated signer's signature, rejects stale or mismatched signatures and accepts retry", async () => {
const revision = fanavaranSignatureRevision(claim);
await expect(
service.saveFanavaranExpertSignature("claim-1", actor, {
revision,
image: "invalid",
}),
).rejects.toMatchObject({ status: 400 });
await expect(
service.saveFanavaranExpertSignature("claim-1", actor, {
revision: "stale",
image,
}),
).rejects.toMatchObject({ status: 409 });
await expect(
service.saveFanavaranExpertSignature("claim-1", actor, {
revision,
image,
}),
).resolves.toMatchObject({ signed: true });
expect(claim.fanavaranExpertSignature).toMatchObject({
actorId: actor.sub,
actorRole: actor.role,
revision,
image,
});
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian", undefined, {
...actor,
sub: "other",
}),
).rejects.toMatchObject({ status: 409 });
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
{ ClaimExpertId: 12 },
actor,
),
).rejects.toMatchObject({ status: 400 });
expect(
service.completeFanavaranExpertisePrerequisites,
).not.toHaveBeenCalled();
claim.fanavaranSync = { baseClaim: { status: "success" } };
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
undefined,
actor,
),
).resolves.toEqual({ Id: 123 });
claim.evaluation.priceDrop = { total: 123 };
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
undefined,
actor,
),
).rejects.toMatchObject({ status: 409 });
});
it("retains unsigned submission when the deployment disables the feature", async () => {
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = "false";
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).resolves.toEqual({ Id: 123 });
expect(
service.claimCaseDbService.findWithFanavaranSignature,
).not.toHaveBeenCalled();
});
});
+106
View File
@@ -0,0 +1,106 @@
import { BadRequestException, ConflictException } from "@nestjs/common";
import { createHash } from "node:crypto";
export type FanavaranExpertSignature = {
actorId: string;
actorRole: string;
name: string;
signedAt: Date;
revision: string;
image: string;
};
export function requiresFanavaranExpertSignature(): boolean {
return ["true", "1"].includes(
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE?.trim().toLowerCase() ?? "",
);
}
export function fanavaranSignatureRevision(claim: any): string {
const row = claim.toObject?.({ flattenMaps: true }) ?? claim;
const {
status,
claimStatus,
evaluation,
vehicle,
damage,
owner,
money,
fanavaranVehicleReview,
fanavaranFieldReview,
snapshot,
requiredDocuments,
media,
} = row;
return createHash("sha256")
.update(
JSON.stringify({
status,
claimStatus,
evaluation,
vehicle,
damage,
owner,
money,
fanavaranVehicleReview,
fanavaranFieldReview,
snapshot,
requiredDocuments,
media,
}),
)
.digest("hex");
}
export function hasFanavaranExpertSignature(
claim: any,
actor?: { sub: string; role?: string },
): boolean {
const signature: FanavaranExpertSignature | undefined =
claim.fanavaranExpertSignature;
return (
!!actor &&
!!signature?.image &&
signature.actorId === String(actor.sub) &&
signature.actorRole === actor.role &&
signature.revision === fanavaranSignatureRevision(claim)
);
}
export function assertFanavaranExpertSignature(
claim: any,
actor?: { sub: string; role?: string },
): void {
if (!hasFanavaranExpertSignature(claim, actor)) {
throw new ConflictException({
code: "FANAVARAN_EXPERT_SIGNATURE_REQUIRED",
message: "ابتدا نسخه فعلی پرونده را امضا کنید و سپس به فناوران بفرستید.",
});
}
}
export function readFanavaranSignatureImage(value: unknown): string {
const invalid = () =>
new BadRequestException("تصویر امضا معتبر نیست. امضا را دوباره ثبت کنید.");
if (
typeof value !== "string" ||
value.length > 100_000 ||
!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(value)
)
throw invalid();
const png = Buffer.from(
value.slice("data:image/png;base64,".length),
"base64",
);
if (
png.length < 45 ||
png.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a" ||
png.toString("ascii", 12, 16) !== "IHDR" ||
png.subarray(-12).toString("hex") !== "0000000049454e44ae426082"
)
throw invalid();
const width = png.readUInt32BE(16);
const height = png.readUInt32BE(20);
if (!width || !height || width > 900 || height > 400) throw invalid();
return value;
}
+33
View File
@@ -3,6 +3,7 @@ import {
Body,
Controller,
Get,
Patch,
Param,
Post,
Query,
@@ -16,6 +17,9 @@ import {
ApiQuery,
ApiTags,
} from "@nestjs/swagger";
import { CurrentUser } from "src/decorators/user.decorator";
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
import { requiresFanavaranExpertSignature } from "./fanavaran-expert-signature";
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import {
@@ -34,6 +38,7 @@ import {
export class FanavaranController {
constructor(
private readonly claimRequestManagementService: ClaimRequestManagementService,
private readonly expertClaimService: ExpertClaimService,
) {}
@Get("clients")
@@ -279,6 +284,26 @@ export class FanavaranController {
);
}
@Get("claim-cases/:claimCaseId/expert-signature")
async expertSignatureStatus(@Param("claimCaseId") id: string, @CurrentUser() actor: any) {
if (!requiresFanavaranExpertSignature()) return { required: false, signed: false };
await this.expertClaimService.assertCanSignFanavaranClaim(id, actor);
return this.claimRequestManagementService.getFanavaranExpertSignatureStatus(id, actor);
}
@Patch("claim-cases/:claimCaseId/expert-signature")
async saveExpertSignature(
@Param("claimCaseId") id: string,
@CurrentUser() actor: any,
@Body() body: { revision?: string; image?: string },
) {
if (!requiresFanavaranExpertSignature()) {
throw new BadRequestException("ثبت امضای کارشناس در این سامانه فعال نیست.");
}
await this.expertClaimService.assertCanSignFanavaranClaim(id, actor);
return this.claimRequestManagementService.saveFanavaranExpertSignature(id, actor, body);
}
@Post(":client/claim-cases/:claimCaseId/expertise/submit")
@ApiOperation({
summary: "Submit Fanavaran expertise request",
@@ -303,13 +328,21 @@ export class FanavaranController {
async submitExpertise(
@Param("client") client: string,
@Param("claimCaseId") claimCaseId: string,
@CurrentUser() actor: any,
@Body() body?: Record<string, unknown>,
) {
const clientKey = this.parseClientParam(client);
if (requiresFanavaranExpertSignature()) {
if (clientKey !== resolveFanavaranClientKey()) {
throw new BadRequestException("شرکت بیمه با تنظیمات این سامانه مطابقت ندارد.");
}
await this.expertClaimService.assertCanSignFanavaranClaim(claimCaseId, actor);
}
return await this.claimRequestManagementService.submitFanavaranExpertiseV2(
claimCaseId,
clientKey,
body && Object.keys(body).length > 0 ? body : undefined,
actor,
);
}
+2
View File
@@ -3,6 +3,7 @@ import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
import { ExpertClaimModule } from "src/expert-claim/expert-claim.module";
import { FanavaranAuditModule } from "./fanavaran-audit.module";
import { FanavaranController } from "./fanavaran.controller";
import { FanavaranLookupModule } from "./fanavaran-lookup.module";
@@ -12,6 +13,7 @@ import { FanavaranHullReadController } from "./fanavaran-hull-read.controller";
@Module({
imports: [
ClaimRequestManagementModule,
ExpertClaimModule,
FanavaranAuditModule,
FanavaranLookupModule,
HttpModule.registerAsync({
@@ -1,6 +1,6 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Model, Types } from "mongoose";
import { BlameDocumentModel } from "../schema/blame-document.schema";
@Injectable()
@@ -17,6 +17,10 @@ export class BlameDocumentDbService {
return newDocument.save();
}
async findByRequestId(id: string): Promise<BlameDocumentModel[]> {
return this.blameDocumentModel.find({ requestId: new Types.ObjectId(id) }).lean();
}
async findById(id: string): Promise<BlameDocumentModel | null> {
return this.blameDocumentModel.findById(id).lean();
}