From c74b29337edaf79ff0488b977656f89e58c2f5bd Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Mon, 23 Nov 2026 11:10:55 +0330 Subject: [PATCH] feat(depreciation): apply Fanavaran tables and age eligibility Use the supplied part, severity and age codes for depreciation. Exclude vehicles older than ten from calculated and manual amounts, preserve historical assessments, and send zero depreciation to Fanavaran for ineligible vehicles. --- docs/fanavaran/README.md | 2 + docs/fanavaran/price-drop.md | 107 ++++ docs/ضرایب افت قیمت.xlsx | Bin 0 -> 12389 bytes .../claim-request-management.service.ts | 5 +- .../schema/claim-case.evaluation.schema.ts | 21 + .../fanavaran-price-drop-age.spec.ts | 66 +++ src/expert-claim/claim-price-drop-v2.spec.ts | 347 +++++++++++++ src/expert-claim/dto/claim-detail-v2.dto.ts | 7 + .../dto/claim-price-drop-v2.dto.ts | 72 ++- src/expert-claim/expert-claim.service.ts | 146 ++++-- .../expert-claim.v2.controller.ts | 4 +- src/helpers/claim-price-drop.spec.ts | 273 ++++++++++- src/helpers/claim-price-drop.ts | 459 +++++++++++------- src/static/fanavaran-price-drop.ts | 123 +++++ 14 files changed, 1424 insertions(+), 208 deletions(-) create mode 100644 docs/fanavaran/price-drop.md create mode 100644 docs/ضرایب افت قیمت.xlsx create mode 100644 src/claim-request-management/fanavaran-price-drop-age.spec.ts create mode 100644 src/expert-claim/claim-price-drop-v2.spec.ts create mode 100644 src/static/fanavaran-price-drop.ts diff --git a/docs/fanavaran/README.md b/docs/fanavaran/README.md index 6340cdf..04dc2ac 100644 --- a/docs/fanavaran/README.md +++ b/docs/fanavaran/README.md @@ -21,6 +21,8 @@ source: fanavaran-module-docs ## Document index +Depreciation coefficients, age codes and expert entry: [Fanavaran price drop](price-drop.md). + | # | Document | Covers | |---|----------|--------| | 1 | [01-write-apis.md](./01-write-apis.md) | Auth + GEN.03 / GEN.12 / GEN.44 / GEN.07 / GEN.08 write APIs | diff --git a/docs/fanavaran/price-drop.md b/docs/fanavaran/price-drop.md new file mode 100644 index 0000000..a74b32e --- /dev/null +++ b/docs/fanavaran/price-drop.md @@ -0,0 +1,107 @@ +# Fanavaran depreciation tables + +The calculation now uses [ضرایب افت قیمت.xlsx](<../ضرایب افت قیمت.xlsx>) and [افت قیمت سن.png](<../افت قیمت سن.png>). Their reference data lives in `src/static/fanavaran-price-drop.ts`; the previous fixed production-year table and part coefficients are retired. + +## Part and severity codes + +These codes identify depreciation categories, **not** tenant car-component IDs. The original component ID remains `partId`. The expert can explicitly choose a category when a tenant's component caption is ambiguous. Clear names receive a suggestion; numeric IDs are never assumed to mean the same thing across insurers. + +The depreciation path preserves saved tenant captions even when their component IDs collide with the legacy global fallback snapshot. It does not replace a tenant's saved roof caption with another tenant's trunk-floor-tray caption merely because both use ID 52. + +| Category code | Caption | Minor / Moderate / Severe codes | Coefficients | +| --- | --- | --- | --- | +| 1 | سقف | 1 / 2 / 3 | 3 / 5 / 7 | +| 2 | کلاف | 4 / 5 / 6 | 2 / 3 / 4 | +| 3 | ستون | 7 / 8 / 9 | 2 / 3 / 4 | +| 4 | درب موتور | 10 / 11 / 12 | 2 / 3 / 4 | +| 5 | سینی جلو | 13 / 14 / 15 | 1 / 2 / 3 | +| 6 | شاسی جلو | 16 / 17 / 18 | 3 / 5 / 7 | +| 7 | گلگیر جلو | 19 / 20 / 21 | 1 / 2 / 3 | +| 8 | درب جلو | 22 / 23 / 24 | 1 / 2 / 3 | +| 9 | درب عقب | 25 / 26 / 27 | 1 / 2 / 3 | +| 10 | رکاب | 28 / 29 / 30 | 1 / 2 / 3 | +| 11 | گلگیر عقب | 31 / 32 / 33 | 2 / 3 / 5 | +| 12 | درب صندوق | 34 / 35 / 36 | 1 / 3 / 5 | +| 13 | سینی عقب | 37 / 38 / 39 | 1 / 2 / 3 | +| 14 | سینی کف صندوق | 40 / 41 / 42 | 2 / 4 / 5 | +| 15 | شاسی عقب | 43 / 44 / 45 | 2 / 4 / 6 | +| 16 | کف اتاق | 46 / 47 / 48 | 4 / 6 / 8 | +| 17 | بلوک سیلندر | Severe only: 49 | Severe only: 3 | + +Front/rear bumpers are absent from the supplied table and no longer receive an automatic coefficient. Rear tray and trunk-floor tray are separate. Glass, pillar trim and roof accessories are not mapped to a door/pillar/roof just because that word occurs in their caption. A submitted part must exist among the case's selected damaged parts, and each part may occur only once per calculation. Non-catalog internal rows without a component ID remain available through the existing manual-total option. + +## Age codes + +| Age at accident | Code | Coefficient | +| --- | --- | --- | +| 0 | 1 | 3 | +| 1 | 2 | 2.9 | +| 2 | 3 | 2.8 | +| 3 | 4 | 2.7 | +| 4 | 5 | 2.6 | +| 5 | 6 | 2.5 | +| 6 | 7 | 2.4 | +| 7 | 8 | 2.3 | +| 8 | 9 | 2.2 | +| 9 | 10 | 2.1 | +| 10 | 11 | 2.05 | + +Suggested age is the Jalali accident year minus the **damaged vehicle's** Jalali model year. It does not use the current year or the guilty party's vehicle, even when an expert or the guilty party owns the claim record. Experts can confirm/correct age directly. A Gregorian model year without month/day is not converted speculatively; use explicit age instead. + +The screenshot marks these age rows effective from `1404/05/28`. Cases with a known earlier accident date cannot use automatic calculation from this table. Cars **older than ten at the accident are not eligible for depreciation**. Their calculated and manual depreciation must be zero, with no invented age/coefficient code. Exactly ten remains eligible. Positive manual totals require a known or explicitly entered eligible age. The UI offers an over-ten option, explains the exclusion and only lets the expert save zero. For pre-table accident dates, the manual-total path remains subject to the same age rule. + +## Formula and currency + +The supplied documents define reference rows, not a replacement formula. The existing formula is retained with the new coefficients: + +```text +Depreciation = vehicle market price × age coefficient × sum(part severity coefficients) / 400 +``` + +All amounts are **Rials**. Integer arithmetic in hundredths of the coefficient prevents floating-point rounding drift; the result is rounded to whole Rials. Example: a 400,000,000 Rial car aged 3 with moderate trunk-floor-tray damage produces `400000000 × 2.7 × 4 / 400 = 10800000` Rials. + +## Existing API routes + +```text +GET /v2/expert-claim/request/:claimRequestId/price-drop +PUT /v2/expert-claim/request/:claimRequestId/price-drop +``` + +The context includes `priceDropCatalog` with `fanavaranPartId`, `severities` and `severityCodes`; `ageCatalog`; `suggestedVehicleAge`; `accidentYear`; `calculationVersion`; `ageTableEffectiveFrom`; and `calculationUnavailableReason` when the accident predates the table. + +Example calculation, where `9876` is an illustrative component ID actually selected on that case: + +```json +{ + "carPrice": 400000000, + "vehicleAge": 3, + "partSeverities": [ + { "partId": 9876, "fanavaranPartId": 14, "severity": "Moderate" } + ] +} +``` + +`fanavaranPartId` is optional when a safe name mapping exists. The older `carModelYear` input remains supported when an accident date is available. Clients never choose coefficients directly: the API derives them from the static source. + +`evaluation.priceDrop` stores version `fanavaran-v1`, age, `fanavaranAgeId` and the coefficient. Each saved part line includes the actual component `partId`, category `fanavaranPartId` and `fanavaranSeverityId`. The response and strict Mongoose schema retain these fields. + +For eligible ages, the manual path remains (zero is also allowed without an age): + +```json +{ "manualPriceDrop": 0 } +``` + +Calculated requests must omit `manualPriceDrop`; its presence explicitly chooses the manual path. The expert UI separates these writes so a previously saved total cannot silently override recalculation. Manual entry also has an optional `carPrice` field for Fanavaran's market-value data. Manual writes preserve an existing market price when omitted and clear obsolete calculated rows. `manualOverride` now survives schema casting. + +## Fanavaran writes and rollout + +The existing documented write contracts still receive the final total in third-party `DropAmountAdditionsDeductions` or car-body `DropAmount`. Category/severity/age codes are calculation/audit metadata; they are not inserted into undocumented outgoing fields. GEN.13 is read-only in the currently supplied API contract. + +Saved historical assessments are never automatically recalculated. When a known over-ten vehicle has an old positive total, a new Fanavaran submission uses zero; the stored historical assessment is preserved until explicitly corrected. The UI identifies results without the new calculation version and lets the expert explicitly recalculate them. Deploy the API first, then the expert UI. No new environment variables or database migration are required. + +## Verification + +- All 17 category codes/captions and all 49 severity codes/coefficients were compared directly with the supplied workbook. +- API regression tests cover age boundaries, date validity, separate severity codes, tenant-ID collisions, explicit mappings, real schema persistence, manual zero, duplicate/unselected parts, vehicle-party isolation and failed writes preserving previous results. +- Expert UI regression tests cover request construction and rendered controls. Browser checks at 1440×1100 and 390×844 cover labels, keyboard, overflow, age zero, severe-only cylinder block, HTTP-error retry and separate calculated/manual requests. Browser API calls used synthetic intercepted responses. +- The full API suite additionally reports ten failures in the unchanged `fanavaran-submit-overrides.spec.ts` fixture, reproduced on an archive of the unmodified commit. These fail at the existing vehicle-review prerequisite before reaching their intended assertions; they are unrelated to depreciation. diff --git a/docs/ضرایب افت قیمت.xlsx b/docs/ضرایب افت قیمت.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..e796670a42ab1e9ae208b4ad9ae6918c51078ab6 GIT binary patch literal 12389 zcmeHtWmH^Swr&9hf#B{A!6`hryAy&3*Wkh3-6W;%UgJBOCw#L<9hE0m$$M zQcjL;mX2=5&%K>3T@Bg29PFvy0O1)60PwK(|K0wBd!YRJfa7NltTvrJG3j>g=)%a- zQe?6gG6TAuN10w=UAl%XV#Zs41}hD%YUD0@4f|1pCuhP$74uK@B*i!E*>CjJ=uA+H z<11WFMDFDCWkTMTYsc3n#qt&qp+g`@6ZMajo94~fZD}58=m~i19&>;1I#u13EQ=D8 zqHkl~E``6I-4_}7tOu{e&DLS_NuTHJ;73n~A7rS*~XXJpJz~qS*%ZEe}+oDED4OmVOsbtZ&Z< zgGYC$@;H-DyxYQ%T_dnwE&-NX4zbV4Tr1#rP)^RZpAsGu{z%10nB?bAd_51y@H8b% zt`xjL0|uiVNV(X|UdEAKmn~o{<-U=iTund0AianA*~0?@K>aUnTCc@Hdk(WbW!PO* zn422ASlYXS*nj^2*FFD(eez#ky&SBf*3E$y0g=Cr?1xS*C1FV_c}mECqJAC_q_But zA74aAy41lyhV`5z6hSVqE#P)=VM#cCub=vIou@n&2TzE$!LuSF9ViN z*Ltu$rY@!~v*Z-L89mw(nai3!6e6TX7Jk30ne|+yU%x%|#WjhRrj5YMDziKn zK^kvk3;WJ9>6{MSJ3ltn*Zt3EcyO+`M&v&Fva=m+=qI8$_9}k4YQhr#5 zWvqX9l3>x)j5An|w7{H%1b__ZWe@tpPduGm?97~;?0#mmfBFm@ETzFv{=AIagFF+_`LB$H)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4eIMAt35uhC+Iv=%@9Ak#vwDzbs=dlTOMMuF%74z*>eOEGD=ZdX&~ z!o?@lY*DALo+OuqIc~>twjaD`pWlK=1g>$iPxmv*{s_bwUwCLX>JxrT8olbl!aFcuG3-u2&e?Mu< zAW|_q<;dsLQ_!d)C}>6=hW;imLs9I;7=JC;$P2^%Y?QQQfPsu(=Te7Ga#Bwce@n$%%U-Z%uqkT#z{3jo6?umTJ`dy}FtFtB!K`psT<~?l zjBl@iJ7eMO=&9FK+uxQf`N#EivS1eS1a=qeU!$0*v-5w07|dn@EofJ${k;-<6)>FKg?8!wCsU>1jq&)moM4d1(T~nf zeSgftYNV*Z5=eQp=ygmDrCew{`0Tw|3wic;o06Gk@Y(Z2G@d3aQ$vXq^#N!|iv*GK zLP)$qS%Nk>$tkDOWw^s9yg5pF{#Cp;p*CIE=IG{{T)istco$BT`Oo6z6%;5kW6b&U zbNepKj1myYUSndw<03yD!G@-jC_|?RXzoJ21Q;lYpDd$TqrXC6BXgcv);TZh&C6)* z8Wi-{LO9<+5PMkbs&_(Y$|Eh_nQkdQ$GQwa2y>#yC!DH`h@$_vRTru$u~gMoO)Ndl z+k}wr#2xrFBG&8mh!N-`!F9+RRX>wwi8{C}?9!@;w`NE&}nmHy}F`{({|h|}sy ze+Bp}iSwU=KljBjANdzb=kJ1lCAR&m;8$2h{QpdI`yJ-ht{yNnA69WK9r3V21ZQ%F2`0rWxPXK<# vUrPLzga0-s{|@@s!2KsA0HDwOFFO4rjH@dl!fX%#K!g2$hI%HppJ)FAfSv+o literal 0 HcmV?d00001 diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 4770e18..f164905 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -1,3 +1,4 @@ +import { resolveClaimPriceDropAge } from "src/helpers/claim-price-drop"; import { unlink } from "node:fs/promises"; import { plainToInstance } from "class-transformer"; import { validateSync } from "class-validator"; @@ -6331,7 +6332,9 @@ export class ClaimRequestManagementService { } const priceDrop = input.claimCase.evaluation?.priceDrop ?? {}; - const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total); + const priceDropVehicleAge = resolveClaimPriceDropAge(input.claimCase, blameForExpertIds); + const priceDropTotal = priceDropVehicleAge != null && priceDropVehicleAge > 10 + ? 0 : this.parseFanavaranMoney(priceDrop?.total); const submittedAt = reply?.submittedAt ?? new Date(); const product = await this.resolveFanavaranClaimProduct( input.claimCase?._id ? String(input.claimCase._id) : undefined, diff --git a/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts b/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts index 429d087..951f88a 100644 --- a/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts +++ b/src/claim-request-management/entites/schema/claim-case.evaluation.schema.ts @@ -276,6 +276,27 @@ export const ClaimFileRatingSchema = @Schema({ _id: false }) export class ClaimPriceDrop { + @Prop({ type: Boolean }) + eligible?: boolean; + + @Prop({ type: String }) + exclusionReason?: string; + + @Prop({ type: Boolean }) + manualOverride?: boolean; + + @Prop({ type: String }) + calculationVersion?: string; + + @Prop({ type: Number }) + vehicleAge?: number; + + @Prop({ type: Number }) + fanavaranAgeId?: number; + + @Prop({ type: Number }) + accidentYear?: number; + @Prop({ type: Number }) total?: number; diff --git a/src/claim-request-management/fanavaran-price-drop-age.spec.ts b/src/claim-request-management/fanavaran-price-drop-age.spec.ts new file mode 100644 index 0000000..23f1e08 --- /dev/null +++ b/src/claim-request-management/fanavaran-price-drop-age.spec.ts @@ -0,0 +1,66 @@ +import { ClaimRequestManagementService } from "./claim-request-management.service"; + +describe("Fanavaran depreciation age eligibility", () => { + it.each( + ["car-body", "third-party"].flatMap((product) => + [10, 11].map((age) => ({ product, age })), + ), + )( + "$product: age $age uses the eligible total only", + async ({ product, age }) => { + const service = Object.create( + ClaimRequestManagementService.prototype, + ) as any; + const first = { + role: "FIRST", + person: { userId: "first" }, + statement: { accidentDate: "2026-11-23" }, + vehicle: { inquiry: { mapped: { ModelField: String(1405 - age) } } }, + }; + const second = { + role: "SECOND", + person: { userId: "second" }, + vehicle: first.vehicle, + }; + const blame = + product === "car-body" + ? { type: "CAR_BODY", parties: [first] } + : { + type: "THIRD_PARTY", + parties: [first, second], + expert: { decision: { guiltyPartyId: "first" } }, + }; + service.blameRequestDbService = { + findById: jest.fn().mockResolvedValue(blame), + }; + service.tryResolveFanavaranExpertiseClaimExpertId = jest + .fn() + .mockResolvedValue({ claimExpertId: 4044 }); + service.resolveFanavaranClaimProduct = jest + .fn() + .mockResolvedValue(product); + service.getFanavaranLookupRows = jest.fn().mockResolvedValue([]); + service.buildCarBodyFanavaranExpertisePayload = jest.fn( + async (input) => ({ payload: { DropAmount: input.priceDropTotal } }), + ); + const claimCase = { + _id: "claim", + blameRequestId: "blame", + owner: { userId: "first" }, + evaluation: { priceDrop: { total: 999, carPrice: 400000000 } }, + }; + const result = await service.buildFanavaranExpertisePayload({ + claimCase, + clientKey: "parsian", + }); + expect( + result.payload[ + product === "car-body" + ? "DropAmount" + : "DropAmountAdditionsDeductions" + ], + ).toBe(age > 10 ? 0 : 999); + expect(claimCase.evaluation.priceDrop.total).toBe(999); // Historical data is preserved. + }, + ); +}); diff --git a/src/expert-claim/claim-price-drop-v2.spec.ts b/src/expert-claim/claim-price-drop-v2.spec.ts new file mode 100644 index 0000000..bfd4385 --- /dev/null +++ b/src/expert-claim/claim-price-drop-v2.spec.ts @@ -0,0 +1,347 @@ +import { BadRequestException } from "@nestjs/common"; +import { model, Schema, Types } from "mongoose"; +import { ExpertClaimService } from "./expert-claim.service"; +import { ClaimPriceDropSchema } from "src/claim-request-management/entites/schema/claim-case.evaluation.schema"; + +const Stored = model( + "FanavaranPriceDropTest", + new Schema({ priceDrop: ClaimPriceDropSchema }), +); + +function setup() { + const claim: any = { + _id: new Types.ObjectId(), + blameRequestId: new Types.ObjectId(), + owner: { userId: "beneficiary" }, + vehicle: { carType: "sedan" }, + damage: { + selectedParts: [ + { + id: 9876, + name: "9876", + label_fa: "قطعه اختصاصی شرکت", + side: "", + catalogKey: "9876", + }, + ], + }, + evaluation: {}, + }; + const blame: any = { + type: "CAR_BODY", + parties: [ + { + role: "FIRST", + person: { userId: "beneficiary" }, + vehicle: { inquiry: { mapped: { ModelField: "1402" } } }, + statement: { accidentDate: "2026-11-23" }, + }, + ], + }; + const service = Object.create(ExpertClaimService.prototype) as any; + service.assertExpertCanEditClaimDuringReviewV2 = jest + .fn() + .mockResolvedValue(undefined); + service.blameRequestDbService = { + find: jest.fn().mockResolvedValue([blame]), + }; + service.claimCaseDbService = { + findById: jest.fn().mockResolvedValue(claim), + findByIdAndUpdate: jest.fn(async (_id, update) => { + // Exercise Mongoose's real strict schema casting: IDs and override flags + // must survive persistence, not merely exist in the response object. + claim.evaluation.priceDrop = new Stored({ + priceDrop: update.$set["evaluation.priceDrop"], + }).toObject().priceDrop; + return claim; + }), + }; + const body = { + carPrice: 400_000_000, + partSeverities: [ + { partId: 9876, fanavaranPartId: 14, severity: "Moderate" }, + ], + }; + return { service, claim, blame, body, id: String(claim._id) }; +} + +describe("Fanavaran depreciation review and persistence", () => { + 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: [] }; + const result = await service.getPriceDropContextV2(id, {}); + expect(result).toMatchObject({ + calculationVersion: "fanavaran-v1", + accidentYear: 1405, + suggestedCarModelYear: 1402, + suggestedVehicleAge: 3, + priceDrop: { total: 123 }, + }); + expect(result.priceDropCatalog).toHaveLength(17); + expect(result.ageCatalog).toHaveLength(11); + expect(result.damagedParts[0]).toMatchObject({ + partId: 9876, + fanavaranPartId: null, + }); + expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled(); + }); + + it("derives age and persists real Fanavaran category/severity/age codes", async () => { + const { service, claim, id, body } = setup(); + const response = await service.upsertPriceDropV2(id, body, {}); + const expected = { + total: 10_800_000, + carPrice: 400_000_000, + carModel: 1402, + accidentYear: 1405, + vehicleAge: 3, + fanavaranAgeId: 4, + coefficientYear: 2.7, + manualOverride: false, + calculationVersion: "fanavaran-v1", + }; + expect(response.priceDrop).toMatchObject(expected); + expect(claim.evaluation.priceDrop).toMatchObject(expected); + expect(claim.evaluation.priceDrop.partLines[0]).toMatchObject({ + partId: 9876, + fanavaranPartId: 14, + fanavaranSeverityId: 41, + coefficient: 4, + }); + }); + + it("never uses a legacy tenant's caption just because component IDs collide", async () => { + const { service, claim, id } = setup(); + // ID 52 means trunk-floor tray in the fallback snapshot, but this tenant + // saved its own live caption: roof. The saved tenant caption is authoritative. + claim.damage.selectedParts = [ + { id: 52, name: "52", catalogKey: "52", side: "", label_fa: "سقف" }, + ]; + const context = await service.getPriceDropContextV2(id, {}); + expect(context.damagedParts[0]).toMatchObject({ + partId: 52, + label_fa: "سقف", + fanavaranPartId: 1, + }); + await service.upsertPriceDropV2( + id, + { + carPrice: 400_000_000, + vehicleAge: 3, + partSeverities: [{ partId: 52, severity: "Severe" }], + }, + {}, + ); + expect(claim.evaluation.priceDrop.partLines[0]).toMatchObject({ + partId: 52, + fanavaranPartId: 1, + fanavaranSeverityId: 3, + coefficient: 7, + }); + }); + + it("allows expert age when inquiry/date is unavailable and never sends a Gregorian year into the age table", async () => { + const { service, claim, blame, id, body } = setup(); + blame.parties[0].vehicle.inquiry.mapped.ModelField = "2020"; + delete blame.parties[0].statement.accidentDate; + await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow( + "سن خودرو", + ); + await service.upsertPriceDropV2(id, { ...body, vehicleAge: 0 }, {}); + expect(claim.evaluation.priceDrop).toMatchObject({ + vehicleAge: 0, + fanavaranAgeId: 1, + total: 12_000_000, + }); + }); + + it("preserves the manual zero path and market price, and clears stale calculated rows", async () => { + const { service, claim, id } = setup(); + claim.evaluation.priceDrop = { + carPrice: 400_000_000, + partLines: [{ coefficient: 7 }], + total: 123, + }; + await service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {}); + expect(claim.evaluation.priceDrop).toMatchObject({ + manualOverride: true, + carPrice: 400_000_000, + total: 0, + partLines: [], + }); + expect(service.blameRequestDbService.find).toHaveBeenCalled(); + }); + + it("explicit recalculation replaces an old manual value and stores its source", async () => { + const { service, claim, id, body } = setup(); + claim.evaluation.priceDrop = { manualOverride: true, total: 42 }; + await service.upsertPriceDropV2(id, body, {}); + expect(claim.evaluation.priceDrop).toMatchObject({ + manualOverride: false, + total: 10_800_000, + calculationVersion: "fanavaran-v1", + }); + }); + + it.each([ + { vehicleAge: -1 }, + { vehicleAge: 1.5 }, + { carPrice: "invalid" }, + { carPrice: -1 }, + { + partSeverities: [ + { partId: 9876, fanavaranPartId: 17, severity: "Minor" }, + ], + }, + { + partSeverities: [ + { partId: 9876, fanavaranPartId: 999, severity: "Severe" }, + ], + }, + { partSeverities: [{ partId: 50, severity: "Severe" }] }, + { partSeverities: [null] }, + { partSeverities: "bad" }, + ])( + "invalid calculation does not overwrite a previously saved result: %j", + async (invalid) => { + const { service, claim, id, body } = setup(); + claim.evaluation.priceDrop = { total: 777 }; + await expect( + service.upsertPriceDropV2(id, { ...body, ...invalid }, {}), + ).rejects.toBeInstanceOf(BadRequestException); + expect(claim.evaluation.priceDrop.total).toBe(777); + expect( + service.claimCaseDbService.findByIdAndUpdate, + ).not.toHaveBeenCalled(); + }, + ); + + it("keeps the existing review authorization check before either write mode", async () => { + const { service, id, body } = setup(); + service.assertExpertCanEditClaimDuringReviewV2.mockRejectedValue( + new Error("denied"), + ); + await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow( + "denied", + ); + await expect( + service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {}), + ).rejects.toThrow("denied"); + expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled(); + }); + + it("respects the age table start date without blocking manual totals", async () => { + const { service, claim, blame, id, body } = setup(); + blame.parties[0].statement.accidentDate = "1404/05/27"; + const context = await service.getPriceDropContextV2(id, {}); + expect(context.calculationUnavailableReason).toContain("۱۴۰۴/۰۵/۲۸"); + await expect( + service.upsertPriceDropV2(id, { ...body, vehicleAge: 3 }, {}), + ).rejects.toThrow("۱۴۰۴/۰۵/۲۸"); + expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled(); + await service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {}); + expect(claim.evaluation.priceDrop).toMatchObject({ + total: 0, + manualOverride: true, + }); + }); + + it("makes an inferred age above ten ineligible in context and saves zero without requiring parts/prices", async () => { + const { service, claim, blame, id } = setup(); + blame.parties[0].vehicle.inquiry.mapped.ModelField = "1394"; + const context = await service.getPriceDropContextV2(id, {}); + expect(context).toMatchObject({ + suggestedVehicleAge: 11, + depreciationEligible: false, + }); + expect(context.ineligibilityReason).toContain("بیشتر از ۱۰ سال"); + await service.upsertPriceDropV2(id, {}, {}); + expect(claim.evaluation.priceDrop).toMatchObject({ + vehicleAge: 11, + eligible: false, + total: 0, + partLines: [], + fanavaranAgeId: null, + }); + }); + + it.each([undefined, 0, 10])( + "an entered age %s cannot bypass known old age for a positive manual override", + async (vehicleAge) => { + const { service, claim, blame, id } = setup(); + blame.parties[0].vehicle.inquiry.mapped.ModelField = "1394"; + await expect( + service.upsertPriceDropV2(id, { manualPriceDrop: 1, vehicleAge }, {}), + ).rejects.toThrow("بیشتر از ۱۰ سال"); + expect( + service.claimCaseDbService.findByIdAndUpdate, + ).not.toHaveBeenCalled(); + }, + ); + + it("accepts manual zero for an old car and preserves its market value", async () => { + const { service, claim, id } = setup(); + await service.upsertPriceDropV2( + id, + { manualPriceDrop: 0, vehicleAge: 12, carPrice: 400_000_000 }, + {}, + ); + expect(claim.evaluation.priceDrop).toMatchObject({ + eligible: false, + total: 0, + vehicleAge: 12, + carPrice: 400_000_000, + }); + }); + + it("keeps exactly age ten eligible for manual and calculated amounts", async () => { + const { service, claim, id, body } = setup(); + await service.upsertPriceDropV2(id, { ...body, vehicleAge: 10 }, {}); + expect(claim.evaluation.priceDrop).toMatchObject({ + eligible: true, + total: 8_200_000, + vehicleAge: 10, + }); + await service.upsertPriceDropV2( + id, + { manualPriceDrop: 99, vehicleAge: 10 }, + {}, + ); + expect(claim.evaluation.priceDrop).toMatchObject({ + eligible: true, + total: 99, + vehicleAge: 10, + }); + }); + + it("requires age for a positive manual amount when inquiry age is unknown, while allowing zero", async () => { + const { service, claim, blame, id } = setup(); + delete blame.parties[0].vehicle.inquiry; + await expect( + service.upsertPriceDropV2(id, { manualPriceDrop: 99 }, {}), + ).rejects.toThrow("سن خودرو"); + await service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {}); + expect(claim.evaluation.priceDrop.total).toBe(0); + }); + + it("allows correction of a mistyped expert-entered age when inquiry age is unknown", async () => { + const { service, claim, blame, id } = setup(); + delete blame.parties[0].vehicle.inquiry; + await service.upsertPriceDropV2( + id, + { vehicleAge: 12, manualPriceDrop: 0 }, + {}, + ); + expect(claim.evaluation.priceDrop.eligible).toBe(false); + await service.upsertPriceDropV2( + id, + { vehicleAge: 10, manualPriceDrop: 99 }, + {}, + ); + expect(claim.evaluation.priceDrop).toMatchObject({ + eligible: true, + vehicleAge: 10, + total: 99, + }); + }); +}); diff --git a/src/expert-claim/dto/claim-detail-v2.dto.ts b/src/expert-claim/dto/claim-detail-v2.dto.ts index db72b58..51bd9b4 100644 --- a/src/expert-claim/dto/claim-detail-v2.dto.ts +++ b/src/expert-claim/dto/claim-detail-v2.dto.ts @@ -285,6 +285,13 @@ export class ClaimDetailV2ResponseDto { signedAt?: Date | string; }; priceDrop?: { + eligible?: boolean; + exclusionReason?: string; + manualOverride?: boolean; + calculationVersion?: string; + vehicleAge?: number; + fanavaranAgeId?: number; + accidentYear?: number; total?: number; carPrice?: number; carModel?: number; diff --git a/src/expert-claim/dto/claim-price-drop-v2.dto.ts b/src/expert-claim/dto/claim-price-drop-v2.dto.ts index 9dae4c5..2cc0073 100644 --- a/src/expert-claim/dto/claim-price-drop-v2.dto.ts +++ b/src/expert-claim/dto/claim-price-drop-v2.dto.ts @@ -5,6 +5,8 @@ import { IsInt, IsNotEmpty, IsNumber, + Min, + Max, IsOptional, IsString, ValidateNested, @@ -26,6 +28,17 @@ export class PriceDropPartSeverityV2Dto { }) @IsIn(["Minor", "Moderate", "Severe"]) severity: PriceDropSeverity; + + @ApiPropertyOptional({ + description: + "Price-drop category code from priceDropCatalog (1–17), NOT a tenant car-component ID. Expert selection overrides a suggested mapping.", + example: 14, + }) + @IsOptional() + @IsInt() + @Min(1) + @Max(17) + fanavaranPartId?: number; } export class UpsertClaimPriceDropV2Dto { @@ -42,11 +55,12 @@ export class UpsertClaimPriceDropV2Dto { @IsString() carModel?: string; - @ApiProperty({ + @ApiPropertyOptional({ example: 450000000, - description: "Market price of the car (Toman)", + description: + "Market price of the damaged car in Rials. Required for calculation; optional for manual override.", }) - carPrice: number | string; + carPrice?: number | string; @ApiPropertyOptional({ example: 1394, @@ -57,15 +71,27 @@ export class UpsertClaimPriceDropV2Dto { @IsNumber() carModelYear?: number; - @ApiProperty({ + @ApiPropertyOptional({ + description: + "Vehicle age at the accident. Ages above ten are ineligible for depreciation, including manual overrides, and save zero. Otherwise derived from Jalali accident year minus model year.", + minimum: 0, + example: 3, + }) + @IsOptional() + @IsInt() + @Min(0) + vehicleAge?: number; + + @ApiPropertyOptional({ type: [PriceDropPartSeverityV2Dto], description: "One row per damaged part on the claim; coefficients come from the price-drop table × severity.", }) + @IsOptional() @IsArray() @ValidateNested({ each: true }) @Type(() => PriceDropPartSeverityV2Dto) - partSeverities: PriceDropPartSeverityV2Dto[]; + partSeverities?: PriceDropPartSeverityV2Dto[]; @ApiPropertyOptional({ description: @@ -94,6 +120,42 @@ export class ClaimPriceDropContextV2Dto { }) suggestedCarModelYear?: number | null; + @ApiPropertyOptional() + accidentYear?: number | null; + + @ApiPropertyOptional() + suggestedVehicleAge?: number | null; + + @ApiPropertyOptional() + inquiryVehicleAge?: number | null; + + @ApiPropertyOptional({ + description: + "False when the damaged vehicle is older than ten at the accident.", + }) + depreciationEligible?: boolean | null; + + @ApiPropertyOptional() + ineligibilityReason?: string | null; + + @ApiProperty() + calculationVersion: string; + + @ApiProperty() + ageTableEffectiveFrom: string; + + @ApiPropertyOptional() + calculationUnavailableReason?: string | null; + + @ApiProperty({ + description: "Fanavaran age codes and coefficients for ages 0–10", + }) + ageCatalog: Array<{ + vehicleAge: number; + fanavaranAgeId: number; + coefficient: number; + }>; + @ApiPropertyOptional() priceDrop?: Record; diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index 6ebc141..84c6e52 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -55,9 +55,18 @@ import { buildDamagedPartsPriceDropLines, buildPriceDropCatalogForApi, calculateClaimPriceDrop, + calculatePriceDropForVehicleAge, + parsePriceDropNumber, PRICE_DROP_SEVERITY_OPTIONS, resolveVehicleModelYearFromBlame, + resolvePriceDropAccidentYear, + resolvePriceDropAccidentDate, + normalizePriceDropSelectedParts, + resolveClaimPriceDropAge, + buildAgeIneligiblePriceDrop, + PRICE_DROP_AGE_INELIGIBLE_MESSAGE, } from "src/helpers/claim-price-drop"; +import { FANAVARAN_PRICE_DROP_AGES, FANAVARAN_PRICE_DROP_VERSION, FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM } from "src/static/fanavaran-price-drop"; import { claimCaseStatusAfterExpertReplyV2, claimIsAwaitingExpertFactorValidationV2, @@ -4472,19 +4481,21 @@ export class ExpertClaimService { await this.assertExpertCanEditClaimDuringReviewV2(claim, actor); const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined; - const selectedNorm = normalizeDamageSelectedParts( + const selectedNorm = normalizePriceDropSelectedParts( claim.damage?.selectedParts, carType, (claim.damage as any)?.selectedOuterParts, ); let suggestedCarModelYear: number | null = null; + let accidentYear: number | null = null; + let calculationUnavailableReason: string | null = null; if (claim.blameRequestId) { const blameRows = await this.blameRequestDbService.find( { _id: new Types.ObjectId(claim.blameRequestId.toString()) }, { lean: true, - select: "parties.role parties.person.userId parties.vehicle.inquiry", + select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate", }, ); const blame = blameRows[0] as Record | undefined; @@ -4492,9 +4503,17 @@ export class ExpertClaimService { claim, blame as Parameters[1], ); + accidentYear = resolvePriceDropAccidentYear(blame); + const accidentDate = resolvePriceDropAccidentDate(blame); + if (accidentDate && accidentDate < FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM) { + calculationUnavailableReason = "جدول سن ارسالی فناوران از ۱۴۰۴/۰۵/۲۸ معتبر است. برای حادثه پیش از این تاریخ مبلغ افت قیمت را دستی ثبت کنید."; + } } const existing = (claim as any).evaluation?.priceDrop; + const knownAges = [existing?.vehicleAge, suggestedCarModelYear != null && accidentYear != null ? accidentYear - suggestedCarModelYear : null] + .filter(age => Number.isInteger(age) && age >= 0); + const vehicleAge = knownAges.some(age => age > 10) ? Math.max(...knownAges) : existing?.vehicleAge ?? knownAges[0] ?? null; return { claimRequestId: String(claim._id), @@ -4504,6 +4523,17 @@ export class ExpertClaimService { carType: claim.vehicle?.carType, }, suggestedCarModelYear, + accidentYear, + suggestedVehicleAge: vehicleAge, + inquiryVehicleAge: suggestedCarModelYear != null && accidentYear != null ? accidentYear - suggestedCarModelYear : null, + depreciationEligible: vehicleAge == null ? null : vehicleAge <= 10, + ineligibilityReason: vehicleAge != null && vehicleAge > 10 ? PRICE_DROP_AGE_INELIGIBLE_MESSAGE : null, + calculationVersion: FANAVARAN_PRICE_DROP_VERSION, + ageTableEffectiveFrom: FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM, + calculationUnavailableReason, + ageCatalog: FANAVARAN_PRICE_DROP_AGES.map(row => ({ + vehicleAge: row.age, fanavaranAgeId: row.id, coefficient: row.coefficient, + })), priceDrop: existing ?? null, severityOptions: PRICE_DROP_SEVERITY_OPTIONS, priceDropCatalog: buildPriceDropCatalogForApi(), @@ -4533,18 +4563,71 @@ export class ExpertClaimService { vehicleSet["vehicle.carModel"] = String(body.carModel).trim(); } + let carModelYear = body.carModelYear; + if (carModelYear != null && (!Number.isInteger(carModelYear) || carModelYear < 1300 || carModelYear >= 1500)) { + throw new BadRequestException("سال ساخت باید یک سال شمسی معتبر باشد؛ برای سال میلادی، سن خودرو در زمان حادثه را وارد کنید."); + } + let accidentYear: number | null = null; + let blame: any = null; + let accidentDate: string | null = null; + if (claim.blameRequestId) { + const blameRows = await this.blameRequestDbService.find( + { _id: new Types.ObjectId(claim.blameRequestId.toString()) }, + { + lean: true, + select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate", + }, + ); + carModelYear ??= + resolveVehicleModelYearFromBlame( + claim, + blameRows[0] as Parameters< + typeof resolveVehicleModelYearFromBlame + >[1], + ) ?? undefined; + blame = blameRows[0]; + accidentYear = resolvePriceDropAccidentYear(blame); + accidentDate = resolvePriceDropAccidentDate(blame); + } + if (body.vehicleAge != null && (!Number.isInteger(body.vehicleAge) || body.vehicleAge < 0)) { + throw new BadRequestException("سن خودرو در زمان حادثه باید عددی صحیح و نامنفی باشد."); + } + const enteredAge = body.vehicleAge ?? (carModelYear != null && accidentYear != null ? accidentYear - carModelYear : undefined); + const vehicleAge = resolveClaimPriceDropAge(claim, blame, enteredAge); + if (vehicleAge != null && vehicleAge > 10) { + if (body.manualPriceDrop != null && body.manualPriceDrop !== 0) { + throw new BadRequestException(PRICE_DROP_AGE_INELIGIBLE_MESSAGE); + } + const priceDrop = { + ...buildAgeIneligiblePriceDrop(vehicleAge, body.carPrice ?? (claim as any).evaluation?.priceDrop?.carPrice), + manualOverride: false, + partLines: [], + ...(accidentYear != null ? { accidentYear } : {}), + ...(carModelYear != null ? { carModel: carModelYear } : {}), + }; + await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { + $set: { ...vehicleSet, "evaluation.priceDrop": priceDrop }, + }); + return { claimRequestId, vehicle: claim.vehicle, priceDrop, partLines: [] }; + } + // Manual override path — expert knows the number, skip calculation entirely if (body.manualPriceDrop != null) { - if (!Number.isFinite(body.manualPriceDrop) || body.manualPriceDrop < 0) { + if (!Number.isSafeInteger(body.manualPriceDrop) || body.manualPriceDrop < 0) { throw new BadRequestException( - "manualPriceDrop must be a non-negative finite number.", + "مبلغ افت قیمت باید عددی صحیح و نامنفی به ریال باشد.", ); } - // Manual path — change totalPriceDrop → total to match calculated path + if (body.manualPriceDrop > 0 && vehicleAge == null) { + throw new BadRequestException("برای ثبت افت قیمت، سن خودرو در زمان حادثه را مشخص کنید."); + } const manualPayload = { + ...(vehicleAge != null ? { vehicleAge, eligible: true } : {}), manualOverride: true, - total: body.manualPriceDrop, // ← was totalPriceDrop + total: parsePriceDropNumber(body.manualPriceDrop), + carPrice: body.carPrice != null ? parsePriceDropNumber(body.carPrice) + : (claim as any).evaluation?.priceDrop?.carPrice, partLines: [], }; @@ -4568,8 +4651,11 @@ export class ExpertClaimService { }; } - // Calculated path — existing logic unchanged - // At the top of the calculated path, after the manualPriceDrop early return: + if (accidentDate && accidentDate < FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM) { + throw new BadRequestException("جدول سن ارسالی فناوران از ۱۴۰۴/۰۵/۲۸ معتبر است. برای حادثه پیش از این تاریخ مبلغ افت قیمت را دستی ثبت کنید."); + } + + // An explicit part list is required when replacing a manual correction. const existingPriceDrop = (claim as any).evaluation?.priceDrop; if ( existingPriceDrop?.manualOverride === true && @@ -4582,38 +4668,24 @@ export class ExpertClaimService { } const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined; - const selectedNorm = normalizeDamageSelectedParts( + const selectedNorm = normalizePriceDropSelectedParts( claim.damage?.selectedParts, carType, (claim.damage as any)?.selectedOuterParts, ); - if (!body.partSeverities?.length) { + if (!Array.isArray(body.partSeverities) || !body.partSeverities.length) { throw new BadRequestException( - "Provide at least one partSeverities line, or use manualPriceDrop for a direct override.", + "شدت آسیب حداقل یک قطعه را انتخاب کنید یا مبلغ نهایی افت قیمت را دستی ثبت کنید.", ); } + if (body.partSeverities.some(p => !p || typeof p !== "object")) { + throw new BadRequestException("فهرست قطعات افت قیمت معتبر نیست. گروه قطعات و شدت آسیب را دوباره انتخاب کنید."); + } - let carModelYear = body.carModelYear; - if (carModelYear == null && claim.blameRequestId) { - const blameRows = await this.blameRequestDbService.find( - { _id: new Types.ObjectId(claim.blameRequestId.toString()) }, - { - lean: true, - select: "parties.role parties.person.userId parties.vehicle.inquiry", - }, - ); - carModelYear = - resolveVehicleModelYearFromBlame( - claim, - blameRows[0] as Parameters< - typeof resolveVehicleModelYearFromBlame - >[1], - ) ?? undefined; - } - if (carModelYear == null || !Number.isFinite(carModelYear)) { + if (body.vehicleAge == null && (carModelYear == null || accidentYear == null)) { throw new BadRequestException( - "carModelYear is required when it cannot be resolved from the linked blame plate inquiry.", + "سن خودرو در زمان حادثه را وارد کنید؛ سال ساخت یا تاریخ حادثه برای محاسبه سن در دسترس نیست.", ); } @@ -4622,6 +4694,7 @@ export class ExpertClaimService { body.partSeverities.map((p) => ({ partId: p.partId, severity: p.severity, + fanavaranPartId: p.fanavaranPartId, })), carType, ); @@ -4634,14 +4707,17 @@ export class ExpertClaimService { ); } - const calculated = calculateClaimPriceDrop( - body.carPrice, - carModelYear, - coefficients, - ); + const calculated = body.vehicleAge != null + ? { + ...calculatePriceDropForVehicleAge(body.carPrice, body.vehicleAge, coefficients), + ...(carModelYear != null ? { carModel: carModelYear } : {}), + ...(accidentYear != null ? { accidentYear } : {}), + } + : calculateClaimPriceDrop(body.carPrice, carModelYear!, coefficients, accidentYear!); const priceDropPayload = { ...calculated, + manualOverride: false, partLines: lines, }; diff --git a/src/expert-claim/expert-claim.v2.controller.ts b/src/expert-claim/expert-claim.v2.controller.ts index 3bde4cd..8c8a423 100644 --- a/src/expert-claim/expert-claim.v2.controller.ts +++ b/src/expert-claim/expert-claim.v2.controller.ts @@ -277,7 +277,7 @@ export class ExpertClaimV2Controller { @ApiOperation({ summary: "Price-drop context for manual expert entry (V2)", description: - "While the claim is locked in EXPERT_REVIEWING: severity labels (جزیی / متوسط / شدید), coefficient catalog, damaged parts with price-drop mapping, suggested Jalali year from linked blame plate inquiry (`ModelField` / `ModelCii`), and saved `evaluation.priceDrop` if any.", + "While locked in EXPERT_REVIEWING: Fanavaran depreciation categories, severity/age codes and coefficients, suggested mappings for selected damaged parts, damaged vehicle model year, accident year, suggested vehicle age, and saved evaluation.priceDrop. Part/category codes are separate from tenant car-component IDs.", }) @ApiParam({ name: "claimRequestId" }) @ApiResponse({ status: 200, type: ClaimPriceDropContextV2Dto }) @@ -295,7 +295,7 @@ export class ExpertClaimV2Controller { @ApiOperation({ summary: "Calculate and save price drop (V2)", description: - "Expert supplies car market price, optional `vehicle.carName` / `vehicle.carModel`, per-damaged-part severity (`partId` from claim detail), and optional `carModelYear` (defaults from blame inquiry). Persists `evaluation.priceDrop` using `(carPrice × yearCoefficient × sumOfCoefficients) / 400`.", + "Expert supplies car market price in Rials, vehicleAge at accident or Jalali carModelYear, and per-damaged-part severity with optional explicit Fanavaran category. Ages 0–10 use (carPrice × ageCoefficient × sumOfCoefficients) / 400; vehicles older than ten are ineligible and save zero. Positive manual overrides require an eligible age. Saves category/severity/age codes and preserves historical results until explicitly recalculated.", }) @ApiParam({ name: "claimRequestId" }) @ApiBody({ type: UpsertClaimPriceDropV2Dto }) diff --git a/src/helpers/claim-price-drop.spec.ts b/src/helpers/claim-price-drop.spec.ts index 746408f..88b7b9b 100644 --- a/src/helpers/claim-price-drop.spec.ts +++ b/src/helpers/claim-price-drop.spec.ts @@ -1,11 +1,35 @@ import { buildCoefficientsFromPartSeverities, calculateClaimPriceDrop, + calculatePriceDropForVehicleAge, + buildPriceDropCatalogForApi, + resolvePriceDropAccidentYear, + normalizePriceDropSelectedParts, resolvePriceDropPartKeyFromDamagePart, resolveVehicleModelYearFromBlame, } from "./claim-price-drop"; describe("claim-price-drop", () => { + it("keeps separate labels for non-catalog internal rows without IDs", () => { + const parts = normalizePriceDropSelectedParts([ + { + id: null, + name: "محفظه داخلی اختصاصی", + side: "internal", + label_fa: "محفظه داخلی اختصاصی", + }, + { + id: null, + name: "قاب داخلی اختصاصی", + side: "internal", + label_fa: "قاب داخلی اختصاصی", + }, + ]); + expect(parts.map((part) => part.label_fa)).toEqual([ + "محفظه داخلی اختصاصی", + "قاب داخلی اختصاصی", + ]); + }); it("maps catalog segment to price drop key", () => { expect( resolvePriceDropPartKeyFromDamagePart({ @@ -22,7 +46,7 @@ describe("claim-price-drop", () => { }); it("calculates total from formula", () => { - const r = calculateClaimPriceDrop(400_000_000, 1394, [2, 3]); + const r = calculateClaimPriceDrop(400_000_000, 1394, [2, 3], 1403); expect(r.sumOfSeverity).toBe(5); expect(r.coefficientYear).toBe(2.1); expect(r.total).toBe((400_000_000 * 2.1 * 5) / 400); @@ -32,6 +56,7 @@ describe("claim-price-drop", () => { const year = resolveVehicleModelYearFromBlame( { owner: { userId: "u1" } }, { + type: "CAR_BODY", parties: [ { role: "FIRST", @@ -80,4 +105,250 @@ describe("claim-price-drop", () => { expect(coefficients).toEqual([3]); expect(lines[0]?.partId).toBe(201); }); + + it.each([ + [0, 1, 3, 15_000_000], + [1, 2, 2.9, 14_500_000], + [2, 3, 2.8, 14_000_000], + [3, 4, 2.7, 13_500_000], + [4, 5, 2.6, 13_000_000], + [5, 6, 2.5, 12_500_000], + [6, 7, 2.4, 12_000_000], + [7, 8, 2.3, 11_500_000], + [8, 9, 2.2, 11_000_000], + [9, 10, 2.1, 10_500_000], + [10, 11, 2.05, 10_250_000], + ])( + "uses age %s and its exact Fanavaran code/coefficient", + (age, id, coefficient, total) => { + expect( + calculatePriceDropForVehicleAge(400_000_000, age, [2, 3]), + ).toMatchObject({ + vehicleAge: age, + fanavaranAgeId: id, + coefficientYear: coefficient, + total, + }); + }, + ); + + it.each([-1, 1.5, NaN, Infinity, "3", null])( + "does not invent an age coefficient for %s", + (age) => { + expect(() => + calculatePriceDropForVehicleAge(400_000_000, age as number, [3]), + ).toThrow("سن خودرو"); + }, + ); + + it.each([11, 12, 30])( + "age %s is excluded with zero depreciation and no invented Fanavaran code", + (age) => { + expect( + calculatePriceDropForVehicleAge(400_000_000, age, [7]), + ).toMatchObject({ + total: 0, + vehicleAge: age, + eligible: false, + fanavaranAgeId: null, + coefficientYear: null, + exclusionReason: "VEHICLE_AGE_OVER_TEN", + }); + }, + ); + + it("ages a model year relative to the accident, not the wall clock", () => { + expect(calculateClaimPriceDrop(400_000_000, 1402, [5], 1405)).toMatchObject( + { vehicleAge: 3, coefficientYear: 2.7, total: 13_500_000 }, + ); + expect(calculateClaimPriceDrop(400_000_000, 1402, [5], 1403)).toMatchObject( + { vehicleAge: 1, coefficientYear: 2.9 }, + ); + }); + + it("has 17 depreciation categories and exactly 49 severity codes, separate from car-component IDs", () => { + const catalog = buildPriceDropCatalogForApi(); + expect(catalog.map((row) => row.fanavaranPartId)).toEqual( + Array.from({ length: 17 }, (_, i) => i + 1), + ); + expect(catalog.flatMap((row) => Object.values(row.severityCodes))).toEqual( + Array.from({ length: 49 }, (_, i) => i + 1), + ); + expect(catalog.find((row) => row.key === "backTray")).toMatchObject({ + fanavaranPartId: 13, + severities: { Minor: 1, Moderate: 2, Severe: 3 }, + }); + expect(catalog.find((row) => row.key === "trunkFloorTray")).toMatchObject({ + fanavaranPartId: 14, + severities: { Minor: 2, Moderate: 4, Severe: 5 }, + }); + expect(catalog.find((row) => row.key === "cylinderBlock")).toMatchObject({ + fanavaranPartId: 17, + severities: { Severe: 3 }, + severityCodes: { Severe: 49 }, + }); + }); + + it.each([ + "سپر جلو", + "سپر عقب", + "شيشه پنجره درب جلو سمت راننده", + "قاب ستون", + "متعلقات سقف", + "موتور و متعلقات (به غیر از سیلندر)", + ])("does not silently assign a depreciation category to %s", (label) => { + expect( + resolvePriceDropPartKeyFromDamagePart({ name: "101", label_fa: label }), + ).toBeNull(); + }); + + it("distinguishes rear tray, trunk-floor tray and cylinder block across Persian spellings", () => { + expect( + resolvePriceDropPartKeyFromDamagePart({ label_fa: "سيني عقب" }), + ).toBe("backTray"); + expect( + resolvePriceDropPartKeyFromDamagePart({ label_fa: "سيني كف صندوق" }), + ).toBe("trunkFloorTray"); + expect( + resolvePriceDropPartKeyFromDamagePart({ + name: "backtray", + label_fa: "سيني كف صندوق", + }), + ).toBe("trunkFloorTray"); + expect( + resolvePriceDropPartKeyFromDamagePart({ + name: "frontdoor", + label_fa: "شیشه درب جلو", + }), + ).toBeNull(); + expect( + resolvePriceDropPartKeyFromDamagePart({ label_fa: "بلوکه سيلندر" }), + ).toBe("cylinderBlock"); + }); + + const unknown = [ + { + id: 9876, + name: "9876", + side: "", + label_fa: "قطعه اختصاصی شرکت", + catalogKey: "9876", + }, + ]; + it("lets the expert map an unknown tenant part explicitly without changing its ID", () => { + expect( + buildCoefficientsFromPartSeverities(unknown, [ + { partId: 9876, fanavaranPartId: 14, severity: "Moderate" }, + ]), + ).toMatchObject({ + coefficients: [4], + errors: [], + lines: [ + { + partId: 9876, + fanavaranPartId: 14, + fanavaranSeverityId: 41, + coefficient: 4, + }, + ], + }); + }); + + it.each(["Minor", "Moderate"])( + "rejects cylinder-block severity %s", + (severity) => { + expect( + buildCoefficientsFromPartSeverities(unknown, [ + { partId: 9876, fanavaranPartId: 17, severity: severity as any }, + ]).errors, + ).toEqual([expect.stringContaining("تعریف نشده")]); + }, + ); + + it("rejects unselected parts even when they exist in the global tenant snapshot", () => { + expect( + buildCoefficientsFromPartSeverities(unknown, [ + { partId: 50, severity: "Severe" }, + ]).errors, + ).not.toHaveLength(0); + }); + + it("rejects duplicate part lines and invalid category codes", () => { + const row = { + partId: 9876, + fanavaranPartId: 14, + severity: "Moderate" as const, + }; + expect( + buildCoefficientsFromPartSeverities(unknown, [row, row]).errors, + ).toEqual([expect.stringContaining("فقط یک")]); + expect( + buildCoefficientsFromPartSeverities(unknown, [ + { ...row, fanavaranPartId: 999 }, + ]).errors, + ).not.toHaveLength(0); + }); + + it("uses the damaged vehicle model even when the owner is the guilty party or an expert", () => { + const blame = { + type: "THIRD_PARTY", + expert: { decision: { guiltyPartyId: "guilty" } }, + parties: [ + { + role: "FIRST", + person: { userId: "guilty" }, + vehicle: { inquiry: { mapped: { ModelField: "1395" } } }, + }, + { + role: "SECOND", + person: { userId: "damaged" }, + vehicle: { inquiry: { mapped: { ModelField: "۱۴۰۳" } } }, + }, + ], + }; + expect( + resolveVehicleModelYearFromBlame({ owner: { userId: "guilty" } }, blame), + ).toBe(1403); + expect( + resolveVehicleModelYearFromBlame({ owner: { userId: "maker" } }, blame), + ).toBe(1403); + }); + + it("leaves a Gregorian model year for explicit expert age selection", () => { + const blame = { + type: "CAR_BODY", + parties: [ + { + role: "FIRST", + person: { userId: "a" }, + vehicle: { inquiry: { mapped: { ModelField: "2023" } } }, + }, + ], + }; + expect( + resolveVehicleModelYearFromBlame({ owner: { userId: "a" } }, blame), + ).toBeNull(); + }); + + it.each([ + "1405/09/02", + "۱۴۰۵/۰۹/۰۲", + "2026-11-23", + new Date("2026-11-23T12:00:00Z"), + ])("reads accident year from %s", (accidentDate) => { + expect( + resolvePriceDropAccidentYear({ + parties: [{ role: "FIRST", statement: { accidentDate } }], + }), + ).toBe(1405); + }); + + it("parses Rial grouping/Persian digits, rounds to whole Rials and rejects invalid money", () => { + expect(calculatePriceDropForVehicleAge("۴۰۰٬۰۰۰٬۰۰۰", 3, [5]).total).toBe( + 13_500_000, + ); + expect(calculatePriceDropForVehicleAge(101, 0, [3]).total).toBe(2); + for (const value of ["invalid", "", -1, NaN, Infinity, 1.2]) + expect(() => calculatePriceDropForVehicleAge(value, 0, [3])).toThrow(); + }); }); diff --git a/src/helpers/claim-price-drop.ts b/src/helpers/claim-price-drop.ts index 38b44be..b288b0b 100644 --- a/src/helpers/claim-price-drop.ts +++ b/src/helpers/claim-price-drop.ts @@ -1,13 +1,25 @@ -import { - ClaimVehicleTypeV2, -} from "src/static/outer-car-parts-catalog"; +import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog"; import { catalogPartIdFromSelectedPart, parseCatalogPartIdInput, - resolvePartForExpertReply, + resolveSelectedPartByPartId, + normalizeDamageSelectedParts, type DamageSelectedPartV2, } from "src/helpers/outer-damage-parts"; +import { BadRequestException } from "@nestjs/common"; +import { + FANAVARAN_PRICE_DROP_PARTS, + FANAVARAN_PRICE_DROP_AGES, + FANAVARAN_PRICE_DROP_VERSION, +} from "src/static/fanavaran-price-drop"; +import { + normalizeMoneyAmountString, + normalizeUnicodeDigitsToEnglish, +} from "src/utils/unicode-digits"; +import { resolveClaimVehicleSources } from "./claim-vehicle-identity"; +import { toJalaliDate } from "./date-jalali"; + /** Canonical severity values for expert input (API). */ export type PriceDropSeverity = "Minor" | "Moderate" | "Severe"; @@ -21,63 +33,21 @@ export const PRICE_DROP_SEVERITY_OPTIONS = ( Object.entries(PRICE_DROP_SEVERITY_FA) as [PriceDropSeverity, string][] ).map(([value, label_fa]) => ({ value, label_fa })); -/** Part → severity → coefficient (same table as V1 expert-claim). */ +/** Coefficients and IDs have one source: the supplied Fanavaran tables. */ export const PRICE_DROP_PART_TABLE: Record< string, - Partial> -> = { - backFender: { Minor: 2, Moderate: 3, Severe: 5 }, - backDoor: { Minor: 1, Moderate: 2, Severe: 3 }, - frontDoor: { Minor: 1, Moderate: 2, Severe: 3 }, - frontFender: { Minor: 1, Moderate: 2, Severe: 3 }, - frontBumper: { Minor: 1, Moderate: 2, Severe: 3 }, - Hood: { Minor: 2, moderate: 3, Severe: 4 }, - Trunk: { minor: 1, moderate: 3, Severe: 5 }, - Roof: { Minor: 3, Moderate: 5, Severe: 7 }, - coil: { Minor: 2, Moderate: 3, Severe: 4 }, - column: { Minor: 2, Moderate: 3, Severe: 4 }, - frontTray: { Minor: 1, Moderate: 2, Severe: 3 }, - backTray: { Minor: 2, moderate: 4, Severe: 5 }, - frontChassis: { Minor: 3, Moderate: 5, Severe: 7 }, - backChassis: { Minor: 2, Moderate: 4, Severe: 6 }, - carFootrest: { Minor: 1, Moderate: 2, Severe: 3 }, - carFloor: { Minor: 4, moderate: 6, Severe: 8 }, -}; - -/** Jalali model year → year coefficient (V1). */ -export const PRICE_DROP_YEAR_COEFFICIENT: Record = { - 1393: 2.05, - 1394: 2.1, - 1395: 2.2, - 1396: 2.3, - 1397: 2.4, - 1398: 2.5, - 1399: 2.6, - 1400: 2.7, - 1401: 2.8, - 1402: 2.9, - 1403: 3, - 1404: 3, -}; - -const PRICE_DROP_PART_LABEL_FA: Record = { - backFender: "گلگیر عقب", - backDoor: "در عقب", - frontDoor: "در جلو", - frontFender: "گلگیر جلو", - frontBumper: "سپر جلو", - Hood: "کاپوت", - Trunk: "صندوق عقب", - Roof: "سقف", - coil: "لوله", - column: "ستون", - frontTray: "سینی جلو", - backTray: "سینی عقب", - frontChassis: "شاسی جلو", - backChassis: "شاسی عقب", - carFootrest: "پا رکاب", - carFloor: "کف خودرو", -}; + Partial> +> = Object.fromEntries( + FANAVARAN_PRICE_DROP_PARTS.map((part) => [ + part.key, + Object.fromEntries( + Object.entries(part.levels).map(([severity, level]) => [ + severity, + level[1], + ]), + ), + ]), +); /** Catalog / damage `name` segments → price-drop part key. */ const SEGMENT_ALIASES: Record = { @@ -85,8 +55,6 @@ const SEGMENT_ALIASES: Record = { backdoor: "backDoor", frontdoor: "frontDoor", frontfender: "frontFender", - frontbumper: "frontBumper", - backbumper: "frontBumper", carhood: "Hood", hood: "Hood", cartrunk: "Trunk", @@ -100,6 +68,8 @@ const SEGMENT_ALIASES: Record = { backchassis: "backChassis", carfootrest: "carFootrest", carfloor: "carFloor", + trunkfloortray: "trunkFloorTray", + cylinderblock: "cylinderBlock", }; const NORM_TO_PART_KEY = new Map(); @@ -111,16 +81,16 @@ for (const [seg, key] of Object.entries(SEGMENT_ALIASES)) { } const PERSIAN_LABEL_ALIASES: Array<[string, string]> = [ + ["سینی کف صندوق", "trunkFloorTray"], + ["بلوکه سیلندر", "cylinderBlock"], + ["بلوک سیلندر", "cylinderBlock"], ["گلگیر عقب", "backFender"], ["درب عقب", "backDoor"], ["درب جلو", "frontDoor"], ["گلگیر جلو", "frontFender"], - ["سپر جلو", "frontBumper"], - ["سپر عقب", "frontBumper"], ["درب موتور", "Hood"], ["کاپوت", "Hood"], ["درب صندوق", "Trunk"], - ["صندوق عقب", "Trunk"], ["سقف", "Roof"], ["کلاف", "coil"], ["ستون", "column"], @@ -141,19 +111,21 @@ export function normalizePriceDropKey(str: string): string { function normalizePersianLabel(str: string): string { return String(str ?? "") .replace(/[يى]/g, "ی") + .replace(/[\u064b-\u065f]/g, "") .replace(/ك/g, "ک") .replace(/[\u200c\s()\-_]/g, "") .trim(); } export function parsePriceDropNumber(input: number | string): number { - if (typeof input === "number" && Number.isFinite(input)) return input; - return Number( - String(input) - .replace(/[۰-۹]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 1728)) - .replace(/,/g, "") - .trim(), - ); + const raw = normalizeMoneyAmountString(String(input ?? "")); + const value = /^\d+$/.test(raw) ? Number(raw) : NaN; + if (!Number.isSafeInteger(value) || value < 0) { + throw new BadRequestException( + "قیمت روز خودرو باید مبلغی معتبر و نامنفی به ریال باشد.", + ); + } + return value; } export function resolveSeverityCoefficient( @@ -171,51 +143,130 @@ export function resolveSeverityCoefficient( return undefined; } +/** Age is measured at the accident, never against a fixed production-year table. */ +export function calculatePriceDropForVehicleAge( + carPrice: number | string, + vehicleAge: number, + coefficients: number[], +) { + if (!Number.isInteger(vehicleAge) || vehicleAge < 0) { + throw new BadRequestException( + "سن خودرو در زمان حادثه باید عددی صحیح و نامنفی باشد.", + ); + } + if (vehicleAge > 10) return buildAgeIneligiblePriceDrop(vehicleAge, carPrice); + const ageRow = FANAVARAN_PRICE_DROP_AGES.find( + (row) => row.age === vehicleAge, + ); + if (!ageRow) + throw new BadRequestException("سن خودرو برای محاسبه افت قیمت معتبر نیست."); + if (coefficients.some((n) => !Number.isSafeInteger(n) || n < 0)) { + throw new BadRequestException( + "ضرایب آسیب برای محاسبه افت قیمت معتبر نیستند.", + ); + } + const price = parsePriceDropNumber(carPrice); + if (price <= 0) + throw new BadRequestException( + "قیمت روز خودرو برای محاسبه افت قیمت باید بیشتر از صفر ریال باشد.", + ); + const sumOfSeverity = coefficients.reduce((sum, n) => sum + n, 0); + // Work in integer hundredths for exact rounding to a whole Rial. + const numerator = + BigInt(price) * + BigInt(Math.round(ageRow.coefficient * 100)) * + BigInt(sumOfSeverity); + const total = Number((numerator + BigInt(20000)) / BigInt(40000)); + if (!Number.isSafeInteger(total)) + throw new BadRequestException( + "مبلغ محاسبه‌شده افت قیمت بیش از محدوده معتبر است.", + ); + return { + calculationVersion: FANAVARAN_PRICE_DROP_VERSION, + eligible: true, + carPrice: price, + vehicleAge, + fanavaranAgeId: ageRow.id, + carValue: coefficients, + sumOfSeverity, + coefficientYear: ageRow.coefficient, + total, + }; +} + +export const PRICE_DROP_AGE_INELIGIBLE_MESSAGE = + "خودروهای با سن بیشتر از ۱۰ سال مشمول افت قیمت نیستند و مبلغ افت قیمت آن‌ها باید صفر باشد."; + +export function buildAgeIneligiblePriceDrop( + vehicleAge: number, + carPrice?: number | string, +) { + return { + calculationVersion: FANAVARAN_PRICE_DROP_VERSION, + eligible: false, + exclusionReason: "VEHICLE_AGE_OVER_TEN", + vehicleAge, + ...(carPrice != null ? { carPrice: parsePriceDropNumber(carPrice) } : {}), + fanavaranAgeId: null, + coefficientYear: null, + carValue: [], + sumOfSeverity: 0, + total: 0, + }; +} + +/** A known age above ten cannot be bypassed with a lower age in the request. */ +export function resolveClaimPriceDropAge( + claim: any, + blame: any, + enteredAge?: number, +): number | null { + const year = resolveVehicleModelYearFromBlame(claim, blame); + const accidentYear = resolvePriceDropAccidentYear(blame); + const derivedAge = + year != null && accidentYear != null ? accidentYear - year : null; + const savedAge = claim?.evaluation?.priceDrop?.vehicleAge; + const valid = (value: unknown): value is number => + typeof value === "number" && Number.isInteger(value) && value >= 0; + if (valid(derivedAge) && derivedAge > 10) return derivedAge; + return [enteredAge, savedAge, derivedAge].find(valid) ?? null; +} + export function calculateClaimPriceDrop( carPrice: number | string, carModelYear: number, coefficients: number[], -): { - carPrice: number; - carModel: number; - carValue: number[]; - sumOfSeverity: number; - coefficientYear: number; - total: number; -} { - const normalizePrice = parsePriceDropNumber(carPrice); - const coefficient = PRICE_DROP_YEAR_COEFFICIENT[carModelYear] ?? 1; - const carValue = coefficients.filter((n) => Number.isFinite(n)); - const sumOfSeverity = carValue.reduce((a, c) => a + c, 0); - const total = (normalizePrice * coefficient * sumOfSeverity) / 400; - + accidentYear: number, +) { + if (!Number.isInteger(carModelYear) || !Number.isInteger(accidentYear)) { + throw new BadRequestException( + "سال ساخت و سال حادثه برای محاسبه سن خودرو معتبر نیستند.", + ); + } return { - carPrice: normalizePrice, + ...calculatePriceDropForVehicleAge( + carPrice, + accidentYear - carModelYear, + coefficients, + ), carModel: carModelYear, - carValue, - sumOfSeverity, - coefficientYear: coefficient, - total: total || 0, + accidentYear, }; } -export function buildPriceDropCatalogForApi(): Array<{ - key: string; - label_fa: string; - severities: Record; -}> { - return Object.keys(PRICE_DROP_PART_TABLE).map((key) => { - const row = PRICE_DROP_PART_TABLE[key]; - return { - key, - label_fa: PRICE_DROP_PART_LABEL_FA[key] ?? key, - severities: { - Minor: resolveSeverityCoefficient(key, "Minor"), - Moderate: resolveSeverityCoefficient(key, "Moderate"), - Severe: resolveSeverityCoefficient(key, "Severe"), - }, - }; - }); +export function buildPriceDropCatalogForApi() { + return FANAVARAN_PRICE_DROP_PARTS.map((part) => ({ + key: part.key, + label_fa: part.label, + fanavaranPartId: part.id, + severities: PRICE_DROP_PART_TABLE[part.key], + severityCodes: Object.fromEntries( + Object.entries(part.levels).map(([severity, level]) => [ + severity, + level[0], + ]), + ), + })); } export function resolvePriceDropPartKeyFromDamagePart(part: { @@ -223,6 +274,14 @@ export function resolvePriceDropPartKeyFromDamagePart(part: { catalogKey?: string; label_fa?: string; }): string | null { + // Current human captions take precedence over inconsistent legacy key names. + const normalizedLabel = normalizePersianLabel( + part.label_fa ?? part.name ?? "", + ); + for (const [label, key] of PERSIAN_LABEL_ALIASES) { + if (normalizedLabel.startsWith(normalizePersianLabel(label))) return key; + } + if (/^(شیشه|قاب|متعلقات|چراغ|آینه)/.test(normalizedLabel)) return null; const candidates: string[] = []; if (part.catalogKey) { for (const seg of String(part.catalogKey).split("_")) { @@ -237,10 +296,6 @@ export function resolvePriceDropPartKeyFromDamagePart(part: { if (hit && PRICE_DROP_PART_TABLE[hit]) return hit; } - const normalizedLabel = normalizePersianLabel(part.label_fa ?? part.name ?? ""); - for (const [label, key] of PERSIAN_LABEL_ALIASES) { - if (normalizedLabel.includes(normalizePersianLabel(label))) return key; - } return null; } @@ -253,6 +308,7 @@ export function buildDamagedPartsPriceDropLines( label_fa: string; priceDropPartKey: string | null; mappable: boolean; + fanavaranPartId: number | null; }> { return selectedParts.map((sp) => { const priceDropPartKey = resolvePriceDropPartKeyFromDamagePart(sp); @@ -263,53 +319,93 @@ export function buildDamagedPartsPriceDropLines( label_fa: sp.label_fa, priceDropPartKey, mappable: priceDropPartKey != null, + fanavaranPartId: + FANAVARAN_PRICE_DROP_PARTS.find((row) => row.key === priceDropPartKey) + ?.id ?? null, }; }); } -/** Resolve Jalali year from linked blame party inquiry (owner party preferred). */ -export function resolveVehicleModelYearFromBlame( - claim: { owner?: { userId?: unknown } }, - blame: { - parties?: Array<{ - role?: string; - person?: { userId?: unknown }; - vehicle?: { - inquiry?: { - mapped?: { ModelField?: unknown; ModelCii?: unknown }; - ModelField?: unknown; - ModelCii?: unknown; - }; - }; - }>; - } | null, -): number | null { - if (!blame?.parties?.length) return null; - const ownerId = - claim.owner?.userId != null ? String(claim.owner.userId) : ""; - let party = - blame.parties.find( - (p) => - ownerId && - p.person?.userId != null && - String(p.person.userId) === ownerId, - ) ?? blame.parties.find((p) => p.role === "FIRST"); - if (!party) party = blame.parties[0]; +/** Keep the tenant's saved caption when its ID collides with the legacy snapshot. */ +export function normalizePriceDropSelectedParts( + selectedParts: unknown, + carType?: ClaimVehicleTypeV2, + selectedOuterParts?: unknown, +): DamageSelectedPartV2[] { + const normalized = normalizeDamageSelectedParts( + selectedParts, + carType, + selectedOuterParts, + ); + const captured = Array.isArray(selectedParts) ? selectedParts : []; + return normalized.map((part) => { + if (part.id == null) return part; + const source = captured.find( + (row) => + row && + typeof row === "object" && + parseCatalogPartIdInput(row.id) === part.id && + typeof row.label_fa === "string" && + row.label_fa.trim(), + ); + return source ? { ...part, label_fa: source.label_fa.trim() } : part; + }); +} - const inquiry = party?.vehicle?.inquiry; - const mapped = inquiry?.mapped ?? inquiry; - const raw = - (mapped as { ModelField?: unknown })?.ModelField ?? - (mapped as { ModelCii?: unknown })?.ModelCii; - if (raw == null || raw === "") return null; - const n = - typeof raw === "number" ? raw : parseInt(String(raw).trim(), 10); - return Number.isFinite(n) ? n : null; +/** Always use the damaged vehicle, including expert-created claims whose owner is the maker. */ +export function resolveVehicleModelYearFromBlame( + claim: any, + blame: any, +): number | null { + const source = resolveClaimVehicleSources(claim, blame); + const records = [ + source.inquiry, + source.policy, + source.vehicle?.inquiry?.carBody?.mapped, + ]; + for (const record of records) { + for (const raw of [ + record?.ModelField, + record?.ModelCii, + record?.BuiltYear, + record?.CarModelYear, + ]) { + if (raw == null || raw === "") continue; + const text = normalizeUnicodeDigitsToEnglish(String(raw)).trim(); + const year = /^\d{4}$/.test(text) ? Number(text) : NaN; + // A Gregorian model year cannot be converted exactly without month/day. + if (Number.isInteger(year) && year >= 1300 && year < 1500) return year; + } + } + return null; +} + +export function resolvePriceDropAccidentDate(blame: any): string | null { + const date = + blame?.parties?.find((p: any) => p.role === "FIRST")?.statement + ?.accidentDate ?? + blame?.parties?.find((p: any) => p.statement?.accidentDate)?.statement + ?.accidentDate; + if (!date) return null; + if (!(date instanceof Date)) { + const text = normalizeUnicodeDigitsToEnglish(String(date)).trim(); + const match = text.match(/^(1[34]\d{2})[/-](\d{1,2})[/-](\d{1,2})$/); + if (match) + return `${match[1]}/${match[2].padStart(2, "0")}/${match[3].padStart(2, "0")}`; + } + const d = new Date(date); + return Number.isNaN(d.getTime()) ? null : toJalaliDate(d); +} + +export function resolvePriceDropAccidentYear(blame: any): number | null { + const date = resolvePriceDropAccidentDate(blame); + return date ? Number(date.split("/")[0]) : null; } export interface PriceDropPartSeverityInput { partId: number | string; severity: PriceDropSeverity; + fanavaranPartId?: number; } export function buildCoefficientsFromPartSeverities( @@ -324,6 +420,8 @@ export function buildCoefficientsFromPartSeverities( label_fa: string; severity: PriceDropSeverity; coefficient: number; + fanavaranPartId: number; + fanavaranSeverityId: number; }>; errors: string[]; } { @@ -334,50 +432,83 @@ export function buildCoefficientsFromPartSeverities( label_fa: string; severity: PriceDropSeverity; coefficient: number; + fanavaranPartId: number; + fanavaranSeverityId: number; }> = []; const errors: string[] = []; + const seen = new Set(); for (const row of partSeverities) { const catalogId = parseCatalogPartIdInput(row.partId); if (catalogId == null) { - errors.push(`Unknown partId "${row.partId}".`); + errors.push( + "قطعه انتخاب‌شده در فهرست قطعات آسیب‌دیده پرونده وجود ندارد.", + ); continue; } - const sp = resolvePartForExpertReply( - catalogId, - selectedParts, - carType, - ); + if (seen.has(catalogId)) { + errors.push("برای هر قطعه فقط یک شدت آسیب قابل ثبت است."); + continue; + } + seen.add(catalogId); + const sp = + resolveSelectedPartByPartId(catalogId, selectedParts) ?? + resolveSelectedPartByPartId( + catalogId, + normalizeDamageSelectedParts(selectedParts, carType), + ); if (!sp) { - errors.push(`Unknown partId "${row.partId}".`); + errors.push( + "قطعه انتخاب‌شده در فهرست قطعات آسیب‌دیده پرونده وجود ندارد.", + ); continue; } - const partKey = resolvePriceDropPartKeyFromDamagePart(sp); + const explicit = + row.fanavaranPartId != null + ? FANAVARAN_PRICE_DROP_PARTS.find( + (part) => part.id === row.fanavaranPartId, + ) + : undefined; + if (row.fanavaranPartId != null && !explicit) { + errors.push("کد گروه افت قیمت فناوران معتبر نیست."); + continue; + } + const partKey = explicit?.key ?? resolvePriceDropPartKeyFromDamagePart(sp); if (!partKey) { errors.push( - `Part "${row.partId}" (${sp.label_fa}) has no price-drop mapping.`, + `گروه افت قیمت قطعه «${sp.label_fa}» را از جدول فناوران انتخاب کنید.`, ); continue; } - const coef = resolveSeverityCoefficient(partKey, row.severity); + const category = FANAVARAN_PRICE_DROP_PARTS.find( + (part) => part.key === partKey, + )!; + const level = ( + category.levels as Partial< + Record + > + )[row.severity]; + const coef = level?.[1]; if (coef === undefined) { errors.push( - `Invalid severity "${row.severity}" for part key "${partKey}".`, + `شدت آسیب برای قطعه «${sp.label_fa}» در جدول فناوران تعریف نشده است.`, ); continue; } + const linePartId = catalogPartIdFromSelectedPart(sp); + if (linePartId == null) { + errors.push("کد قطعه آسیب‌دیده برای محاسبه افت قیمت مشخص نیست."); + continue; + } coefficients.push(coef); - const linePartId = catalogPartIdFromSelectedPart(sp); - if (linePartId == null) { - errors.push(`Part "${row.partId}" has no catalog id.`); - continue; - } lines.push({ partId: linePartId, priceDropPartKey: partKey, label_fa: sp.label_fa, severity: row.severity, coefficient: coef, + fanavaranPartId: category.id, + fanavaranSeverityId: level![0], }); } diff --git a/src/static/fanavaran-price-drop.ts b/src/static/fanavaran-price-drop.ts new file mode 100644 index 0000000..2e07dee --- /dev/null +++ b/src/static/fanavaran-price-drop.ts @@ -0,0 +1,123 @@ +/** Transcribed from docs/ضرایب افت قیمت.xlsx; these are NOT car-component IDs. */ +export const FANAVARAN_PRICE_DROP_PARTS = [ + { + key: "Roof", + id: 1, + label: "سقف", + levels: { Minor: [1, 3], Moderate: [2, 5], Severe: [3, 7] }, + }, + { + key: "coil", + id: 2, + label: "کلاف", + levels: { Minor: [4, 2], Moderate: [5, 3], Severe: [6, 4] }, + }, + { + key: "column", + id: 3, + label: "ستون", + levels: { Minor: [7, 2], Moderate: [8, 3], Severe: [9, 4] }, + }, + { + key: "Hood", + id: 4, + label: "درب موتور", + levels: { Minor: [10, 2], Moderate: [11, 3], Severe: [12, 4] }, + }, + { + key: "frontTray", + id: 5, + label: "سینی جلو", + levels: { Minor: [13, 1], Moderate: [14, 2], Severe: [15, 3] }, + }, + { + key: "frontChassis", + id: 6, + label: "شاسی جلو", + levels: { Minor: [16, 3], Moderate: [17, 5], Severe: [18, 7] }, + }, + { + key: "frontFender", + id: 7, + label: "گلگیر جلو", + levels: { Minor: [19, 1], Moderate: [20, 2], Severe: [21, 3] }, + }, + { + key: "frontDoor", + id: 8, + label: "درب جلو", + levels: { Minor: [22, 1], Moderate: [23, 2], Severe: [24, 3] }, + }, + { + key: "backDoor", + id: 9, + label: "درب عقب", + levels: { Minor: [25, 1], Moderate: [26, 2], Severe: [27, 3] }, + }, + { + key: "carFootrest", + id: 10, + label: "رکاب", + levels: { Minor: [28, 1], Moderate: [29, 2], Severe: [30, 3] }, + }, + { + key: "backFender", + id: 11, + label: "گلگیر عقب", + levels: { Minor: [31, 2], Moderate: [32, 3], Severe: [33, 5] }, + }, + { + key: "Trunk", + id: 12, + label: "درب صندوق", + levels: { Minor: [34, 1], Moderate: [35, 3], Severe: [36, 5] }, + }, + { + key: "backTray", + id: 13, + label: "سینی عقب", + levels: { Minor: [37, 1], Moderate: [38, 2], Severe: [39, 3] }, + }, + { + key: "trunkFloorTray", + id: 14, + label: "سینی کف صندوق", + levels: { Minor: [40, 2], Moderate: [41, 4], Severe: [42, 5] }, + }, + { + key: "backChassis", + id: 15, + label: "شاسی عقب", + levels: { Minor: [43, 2], Moderate: [44, 4], Severe: [45, 6] }, + }, + { + key: "carFloor", + id: 16, + label: "کف اتاق", + levels: { Minor: [46, 4], Moderate: [47, 6], Severe: [48, 8] }, + }, + { + key: "cylinderBlock", + id: 17, + label: "بلوک سیلندر", + levels: { Severe: [49, 3] }, + }, +] as const; + +/** docs/افت قیمت سن.png: age, computer code, coefficient. No >10 row exists. */ +export const FANAVARAN_PRICE_DROP_AGES = [ + { age: 0, id: 1, coefficient: 3 }, + { age: 1, id: 2, coefficient: 2.9 }, + { age: 2, id: 3, coefficient: 2.8 }, + { age: 3, id: 4, coefficient: 2.7 }, + { age: 4, id: 5, coefficient: 2.6 }, + { age: 5, id: 6, coefficient: 2.5 }, + { age: 6, id: 7, coefficient: 2.4 }, + { age: 7, id: 8, coefficient: 2.3 }, + { age: 8, id: 9, coefficient: 2.2 }, + { age: 9, id: 10, coefficient: 2.1 }, + { age: 10, id: 11, coefficient: 2.05 }, +] as const; + +export const FANAVARAN_PRICE_DROP_VERSION = "fanavaran-v1"; +export const FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM = "1404/05/28";