From 268258a23ce97bda585b488aa5fac04d5ba3b1dc Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Sun, 4 Oct 2026 12:01:45 +0330 Subject: [PATCH] Added extra fanavaran fields --- docs/fanavaran-stage-field-review.md | 41 ++ docs/fanavaran-vehicle-review.md | 2 + docs/fanavaran/car-body-stage-fields.md | 20 +- docs/fanavaran/third-party-stage-fields.md | 12 +- .../claim-request-management.service.ts | 110 +++- .../entites/schema/claim-cases.schema.ts | 5 + .../fanavaran-stage-fields.ts | 197 +++++++ .../dto/fanavaran-stage-fields.dto.ts | 97 ++++ .../dto/fanavaran-vehicle-review.dto.ts | 22 +- src/expert-claim/expert-claim.service.ts | 236 ++++++++- .../expert-claim.v2.controller.ts | 14 + .../fanavaran-stage-fields.spec.ts | 494 ++++++++++++++++++ .../fanavaran-vehicle-review.spec.ts | 4 +- 13 files changed, 1216 insertions(+), 38 deletions(-) create mode 100644 docs/fanavaran-stage-field-review.md create mode 100644 src/claim-request-management/fanavaran-stage-fields.ts create mode 100644 src/expert-claim/dto/fanavaran-stage-fields.dto.ts create mode 100644 src/expert-claim/fanavaran-stage-fields.spec.ts diff --git a/docs/fanavaran-stage-field-review.md b/docs/fanavaran-stage-field-review.md new file mode 100644 index 0000000..ecbce65 --- /dev/null +++ b/docs/fanavaran-stage-field-review.md @@ -0,0 +1,41 @@ +# Expert editing of Fanavaran stage fields + +The expert panel's existing Fanavaran review tab now includes accident and assessment fields, alongside the four vehicle classification fields. All supported expert-panel roles use the existing claim-detail authorization and tenant/assignment/branch checks. + +## Supported fields and lookups + +| Field | Case type | Sending stage | Input / lookup | +| --- | --- | --- | --- | +| AccidentLocationAddress | Both | Base claim | Non-empty address, up to 1,000 characters | +| AccidentCityId | Both | Base claim | `cities` | +| AccidentReportTypeId | Both | Base claim | `accident-report-type` | +| DmgHistoryStatus | Third-party | Damage case | `dmg-history-status` (`dmg-case-history-status` upstream) | +| InspectionPlaceId | Third-party | Expertise | `inspection-place` | +| AccidentTypeId | Car-body | Base claim | `vehicle-hull-accident-types` | +| CulpritTypeId | Car-body | Base claim | `vehicle-hull-accident-culprit-type`; never the third-party culprit codebook | +| AuthorityCulpritId | Car-body | Base claim | `detection-accident-culprits` | +| CustomerFaultPercent | Car-body | Base claim | Integer 0–100, including zero | +| RepairDuration | Car-body | Expertise | Positive integer days | +| VehicleCurrentValue | Car-body | Expertise | Positive integer **rials**, forwarded unchanged | + +All seven lookup definitions already existed. Options use the deployment's active Fanavaran client and its existing live/cache lookup service. Only active canonical `Id` values are accepted; captions are resolved server-side. Array and nested `data` lookup envelopes are supported. Missing/empty lookups are shown as unavailable and cannot be replaced with guessed IDs. + +`VehicleCurrentValue` can remain unset when no expert override exists, preserving the existing case-value/policy-value fallback. A stored override cannot be cleared with null or an empty string. This review does not change the application's other valuation fields or calculate price drop. + +## Sending and editing + +- The initial vehicle approval accepts the applicable stage fields in the same database update. Only after that update does the existing automatic base/damage submission resume. The new panel requires valid fields and explicit consent before initial approval. +- For already approved cases, experts save changes independently, before the relevant stage is sent. Saving fields does not itself perform a remote write. +- Base fields lock when the base claim exists; `DmgHistoryStatus` locks when the damage case exists; assessment fields lock when expertise exists. Stage IDs and successful sync states are checked in both validation and the conditional database update. +- Car-body still skips damage-case creation, sends only its base/expertise whitelist, and retains required null values. Third-party payloads retain their existing explicit null keys. +- No attempt is made to edit already sent base fields through the unreliable hull PUT route. + +## Endpoints and persistence + +- `GET /v2/expert-claim/request/:id/fanavaran-stage-fields`: applicable field definitions, current/default/submitted values, captions, compact lookup rows and per-field editability. This read does not submit a claim or persist a preview. +- `PATCH /v2/expert-claim/request/:id/fanavaran-stage-fields`: `{ values: { ...changedFields }, expectedVersion: 0, confirmed: true }`. Values must apply to the product and belong to an unsent stage. Stale versions or stages sent during validation return `409`. +- Existing `PUT .../fanavaran-vehicle-review` additionally accepts optional `stageFields` and `stageFieldsVersion` for the initial combined approval. Older clients retain their existing behavior. + +Validated overrides and captions are stored in optional `claimCases.fanavaranFieldReview`, with version, reviewer and review timestamp. History events record before/after values and verified captions. Existing claims keep their existing defaults/fallbacks until reviewed; no migration or bulk data rewrite is required. + +The review covers the eleven requested fields and the existing vehicle classification. It does not expose derived totals, provider identifiers, staff-role identifiers or every remaining field in the stage documents for arbitrary editing. diff --git a/docs/fanavaran-vehicle-review.md b/docs/fanavaran-vehicle-review.md index c75ba44..f3c30f3 100644 --- a/docs/fanavaran-vehicle-review.md +++ b/docs/fanavaran-vehicle-review.md @@ -36,6 +36,8 @@ The panel applies the suggestion once, displays its matched-field count and raw The approval endpoint re-resolves every caption server-side and rejects inactive values or a group/use/system/kind relationship mismatch. Client-supplied captions are never trusted. A successful approval resumes base-claim submission and, when selected damage parts already exist, the damage-case stage. +The same tab also supports [expert editing of accident and assessment fields](fanavaran-stage-field-review.md). Initial approval can save `stageFields` with `stageFieldsVersion` atomically alongside vehicle classification, before automatic submission resumes. Fields for subsequent unsent stages remain editable independently after the vehicle classification locks. + ## Outbound enforcement Base claim, damage case, attachments, and expertise writes enforce the persisted approval. Automatic stages are deferred with a skip reason; manual stages return `409` with code `FANAVARAN_VEHICLE_REVIEW_REQUIRED`. Read-only previews remain available for diagnosis. diff --git a/docs/fanavaran/car-body-stage-fields.md b/docs/fanavaran/car-body-stage-fields.md index 5b59293..891d9b2 100644 --- a/docs/fanavaran/car-body-stage-fields.md +++ b/docs/fanavaran/car-body-stage-fields.md @@ -2,6 +2,8 @@ Snapshot of **what hull submit actually sends** after `toFanavaranHullBaseClaimPayload` / `toFanavaranHullExpertisePayload`. +Experts can now review address, city, report type, accident/culprit/authority IDs, fault percentage, repair duration and vehicle value before their sending stage. See [expert field review](../fanavaran-stage-field-review.md); defaults below remain fallbacks for unreviewed records. + Staged flow (VHUD): 1. Base: `POST /car/vehicle-hull-claims` (GEN.03) @@ -35,15 +37,15 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload` | AccidentDate | تاریخ حادثه | string Jalali | **no** | **user** first-party `statement.accidentDate`, else createdAt | | AccidentTime | ساعت حادثه | string `HH:mm` | **no** | **user** `statement.accidentTime` if set | | AnnouncementDate | تاریخ اعلام | string Jalali | **no** | **derived** = AccidentDate | -| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **system** `"استان تهران شهر تهران"` | +| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **user** expert review, else **system** `"استان تهران شهر تهران"` | | AccidentCauseId | علت حادثه | number | **no** | **system** `6` · lookup `accident-causes` | -| AccidentCityId | شهر حادثه | number | **no** | **system** `701` · lookup `cities` | -| AccidentReportTypeId | نحوه اعلام | number | **no** | **system** `155` · lookup `accident-report-type` | -| AccidentTypeId | نوع حادثه بدنه | number | **no** | **system** `2` تصادف(حادثه) · **lookup** `GET /lookups/vehicle-hull-accident-types` | -| CulpritTypeId | نوع مقصر بدنه | number | **no** | **system** `300` (ثالث `337` remapped) · **lookup** `GET /lookups/vehicle-hull-accident-culprit-type` | -| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | **lookup** `GET /lookups/detection-accident-culprits` (caption بیمه‌گذار, fallback `1`) | +| AccidentCityId | شهر حادثه | number | **no** | **user** expert review, else **system** `701` · lookup `cities` | +| AccidentReportTypeId | نحوه اعلام | number | **no** | **user** expert review, else **system** `155` · lookup `accident-report-type` | +| AccidentTypeId | نوع حادثه بدنه | number | **no** | **user** expert review, else **system** `2` تصادف(حادثه) · **lookup** `GET /lookups/vehicle-hull-accident-types` | +| CulpritTypeId | نوع مقصر بدنه | number | **no** | **user** expert review, else **system** `300` (ثالث `337` remapped) · **lookup** `GET /lookups/vehicle-hull-accident-culprit-type` | +| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | **user** expert review, else **lookup** `GET /lookups/detection-accident-culprits` (caption بیمه‌گذار, fallback `1`) | | AccidentCulpritId | شناسه مقصر فناوران | number | preferred | **inquiry** parties `inquiry-by-unique-identifier`, fallback hull policy `CustomerId` | -| CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **system** `100` | +| CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` | | CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` | | IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` | | IsLicenseReplaced | گواهینامه تعویضی است؟ | number | **must be null** | never copy ثالث `IsLicenseReplacement` | @@ -119,8 +121,8 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro | Wage | اجرت کل | number | **no** | **user** sum `salary` | | ComponentReplacementCost | قطعه کل | number | **no** | **user** sum `price` | | WasteValue | داغی کل | number | **no** | **user** daghi | -| RepairDuration | مدت تعمیر (روز) | number | **no** | **system** `3` | -| VehicleCurrentValue | ارزش روز خودرو | number | preferred | **user** `vehicle.carPrice` / `vehicle.price`, else **inquiry** policy `VehicleValue` | +| RepairDuration | مدت تعمیر (روز) | number | **no** | **user** expert review, else **system** `3` | +| VehicleCurrentValue | ارزش روز خودرو | number | preferred | **user** expert field review (rials), else `vehicle.carPrice` / `vehicle.price`, else **inquiry** policy `VehicleValue` | | DropAmount | افت قیمت | number | **no** | **user** price-drop total or `0` | | CarryAndRescueCost | حمل و نجات | number | yes | null | | WreckHighestValue | بالاترین ارزش لاشه | number | yes | null | diff --git a/docs/fanavaran/third-party-stage-fields.md b/docs/fanavaran/third-party-stage-fields.md index 051b19e..87115e5 100644 --- a/docs/fanavaran/third-party-stage-fields.md +++ b/docs/fanavaran/third-party-stage-fields.md @@ -2,6 +2,8 @@ Snapshot of **what `ClaimRequestManagementService` actually sends** for `THIRD_PARTY` as of this version. +Experts can now override address, city, report type, damage history and inspection place before their sending stage. See [expert field review](../fanavaran-stage-field-review.md); defaults below remain fallbacks for unreviewed records. + - Base: `POST /car/third-party-car-financial-claims` (GEN.03) - Damage case: `POST …/{claimId}/dmg-cases` (GEN.12) - Attachments: `POST …/{claimId}/files` (GEN.07, multipart) @@ -38,10 +40,10 @@ Parsian tenant defaults used below: `ClaimExpertId=154`, `ExpertiseClaimExpertId | AnnouncementDate | تاریخ اعلام | string Jalali | **no** | **derived** = AccidentDate | | | DocReceivedDate | تاریخ وصول مدارک | string Jalali | **no** | **derived** = AccidentDate | Third-party only (not on hull whitelist) | | AccidentTime | ساعت حادثه | string `HH:mm` | **no** | **user** / **derived** from createdAt | | -| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **system** `"استان تهران شهر تهران"` | Should later be **user** | +| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **user** expert review, else **system** `"استان تهران شهر تهران"` | | | AccidentCauseId | علت حادثه | number | **no** | **system** `6` | Lookup: `GET /lookups/accident-causes`. Expert `accidentReason.fanavaran` exists but is not yet wired as the sent id | -| AccidentCityId | شهر محل حادثه | number | **no** | **system** `701` تهران | Lookup: `GET /lookups/cities` | -| AccidentReportTypeId | نحوه اعلام حادثه | number | **no** | **system** `155` | Lookup: `GET /lookups/accident-report-type` | +| AccidentCityId | شهر محل حادثه | number | **no** | **user** expert review, else **system** `701` تهران | Lookup: `GET /lookups/cities` | +| AccidentReportTypeId | نحوه اعلام حادثه | number | **no** | **user** expert review, else **system** `155` | Lookup: `GET /lookups/accident-report-type` | | AccidentVehicleUsedId | نوع کاربری خودرو | number | **no** | **inquiry** VIN / policy vehicle `UsedId`, else tenant `1` | Lookup: `GET /lookups/vehicle-use-types` | | CulpritTypeId | نوع مقصر | number | **no** | **system** `337` | Lookup: `GET /lookups/accident-culprit-type` (ثالث, not hull) | | CulpritLicenceTypeId | نوع گواهینامه مقصر | number | **no** | **system** `2` | Lookup: `GET /lookups/driving-licence-types` | @@ -127,7 +129,7 @@ If `DriverId` is missing, **submit** (not preview) registers GEN.44 `POST /commo | PreviousPolicyEndDate | پایان بیمه‌نامه قبلی | string | empty ok | **derived** from EndDate | | InsuranceCorpId | شرکت بیمه زیان‌دیده | number | **no** | **lookup** insurance-corp for tenant | | DmgCaseTypeId | نوع مورد خسارت | number | **no** | **system** `175` · lookup `dmg-case-type` | -| DmgHistoryStatus | وضعیت سابقه خسارت | number | **no** | **system** `5214` · lookup `dmg-history-status` | +| DmgHistoryStatus | وضعیت سابقه خسارت | number | **no** | **user** expert review, else **system** `5214` · lookup `dmg-history-status` | | FaultPercent | درصد تقصیر | number | **no** | **system** `100` | | DriverIsOwner | راننده همان مالک؟ | number | **no** | **user** `driverIsInsurer` → 1/0 | | LicenceNo | شماره گواهینامه زیان‌دیده | string | **no** | **user**, else dummy | @@ -169,7 +171,7 @@ Requires local `dmgCaseId`. `ClaimExpertId` here is the **assessor** role (Parsi | ClaimExpertId | کارشناس ارزیاب | number | **no** | **staff** / tenant `ExpertiseClaimExpertId` | | DmgAssessmentDate | تاریخ بازدید | string Jalali | **no** | **derived** expert reply `submittedAt` | | InspectionTime | ساعت بازدید | string `HH:mm` | **no** | **derived** | -| InspectionPlaceId | محل بازدید | number | **no** | **system** `282` · lookup `GET /lookups/inspection-place` | +| InspectionPlaceId | محل بازدید | number | **no** | **user** expert review, else **system** `282` · lookup `GET /lookups/inspection-place` | | RepairWage | اجرت کل | number | **no** | **user** sum of part `salary` | | ComponentReplacementCost | قطعه کل | number | **no** | **user** sum of part `price` | | WasteValue | داغی کل | number | **no** | **user** daghi prices | diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index ac3abd5..bdc7869 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -58,6 +58,11 @@ import { fanavaranHullNestedClaimId, toFanavaranHullBaseClaimPayload, } from "./fanavaran-hull-base-claim"; +import { + activeStageLookupRows, applyFanavaranStageFieldReview, + fanavaranFieldStageSent, fanavaranStageFields, + type FanavaranFieldValues, +} from "./fanavaran-stage-fields"; import { collectFanavaranExpertiseReadinessWarnings, hullExpertiseAssertFields, @@ -4395,7 +4400,8 @@ export class ClaimRequestManagementService { vehicleCurrentValue = vehicleCurrentValueFromHullPolicyRecord(policy); } - const repairDuration = FANAVARAN_DEFAULT_HULL_REPAIR_DURATION; + vehicleCurrentValue = input.claimCase?.fanavaranFieldReview?.values?.VehicleCurrentValue ?? vehicleCurrentValue; + const repairDuration = input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ?? FANAVARAN_DEFAULT_HULL_REPAIR_DURATION; return { replyKey: input.replyKey, @@ -4757,7 +4763,7 @@ export class ClaimRequestManagementService { "shsNam", ]) ?? (typeof apiVehicle?.ChassisNo === "string" ? apiVehicle.ChassisNo : null), - DmgHistoryStatus: input.defaults.DmgHistoryStatus, + DmgHistoryStatus: input.claimCase?.fanavaranFieldReview?.values?.DmgHistoryStatus ?? input.defaults.DmgHistoryStatus, Desc: this.formatFanavaranSelectedPartsDesc(input.selectedParts), DmgCaseTypeId: input.defaults.DmgCaseTypeId, DriverId: driverFanavaranId ?? null, @@ -6189,12 +6195,17 @@ export class ClaimRequestManagementService { logPrefix, claimCaseId, }); + applyFanavaranStageFieldReview(payload, claimCase, "car-body", "baseClaim"); delete payload.IsLicenseReplacement; const hull = toFanavaranHullBaseClaimPayload(payload); for (const key of Object.keys(payload)) delete payload[key]; Object.assign(payload, hull); } + if (fanavaranClaimProductFromBlameType(blameCase.type) === "third-party") { + applyFanavaranStageFieldReview(payload, claimCase, "third-party", "baseClaim"); + } + const fileRoleExpertIds = await this.resolveFanavaranFileRoleExpertIdsForBlame(blameCase); if (fileRoleExpertIds) { @@ -6983,6 +6994,93 @@ export class ClaimRequestManagementService { return definition; } + /** Read-only panel context. Does not create a remote claim or persist a preview. */ + async getFanavaranStageFieldsContext(claim: any, blame: any) { + if (!blame || !isFanavaranSubmitSupportedBlameType(blame.type)) { + throw new BadRequestException( + "Fanavaran field review only applies to third-party and car-body claims.", + ); + } + const product = fanavaranClaimProductFromBlameType(blame.type); + const clientKey = resolveFanavaranClientKey(); + const defaults = getFanavaranClientProfile(clientKey).defaults; + const definitions = fanavaranStageFields(product); + const options = new Map>(); + await Promise.all( + definitions + .filter((field) => field.lookup) + .map(async (field) => { + options.set( + field.lookup, + activeStageLookupRows( + await this.getFanavaranLookupRows(clientKey, field.lookup), + ), + ); + }), + ); + const initial: FanavaranFieldValues = { + AccidentLocationAddress: FANAVARAN_ACCIDENT_LOCATION_ADDRESS, + AccidentCityId: defaults.AccidentCityId, + AccidentReportTypeId: defaults.AccidentReportTypeId, + DmgHistoryStatus: defaults.DmgHistoryStatus, + InspectionPlaceId: 282, + AccidentTypeId: 2, + CulpritTypeId: 300, + AuthorityCulpritId: authorityCulpritIdFromDetectionRows( + options.get("detection-accident-culprits") ?? [], + ), + CustomerFaultPercent: FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, + RepairDuration: FANAVARAN_DEFAULT_HULL_REPAIR_DURATION, + }; + if (product === "car-body") { + const price = + this.parseFanavaranMoney(claim?.vehicle?.carPrice) || + this.parseFanavaranMoney(claim?.vehicle?.price) || + this.parseFanavaranMoney(claim?.evaluation?.priceDrop?.carPrice) || + (await this.resolveHullVehicleCurrentValueFromPolicy(clientKey, claim)); + if (price > 0) initial.VehicleCurrentValue = price; + } + return { + product, + version: claim.fanavaranFieldReview?.version ?? 0, + reviewedAt: claim.fanavaranFieldReview?.reviewedAt, + reviewedByActorName: claim.fanavaranFieldReview?.reviewedByActorName, + fields: definitions.map((field) => { + const sent = fanavaranFieldStageSent(claim, field.stage); + const sentValue = sent + ? claim.fanavaranSync?.[field.stage]?.lastPayload?.[field.key] + : undefined; + const reviewedValue = claim.fanavaranFieldReview?.values?.[field.key]; + const value = sentValue ?? reviewedValue ?? initial[field.key] ?? null; + const rows = field.lookup + ? (options.get(field.lookup) ?? []) + : undefined; + return { + ...field, + value, + source: + sentValue != null + ? "submitted" + : reviewedValue != null + ? "reviewed" + : "default", + editable: !sent, + ...(field.lookup + ? { + options: rows, + lookupUnavailable: !rows.length, + caption: + rows.find((row) => row.Id === value)?.Caption ?? + (reviewedValue === value + ? claim.fanavaranFieldReview?.captions?.[field.key] + : undefined), + } + : {}), + }; + }), + }; + } + private async getFanavaranLookupRows( clientKey: FanavaranClientKey, name: string, @@ -6994,7 +7092,11 @@ export class ClaimRequestManagementService { definition.url, definition.cacheFile, ); - return Array.isArray(data) ? data : []; + let rows: unknown = data; + for (let level = 0; level < 3 && rows && !Array.isArray(rows) && typeof rows === "object"; level++) { + rows = (rows as { data?: unknown }).data; + } + return Array.isArray(rows) ? rows : []; } catch { this.logger.warn( `Lookup "${name}" unavailable for ${clientKey}; returning empty.`, @@ -7239,7 +7341,7 @@ export class ClaimRequestManagementService { const priceDrop = input.claimCase.evaluation?.priceDrop ?? {}; const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total); - const inspectionPlaceId = 282; + const inspectionPlaceId = input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282; const dropAmountStatus = 5458; const dmgSections = parts.map((part) => 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 7e28a49..86c9e03 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 { FanavaranFieldReview } from "../../fanavaran-stage-fields"; import { CaseInquiries, CaseInquiriesSchema, @@ -342,6 +343,10 @@ export class ClaimCase { @Prop({ type: FanavaranVehicleReviewSchema }) fanavaranVehicleReview?: FanavaranVehicleReview; + /** Validated expert edits; separate stages lock after their remote creation. */ + @Prop({ type: MongooseSchema.Types.Mixed }) + fanavaranFieldReview?: FanavaranFieldReview; + @Prop({ type: ClaimDamageSelectionSchema, default: () => ({}) }) damage?: ClaimDamageSelection; diff --git a/src/claim-request-management/fanavaran-stage-fields.ts b/src/claim-request-management/fanavaran-stage-fields.ts new file mode 100644 index 0000000..fb6f40e --- /dev/null +++ b/src/claim-request-management/fanavaran-stage-fields.ts @@ -0,0 +1,197 @@ +import type { FanavaranClaimProduct } from "./fanavaran-claim-product"; + +export type FanavaranFieldStage = "baseClaim" | "damageCase" | "expertise"; +export type FanavaranFieldValues = Partial< + Record +>; +export type FanavaranFieldKey = + | "AccidentLocationAddress" + | "AccidentCityId" + | "AccidentReportTypeId" + | "DmgHistoryStatus" + | "InspectionPlaceId" + | "AccidentTypeId" + | "CulpritTypeId" + | "AuthorityCulpritId" + | "CustomerFaultPercent" + | "RepairDuration" + | "VehicleCurrentValue"; + +export interface FanavaranFieldReview { + values: FanavaranFieldValues; + captions: Partial>; + version: number; + reviewedAt: Date; + reviewedByActorId: string; + reviewedByActorName?: string; + reviewedByRole: string; +} + +export interface FanavaranStageFieldDefinition { + key: FanavaranFieldKey; + label: string; + stage: FanavaranFieldStage; + type: "text" | "lookup" | "number"; + lookup?: string; + min?: number; + max?: number; + unit?: string; + optional?: boolean; +} + +const common: FanavaranStageFieldDefinition[] = [ + { + key: "AccidentLocationAddress", + label: "نشانی محل حادثه", + stage: "baseClaim", + type: "text", + }, + { + key: "AccidentCityId", + label: "شهر محل حادثه", + stage: "baseClaim", + type: "lookup", + lookup: "cities", + }, + { + key: "AccidentReportTypeId", + label: "نحوه اعلام حادثه", + stage: "baseClaim", + type: "lookup", + lookup: "accident-report-type", + }, +]; + +export function fanavaranStageFields( + product: FanavaranClaimProduct, +): FanavaranStageFieldDefinition[] { + return product === "car-body" + ? [ + ...common, + { + key: "AccidentTypeId", + label: "نوع حادثه بدنه", + stage: "baseClaim", + type: "lookup", + lookup: "vehicle-hull-accident-types", + }, + { + key: "CulpritTypeId", + label: "نوع مقصر بدنه", + stage: "baseClaim", + type: "lookup", + lookup: "vehicle-hull-accident-culprit-type", + }, + { + key: "AuthorityCulpritId", + label: "مرجع تعیین مقصر", + stage: "baseClaim", + type: "lookup", + lookup: "detection-accident-culprits", + }, + { + key: "CustomerFaultPercent", + label: "درصد تقصیر بیمه‌گذار", + stage: "baseClaim", + type: "number", + min: 0, + max: 100, + unit: "درصد", + }, + { + key: "RepairDuration", + label: "مدت تعمیر", + stage: "expertise", + type: "number", + min: 1, + unit: "روز", + }, + { + key: "VehicleCurrentValue", + label: "ارزش روز خودرو", + stage: "expertise", + type: "number", + min: 1, + unit: "ریال", + optional: true, + }, + ] + : [ + ...common, + { + key: "DmgHistoryStatus", + label: "وضعیت سابقه خسارت", + stage: "damageCase", + type: "lookup", + lookup: "dmg-history-status", + }, + { + key: "InspectionPlaceId", + label: "محل بازدید", + stage: "expertise", + type: "lookup", + lookup: "inspection-place", + }, + ]; +} + +export function fanavaranFieldStageSent( + claim: any, + stage: FanavaranFieldStage, +): boolean { + const id = { + baseClaim: "claimId", + damageCase: "dmgCaseId", + expertise: "expertiseId", + }[stage]; + return ( + claim?.[id] != null || + claim?.fanavaranSync?.[stage]?.[id] != null || + claim?.fanavaranSync?.[stage]?.status === "success" || + (stage === "baseClaim" && claim?.claimNo != null) + ); +} + +/** Strict codebook IDs, never provider legacy codes or guessed captions. */ +export function activeStageLookupRows( + raw: unknown, +): Array<{ Id: number; Caption: string }> { + let value = raw; + for ( + let level = 0; + level < 3 && value && !Array.isArray(value) && typeof value === "object"; + level++ + ) { + value = (value as { data?: unknown }).data; + } + if (!Array.isArray(value)) return []; + return value + .filter( + (row) => + row && + typeof row === "object" && + row.IsActive !== false && + Number(row.IsActive) !== 0 && + Number.isSafeInteger(Number(row.Id)) && + Number(row.Id) > 0 && + typeof row.Caption === "string" && + row.Caption.trim(), + ) + .map((row) => ({ Id: Number(row.Id), Caption: row.Caption.trim() })) + .sort((a, b) => a.Caption.localeCompare(b.Caption, "fa")); +} + +/** Apply only applicable, reviewed fields at their own outbound stage. */ +export function applyFanavaranStageFieldReview( + payload: Record, + claim: any, + product: FanavaranClaimProduct, + stage: FanavaranFieldStage, +): void { + const values = claim?.fanavaranFieldReview?.values; + if (!values) return; + for (const field of fanavaranStageFields(product)) { + const value = values[field.key]; + if (field.stage === stage && value != null) payload[field.key] = value; + } +} diff --git a/src/expert-claim/dto/fanavaran-stage-fields.dto.ts b/src/expert-claim/dto/fanavaran-stage-fields.dto.ts new file mode 100644 index 0000000..b290bd7 --- /dev/null +++ b/src/expert-claim/dto/fanavaran-stage-fields.dto.ts @@ -0,0 +1,97 @@ +import { Type } from "class-transformer"; +import { + Equals, + IsInt, + IsOptional, + IsString, + Max, + MaxLength, + Min, + ValidateNested, +} from "class-validator"; +import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; + +export class FanavaranStageFieldValuesDto { + @ApiPropertyOptional() + @IsOptional() + @IsString() + @MaxLength(1000) + AccidentLocationAddress?: string; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + AccidentCityId?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + AccidentReportTypeId?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + DmgHistoryStatus?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + InspectionPlaceId?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + AccidentTypeId?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + CulpritTypeId?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + AuthorityCulpritId?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(0) + @Max(100) + CustomerFaultPercent?: number; + + @ApiPropertyOptional() + @IsOptional() + @IsInt() + @Min(1) + RepairDuration?: number; + + @ApiPropertyOptional({ description: "Fanavaran amount in rials" }) + @IsOptional() + @IsInt() + @Min(1) + VehicleCurrentValue?: number; +} + +export class UpdateFanavaranStageFieldsDto { + @ApiProperty({ type: FanavaranStageFieldValuesDto }) + @ValidateNested() + @Type(() => FanavaranStageFieldValuesDto) + values: FanavaranStageFieldValuesDto; + + @ApiProperty({ description: "Current field-review version; 0 when absent" }) + @IsInt() + @Min(0) + expectedVersion: number; + + @ApiProperty() + @Equals(true) + confirmed: true; +} diff --git a/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts b/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts index 14ed809..564b8f8 100644 --- a/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts +++ b/src/expert-claim/dto/fanavaran-vehicle-review.dto.ts @@ -1,7 +1,27 @@ import { ApiProperty } from "@nestjs/swagger"; -import { Equals, IsInt, Min } from "class-validator"; +import { + Equals, + IsInt, + IsOptional, + Min, + ValidateNested, +} from "class-validator"; +import { Type } from "class-transformer"; +import { FanavaranStageFieldValuesDto } from "./fanavaran-stage-fields.dto"; export class ApproveFanavaranVehicleReviewDto { + @ApiProperty({ required: false, type: FanavaranStageFieldValuesDto }) + @IsOptional() + @ValidateNested() + @Type(() => FanavaranStageFieldValuesDto) + stageFields?: FanavaranStageFieldValuesDto; + + @ApiProperty({ required: false, description: "Current field-review version" }) + @IsOptional() + @IsInt() + @Min(0) + stageFieldsVersion?: number; + @ApiProperty({ example: 1, description: "Fanavaran vehicle-groups Id" }) @IsInt() @Min(1) diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index d434f0c..ac8d9df 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -184,6 +184,11 @@ import { import { claimPriceCapAppliesToBlame } from "src/helpers/claim-price-cap"; import { LookupsService } from "src/lookups/lookups.service"; import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto"; +import { UpdateFanavaranStageFieldsDto } from "./dto/fanavaran-stage-fields.dto"; +import { + fanavaranFieldStageSent, type FanavaranFieldReview, + type FanavaranFieldValues, +} from "src/claim-request-management/fanavaran-stage-fields"; import { buildFanavaranVehicleSuggestion, collectFanavaranVehicleInquiryRecords, @@ -5677,6 +5682,18 @@ export class ExpertClaimService { "Vehicle classification cannot be changed after the claim was sent to Fanavaran.", ); } + const fields = + body.stageFields !== undefined + ? await this.prepareFanavaranStageFieldReview( + claim, + { + values: body.stageFields, + expectedVersion: body.stageFieldsVersion, + confirmed: body.confirmed, + }, + actor, + ) + : undefined; const [groupsRaw, useTypesRaw, systemsRaw, vehicleKind] = await Promise.all( [ this.lookupsService.getClientRemoteLookup("vehicle-groups"), @@ -5735,30 +5752,47 @@ export class ExpertClaimService { approvedByRole: String(actor.role), version: Number((claim as any).fanavaranVehicleReview?.version ?? 0) + 1, }; - const updated = await this.claimCaseDbService.findByIdAndUpdate( - claimRequestId, + const updated = await this.claimCaseDbService.findOneAndUpdate( { - $set: { fanavaranVehicleReview: review }, + _id: claimRequestId, + claimId: null, + claimNo: null, + ...(fields?.filter ?? {}), + }, + { + $set: { + fanavaranVehicleReview: review, + ...(fields ? { fanavaranFieldReview: fields.review } : {}), + }, $push: { history: { - type: "FANAVARAN_VEHICLE_REVIEW_APPROVED", - actor: { - actorId: new Types.ObjectId(String(actor.sub)), - actorName: actor.fullName, - actorType: actor.role, - }, - timestamp: review.approvedAt, - metadata: { - version: review.version, - vehicleGroupId: body.vehicleGroupId, - vehicleUseTypeId: body.vehicleUseTypeId, - vehicleSystemId: body.vehicleSystemId, - vehicleKindId: body.vehicleKindId, - }, + $each: [ + { + type: "FANAVARAN_VEHICLE_REVIEW_APPROVED", + actor: { + actorId: new Types.ObjectId(String(actor.sub)), + actorName: actor.fullName, + actorType: actor.role, + }, + timestamp: review.approvedAt, + metadata: { + version: review.version, + vehicleGroupId: body.vehicleGroupId, + vehicleUseTypeId: body.vehicleUseTypeId, + vehicleSystemId: body.vehicleSystemId, + vehicleKindId: body.vehicleKindId, + }, + }, + ...(fields ? [fields.history] : []), + ], }, }, }, ); + if (!updated) + throw new ConflictException( + "The case changed during review. Refresh before saving.", + ); const baseClaim = await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCreated( claimRequestId, @@ -5776,6 +5810,174 @@ export class ExpertClaimService { }; } + async getFanavaranStageFieldsV2(claimRequestId: string, actor: any) { + await this.getClaimDetailV2(claimRequestId, actor); + const claim = await this.claimCaseDbService.findById(claimRequestId); + if (!claim) throw new NotFoundException("Claim request not found"); + const blame = await this.loadBlameForClaim(claim); + return this.claimRequestManagementService.getFanavaranStageFieldsContext( + claim, + blame, + ); + } + + private async prepareFanavaranStageFieldReview( + claim: any, + body: UpdateFanavaranStageFieldsDto, + actor: any, + ) { + if ( + body.confirmed !== true || + !body.values || + typeof body.values !== "object" || + Array.isArray(body.values) + ) { + throw new BadRequestException( + "Explicit confirmation and field values are required.", + ); + } + const version = claim.fanavaranFieldReview?.version ?? 0; + if ( + !Number.isSafeInteger(body.expectedVersion) || + body.expectedVersion !== version + ) { + throw new ConflictException( + "The Fanavaran fields changed. Refresh before saving.", + ); + } + const context = + await this.claimRequestManagementService.getFanavaranStageFieldsContext( + claim, + await this.loadBlameForClaim(claim), + ); + const values: FanavaranFieldValues = {}; + const captions: FanavaranFieldReview["captions"] = {}; + const stages = new Set(); + const before: FanavaranFieldValues = {}; + for (const [key, raw] of Object.entries(body.values)) { + const field = context.fields.find((field) => field.key === key); + if (!field) + throw new BadRequestException( + `Field ${key} does not apply to this case type.`, + ); + if (fanavaranFieldStageSent(claim, field.stage)) { + throw new ConflictException( + `Field ${key} has already been sent to Fanavaran and cannot be changed.`, + ); + } + let value: string | number = raw; + if (field.type === "text") { + if ( + typeof raw !== "string" || + !raw.trim() || + raw.trim().length > 1000 + ) { + throw new BadRequestException( + `${key} must be a non-empty address of at most 1000 characters.`, + ); + } + value = raw.trim(); + } else { + if ( + typeof raw !== "number" || + !Number.isSafeInteger(raw) || + raw < (field.min ?? 1) || + (field.max != null && raw > field.max) + ) { + throw new BadRequestException( + `Field ${key} is out of range or invalid.`, + ); + } + if (field.type === "lookup") { + const row = field.options?.find((row) => row.Id === raw); + if (!row) + throw new BadRequestException( + `Field ${key} must use an active Fanavaran lookup value. Reload the options and try again.`, + ); + captions[field.key] = row.Caption; + } + } + values[field.key] = value; + before[field.key] = field.value; + stages.add(field.stage); + } + if (!Object.keys(values).length) + throw new BadRequestException("No Fanavaran fields were supplied."); + const review: FanavaranFieldReview = { + values: { ...claim.fanavaranFieldReview?.values, ...values }, + captions: { ...claim.fanavaranFieldReview?.captions, ...captions }, + version: version + 1, + reviewedAt: new Date(), + reviewedByActorId: String(actor.sub), + reviewedByActorName: actor.fullName, + reviewedByRole: String(actor.role), + }; + const conditions: Record[] = [ + version === 0 + ? { + $or: [ + { "fanavaranFieldReview.version": { $exists: false } }, + { "fanavaranFieldReview.version": 0 }, + ], + } + : { "fanavaranFieldReview.version": version }, + ]; + for (const stage of stages) { + const id = { + baseClaim: "claimId", + damageCase: "dmgCaseId", + expertise: "expertiseId", + }[stage]; + conditions.push({ + [id]: null, + [`fanavaranSync.${stage}.${id}`]: null, + [`fanavaranSync.${stage}.status`]: { $ne: "success" }, + }); + if (stage === "baseClaim") conditions.push({ claimNo: null }); + } + return { + review, + filter: { $and: conditions }, + history: { + type: "FANAVARAN_FIELDS_REVIEWED", + actor: { + actorId: new Types.ObjectId(String(actor.sub)), + actorName: actor.fullName, + actorType: actor.role, + }, + timestamp: review.reviewedAt, + metadata: { version: review.version, before, after: values, captions }, + }, + }; + } + + async updateFanavaranStageFieldsV2( + claimRequestId: string, + body: UpdateFanavaranStageFieldsDto, + actor: any, + ) { + await this.getClaimDetailV2(claimRequestId, actor); + const claim = await this.claimCaseDbService.findById(claimRequestId); + if (!claim) throw new NotFoundException("Claim request not found"); + const fields = await this.prepareFanavaranStageFieldReview( + claim, + body, + actor, + ); + const updated = await this.claimCaseDbService.findOneAndUpdate( + { _id: claimRequestId, ...fields.filter }, + { + $set: { fanavaranFieldReview: fields.review }, + $push: { history: fields.history }, + }, + ); + if (!updated) + throw new ConflictException( + "The case changed or its stage was sent. Refresh before saving.", + ); + return { version: fields.review.version }; + } + /** V2 price-drop: claim locked by this expert during damage assessment. */ private async assertExpertCanEditClaimDuringReviewV2( claim: any, diff --git a/src/expert-claim/expert-claim.v2.controller.ts b/src/expert-claim/expert-claim.v2.controller.ts index adcad94..152b169 100644 --- a/src/expert-claim/expert-claim.v2.controller.ts +++ b/src/expert-claim/expert-claim.v2.controller.ts @@ -56,6 +56,7 @@ import { ClaimRequestManagementService } from "src/claim-request-management/clai import { OuterPartCatalogItemDto } from "src/claim-request-management/dto/select-outer-parts-v2.dto"; import { submitExpertReplyValidationPipe } from "./pipes/submit-expert-reply-validation.pipe"; import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto"; +import { UpdateFanavaranStageFieldsDto } from "./dto/fanavaran-stage-fields.dto"; class InPersonVisitV2Dto { @ApiPropertyOptional({ example: "Paint damage requires physical inspection" }) @@ -245,6 +246,19 @@ export class ExpertClaimV2Controller { ); } + @Get("request/:claimRequestId/fanavaran-stage-fields") + @ApiOperation({ summary: "Case-specific Fanavaran fields, active lookup options and per-stage editability" }) + async getFanavaranStageFieldsV2(@Param("claimRequestId") id: string, @CurrentUser() actor: any) { + return this.expertClaimService.getFanavaranStageFieldsV2(id, actor); + } + + @Patch("request/:claimRequestId/fanavaran-stage-fields") + @ApiOperation({ summary: "Validate and save expert edits for unsent Fanavaran stages" }) + @ApiBody({ type: UpdateFanavaranStageFieldsDto }) + async updateFanavaranStageFieldsV2(@Param("claimRequestId") id: string, @Body() body: UpdateFanavaranStageFieldsDto, @CurrentUser() actor: any) { + return this.expertClaimService.updateFanavaranStageFieldsV2(id, body, actor); + } + @Get("request/:claimRequestId/price-drop") @ApiOperation({ summary: "Price-drop context for manual expert entry (V2)", diff --git a/src/expert-claim/fanavaran-stage-fields.spec.ts b/src/expert-claim/fanavaran-stage-fields.spec.ts new file mode 100644 index 0000000..ef2d827 --- /dev/null +++ b/src/expert-claim/fanavaran-stage-fields.spec.ts @@ -0,0 +1,494 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, +} from "@nestjs/common"; +import { ExpertClaimService } from "./expert-claim.service"; +import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; +import { + activeStageLookupRows, + applyFanavaranStageFieldReview, + fanavaranStageFields, +} from "src/claim-request-management/fanavaran-stage-fields"; + +const actor = { + sub: "507f1f77bcf86cd799439011", + role: "damage_expert", + fullName: "کارشناس", +}; +const id = "507f1f77bcf86cd799439012"; +const vehicleBody = { + vehicleGroupId: 1, + vehicleUseTypeId: 1, + vehicleSystemId: 14, + vehicleKindId: 7456, + confirmed: true as const, +}; + +function setup(product = "third-party", extra: any = {}) { + const claim = { + _id: id, + blameRequestId: "blame", + damage: { selectedParts: [] }, + ...extra, + }; + const management = Object.create( + ClaimRequestManagementService.prototype, + ) as any; + management.getFanavaranLookupRows = jest + .fn() + .mockImplementation(async (_client, name) => { + const ids = { + cities: 702, + "accident-report-type": 156, + "dmg-history-status": 5215, + "inspection-place": 283, + "vehicle-hull-accident-types": 4, + "vehicle-hull-accident-culprit-type": 301, + "detection-accident-culprits": 8, + }; + return [ + { Id: ids[name], Caption: "گزینه معتبر", IsActive: 1 }, + { Id: 999, Caption: "غیرفعال", IsActive: 0 }, + ]; + }); + management.resolveHullVehicleCurrentValueFromPolicy = jest + .fn() + .mockResolvedValue(1000000000); + management.autoSubmitToFanavaranV2OnClaimCreated = jest + .fn() + .mockImplementation(async () => { + expect(claim.fanavaranFieldReview).toBeDefined(); + return { submitted: false }; + }); + management.autoSubmitFanavaranDamageCaseOnOuterPartsSelected = jest.fn(); + const service = Object.create(ExpertClaimService.prototype) as any; + service.getClaimDetailV2 = jest.fn().mockResolvedValue({}); + service.blameRequestDbService = { + findById: jest + .fn() + .mockResolvedValue({ + type: product === "car-body" ? "CAR_BODY" : "THIRD_PARTY", + }), + }; + service.claimCaseDbService = { + findById: jest.fn().mockResolvedValue(claim), + findOneAndUpdate: jest + .fn() + .mockImplementation(async (_filter, update) => + Object.assign(claim, update.$set), + ), + }; + service.claimRequestManagementService = management; + service.lookupsService = { + getClientRemoteLookup: jest.fn().mockImplementation(async (name) => { + if (name === "vehicle-groups") return [{ Id: 1, Caption: "سواری" }]; + if (name === "vehicle-use-types") + return [{ Id: 1, Caption: "شخصی", VehicleGroupId: 1 }]; + return [{ Id: 14, Caption: "پراید", VehicleGroupId: 1 }]; + }), + getActiveVehicleKindById: jest + .fn() + .mockResolvedValue({ + Id: 7456, + Caption: "پراید", + VehicleGroupId: 1, + VehicleSystemId: 14, + }), + }; + return { service, management, claim }; +} + +describe("Expert Fanavaran stage fields", () => { + it.each(["third-party", "car-body"])( + "puts reviewed base fields into the actual %s preview after derived/default enrichment", + async (product) => { + const { management, claim } = setup(product, { + fanavaranFieldReview: { + values: { + AccidentLocationAddress: "نشانی واقعی", + AccidentCityId: 702, + AccidentReportTypeId: 156, + AccidentTypeId: 4, + CulpritTypeId: 301, + AuthorityCulpritId: 8, + CustomerFaultPercent: 0, + }, + }, + fanavaranVehicleReview: { vehicleUseType: { id: 1 } }, + fanavaranSync: { baseClaim: { policyId: 123 } }, + }); + management.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() }; + management.fanavaranAuditService = { + generateTrackingCode: jest.fn().mockReturnValue("test"), + }; + management.claimCaseDbService = { + findById: jest.fn().mockResolvedValue(claim), + findByIdAndUpdate: jest.fn(), + }; + management.blameRequestDbService = { + findById: jest + .fn() + .mockResolvedValue({ + type: product === "car-body" ? "CAR_BODY" : "THIRD_PARTY", + parties: [{ role: "FIRST" }], + createdAt: new Date(), + }), + }; + management.resolveAccidentVehicleUsedFromApis = jest + .fn() + .mockResolvedValue({ usedId: 1 }); + management.resolveFanavaranFileRoleExpertIdsForBlame = jest + .fn() + .mockResolvedValue(null); + management.enrichCarBodyHullBaseClaimPayload = jest + .fn() + .mockImplementation(async ({ payload }) => { + payload.CustomerFaultPercent = 100; + payload.AuthorityCulpritId = 1; + }); + const payload = await management.previewFanavaranSubmitV2(id, "parsian", { + persistPayload: false, + forceRefreshPolicy: false, + }); + expect(payload).toMatchObject({ + AccidentLocationAddress: "نشانی واقعی", + AccidentCityId: 702, + AccidentReportTypeId: 156, + }); + if (product === "car-body") { + expect(payload).toMatchObject({ + AccidentTypeId: 4, + CulpritTypeId: 301, + AuthorityCulpritId: 8, + CustomerFaultPercent: 0, + IsLicenseReplaced: null, + }); + expect(payload.DamagedCount).toBeUndefined(); + expect(payload.IsLicenseReplacement).toBeUndefined(); + } else expect(payload.AuthorityCulpritId).toBeNull(); + }, + ); + + it("puts reviewed repair duration and rial value into actual hull assessment payload", async () => { + const { management, claim } = setup("car-body", { + vehicle: { carPrice: "3000000000" }, + fanavaranFieldReview: { + values: { RepairDuration: 12, VehicleCurrentValue: 12000000000 }, + }, + }); + const result = await management.buildCarBodyFanavaranExpertisePayload({ + claimCase: claim, + blame: { parties: [] }, + clientKey: "parsian", + profile: {}, + parts: [], + claimExpertId: 29, + submittedAt: new Date(), + priceDropTotal: 0, + priceDropCarPrice: "5000000000", + warnings: [], + }); + expect(result.payload).toMatchObject({ + RepairDuration: 12, + VehicleCurrentValue: 12000000000, + }); + expect(result.payload.InspectionPlaceId).toBeUndefined(); + expect(result.payload.DmgCaseId).toBeUndefined(); + }); + + it("puts the reviewed inspection place into actual third-party assessment payload", async () => { + const { management, claim } = setup("third-party", { + dmgCaseId: 20, + fanavaranFieldReview: { values: { InspectionPlaceId: 283 } }, + }); + management.blameRequestDbService = { + findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }), + }; + management.resolveFanavaranFileRoleExpertIdsForBlame = jest + .fn() + .mockResolvedValue(null); + management.resolveFanavaranClaimProduct = jest + .fn() + .mockResolvedValue("third-party"); + const result = await management.buildFanavaranExpertisePayload({ + claimCase: claim, + clientKey: "parsian", + }); + expect(result.payload).toMatchObject({ + InspectionPlaceId: 283, + DmgCaseId: 20, + }); + }); + + it("puts reviewed damage history into the actual third-party damage-case payload", async () => { + const { management, claim } = setup("third-party", { + fanavaranFieldReview: { values: { DmgHistoryStatus: 5215 } }, + fanavaranVehicleReview: { + vehicleKind: { id: 7456 }, + vehicleUseType: { id: 1 }, + }, + }); + management.logger = { log: jest.fn(), warn: jest.fn() }; + management.claimCaseDbService = { findByIdAndUpdate: jest.fn() }; + management.pickDamagedPartyForFanavaran = jest + .fn() + .mockReturnValue({ person: {} }); + management.resolveOwnershipPlateForClaim = jest.fn().mockReturnValue(null); + management.fetchFanavaranVehicleByVinCandidates = jest + .fn() + .mockResolvedValue(null); + management.resolveDriverFanavaranIdFromBlameCase = jest + .fn() + .mockResolvedValue(null); + management.fanavaranLookupService = { + resolveInsuranceCorpId: jest.fn().mockResolvedValue(1), + }; + const payload = await management.buildFanavaranDamageCasePayload({ + claimCase: claim, + blameCase: { type: "THIRD_PARTY" }, + selectedParts: ["سپر"], + clientKey: "parsian", + defaults: { + DmgHistoryStatus: 5214, + AccidentVehicleUsedId: 1, + CulpritLicenceTypeId: 2, + DmgCaseTypeId: 175, + FaultPercent: 100, + }, + }); + expect(payload.DmgHistoryStatus).toBe(5215); + expect(payload.LicenceCountryId).toBeNull(); + }); + + it("uses the car-body codebooks and preserves submitted values in read-only base fields", async () => { + const { service } = setup("car-body", { + claimId: 10, + fanavaranSync: { baseClaim: { lastPayload: { AccidentCityId: 703 } } }, + }); + const context = await service.getFanavaranStageFieldsV2(id, actor); + expect(context.fields).toHaveLength(9); + expect( + context.fields.find((field) => field.key === "CulpritTypeId").lookup, + ).toBe("vehicle-hull-accident-culprit-type"); + expect( + context.fields.find((field) => field.key === "AccidentCityId"), + ).toMatchObject({ value: 703, editable: false, source: "submitted" }); + expect( + context.fields.find((field) => field.key === "RepairDuration").editable, + ).toBe(true); + expect( + context.fields.find((field) => field.key === "VehicleCurrentValue"), + ).toMatchObject({ value: 1000000000, unit: "ریال" }); + }); + + it("saves fields atomically before vehicle approval releases automatic submission", async () => { + const { service, management } = setup(); + await service.approveFanavaranVehicleReviewV2( + id, + { + ...vehicleBody, + stageFieldsVersion: 0, + stageFields: { + AccidentLocationAddress: " نشانی واقعی ", + AccidentCityId: 702, + AccidentReportTypeId: 156, + DmgHistoryStatus: 5215, + InspectionPlaceId: 283, + }, + }, + actor, + ); + const [, update] = + service.claimCaseDbService.findOneAndUpdate.mock.calls[0]; + expect(update.$set.fanavaranFieldReview.values).toMatchObject({ + AccidentLocationAddress: "نشانی واقعی", + InspectionPlaceId: 283, + }); + expect(update.$set.fanavaranFieldReview.captions.AccidentCityId).toBe( + "گزینه معتبر", + ); + expect(update.$push.history.$each.map((event) => event.type)).toEqual([ + "FANAVARAN_VEHICLE_REVIEW_APPROVED", + "FANAVARAN_FIELDS_REVIEWED", + ]); + expect( + management.autoSubmitToFanavaranV2OnClaimCreated, + ).toHaveBeenCalledTimes(1); + }); + + it.each([ + ["third-party", { AccidentCityId: 999 }], + ["third-party", { AccidentTypeId: 4 }], + ["third-party", { AccidentLocationAddress: " " }], + ["car-body", { CulpritTypeId: 337 }], + ["car-body", { DmgHistoryStatus: 5215 }], + ["car-body", { CustomerFaultPercent: 101 }], + ["car-body", { RepairDuration: -1 }], + ["car-body", { VehicleCurrentValue: null }], + ["car-body", { VehicleCurrentValue: Number.MAX_SAFE_INTEGER + 1 }], + ])( + "rejects invalid or inapplicable values for %s", + async (product, values) => { + const { service } = setup(product); + await expect( + service.updateFanavaranStageFieldsV2( + id, + { values, expectedVersion: 0, confirmed: true }, + actor, + ), + ).rejects.toBeInstanceOf(BadRequestException); + expect( + service.claimCaseDbService.findOneAndUpdate, + ).not.toHaveBeenCalled(); + }, + ); + + it("preserves zero fault percentage and raw rial amounts", async () => { + const { service, claim } = setup("car-body"); + await service.updateFanavaranStageFieldsV2( + id, + { + values: { + CustomerFaultPercent: 0, + VehicleCurrentValue: 12000000000, + RepairDuration: 9, + }, + expectedVersion: 0, + confirmed: true, + }, + actor, + ); + expect(claim.fanavaranFieldReview.values).toMatchObject({ + CustomerFaultPercent: 0, + VehicleCurrentValue: 12000000000, + RepairDuration: 9, + }); + }); + + it.each([ + [{ claimId: 10 }, { AccidentCityId: 702 }], + [ + { fanavaranSync: { baseClaim: { status: "success" } } }, + { AccidentCityId: 702 }, + ], + [{ dmgCaseId: 20 }, { DmgHistoryStatus: 5215 }], + [{ expertiseId: 30 }, { InspectionPlaceId: 283 }], + ])( + "rejects edits once the relevant stage has been sent", + async (extra, values) => { + const { service } = setup("third-party", extra); + await expect( + service.updateFanavaranStageFieldsV2( + id, + { values, expectedVersion: 0, confirmed: true }, + actor, + ), + ).rejects.toBeInstanceOf(ConflictException); + }, + ); + + it("allows remaining-stage edits after base creation and adds version/stage guards to the database write", async () => { + const { service } = setup("third-party", { claimId: 10 }); + await service.updateFanavaranStageFieldsV2( + id, + { + values: { DmgHistoryStatus: 5215, InspectionPlaceId: 283 }, + expectedVersion: 0, + confirmed: true, + }, + actor, + ); + const [filter] = service.claimCaseDbService.findOneAndUpdate.mock.calls[0]; + expect(filter.$and).toContainEqual({ + dmgCaseId: null, + "fanavaranSync.damageCase.dmgCaseId": null, + "fanavaranSync.damageCase.status": { $ne: "success" }, + }); + expect(filter.$and).toContainEqual({ + expertiseId: null, + "fanavaranSync.expertise.expertiseId": null, + "fanavaranSync.expertise.status": { $ne: "success" }, + }); + }); + + it("rejects stale versions and a stage sent while lookups were loading", async () => { + const { service } = setup("car-body", { + fanavaranFieldReview: { version: 2 }, + }); + await expect( + service.updateFanavaranStageFieldsV2( + id, + { values: { RepairDuration: 4 }, expectedVersion: 1, confirmed: true }, + actor, + ), + ).rejects.toBeInstanceOf(ConflictException); + service.claimCaseDbService.findOneAndUpdate.mockResolvedValue(null); + await expect( + service.updateFanavaranStageFieldsV2( + id, + { values: { RepairDuration: 4 }, expectedVersion: 2, confirmed: true }, + actor, + ), + ).rejects.toBeInstanceOf(ConflictException); + }); + + it("enforces existing claim access before reading or writing fields", async () => { + const { service, management } = setup(); + service.getClaimDetailV2.mockRejectedValue(new ForbiddenException()); + await expect( + service.getFanavaranStageFieldsV2(id, actor), + ).rejects.toBeInstanceOf(ForbiddenException); + await expect( + service.updateFanavaranStageFieldsV2( + id, + { + values: { AccidentCityId: 702 }, + expectedVersion: 0, + confirmed: true, + }, + actor, + ), + ).rejects.toBeInstanceOf(ForbiddenException); + expect(management.getFanavaranLookupRows).not.toHaveBeenCalled(); + }); + + it("normalizes cached lookup envelopes without admitting inactive/legacy IDs", () => { + expect( + activeStageLookupRows({ + data: { + data: [ + { Id: "7", Caption: "فعال", IsActive: "1" }, + { Id: 8, Caption: "غیرفعال", IsActive: "0" }, + { Code: 9, Caption: "کد قدیمی" }, + ], + }, + }), + ).toEqual([{ Id: 7, Caption: "فعال" }]); + }); + + it("keeps third-party keys out of hull stage payloads and existing nulls intact", () => { + const payload = { ArchiveNo: null }; + applyFanavaranStageFieldReview( + payload, + { + fanavaranFieldReview: { + values: { + DmgHistoryStatus: 5215, + CustomerFaultPercent: 0, + InspectionPlaceId: 283, + AccidentCityId: 702, + }, + }, + }, + "car-body", + "baseClaim", + ); + expect(payload).toEqual({ + ArchiveNo: null, + CustomerFaultPercent: 0, + AccidentCityId: 702, + }); + expect(fanavaranStageFields("third-party")).toHaveLength(5); + }); +}); diff --git a/src/expert-claim/fanavaran-vehicle-review.spec.ts b/src/expert-claim/fanavaran-vehicle-review.spec.ts index 4832177..6a07c89 100644 --- a/src/expert-claim/fanavaran-vehicle-review.spec.ts +++ b/src/expert-claim/fanavaran-vehicle-review.spec.ts @@ -29,7 +29,7 @@ function makeService(overrides?: { kind?: typeof kind }) { service.getClaimDetailV2 = jest.fn().mockResolvedValue({}); service.claimCaseDbService = { findById: jest.fn().mockResolvedValue(claim), - findByIdAndUpdate: jest.fn().mockImplementation((_id, update) => + findOneAndUpdate: jest.fn().mockImplementation((_id, update) => Promise.resolve({ ...claim, fanavaranVehicleReview: update.$set.fanavaranVehicleReview, @@ -103,7 +103,7 @@ describe("Fanavaran vehicle review", () => { actor, ), ).rejects.toBeInstanceOf(BadRequestException); - expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled(); + expect(service.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled(); }); it("blocks outbound stages until all four values are approved", () => {