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
@@ -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.
},
);