From 475780f17e8d12ac01827f07bc0ccb6090fb71e7 Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Tue, 24 Nov 2026 11:23:08 +0330 Subject: [PATCH] feat(claims): require optional expert signatures and enrich PDF reports --- .env.example | 3 + README.md | 6 + .../case-expert-report.builder.spec.ts | 16 +- .../case-expert-report.builder.ts | 27 +++- .../case-expert-report.module.ts | 8 +- .../case-expert-report.service.ts | 29 +++- .../case-expert-report.types.ts | 4 + src/case-expert-report/report-media.ts | 132 ++++++++++++++++ .../claim-request-management.module.ts | 1 + .../claim-request-management.service.ts | 146 +++++++++++++++++- .../db-service/claim-case.db.service.ts | 4 + .../db-service/factor-image.db.service.ts | 6 +- .../entites/schema/claim-cases.schema.ts | 4 + .../fanavaran-price-drop-age.spec.ts | 4 +- src/core/config/config.schema.ts | 4 + src/expert-claim/claim-price-drop-v2.spec.ts | 12 +- src/expert-claim/expert-claim.service.ts | 23 +++ src/expert-insurer/expert-insurer.service.ts | 18 ++- .../fanavaran-expert-signature.spec.ts | 144 +++++++++++++++++ src/fanavaran/fanavaran-expert-signature.ts | 106 +++++++++++++ src/fanavaran/fanavaran.controller.ts | 33 ++++ src/fanavaran/fanavaran.module.ts | 2 + .../db-service/blame-document.db.service.ts | 6 +- test/contracts/api-routes.json | 18 +++ 24 files changed, 722 insertions(+), 34 deletions(-) create mode 100644 src/case-expert-report/report-media.ts create mode 100644 src/fanavaran/fanavaran-expert-signature.spec.ts create mode 100644 src/fanavaran/fanavaran-expert-signature.ts diff --git a/.env.example b/.env.example index ffddbbc..38ab8d9 100644 --- a/.env.example +++ b/.env.example @@ -130,3 +130,6 @@ MIC_SMS_TOKEN_TTL=86399 # Total normal send attempts; a single 401 refresh/resend is additional. MIC_SMS_ATTEMPTS=2 MIC_SMS_TIMEOUT_MS=15000 + +# Require the submitting expert to sign before final Fanavaran submission. +FANAVARAN_REQUIRE_EXPERT_SIGNATURE=false diff --git a/README.md b/README.md index 9077486..5a20a3a 100644 --- a/README.md +++ b/README.md @@ -12,3 +12,9 @@ Insurer setup and staff/branch management: [guide](docs/insurer-staff-management ### Moalem SMS For MIC SMS environment settings, shared token-cache indexes and a test-send command, see [Moalem SMS adapter](docs/MIC/moalem-sms.md). + +### Expert signature before final Fanavaran submission + +Set `FANAVARAN_REQUIRE_EXPERT_SIGNATURE=true` in the API service environment and restart the API for the deployment that requires it. The expert app reads the setting from the API. The default is `false`. + +With the setting enabled, the submitting expert signs the saved assessment in the Fanavaran tab, then clicks final submission. Changes to the signed assessment require a fresh signature. Automatic final expertise submission waits for this action, and manual final submissions use the saved fields without JSON overrides. Initial Fanavaran stages can still run at their usual points. The insurer PDF includes available party and expert signatures. diff --git a/src/case-expert-report/case-expert-report.builder.spec.ts b/src/case-expert-report/case-expert-report.builder.spec.ts index 6cc912e..0f09e0d 100644 --- a/src/case-expert-report/case-expert-report.builder.spec.ts +++ b/src/case-expert-report/case-expert-report.builder.spec.ts @@ -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) => [ diff --git a/src/case-expert-report/case-expert-report.builder.ts b/src/case-expert-report/case-expert-report.builder.ts index 9b32e9d..0f64806 100644 --- a/src/case-expert-report/case-expert-report.builder.ts +++ b/src/case-expert-report/case-expert-report.builder.ts @@ -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 | null, ): InsurerFileReportSection | undefined { if (!claim) return undefined; + const refs = (claim.fanavaran ?? {}) as Record; const sync = (claim.fanavaranSync as Record | 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 | 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), ]); diff --git a/src/case-expert-report/case-expert-report.module.ts b/src/case-expert-report/case-expert-report.module.ts index 85ec3a2..3e220d7 100644 --- a/src/case-expert-report/case-expert-report.module.ts +++ b/src/case-expert-report/case-expert-report.module.ts @@ -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], diff --git a/src/case-expert-report/case-expert-report.service.ts b/src/case-expert-report/case-expert-report.service.ts index b278bc1..2ab1700 100644 --- a/src/case-expert-report/case-expert-report.service.ts +++ b/src/case-expert-report/case-expert-report.service.ts @@ -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), + }; } } diff --git a/src/case-expert-report/case-expert-report.types.ts b/src/case-expert-report/case-expert-report.types.ts index e292564..0c1aeec 100644 --- a/src/case-expert-report/case-expert-report.types.ts +++ b/src/case-expert-report/case-expert-report.types.ts @@ -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[]; }; diff --git a/src/case-expert-report/report-media.ts b/src/case-expert-report/report-media.ts new file mode 100644 index 0000000..22c2819 --- /dev/null +++ b/src/case-expert-report/report-media.ts @@ -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 = { + 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 = { + front: "نمای جلو", + back: "نمای عقب", + left: "نمای چپ", + right: "نمای راست", +}; + +export function buildReportAttachments( + claim: any, + blame: any, + blameDocuments: { path: string; documentType: string }[], + invoices: { path: string }[], +): ReportAttachment[] { + const attachments = new Map(); + 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; +} diff --git a/src/claim-request-management/claim-request-management.module.ts b/src/claim-request-management/claim-request-management.module.ts index 7bae105..f86192a 100644 --- a/src/claim-request-management/claim-request-management.module.ts +++ b/src/claim-request-management/claim-request-management.module.ts @@ -118,6 +118,7 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz VideoCaptureDbService, ClaimRequiredDocumentDbService, ClaimSignDbService, + ClaimFactorsImageDbService, ], }) export class ClaimRequestManagementModule {} diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index f164905..88d0b47 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -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, + actor?: { sub: string; role?: string }, ): Promise { 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, auditSource: FanavaranAuditSource, preservePayload = false, + signingActor?: { sub: string; role?: string }, + signedRevision?: string, ): Promise { 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, diff --git a/src/claim-request-management/entites/db-service/claim-case.db.service.ts b/src/claim-request-management/entites/db-service/claim-case.db.service.ts index d55f80a..2fed47f 100644 --- a/src/claim-request-management/entites/db-service/claim-case.db.service.ts +++ b/src/claim-request-management/entites/db-service/claim-case.db.service.ts @@ -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, ): Promise { diff --git a/src/claim-request-management/entites/db-service/factor-image.db.service.ts b/src/claim-request-management/entites/db-service/factor-image.db.service.ts index 5348448..e52fda8 100644 --- a/src/claim-request-management/entites/db-service/factor-image.db.service.ts +++ b/src/claim-request-management/entites/db-service/factor-image.db.service.ts @@ -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 { + return this.model.find({ claimId: new Types.ObjectId(id) }).lean(); + } + async findById(id: string): Promise { return this.model.findById(id).lean(); } diff --git a/src/claim-request-management/entites/schema/claim-cases.schema.ts b/src/claim-request-management/entites/schema/claim-cases.schema.ts index 3f68aab..47707a5 100644 --- a/src/claim-request-management/entites/schema/claim-cases.schema.ts +++ b/src/claim-request-management/entites/schema/claim-cases.schema.ts @@ -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; diff --git a/src/claim-request-management/fanavaran-price-drop-age.spec.ts b/src/claim-request-management/fanavaran-price-drop-age.spec.ts index 23f1e08..76e43a8 100644 --- a/src/claim-request-management/fanavaran-price-drop-age.spec.ts +++ b/src/claim-request-management/fanavaran-price-drop-age.spec.ts @@ -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. }, ); diff --git a/src/core/config/config.schema.ts b/src/core/config/config.schema.ts index 3427827..68cd4be 100644 --- a/src/core/config/config.schema.ts +++ b/src/core/config/config.schema.ts @@ -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", }) diff --git a/src/expert-claim/claim-price-drop-v2.spec.ts b/src/expert-claim/claim-price-drop-v2.spec.ts index bfd4385..a1cd078 100644 --- a/src/expert-claim/claim-price-drop-v2.spec.ts +++ b/src/expert-claim/claim-price-drop-v2.spec.ts @@ -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: [] }; diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index a5b3007..535373b 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -3976,6 +3976,9 @@ export class ExpertClaimService { let evaluationForApi: Record | 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> { if (Array.isArray(value)) return value as Array>; 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 | undefined; + this.assertPriceDropProduct(blame?.type); suggestedCarModelYear = resolveVehicleModelYearFromBlame( claim, blame as Parameters[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, diff --git a/src/expert-insurer/expert-insurer.service.ts b/src/expert-insurer/expert-insurer.service.ts index 88f5910..55820f6 100644 --- a/src/expert-insurer/expert-insurer.service.ts +++ b/src/expert-insurer/expert-insurer.service.ts @@ -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 } : {}), }; } diff --git a/src/fanavaran/fanavaran-expert-signature.spec.ts b/src/fanavaran/fanavaran-expert-signature.spec.ts new file mode 100644 index 0000000..88670ab --- /dev/null +++ b/src/fanavaran/fanavaran-expert-signature.spec.ts @@ -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(); + }); +}); diff --git a/src/fanavaran/fanavaran-expert-signature.ts b/src/fanavaran/fanavaran-expert-signature.ts new file mode 100644 index 0000000..01461ce --- /dev/null +++ b/src/fanavaran/fanavaran-expert-signature.ts @@ -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; +} diff --git a/src/fanavaran/fanavaran.controller.ts b/src/fanavaran/fanavaran.controller.ts index ae8b1a6..3b29b8a 100644 --- a/src/fanavaran/fanavaran.controller.ts +++ b/src/fanavaran/fanavaran.controller.ts @@ -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, ) { 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, ); } diff --git a/src/fanavaran/fanavaran.module.ts b/src/fanavaran/fanavaran.module.ts index 7b99955..871520d 100644 --- a/src/fanavaran/fanavaran.module.ts +++ b/src/fanavaran/fanavaran.module.ts @@ -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({ diff --git a/src/request-management/entities/db-service/blame-document.db.service.ts b/src/request-management/entities/db-service/blame-document.db.service.ts index 16a6315..8a1f665 100644 --- a/src/request-management/entities/db-service/blame-document.db.service.ts +++ b/src/request-management/entities/db-service/blame-document.db.service.ts @@ -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 { + return this.blameDocumentModel.find({ requestId: new Types.ObjectId(id) }).lean(); + } + async findById(id: string): Promise { return this.blameDocumentModel.findById(id).lean(); } diff --git a/test/contracts/api-routes.json b/test/contracts/api-routes.json index 18865c3..096d642 100644 --- a/test/contracts/api-routes.json +++ b/test/contracts/api-routes.json @@ -1645,6 +1645,15 @@ ], "roles": [] }, + { + "controller": "FanavaranController", + "method": "GET", + "path": "/v2/fanavaran/claim-cases/:claimCaseId/expert-signature", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, { "controller": "FanavaranController", "method": "GET", @@ -2305,6 +2314,15 @@ "file_reviewer" ] }, + { + "controller": "FanavaranController", + "method": "PATCH", + "path": "/v2/fanavaran/claim-cases/:claimCaseId/expert-signature", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, { "controller": "RegistrarClaimMirrorController", "method": "PATCH",