forked from Yara724/api
Compare commits
2
Commits
3bf6fcc8b0
...
036d218ebd
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
036d218ebd | ||
|
|
c74b29337e |
@@ -19,7 +19,7 @@ Content-Type: application/json
|
||||
|
||||
## بدنه درخواست
|
||||
|
||||
تمام مبلغها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته میشوند؛ برای نمونه هر دو مقدار `"100000"` و `"۱۰۰,۰۰۰"` معتبرند.
|
||||
تمام مبلغها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته میشوند؛ برای نمونه هر دو مقدار `"1000000"` و `"۱۰۰,۰۰۰"` معتبرند.
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -29,12 +29,12 @@ Content-Type: application/json
|
||||
"partId": 201,
|
||||
"typeOfDamage": "تعویض",
|
||||
"price": "2500000",
|
||||
"salary": "400000",
|
||||
"totalPayment": "2900000",
|
||||
"salary": "1000000",
|
||||
"totalPayment": "3500000",
|
||||
"factorNeeded": false,
|
||||
"daghi": {
|
||||
"option": "ارزش لوازم بازیافتی",
|
||||
"price": "300000"
|
||||
"price": "1000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -54,21 +54,29 @@ Content-Type: application/json
|
||||
| --- | --- | --- |
|
||||
| `partId` | بله | عدد صحیح؛ باید متعلق به قطعات آسیبدیده همان پرونده باشد. |
|
||||
| `typeOfDamage` | بله | دقیقاً یکی از `"تعمیر"` یا `"تعویض"`. |
|
||||
| `price` | برای `"تعویض"` بله؛ برای `"تعمیر"` اختیاری | در صورت ارسال، مبلغ بین 100,000 تا 10,000,000,000 تومان. |
|
||||
| `salary` | بله | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
|
||||
| `price` | فقط تعویض با قیمت قطعی | برای ردیف `factorNeeded=true` قیمت قطعه ارسال نشود؛ متن `factor` یا `فاکتور` مبلغ نیست. در صورت ارسال مبلغ، بازه 1,000,000 تا 100,000,000,000 ریال معتبر است. |
|
||||
| `salary` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
|
||||
| `totalPayment` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. فقط در جریان V1، مجموع این فیلدها در کل پرونده نباید از 530,000,000 ریال بیشتر شود. |
|
||||
| `factorNeeded` | بله | مقدار Boolean واقعی (`true` یا `false`)؛ رشته ارسال نکنید. |
|
||||
| `factorNeeded` | بله | مقدار Boolean واقعی؛ فقط ردیف تعویض میتواند `true` باشد. در تعمیر باید `false` باشد. |
|
||||
| `daghi` | برای `"تعویض"` بله | برای `"تعمیر"` لازم نیست و در ثبت نهایی حذف میشود. |
|
||||
| `daghi.option` | در صورت وجود `daghi` بله | یکی از `"ارزش لوازم بازیافتی"`، `"تحویل داغی"`، `"فاقد ارزش"` یا `"با احتساب داغی"`. |
|
||||
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
|
||||
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
|
||||
| `daghi.branchId` | فقط وقتی `option` برابر `"تحویل داغی"` است | Mongo ObjectId معتبرِ شعبه. |
|
||||
|
||||
نکتهها:
|
||||
|
||||
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 100,000 تومان است.
|
||||
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 1,000,000 ریال است.
|
||||
- محدودیت هر فیلد مبلغ مستقل است؛ سقف 530 میلیون ریال فقط برای **مجموع `totalPayment` تمام ردیفهای پرونده V1** اعمال میشود. جریانهای V2 تا V6 سقف مجموع ندارند.
|
||||
- فیلدهای ناشناخته در body حذف میشوند. فرانتاند نباید برای انتقال داده به آنها تکیه کند.
|
||||
|
||||
### تغییر روش قیمتگذاری و خطاها
|
||||
|
||||
- انتخاب فاکتور، قیمت قطعی قطعه را پاک میکند؛ `salary` و `totalPayment` همچنان مبلغ عددی معتبر لازم دارند.
|
||||
- تبدیل تعویض به تعمیر، روش فاکتور، قیمت قطعه و اطلاعات داغی را یکجا پاک میکند و مجموع شناختهشده را از اجرت محاسبه میکند.
|
||||
- تبدیل فاکتور به قیمت، `factorNeeded` را خاموش و انتخاب قیمت جدید را الزامی میکند؛ قیمت قدیمی بهطور پنهان استفاده نمیشود.
|
||||
- خطای اعتبارسنجی، پرچم فاکتور یا وضعیت ذخیرهشده پرونده را تغییر نمیدهد. UI پیش از ذخیره تغییرات انتخاب قطعات، پیشاعتبارسنجی میکند و ارسال تکراری همزمان را مسدود میکند.
|
||||
- پیامهای خطای این مسیر با واحد ریال نمایش داده میشوند.
|
||||
|
||||
## پاسخ موفق
|
||||
|
||||
پاسخ `200` شامل مسیر بعدی workflow است. نمونه:
|
||||
@@ -106,7 +114,7 @@ Content-Type: application/json
|
||||
"validationErrors": [
|
||||
{
|
||||
"field": "parts[0].salary",
|
||||
"message": "باید مبلغ صحیح و غیرمنفی به تومان باشد."
|
||||
"message": "باید مبلغ صحیح و غیرمنفی به ریال باشد."
|
||||
},
|
||||
{
|
||||
"field": "parts[0].factorNeeded",
|
||||
@@ -125,14 +133,14 @@ Content-Type: application/json
|
||||
```json
|
||||
{
|
||||
"statusCode": 400,
|
||||
"message": "قیمت قطعه 201 باید حداقل ۱۰۰٬۰۰۰ و حداکثر ۱۰٬۰۰۰٬۰۰۰٬۰۰۰ تومان باشد.",
|
||||
"message": "قیمت قطعه 201 باید حداقل ۱٬۰۰۰٬۰۰۰ و حداکثر ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
|
||||
"error": "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
"code": "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
"field": "parts[0].price",
|
||||
"partId": "201",
|
||||
"rule": "amount_out_of_range",
|
||||
"minAmount": 100000,
|
||||
"maxAmount": 10000000000
|
||||
"minAmount": 1000000,
|
||||
"maxAmount": 100000000000
|
||||
}
|
||||
```
|
||||
|
||||
@@ -142,7 +150,7 @@ Content-Type: application/json
|
||||
| --- | --- |
|
||||
| `required` | فیلد لازم ارسال نشده است. |
|
||||
| `invalid_value` | مقدار enum یا شناسه معتبر نیست. |
|
||||
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به تومان نیست. |
|
||||
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به ریال نیست. |
|
||||
| `amount_out_of_range` | مبلغ خارج از بازه `minAmount` و `maxAmount` است. |
|
||||
|
||||
در صورت `amount_out_of_range`، برای نمایش محدوده از اعداد `minAmount` و `maxAmount` استفاده کنید، نه از parse کردن متن `message`.
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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.
|
||||
Binary file not shown.
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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.
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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<string, unknown>;
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ export class PartPricingV2Dto {
|
||||
|
||||
@ApiProperty({
|
||||
enum: TypeOfDamage,
|
||||
description: "'change' requires price; 'repair' may omit it.",
|
||||
description: "Replacement requires a part price unless factorNeeded=true. Repairs cannot request a part invoice.",
|
||||
})
|
||||
@IsEnum(TypeOfDamage)
|
||||
typeOfDamage: TypeOfDamage;
|
||||
@@ -58,11 +58,11 @@ export class PartPricingV2Dto {
|
||||
@ApiPropertyOptional({
|
||||
example: "5000000",
|
||||
description:
|
||||
"Required for change lines; omitted for repair lines. Every supplied amount must be between 1,000,000 and 100,000,000,000 Rial.",
|
||||
"Required for priced replacement lines; omit for repair lines and replacement lines awaiting an invoice (factorNeeded=true). Every supplied amount must be between 1,000,000 and 100,000,000,000 Rial.",
|
||||
})
|
||||
@ValidateIf(
|
||||
(part: PartPricingV2Dto) =>
|
||||
part.typeOfDamage === TypeOfDamage.Change ||
|
||||
(part.typeOfDamage === TypeOfDamage.Change && part.factorNeeded !== true) ||
|
||||
(part.price != null &&
|
||||
(typeof part.price !== 'string' || part.price.trim() !== '')),
|
||||
)
|
||||
@@ -106,7 +106,7 @@ export class PartPricingV2Dto {
|
||||
@ApiProperty({
|
||||
example: false,
|
||||
description:
|
||||
"If true, the owner must upload a repair factor image for this line; expert confirms cost later (validate-factors). Priced lines omit this or set false.",
|
||||
"Replacement lines only: if true, the owner uploads the part invoice and the expert confirms its cost later (validate-factors). Omit price in this mode. Repair lines must set false.",
|
||||
})
|
||||
@IsBoolean()
|
||||
factorNeeded: boolean;
|
||||
|
||||
@@ -84,6 +84,24 @@ const validV2Reply = {
|
||||
};
|
||||
|
||||
describe("ExpertClaimService expert-reply pricing", () => {
|
||||
it("saves a replacement invoice without a part price and enters the invoice upload workflow", async () => {
|
||||
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(BlameRequestType.THIRD_PARTY);
|
||||
const response = await service.submitExpertReplyV2("v2-claim", { parts: [{ partId: 1, typeOfDamage: TypeOfDamage.Change, salary: "1000000", totalPayment: "1000000", factorNeeded: true, daghi: { option: DaghiOption.NO_VALUE } }] }, { sub: V2_EXPERT_ID, role: RoleEnum.FIELD_EXPERT });
|
||||
expect(response).toMatchObject({ factorNeeded: true, allPartsFactorNeeded: true, currentStep: "OWNER_UPLOAD_FACTOR_DOCUMENTS" });
|
||||
const saved = findByIdAndUpdate.mock.calls[0][1]["evaluation.damageExpertReply"].parts[0];
|
||||
expect(saved.factorNeeded).toBe(true);
|
||||
expect(saved.price).toBeUndefined();
|
||||
});
|
||||
|
||||
it("a failed invoice/repair submission cannot persist flags or poison a subsequent priced repair", async () => {
|
||||
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(BlameRequestType.THIRD_PARTY);
|
||||
const actor = { sub: V2_EXPERT_ID, role: RoleEnum.FIELD_EXPERT };
|
||||
await expect(service.submitExpertReplyV2("v2-claim", { parts: [{ ...validV2Reply.parts[0], factorNeeded: true }] }, actor)).rejects.toMatchObject({ response: { field: "parts[0].factorNeeded" } });
|
||||
expect(findByIdAndUpdate).not.toHaveBeenCalled();
|
||||
const response = await service.submitExpertReplyV2("v2-claim", validV2Reply, actor);
|
||||
expect(response.factorNeeded).toBe(false);
|
||||
expect(findByIdAndUpdate.mock.calls[0][1]["evaluation.damageExpertReply"].parts[0].factorNeeded).toBe(false);
|
||||
});
|
||||
it("requires the current car price for a car-body expert reply", async () => {
|
||||
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(
|
||||
BlameRequestType.CAR_BODY,
|
||||
|
||||
@@ -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<string, unknown> | undefined;
|
||||
@@ -4492,9 +4503,17 @@ export class ExpertClaimService {
|
||||
claim,
|
||||
blame as Parameters<typeof resolveVehicleModelYearFromBlame>[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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -3,6 +3,41 @@ import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-d
|
||||
import { submitExpertReplyValidationPipe } from "./submit-expert-reply-validation.pipe";
|
||||
|
||||
describe("submitExpertReplyValidationPipe", () => {
|
||||
const replacementInvoice = {
|
||||
partId: 201,
|
||||
typeOfDamage: TypeOfDamage.Change,
|
||||
salary: "1000000",
|
||||
totalPayment: "1000000",
|
||||
factorNeeded: true,
|
||||
daghi: { option: "فاقد ارزش" },
|
||||
};
|
||||
|
||||
it("accepts replacement invoices without a numeric part quote", async () => {
|
||||
const result = await submitExpertReplyValidationPipe.transform(
|
||||
{ parts: [replacementInvoice] },
|
||||
{ type: "body", metatype: SubmitExpertReplyV2Dto },
|
||||
);
|
||||
expect(result.parts[0].factorNeeded).toBe(true);
|
||||
expect(result.parts[0].price).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([{ factorNeeded: false }, { price: "factor" }, { price: "فاکتور" }])(
|
||||
"continues rejecting absent priced quotes and nonnumeric price markers: %j",
|
||||
async (invalid) => {
|
||||
await expect(
|
||||
submitExpertReplyValidationPipe.transform(
|
||||
{ parts: [{ ...replacementInvoice, ...invalid }] },
|
||||
{ type: "body", metatype: SubmitExpertReplyV2Dto },
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
response: {
|
||||
validationErrors: expect.arrayContaining([
|
||||
expect.objectContaining({ field: "parts[0].price" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
it("converts DTO validation failures into Persian, field-addressable errors", async () => {
|
||||
await expect(
|
||||
submitExpertReplyValidationPipe.transform(
|
||||
@@ -61,7 +96,7 @@ describe("submitExpertReplyValidationPipe", () => {
|
||||
validationErrors: expect.arrayContaining([
|
||||
{
|
||||
field: "parts[0].salary",
|
||||
message: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
|
||||
message: "باید مبلغ صحیح و غیرمنفی به ریال باشد.",
|
||||
},
|
||||
]),
|
||||
},
|
||||
|
||||
@@ -18,7 +18,7 @@ const constraintMessages: Record<string, string> = {
|
||||
isInt: "باید یک عدد صحیح باشد.",
|
||||
isEnum: "مقدار واردشده معتبر نیست.",
|
||||
nestedValidation: "اطلاعات این بخش معتبر نیست.",
|
||||
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
|
||||
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به ریال باشد.",
|
||||
};
|
||||
|
||||
function flattenValidationErrors(
|
||||
@@ -31,11 +31,16 @@ function flattenValidationErrors(
|
||||
? `${parentPath}[${error.property}]`
|
||||
: `${parentPath}.${error.property}`
|
||||
: error.property;
|
||||
const ownErrors = Object.keys(error.constraints ?? {}).map((constraint) => ({
|
||||
field,
|
||||
message: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
|
||||
}));
|
||||
return [...ownErrors, ...flattenValidationErrors(error.children ?? [], field)];
|
||||
const ownErrors = Object.keys(error.constraints ?? {}).map(
|
||||
(constraint) => ({
|
||||
field,
|
||||
message: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
|
||||
}),
|
||||
);
|
||||
return [
|
||||
...ownErrors,
|
||||
...flattenValidationErrors(error.children ?? [], field),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
+295
-164
@@ -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<Record<string, number>>
|
||||
> = {
|
||||
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<number, number> = {
|
||||
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<string, string> = {
|
||||
backFender: "گلگیر عقب",
|
||||
backDoor: "در عقب",
|
||||
frontDoor: "در جلو",
|
||||
frontFender: "گلگیر جلو",
|
||||
frontBumper: "سپر جلو",
|
||||
Hood: "کاپوت",
|
||||
Trunk: "صندوق عقب",
|
||||
Roof: "سقف",
|
||||
coil: "لوله",
|
||||
column: "ستون",
|
||||
frontTray: "سینی جلو",
|
||||
backTray: "سینی عقب",
|
||||
frontChassis: "شاسی جلو",
|
||||
backChassis: "شاسی عقب",
|
||||
carFootrest: "پا رکاب",
|
||||
carFloor: "کف خودرو",
|
||||
};
|
||||
Partial<Record<PriceDropSeverity, number>>
|
||||
> = 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<string, string> = {
|
||||
@@ -85,8 +55,6 @@ const SEGMENT_ALIASES: Record<string, string> = {
|
||||
backdoor: "backDoor",
|
||||
frontdoor: "frontDoor",
|
||||
frontfender: "frontFender",
|
||||
frontbumper: "frontBumper",
|
||||
backbumper: "frontBumper",
|
||||
carhood: "Hood",
|
||||
hood: "Hood",
|
||||
cartrunk: "Trunk",
|
||||
@@ -100,6 +68,8 @@ const SEGMENT_ALIASES: Record<string, string> = {
|
||||
backchassis: "backChassis",
|
||||
carfootrest: "carFootrest",
|
||||
carfloor: "carFloor",
|
||||
trunkfloortray: "trunkFloorTray",
|
||||
cylinderblock: "cylinderBlock",
|
||||
};
|
||||
|
||||
const NORM_TO_PART_KEY = new Map<string, string>();
|
||||
@@ -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<PriceDropSeverity, number | undefined>;
|
||||
}> {
|
||||
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<number>();
|
||||
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<PriceDropSeverity, readonly [number, number]>
|
||||
>
|
||||
)[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],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,40 @@ import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-d
|
||||
import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum";
|
||||
|
||||
describe("getExpertReplyPricingValidationError", () => {
|
||||
const invoice = {
|
||||
partId: 201,
|
||||
typeOfDamage: TypeOfDamage.Change,
|
||||
factorNeeded: true,
|
||||
salary: "1000000",
|
||||
totalPayment: "1000000",
|
||||
daghi: { option: DaghiOption.NO_VALUE },
|
||||
};
|
||||
it("allows replacement invoices without a part price while validating known labor/total", () => {
|
||||
expect(
|
||||
getExpertReplyPricingValidationError([invoice], {
|
||||
locale: "fa",
|
||||
enforceAmountBounds: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
getExpertReplyPricingValidationError([{ ...invoice, salary: "bad" }], {
|
||||
locale: "fa",
|
||||
enforceAmountBounds: true,
|
||||
}),
|
||||
).toMatchObject({ field: "parts[0].salary" });
|
||||
});
|
||||
it("rejects repair plus invoice and non-boolean invoice flags", () => {
|
||||
for (const part of [
|
||||
{ ...invoice, typeOfDamage: TypeOfDamage.Repair },
|
||||
{ ...invoice, factorNeeded: "true" },
|
||||
])
|
||||
expect(
|
||||
getExpertReplyPricingValidationError([part], { locale: "fa" }),
|
||||
).toMatchObject({
|
||||
field: "parts[0].factorNeeded",
|
||||
rule: "invalid_value",
|
||||
});
|
||||
});
|
||||
it("rejects a blank pricing line", () => {
|
||||
expect(
|
||||
getExpertReplyPricingValidationError([
|
||||
|
||||
@@ -5,6 +5,7 @@ import { parseMoneyAmountToman } from "src/utils/unicode-digits";
|
||||
type ExpertReplyPricingPart = {
|
||||
partId?: unknown;
|
||||
typeOfDamage?: unknown;
|
||||
factorNeeded?: unknown;
|
||||
price?: unknown;
|
||||
salary?: unknown;
|
||||
totalPayment?: unknown;
|
||||
@@ -20,11 +21,7 @@ export type ExpertReplyPricingValidationError = {
|
||||
code: "EXPERT_REPLY_VALIDATION_ERROR";
|
||||
field: string;
|
||||
partId?: string | number;
|
||||
rule:
|
||||
| "required"
|
||||
| "invalid_value"
|
||||
| "invalid_amount"
|
||||
| "amount_out_of_range";
|
||||
rule: "required" | "invalid_value" | "invalid_amount" | "amount_out_of_range";
|
||||
minAmount?: number;
|
||||
maxAmount?: number;
|
||||
};
|
||||
@@ -102,6 +99,25 @@ export function getExpertReplyPricingValidationError(
|
||||
);
|
||||
}
|
||||
|
||||
if (part.factorNeeded != null && typeof part.factorNeeded !== "boolean") {
|
||||
return localizedError(
|
||||
"وضعیت نیاز به فاکتور باید درست یا نادرست باشد.",
|
||||
`parts[${index}].factorNeeded`,
|
||||
"invalid_value",
|
||||
String(part.partId),
|
||||
);
|
||||
}
|
||||
if (
|
||||
part.typeOfDamage === TypeOfDamage.Repair &&
|
||||
part.factorNeeded === true
|
||||
) {
|
||||
return localizedError(
|
||||
"برای قطعه تعمیری نمیتوان درخواست فاکتور قطعه ثبت کرد.",
|
||||
`parts[${index}].factorNeeded`,
|
||||
"invalid_value",
|
||||
String(part.partId),
|
||||
);
|
||||
}
|
||||
const daghi = part.daghi;
|
||||
if (
|
||||
part.typeOfDamage === TypeOfDamage.Change &&
|
||||
@@ -125,13 +141,12 @@ export function getExpertReplyPricingValidationError(
|
||||
(typeof part.price !== "string" || part.price.trim() !== "");
|
||||
|
||||
const amountIsValid = (amount: number | null) => amount !== null;
|
||||
const priceIsRequired = part.typeOfDamage === TypeOfDamage.Change;
|
||||
const priceIsRequired =
|
||||
part.typeOfDamage === TypeOfDamage.Change && part.factorNeeded !== true;
|
||||
|
||||
const requiredAmountFields: Array<[
|
||||
"price" | "salary" | "totalPayment",
|
||||
number | null,
|
||||
boolean,
|
||||
]> = [
|
||||
const requiredAmountFields: Array<
|
||||
["price" | "salary" | "totalPayment", number | null, boolean]
|
||||
> = [
|
||||
["price", price, priceIsRequired || hasPrice],
|
||||
["salary", salary, true],
|
||||
["totalPayment", totalPayment, true],
|
||||
@@ -160,11 +175,13 @@ export function getExpertReplyPricingValidationError(
|
||||
}
|
||||
|
||||
if (options.enforceAmountBounds) {
|
||||
const monetaryFields: Array<[
|
||||
"price" | "salary" | "totalPayment" | "daghi.price",
|
||||
number | null,
|
||||
boolean,
|
||||
]> = [
|
||||
const monetaryFields: Array<
|
||||
[
|
||||
"price" | "salary" | "totalPayment" | "daghi.price",
|
||||
number | null,
|
||||
boolean,
|
||||
]
|
||||
> = [
|
||||
["price", price, priceIsRequired || hasPrice],
|
||||
["salary", salary, true],
|
||||
["totalPayment", totalPayment, true],
|
||||
@@ -192,7 +209,7 @@ export function getExpertReplyPricingValidationError(
|
||||
? "مبلغ کل"
|
||||
: "قیمت داغی";
|
||||
return localizedError(
|
||||
`${fieldName} قطعه ${String(part.partId)} باید حداقل ${toPersianAmount(EXPERT_REPLY_MIN_AMOUNT_TOMAN)} و حداکثر ${toPersianAmount(EXPERT_REPLY_MAX_AMOUNT_TOMAN)} تومان باشد.`,
|
||||
`${fieldName} قطعه ${String(part.partId)} باید حداقل ${toPersianAmount(EXPERT_REPLY_MIN_AMOUNT_TOMAN)} و حداکثر ${toPersianAmount(EXPERT_REPLY_MAX_AMOUNT_TOMAN)} ریال باشد.`,
|
||||
`parts[${index}].${field}`,
|
||||
"amount_out_of_range",
|
||||
String(part.partId),
|
||||
@@ -210,7 +227,7 @@ export function getExpertReplyPricingValidationError(
|
||||
) {
|
||||
if (options.locale === "fa") {
|
||||
return localizedError(
|
||||
`قیمت داغی قطعه ${String(part.partId)} باید بهصورت مبلغ صحیح و غیرمنفی (تومان) وارد شود.`,
|
||||
`قیمت داغی قطعه ${String(part.partId)} باید بهصورت مبلغ صحیح و غیرمنفی (ریال) وارد شود.`,
|
||||
`parts[${index}].daghi.price`,
|
||||
"invalid_amount",
|
||||
String(part.partId),
|
||||
|
||||
@@ -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";
|
||||
Reference in New Issue
Block a user