forked from Yara724/api
Compare commits
9
Commits
e31e2c7be6
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e0e6f83dc | ||
|
|
f29461fa67 | ||
|
|
475780f17e | ||
|
|
297664a9a6 | ||
|
|
187a0ea3a9 | ||
|
|
036d218ebd | ||
|
|
c74b29337e | ||
|
|
3bf6fcc8b0 | ||
|
|
70e7edcd19 |
@@ -130,3 +130,6 @@ MIC_SMS_TOKEN_TTL=86399
|
||||
# Total normal send attempts; a single 401 refresh/resend is additional.
|
||||
MIC_SMS_ATTEMPTS=2
|
||||
MIC_SMS_TIMEOUT_MS=15000
|
||||
|
||||
# Require the submitting expert to sign before final Fanavaran submission.
|
||||
FANAVARAN_REQUIRE_EXPERT_SIGNATURE=false
|
||||
|
||||
@@ -12,3 +12,9 @@ Insurer setup and staff/branch management: [guide](docs/insurer-staff-management
|
||||
### Moalem SMS
|
||||
|
||||
For MIC SMS environment settings, shared token-cache indexes and a test-send command, see [Moalem SMS adapter](docs/MIC/moalem-sms.md).
|
||||
|
||||
### Expert signature before final Fanavaran submission
|
||||
|
||||
Set `FANAVARAN_REQUIRE_EXPERT_SIGNATURE=true` in the API service environment and restart the API for the deployment that requires it. The expert app reads the setting from the API. The default is `false`.
|
||||
|
||||
With the setting enabled, the submitting expert signs the saved assessment in the Fanavaran tab, then clicks final submission. Changes to the signed assessment require a fresh signature. Automatic final expertise submission waits for this action, and manual final submissions use the saved fields without JSON overrides. Initial Fanavaran stages can still run at their usual points. The insurer PDF includes available party and expert signatures.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Claim resend and invoice workflow regressions — 2026-11-23
|
||||
|
||||
## Reported failures and causes
|
||||
|
||||
- **Resend PUT returned a generic 422.** The exact reported body (part ID 15, no documents and a non-empty description) is accepted for a first resend cycle. The service explicitly returns `DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED` after an earlier resend was fulfilled. The expert proxy discarded that code, and the English explanation fell through to a generic Persian form-validation message. The one-completed-resend policy remains unchanged. The API now gives a specific Persian explanation; the expert proxy retains the code; the sidebar explains and disables a completed resend when its case detail is available, and displays server errors inline.
|
||||
- **Invoice approval shared the assessment submission UI.** Its decisions lived under user opinions and depended on globally initialized factor drafts. It could reach assessment selection/pricing validation and demand damaged parts. Review now belongs to each saved assessment part, beside its invoice viewer. The independent action calls `PATCH /v2/expert-claim/validate-factors/:id` with one decision; it does not update selected damaged parts or resubmit the assessment.
|
||||
- **Mixed replies required a refresh after signing.** The owner page delayed dispatching the pre-signature step by three seconds, the upload callback captured old case state, and the part list also read a stale Redux step. The mutation response now immediately updates the case query, the current API step drives upload permissions, and signature/upload operations invalidate the case query. Pending invoice work also stays visible in in-person flows rather than being hidden by a completion summary.
|
||||
- **Invoice validation could persist changes before rejecting a total.** The service now validates the proposed decisions and the completed-batch V1 total before persistence. The update checks the original case phase and update timestamp (or the parts snapshot for legacy fixtures) to reject a stale write. Invalid/duplicate/unrelated decisions cause no writes. A rejected invoice needs a reason and an expert amount.
|
||||
|
||||
## UI behavior
|
||||
|
||||
- Review actions appear only on `/requests/check`, for claim, field and file-reviewer experts, in the invoice review phase and after all required invoices are uploaded. Insurers and file makers retain viewing access.
|
||||
- Each pending invoice can be approved or repriced/rejected in its own dialog. Enter the **whole line total including labor, in rials**. This is not an additional amount to add to the existing line.
|
||||
- Local validation and server failures keep the dialog/draft available for correction and retry. Cancelling does not save a decision. Saved decisions disappear from the pending controls; case queries refresh. Completing the batch uses `caseStatus` to return to the list, including V5 FileMaker approval.
|
||||
- Signing a mixed reply enables invoice upload on the current page. Every upload refreshes the case. Once all invoices arrive, upload controls and the signature action are replaced by the expert-review waiting state.
|
||||
- The live claim query and in-person query take precedence over the original detail snapshot so refreshed decisions are visible.
|
||||
- The previous invoice controls under user opinions and their unused validation component were removed.
|
||||
|
||||
## Verification
|
||||
|
||||
`test/claim-invoice-resend.e2e-spec.ts` exercises the real Nest controllers, JWT/role guards, DTO validation and workflow services with in-memory persistence. It covers v1–v6 × THIRD_PARTY/CAR_BODY × mixed/all-factor/priced assessments, mixed signing before upload, sequential uploads, duplicate upload rejection, per-invoice partial batches, completion/V5 handoff, malformed/duplicate/unknown decisions, Persian amounts, rejected invoice reasons, cap failure with no writes followed by a corrected retry, stale writes, and the exact resend payload followed by the documented 422 rule.
|
||||
|
||||
The full HTTP suite passes 72 tests with four pre-existing skips. The general API suite retains the ten previously documented failures in `fanavaran-submit-overrides.spec.ts`; they fail at its vehicle-review prerequisite and are unrelated to these changes.
|
||||
|
||||
Both UI suites include invoice regressions. Browser checks at 1440×1100 and 390×844 exercise the rendered expert invoice viewer/review action, required amount validation, an HTTP error with retry, and the actual user result page with canvas signing and two successive invoice uploads without a reload. Browser API replies are intercepted synthetic fixtures; no production case, SMS, Fanavaran or object storage is used. Test artifacts live under `/tmp/invoice-review-*`, and temporary preview routes are removed.
|
||||
|
||||
These are targeted workflow tests, not a claim that every production integration or every application route was manually exercised. Deploy **API, expert UI and user UI together**; there is no environment or database migration requirement.
|
||||
@@ -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.
|
||||
@@ -20,6 +20,7 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw
|
||||
| --- | --- | --- |
|
||||
| List/create insurers | `GET/POST /super-admin/management/clients` | Unavailable |
|
||||
| Edit insurer metadata | `PATCH /super-admin/management/clients/:id` | Unavailable |
|
||||
| Read or update case working hours | `GET/PATCH /super-admin/management/working-hours?clientId=...` | `GET/PATCH /expert-insurer/management/working-hours` |
|
||||
| List/create insurer login accounts | `GET/POST /super-admin/management/clients/:clientId/accounts` | Unavailable |
|
||||
| Edit insurer login account | `PATCH /super-admin/management/clients/:clientId/accounts/:id` | Unavailable |
|
||||
| List/create staff | `GET/POST /super-admin/management/staff?clientId=...` | `GET/POST /expert-insurer/management/staff` |
|
||||
@@ -30,6 +31,24 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw
|
||||
|
||||
Staff list queries accept `search`, `role`, `page` and `limit` (default 20, capped at 100). Responses contain `list`, `total`, `page` and `limit`. Branch responses contain `list`; clients contain `clients`. Account lists share the staff pagination contract.
|
||||
|
||||
## Case working hours
|
||||
|
||||
Insurers edit their own hours in **تنظیمات شرکت بیمه** (`/settings`). Super-admins use **ساعات کاری** on the relevant company in `/insurers`. Existing companies default to 24/7. Saving a change applies it immediately to new case submissions, including submissions for existing cases.
|
||||
|
||||
Schedules use Tehran time and allow one opening window per weekday. Omitted days are closed. For an overnight shift, enter an end time earlier than the start. The API numbers weekdays from Sunday (`0`) through Saturday (`6`) and accepts `24:00` as the end of a day. For example, `{"alwaysOpen":false,"windows":[{"weekday":6,"opensAt":"08:00","closesAt":"16:00"}]}` opens Saturday from 08:00 inclusive to 16:00 exclusive. Enable `alwaysOpen` to allow access around the clock.
|
||||
|
||||
Case creation and updates use the liable insurer's hours once it is identified. At intake, staff use their own insurer's hours. For public intake before the case insurer is known, set the API's existing `CLIENT_ID` to the deployment insurer's numeric client code. If an intake has no known insurer and the deployment has no configured insurer, the schedule applies once the insurer is identified. Case reads, login and schedule settings are available outside those hours. Blocked case updates return HTTP 403 with `OUTSIDE_WORKING_HOURS` and the next opening.
|
||||
|
||||
## Refer a case for damage assessment
|
||||
|
||||
In the insurer case details, use **ارجاع پرونده** to choose an active expert in an active branch of the same company. The destination role follows the original workflow: damage expert for V1/V6, field expert for V2/V3, and file reviewer for V4/V5.
|
||||
|
||||
Referral becomes available once intake and evidence capture are complete and the claim is ready for damage assessment or factor validation. V4/V5 files still in the FileMaker or capture steps stay in those workflows. Any successful Fanavaran stage, including automatic base-claim registration, closes referral eligibility.
|
||||
|
||||
The referral updates the claim's review branch and clears the previous review lock. The new expert opens the case from the expert review list. The intake owner and branch remain in the linked blame case, and V5 approval stays with the original FileMaker. The case timeline records the insurer account and the previous and new experts and branches.
|
||||
|
||||
The insurer routes are `GET /expert-insurer/files/:publicId/review-referral` for eligible experts and the current revision, and `PATCH /expert-insurer/files/:publicId/review-referral` with `expertId` and `revision`. A concurrent write or submission can require refreshing the referral options.
|
||||
|
||||
## Fields
|
||||
|
||||
`role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism.
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
# Persian panel and report presentation
|
||||
|
||||
The expert/user panels and insurer file report use Persian interface labels and system values. The report builder translates persisted lifecycle statuses and known inquiry fields. Unmapped provider field names are omitted instead of being printed as raw English keys. Cached report fields receive the same protection in the PDF renderer.
|
||||
|
||||
Actual identifiers and user-entered facts are preserved: VINs, policy numbers, phone numbers, email addresses and saved vehicle names are not translated or rewritten. National codes remain available in explicitly labelled identity fields; they are never used as a person's display name. No stored case, inquiry or Fanavaran payload is changed by report formatting.
|
||||
|
||||
## Person labels
|
||||
|
||||
The presentation helper prefers a saved full name or first/last name, then an explicitly recorded phone number. Numeric placeholders, database IDs, national codes, email addresses and generic English placeholder names are rejected as names. If neither name nor phone exists, the interface uses a Persian unavailable label. Insurer detail/report views resolve current user profiles by the case's user ID, with a per-request lookup cache. Timeline names resolve the actual event actor rather than the other party or the claim owner by default.
|
||||
|
||||
Driver and owner names are resolved separately. A licence number is never substituted for its issue date. Monetary amounts already stored in rials are labelled ریال without changing their numeric value.
|
||||
|
||||
## Shared damaged-parts catalogue
|
||||
|
||||
The user application no longer asks for a vehicle body type or side before selecting parts, including the objection/additional-parts picker. It searches the shared catalogue by name or code and submits the selected numeric IDs. It does not invent a vehicle type. Existing vehicle identity data used by inquiries and pricing is retained.
|
||||
|
||||
Selections persisted under the old side buckets are merged into the shared selection, deduplicated by ID and preserved. Search does not clear selections. The picker displays loading/failure/retry states, and its catalogue cache is scoped to the current account. Existing document, bank-information and photo steps remain in their flow-specific order.
|
||||
|
||||
## Verification
|
||||
|
||||
- API report/presentation tests: 52 passing tests, plus 21 insurer summary/timeline regression tests.
|
||||
- Both frontend `npm run test:ui` suites, including new Persian presentation and flat-catalogue scenarios covering all six flows.
|
||||
- Type checking and production builds for both frontends; API build.
|
||||
- Real local browser pages at desktop (1440 × 1100, v1) and mobile (390 × 844, v6), using synthetic cases and intercepted API responses: catalogue failure/retry, thin catalogue rows, search by code, selections across searches, no vehicle-type/side prompt, correct IDs-only submission and document-step navigation.
|
||||
- A report was rendered using the actual report builder and PDF component. Persian layout and extracted text were checked; Latin content in the fixture was limited to actual identifiers. Local existing fonts were used for this offline rendering check; production font configuration was unchanged.
|
||||
- The full API suite still has ten previously identified failures in `fanavaran-submit-overrides.spec.ts`, whose fixtures lack reviewed vehicle data. Those unrelated fixtures were not changed.
|
||||
|
||||
No production database or external provider was used for the browser/PDF checks. These checks do not claim every production record or every page was manually exercised.
|
||||
Binary file not shown.
@@ -41,6 +41,7 @@ describe("AI analysis file access", () => {
|
||||
service as any,
|
||||
{} as any,
|
||||
ai as any,
|
||||
{} as any,
|
||||
db as any,
|
||||
);
|
||||
await expect(controller[method](actor, "other-tenant")).rejects.toThrow(
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ClaimReviewInterceptor } from "./expert-claim/review-referral/claim-review.interceptor";
|
||||
import { CaseWorkingHoursInterceptor } from "./client/working-hours/case-working-hours.interceptor";
|
||||
import { EvidenceAccessModule } from "./evidence-access/evidence-access.module";
|
||||
import { PersianErrorFilter } from "./common/errors/persian-error.filter";
|
||||
import { PersianErrorInterceptor } from "./common/errors/persian-error.interceptor";
|
||||
@@ -68,6 +70,8 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
|
||||
providers: [
|
||||
{ provide: APP_FILTER, useClass: PersianErrorFilter },
|
||||
{ provide: APP_INTERCEPTOR, useClass: PersianErrorInterceptor },
|
||||
{ provide: APP_INTERCEPTOR, useClass: CaseWorkingHoursInterceptor },
|
||||
{ provide: APP_INTERCEPTOR, useClass: ClaimReviewInterceptor },
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: UnicodeDigitsNormalizeInterceptor,
|
||||
|
||||
@@ -297,10 +297,10 @@ describe("buildInsurerFileReport", () => {
|
||||
"سپر جلو",
|
||||
);
|
||||
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
|
||||
"۲٬۵۰۰٬۰۰۰ تومان",
|
||||
"۲٬۵۰۰٬۰۰۰ ریال",
|
||||
);
|
||||
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / مبلغ کل")).toBe(
|
||||
"۳٬۰۰۰٬۰۰۰ تومان",
|
||||
"۳٬۰۰۰٬۰۰۰ ریال",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -352,7 +352,7 @@ describe("buildInsurerFileReport", () => {
|
||||
"چراغ جلو",
|
||||
);
|
||||
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
|
||||
"۴٬۰۰۰٬۰۰۰ تومان",
|
||||
"۴٬۰۰۰٬۰۰۰ ریال",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -570,20 +570,8 @@ describe("buildInsurerFileReport", () => {
|
||||
);
|
||||
expect(driver).toContain("گواهینامه دارد: بله");
|
||||
expect(driver).toContain("نوع گواهینامه: پایه دو");
|
||||
expect(
|
||||
getFieldValue(
|
||||
report,
|
||||
PR.damagedVehicleSection,
|
||||
"خودرو / سوابق تلاش استعلام / تلاش ۱ / نوع پلاک استعلامشده",
|
||||
),
|
||||
).toBe("پلاک فعلی");
|
||||
expect(
|
||||
getFieldValue(
|
||||
report,
|
||||
PR.damagedVehicleSection,
|
||||
"خودرو / سوابق تلاش استعلام / تلاش ۱ / خطا",
|
||||
),
|
||||
).toBe("موردی یافت نشد");
|
||||
expect(report.sections.flatMap(section => section.fields)
|
||||
.some(field => field.label.includes("سوابق تلاش استعلام"))).toBe(false);
|
||||
|
||||
const renderedText = report.sections
|
||||
.flatMap((section) => [
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
|
||||
import {
|
||||
resolveClaimOwnerParty,
|
||||
resolveDamagedPartyRow,
|
||||
@@ -24,6 +25,7 @@ const SKIP_FLATTEN_KEYS = new Set([
|
||||
"history",
|
||||
"workflow",
|
||||
"evidence",
|
||||
"attempts",
|
||||
"confirmation",
|
||||
"inquiries",
|
||||
"raw",
|
||||
@@ -96,11 +98,11 @@ function normalizeNumber(value: unknown): number | undefined {
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function formatToman(value: unknown): string | undefined {
|
||||
function formatRial(value: unknown): string | undefined {
|
||||
if (value === undefined || value === null || value === "") return undefined;
|
||||
const amount = normalizeNumber(value);
|
||||
if (amount === undefined) return asString(value);
|
||||
return `${PERSIAN_NUMBER_FORMATTER.format(amount)} تومان`;
|
||||
if (amount === undefined) return /factor|invoice/i.test(String(value)) ? "طبق فاکتور" : /[a-z]/i.test(String(value)) ? undefined : asString(value);
|
||||
return `${PERSIAN_NUMBER_FORMATTER.format(amount)} ریال`;
|
||||
}
|
||||
|
||||
function firstDefined(...values: unknown[]): string | undefined {
|
||||
@@ -188,7 +190,7 @@ function dedupeFields(
|
||||
|
||||
for (const field of fields) {
|
||||
const value = asString(field.value);
|
||||
if (!value) continue;
|
||||
if (!value || !field.label) continue;
|
||||
const key = `${field.label}::${value}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
@@ -227,9 +229,7 @@ function expertNameFromSnapshot(snapshot?: {
|
||||
lastName?: string;
|
||||
}): string | undefined {
|
||||
if (!snapshot) return undefined;
|
||||
const name = [snapshot.firstName, snapshot.lastName]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
const name = personDisplayName(snapshot);
|
||||
return name || undefined;
|
||||
}
|
||||
|
||||
@@ -254,7 +254,7 @@ function collectExpertNames(
|
||||
if (!reply) continue;
|
||||
const actor = (reply.actorDetail as { actorName?: string } | undefined)
|
||||
?.actorName;
|
||||
if (actor) names.add(actor);
|
||||
if (meaningfulPersonName(actor)) names.add(meaningfulPersonName(actor));
|
||||
const snap = expertNameFromSnapshot(
|
||||
reply.expertProfileSnapshot as
|
||||
| { firstName?: string; lastName?: string }
|
||||
@@ -263,7 +263,7 @@ function collectExpertNames(
|
||||
if (snap) names.add(snap);
|
||||
}
|
||||
|
||||
return names.size ? [...names].join(", ") : undefined;
|
||||
return names.size ? [...names].join("، ") : undefined;
|
||||
}
|
||||
|
||||
function inquiryRoleData(
|
||||
@@ -598,8 +598,8 @@ function buildPartyOwnerSection(
|
||||
{
|
||||
label: PR.name,
|
||||
value: options?.useClaimOwnerFallback
|
||||
? firstDefined(person?.fullName, claimOwner?.fullName)
|
||||
: firstDefined(person?.fullName),
|
||||
? personDisplayName(person, claimOwner)
|
||||
: personDisplayName(person),
|
||||
},
|
||||
{ label: PR.phone, value: asString(person?.phoneNumber) },
|
||||
{
|
||||
@@ -644,7 +644,7 @@ function buildParticipantRolesSection(
|
||||
(candidate) => String(candidate.participantId) === String(participantId),
|
||||
);
|
||||
const value = [
|
||||
asString(participant?.fullName),
|
||||
personDisplayName(participant),
|
||||
participant?.nationalCode
|
||||
? `${PR.nationalCode}: ${asString(participant.nationalCode)}`
|
||||
: undefined,
|
||||
@@ -696,8 +696,6 @@ function licenseFieldsFromInquiry(inquiry?: Record<string, unknown>): {
|
||||
inquiry.issueDate,
|
||||
inquiry.LicenseIssueDate,
|
||||
inquiry.licenseIssueDate,
|
||||
inquiry.ExpireDate,
|
||||
inquiry.expireDate,
|
||||
),
|
||||
};
|
||||
}
|
||||
@@ -716,9 +714,11 @@ function buildDriverSection(
|
||||
String(role),
|
||||
);
|
||||
const { licenseType, licenseDate } = licenseFieldsFromInquiry(licenseInquiry);
|
||||
const driverId = damagedParty?.participantRoles?.driver;
|
||||
const driver = (sanitizeStoredInquiryParticipants(damagedParty?.participants) ?? []).find(participant => participant.participantId === driverId);
|
||||
|
||||
return buildSection(PR.driverSection, [
|
||||
{ label: PR.name, value: asString(person.fullName) },
|
||||
{ label: PR.name, value: personDisplayName(driver,{fullName:person.driverFullName,phoneNumber:person.driverPhoneNumber}) },
|
||||
{
|
||||
label: PR.licenseType,
|
||||
value:
|
||||
@@ -733,11 +733,9 @@ function buildDriverSection(
|
||||
{
|
||||
label: PR.licenseDate,
|
||||
value:
|
||||
asString(person.driverLicenseDate) ||
|
||||
licenseDate ||
|
||||
asString(person.driverLicense),
|
||||
asString(person.driverLicenseDate) || licenseDate,
|
||||
},
|
||||
{ label: PR.phone, value: asString(person.phoneNumber) },
|
||||
{ label: PR.phone, value: asString(person.driverPhoneNumber) },
|
||||
{ label: PR.nationalCode, value: asString(person.nationalCodeOfDriver) },
|
||||
{ label: PR.birthDate, value: formatBirthDate(person.driverBirthday) },
|
||||
{ label: PR.licenseNumber, value: asString(person.driverLicense) },
|
||||
@@ -774,7 +772,7 @@ function buildPartyStatementSection(
|
||||
},
|
||||
{
|
||||
label: PR.name,
|
||||
value: firstDefined(party.person?.fullName),
|
||||
value: personDisplayName(party.person),
|
||||
},
|
||||
{
|
||||
label: PR.admitsGuilt,
|
||||
@@ -824,6 +822,7 @@ function buildFanavaranCodesSection(
|
||||
claim?: Record<string, unknown> | null,
|
||||
): InsurerFileReportSection | undefined {
|
||||
if (!claim) return undefined;
|
||||
const refs = (claim.fanavaran ?? {}) as Record<string, unknown>;
|
||||
const sync =
|
||||
(claim.fanavaranSync as Record<string, unknown> | undefined) ?? {};
|
||||
const baseClaim =
|
||||
@@ -836,31 +835,31 @@ function buildFanavaranCodesSection(
|
||||
return buildSection(PR.fanavaranSection, [
|
||||
{
|
||||
label: PR.fanavaranClaimNo,
|
||||
value: firstDefined(claim.claimNo, baseClaim.claimNo),
|
||||
value: firstDefined(refs.claimNo, claim.claimNo, baseClaim.claimNo),
|
||||
},
|
||||
{
|
||||
label: PR.fanavaranClaimId,
|
||||
value: firstDefined(claim.claimId, baseClaim.claimId),
|
||||
value: firstDefined(refs.claimId, claim.claimId, baseClaim.claimId),
|
||||
},
|
||||
{
|
||||
label: PR.fanavaranDamageCaseId,
|
||||
value: firstDefined(
|
||||
claim.dmgCaseId,
|
||||
refs.dmgCaseId, claim.dmgCaseId,
|
||||
damageCase.dmgCaseId,
|
||||
expertise.dmgCaseId,
|
||||
),
|
||||
},
|
||||
{
|
||||
label: PR.fanavaranExpertiseId,
|
||||
value: firstDefined(claim.expertiseId, expertise.expertiseId),
|
||||
value: firstDefined(refs.expertiseId, claim.expertiseId, expertise.expertiseId),
|
||||
},
|
||||
{
|
||||
label: PR.fanavaranPolicyId,
|
||||
value: firstDefined(baseClaim.policyId),
|
||||
value: firstDefined(refs.policyId, baseClaim.policyId),
|
||||
},
|
||||
{
|
||||
label: PR.fanavaranDriverId,
|
||||
value: firstDefined(baseClaim.driverId),
|
||||
value: firstDefined(refs.driverId, baseClaim.driverId),
|
||||
},
|
||||
{
|
||||
label: PR.fanavaranVehicleKindId,
|
||||
@@ -875,6 +874,7 @@ function buildFanavaranCodesSection(
|
||||
|
||||
function buildEvaluationSection(
|
||||
claim?: Record<string, unknown> | null,
|
||||
isCarBody = false,
|
||||
): InsurerFileReportSection | undefined {
|
||||
if (!claim) return undefined;
|
||||
const reply = resolveEvaluationReply(claim);
|
||||
@@ -892,12 +892,20 @@ function buildEvaluationSection(
|
||||
},
|
||||
{
|
||||
label: PR.evaluationExpert,
|
||||
value: actorDetail?.actorName ?? snapshotName,
|
||||
value: snapshotName || meaningfulPersonName(actorDetail?.actorName),
|
||||
},
|
||||
{
|
||||
label: PR.evaluationSubmittedAt,
|
||||
value: formatDateTime(resolveEvaluationSubmittedAt(claim, reply)),
|
||||
},
|
||||
{
|
||||
label: "ارزش روز خودرو",
|
||||
value: formatRial((claim.vehicle as ReportRecord | undefined)?.carPrice ?? (claim.vehicle as ReportRecord | undefined)?.price),
|
||||
},
|
||||
{
|
||||
label: "افت قیمت",
|
||||
value: isCarBody ? undefined : formatRial((claim.evaluation as any)?.priceDrop?.total),
|
||||
},
|
||||
{
|
||||
label: PR.evaluationResponse,
|
||||
value: asString(reply?.description),
|
||||
@@ -930,7 +938,7 @@ function evaluationDaghiValue(value: unknown): string | undefined {
|
||||
}
|
||||
const daghi = value as ReportRecord;
|
||||
const option = asString(persianReportValue("daghi.option", daghi.option));
|
||||
const price = formatToman(daghi.price);
|
||||
const price = formatRial(daghi.price);
|
||||
return [option, price].filter(Boolean).join(" - ") || undefined;
|
||||
}
|
||||
|
||||
@@ -953,14 +961,14 @@ function buildEvaluationPartsSection(
|
||||
persianReportValue("evaluation.part.typeOfDamage", part.typeOfDamage),
|
||||
),
|
||||
},
|
||||
{ label: `${prefix} / ${PR.partPrice}`, value: formatToman(part.price) },
|
||||
{ label: `${prefix} / ${PR.partPrice}`, value: formatRial(part.price) },
|
||||
{
|
||||
label: `${prefix} / ${PR.repairSalary}`,
|
||||
value: formatToman(part.salary),
|
||||
value: formatRial(part.salary),
|
||||
},
|
||||
{
|
||||
label: `${prefix} / ${PR.totalPayment}`,
|
||||
value: formatToman(part.totalPayment),
|
||||
value: formatRial(part.totalPayment),
|
||||
},
|
||||
{
|
||||
label: `${prefix} / ${PR.factorNeeded}`,
|
||||
@@ -1109,7 +1117,7 @@ export function buildInsurerFileReport(file: {
|
||||
? (resolveClaimOwnerParty(blameContext as any) as ReportParty | null)
|
||||
: null;
|
||||
const isCarBody =
|
||||
String((blameContext?.type as string | undefined) ?? "") === "CAR_BODY";
|
||||
(blameContext?.type ?? overview.type ?? claim?.blameRequestType) === "CAR_BODY";
|
||||
const includeGuiltySections =
|
||||
!!guiltyParty && !(isCarBody && sameParty(damagedParty, guiltyParty));
|
||||
|
||||
@@ -1173,7 +1181,7 @@ export function buildInsurerFileReport(file: {
|
||||
)
|
||||
: undefined,
|
||||
buildFanavaranCodesSection(claim),
|
||||
buildEvaluationSection(claim),
|
||||
buildEvaluationSection(claim, isCarBody),
|
||||
buildEvaluationPartsSection(claim),
|
||||
buildAccidentReportSection(blameContext, claim, damagedParty),
|
||||
]);
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { RequestManagementModule } from "src/request-management/request-management.module";
|
||||
import { ExpertInsurerModule } from "src/expert-insurer/expert-insurer.module";
|
||||
import { CaseExpertReportInsurerController } from "./case-expert-report.controller";
|
||||
import { CaseExpertReportService } from "./case-expert-report.service";
|
||||
|
||||
@Module({
|
||||
imports: [ExpertInsurerModule],
|
||||
imports: [
|
||||
ExpertInsurerModule,
|
||||
RequestManagementModule,
|
||||
ClaimRequestManagementModule,
|
||||
],
|
||||
controllers: [CaseExpertReportInsurerController],
|
||||
providers: [CaseExpertReportService],
|
||||
exports: [CaseExpertReportService],
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||
import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.db.service";
|
||||
import { Types } from "mongoose";
|
||||
import { BlameDocumentDbService } from "src/request-management/entities/db-service/blame-document.db.service";
|
||||
import { buildReportAttachments, buildReportSignatures } from "./report-media";
|
||||
import { buildInsurerFileReport } from "./case-expert-report.builder";
|
||||
import { InsurerFileReportViewModel } from "./case-expert-report.types";
|
||||
|
||||
@@ -7,6 +11,8 @@ import { InsurerFileReportViewModel } from "./case-expert-report.types";
|
||||
export class CaseExpertReportService {
|
||||
constructor(
|
||||
private readonly expertInsurerService: ExpertInsurerService,
|
||||
private readonly blameDocumentDbService: BlameDocumentDbService,
|
||||
private readonly factorImageDbService: ClaimFactorsImageDbService,
|
||||
) {}
|
||||
|
||||
async generateForInsurer(
|
||||
@@ -21,7 +27,28 @@ export class CaseExpertReportService {
|
||||
const file = await this.expertInsurerService.retrieveFileDetailsByPublicId(
|
||||
clientKey,
|
||||
publicId,
|
||||
true,
|
||||
);
|
||||
return buildInsurerFileReport(file);
|
||||
const blame = file.reportBlame ?? file.blame;
|
||||
const blameId = String(blame?._id ?? "");
|
||||
const claimId = String(file.claim?.claimRequestId ?? "");
|
||||
const [blameDocuments, invoices] = await Promise.all([
|
||||
Types.ObjectId.isValid(blameId)
|
||||
? this.blameDocumentDbService.findByRequestId(blameId)
|
||||
: [],
|
||||
Types.ObjectId.isValid(claimId)
|
||||
? this.factorImageDbService.findByClaimId(claimId)
|
||||
: [],
|
||||
]);
|
||||
return {
|
||||
...buildInsurerFileReport({ ...file, blame }),
|
||||
attachments: buildReportAttachments(
|
||||
file.claim,
|
||||
blame,
|
||||
blameDocuments,
|
||||
invoices,
|
||||
),
|
||||
signatures: buildReportSignatures(blame, file.claim),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,13 @@ export type InsurerFileReportSection = {
|
||||
fields: InsurerFileReportField[];
|
||||
};
|
||||
|
||||
export type ReportAttachment = { label: string; url?: string; image?: string };
|
||||
|
||||
export type InsurerFileReportViewModel = {
|
||||
title: string;
|
||||
publicId: string;
|
||||
requestNo?: string;
|
||||
sections: InsurerFileReportSection[];
|
||||
signatures?: ReportAttachment[];
|
||||
attachments?: ReportAttachment[];
|
||||
};
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
PR,
|
||||
persianFieldPath,
|
||||
persianReportValue,
|
||||
persianStatus,
|
||||
} from "./persian-report-labels";
|
||||
import { buildInsurerFileReport } from "./case-expert-report.builder";
|
||||
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
|
||||
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
|
||||
|
||||
describe("Persian report presentation", () => {
|
||||
it.each([...Object.values(ClaimCaseStatus), ...Object.values(CaseStatus)])(
|
||||
"translates persisted status %s",
|
||||
(status) => expect(persianStatus(status)).not.toMatch(/[a-z]/i),
|
||||
);
|
||||
it("uses meaningful Persian labels and suppresses unknown provider field keys", () => {
|
||||
expect(persianFieldPath("party.vehicle.vin")).toBe(
|
||||
"خودرو / شماره شناسایی خودرو",
|
||||
);
|
||||
expect(
|
||||
persianFieldPath("party.vehicle.inquiry.unmappedProviderField"),
|
||||
).toBe("");
|
||||
expect(persianReportValue("vehicle.expedited", true)).toBe("فوری");
|
||||
expect(persianReportValue("vehicle.carType", "sedan")).toBe("سواری");
|
||||
expect(persianReportValue("vehicle.status", "NEW_UNKNOWN_STATUS")).toBe(
|
||||
"وضعیت نامشخص",
|
||||
);
|
||||
});
|
||||
it("keeps factual identifiers intact, uses phones for unnamed users and keeps driver/owner identities separate", () => {
|
||||
const vin = "IR1ABC23456789012";
|
||||
const report = buildInsurerFileReport({
|
||||
overview: { publicId: "QA-1" },
|
||||
blame: {
|
||||
type: "CAR_BODY",
|
||||
status: "COMPLETED",
|
||||
parties: [
|
||||
{
|
||||
role: "FIRST",
|
||||
person: {
|
||||
userId: "650000000000000000000001",
|
||||
fullName: "1234567890",
|
||||
phoneNumber: "09120000000",
|
||||
driverIsInsurer: false,
|
||||
nationalCodeOfDriver: "1111111111",
|
||||
driverLicense: "987654321",
|
||||
},
|
||||
participants: [
|
||||
{
|
||||
participantId: "driver",
|
||||
fullName: "حسن احمدی",
|
||||
nationalCode: "1111111111",
|
||||
birthday: "1370/01/01",
|
||||
},
|
||||
],
|
||||
participantRoles: { driver: "driver" },
|
||||
vehicle: {
|
||||
vin,
|
||||
carType: "sedan",
|
||||
unknownProviderField: "DO_NOT_SHOW",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
claim: {
|
||||
owner: { userId: "650000000000000000000001" },
|
||||
evaluation: {
|
||||
damageExpertReply: {
|
||||
parts: [
|
||||
{
|
||||
carPartDamage: { label_fa: "گلگیر جلو" },
|
||||
typeOfDamage: "تعویض",
|
||||
price: "2000000",
|
||||
totalPayment: "3000000",
|
||||
factorNeeded: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const fields = report.sections.flatMap((section) => section.fields);
|
||||
expect(fields.every((field) => !/[a-z]/i.test(field.label))).toBe(true);
|
||||
expect(fields.some((field) => field.value === vin)).toBe(true);
|
||||
expect(fields.some((field) => field.value === "DO_NOT_SHOW")).toBe(false);
|
||||
expect(
|
||||
report.sections
|
||||
.find((section) => section.title === PR.ownerSection)
|
||||
?.fields.find((field) => field.label === PR.name)?.value,
|
||||
).toBe("09120000000");
|
||||
const driver = report.sections.find(
|
||||
(section) => section.title === PR.driverSection,
|
||||
);
|
||||
expect(driver?.fields.find((field) => field.label === PR.name)?.value).toBe(
|
||||
"حسن احمدی",
|
||||
);
|
||||
expect(
|
||||
driver?.fields.find((field) => field.label === PR.licenseDate),
|
||||
).toBeUndefined();
|
||||
expect(fields.some((field) => field.value === "۲٬۰۰۰٬۰۰۰ ریال")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { UNIFIED_FILE_STATUS_CATALOG } from "src/helpers/unified-file-status";
|
||||
export const PR = {
|
||||
reportTitle: "گزارش پرونده بیمه گر",
|
||||
reportTitle: "گزارش پرونده بیمهگر",
|
||||
publicId: "شناسه عمومی",
|
||||
requestNo: "شماره درخواست",
|
||||
empty: "-",
|
||||
@@ -21,17 +22,20 @@ export const PR = {
|
||||
fanavaranSection: "کدهای فناوران",
|
||||
evaluationSection: "نتیجه ارزیابی",
|
||||
accidentSection: "گزارش حادثه",
|
||||
name: "نام",
|
||||
name: "نام و نام خانوادگی",
|
||||
phone: "شماره تلفن",
|
||||
nationalCode: "کد ملی",
|
||||
birthDate: "تاریخ تولد",
|
||||
sheba: "شماره شبا",
|
||||
licenseType: "نوع گواهینامه",
|
||||
licenseDate: "تاریخ گواهینامه",
|
||||
licenseDate: "تاریخ صدور گواهینامه",
|
||||
licenseNumber: "شماره گواهینامه",
|
||||
hasDrivingLicense: "گواهینامه دارد",
|
||||
driverLicense: "گواهینامه راننده",
|
||||
insuranceCompany: "شرکت بیمه",
|
||||
expedited: "رسیدگی فوری",
|
||||
status: "وضعیت",
|
||||
color: "رنگ",
|
||||
policyNumber: "شماره بیمهنامه",
|
||||
policyStartDate: "تاریخ شروع بیمهنامه",
|
||||
policyEndDate: "تاریخ پایان بیمهنامه",
|
||||
@@ -40,8 +44,8 @@ export const PR = {
|
||||
fileRegisteredAt: "تاریخ و ساعت ثبت پرونده",
|
||||
evaluationRegisteredAt: "تاریخ و ساعت ثبت نتیجه ارزیابی",
|
||||
fanavaranClaimNo: "شماره پرونده فناوران",
|
||||
fanavaranClaimId: "کد پرونده فناوران",
|
||||
fanavaranDamageCaseId: "کد کیس خسارت فناوران",
|
||||
fanavaranClaimId: "کد رایانه پرونده فناوران",
|
||||
fanavaranDamageCaseId: "کد پرونده خسارت فناوران",
|
||||
fanavaranExpertiseId: "کد کارشناسی فناوران",
|
||||
fanavaranPolicyId: "کد بیمهنامه فناوران",
|
||||
fanavaranDriverId: "کد راننده فناوران",
|
||||
@@ -78,9 +82,9 @@ export const PR = {
|
||||
weather: "وضعیت آب و هوا",
|
||||
road: "وضعیت جاده",
|
||||
light: "وضعیت نور",
|
||||
blameStatus: "وضعیت مقصر",
|
||||
blameStatus: "وضعیت پرونده تعیین مقصر",
|
||||
claimStatus: "وضعیت خسارت",
|
||||
expertDecision: "نظر کارشناس مقصر",
|
||||
expertDecision: "نظر کارشناس تصادف",
|
||||
accidentWay: "نحوه برخورد",
|
||||
accidentReason: "علت حادثه",
|
||||
accidentType: "نوع حادثه",
|
||||
@@ -89,7 +93,11 @@ export const PR = {
|
||||
partyDescription: "توضیحات طرف",
|
||||
} as const;
|
||||
|
||||
const KEY_LABELS: Record<string, string> = {
|
||||
export const KEY_LABELS: Record<string, string> = {
|
||||
hasEndorsement: "دارای الحاقیه",
|
||||
expedited: "رسیدگی فوری",
|
||||
status: "وضعیت",
|
||||
color: "رنگ",
|
||||
policyNumber: "شماره بیمهنامه",
|
||||
company: "شرکت بیمه",
|
||||
insurerCompany: "شرکت بیمهگر",
|
||||
@@ -140,8 +148,8 @@ const KEY_LABELS: Record<string, string> = {
|
||||
MapTypNam: "نام نوع خودرو",
|
||||
MtrNum: "شماره موتور",
|
||||
ShsNum: "شماره شاسی",
|
||||
vin: "VIN",
|
||||
VinNumberField: "VIN",
|
||||
vin: "شماره شناسایی خودرو",
|
||||
VinNumberField: "شماره شناسایی خودرو",
|
||||
DisFnYrPrcnt: "درصد تخفیف مالی",
|
||||
DisLfYrPrcnt: "درصد تخفیف جانی",
|
||||
DisPrsnYrPrcnt: "درصد تخفیف شخص ثالث",
|
||||
@@ -209,7 +217,7 @@ const KEY_LABELS: Record<string, string> = {
|
||||
previousPlate: "پلاک قبلی",
|
||||
previousPlateId: "پلاک قبلی",
|
||||
previousPolicyholderNationalCode: "کد ملی بیمهگذار پلاک قبلی",
|
||||
vehicleVin: "شماره شاسی (VIN)",
|
||||
vehicleVin: "شماره شناسایی خودرو",
|
||||
driver: "راننده",
|
||||
vehicleOwner: "مالک وسیله نقلیه",
|
||||
thirdPartyPolicyholder: "بیمهگذار شخص ثالث",
|
||||
@@ -222,7 +230,27 @@ const KEY_LABELS: Record<string, string> = {
|
||||
error: "خطا",
|
||||
};
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
export const STATUS_LABELS: Record<string, string> = {
|
||||
...Object.fromEntries(UNIFIED_FILE_STATUS_CATALOG.map(item => [item.key,item.labelFa])),
|
||||
OPEN: "پرونده باز",
|
||||
CREATED: "ثبتشده",
|
||||
SELECTING_OUTER_PARTS: "در حال انتخاب قطعات آسیبدیده",
|
||||
SELECTING_OTHER_PARTS: "در حال ثبت سایر قطعات",
|
||||
UPLOADING_REQUIRED_DOCUMENTS: "در حال بارگذاری مدارک",
|
||||
CAPTURING_PART_DAMAGES: "در حال ثبت تصاویر خسارت",
|
||||
WAITING_FOR_EXPERT: "در انتظار کارشناس تصادف",
|
||||
WAITING_FOR_USER_RESEND: "در انتظار تکمیل اطلاعات کاربر",
|
||||
IN_PERSON_VISIT_PENDING: "در انتظار مراجعه حضوری",
|
||||
WAITING_FOR_INSURER_APPROVAL: "در انتظار تأیید پرونده",
|
||||
INSURER_REVIEW_AWAITING_OWNER_SIGN: "در انتظار امضای مالک",
|
||||
INSURER_REVIEW_MIXED_FACTORS_PENDING: "در انتظار تأیید مبالغ و بارگذاری فاکتورها",
|
||||
OWNER_REPAIR_FACTOR_UPLOAD_PENDING: "در انتظار بارگذاری فاکتورها",
|
||||
EXPERT_VALIDATING_REPAIR_FACTORS: "در انتظار بررسی فاکتورها توسط کارشناس",
|
||||
WAITING_FOR_FILE_REVIEWER: "در انتظار کارشناس ارزیاب",
|
||||
WAITING_FOR_FILE_MAKER_APPROVAL: "در انتظار تأیید کارشناس مسئول پرونده",
|
||||
FILE_MAKER_REJECTED: "نیازمند اصلاح توسط کارشناس ارزیاب",
|
||||
AUTO_CLOSED: "بستهشده خودکار",
|
||||
|
||||
AGREED: "توافق",
|
||||
DISAGREEMENT: "اختلاف نظر",
|
||||
UNKNOWN: "نامشخص",
|
||||
@@ -333,7 +361,9 @@ export function persianFieldPath(path: string): string {
|
||||
if (!path) return PR.data;
|
||||
const parts = path.split(".").filter(Boolean);
|
||||
const last = parts[parts.length - 1] ?? path;
|
||||
const translatedLast = KEY_LABELS[last] ?? last;
|
||||
const translate = (key: string) => KEY_LABELS[key] ?? (/^\d+$/.test(key) ? Number(key).toLocaleString("fa-IR") : /[a-z]/i.test(key) ? "" : key);
|
||||
const translatedLast = translate(last);
|
||||
if (!translatedLast) return "";
|
||||
|
||||
const inquiryRoot = parts.find(
|
||||
(p) => p === "thirdParty" || p === "carBody" || p === "mapped",
|
||||
@@ -386,7 +416,7 @@ export function persianFieldPath(path: string): string {
|
||||
|
||||
if (parts.length === 1) return translatedLast;
|
||||
|
||||
const translated = parts.map((part) => KEY_LABELS[part] ?? part);
|
||||
const translated = parts.map(translate).filter(Boolean);
|
||||
return translated.join(" / ");
|
||||
}
|
||||
|
||||
@@ -399,36 +429,37 @@ export function persianReportValue(
|
||||
value: unknown,
|
||||
): unknown {
|
||||
if (value === undefined || value === null || value === "") return value;
|
||||
if (typeof value === "boolean") return value ? "بله" : "خیر";
|
||||
if (typeof value === "boolean") return path.endsWith("expedited") ? value ? "فوری" : "عادی" : value ? "بله" : "خیر";
|
||||
if (typeof value !== "string" && typeof value !== "number") return value;
|
||||
|
||||
const raw = String(value).trim();
|
||||
const key = raw.toUpperCase().replace(/[\s-]+/g, "_");
|
||||
const field = path.split(".").filter(Boolean).pop() ?? "";
|
||||
|
||||
if (field === "expedited") return raw === "true" || raw === "1" ? "فوری" : "عادی";
|
||||
if (field === "licenseType" || field === "LicenseType") {
|
||||
return LICENSE_TYPE_LABELS[key] ?? raw;
|
||||
return LICENSE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "عنوان گواهینامه ثبت نشده است" : raw);
|
||||
}
|
||||
if (field === "registrationState") {
|
||||
return REGISTRATION_STATE_LABELS[key] ?? raw;
|
||||
return REGISTRATION_STATE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
|
||||
}
|
||||
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? raw;
|
||||
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
|
||||
if (field === "role" || field.endsWith("Role")) {
|
||||
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? raw;
|
||||
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نقش ثبتنشده" : raw);
|
||||
}
|
||||
if (field === "blameRequestType" || field === "fileType") {
|
||||
return CASE_TYPE_LABELS[key] ?? raw;
|
||||
return CASE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع پرونده ثبت نشده است" : raw);
|
||||
}
|
||||
if (
|
||||
(field === "carType" || field === "type") &&
|
||||
path.toLowerCase().includes("vehicle")
|
||||
) {
|
||||
return VEHICLE_TYPE_LABELS[key] ?? raw;
|
||||
return VEHICLE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع خودرو ثبت نشده است" : raw);
|
||||
}
|
||||
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? raw;
|
||||
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? raw;
|
||||
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? (/[a-z]/i.test(raw) ? "نوع خسارت ثبت نشده است" : raw);
|
||||
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "استعلام ناموفق بود" : raw);
|
||||
if (/status$/i.test(field)) {
|
||||
return STATUS_LABELS[raw] ?? VALIDITY_LABELS[key] ?? raw;
|
||||
return STATUS_LABELS[key] ?? VALIDITY_LABELS[key] ?? (/[a-z]/i.test(raw) ? "وضعیت نامشخص" : raw);
|
||||
}
|
||||
|
||||
if (raw === "true" || raw === "false") return STATUS_LABELS[raw];
|
||||
@@ -438,7 +469,7 @@ export function persianReportValue(
|
||||
export function persianStatus(value: unknown): string | undefined {
|
||||
if (value === undefined || value === null || value === "") return undefined;
|
||||
const key = String(value);
|
||||
return STATUS_LABELS[key] ?? key;
|
||||
return STATUS_LABELS[key] ?? STATUS_LABELS[key.toLowerCase()] ?? (/[a-z]/i.test(key) ? "وضعیت نامشخص" : key);
|
||||
}
|
||||
|
||||
export function persianAccidentCondition(
|
||||
@@ -454,5 +485,5 @@ export function persianAccidentCondition(
|
||||
: kind === "road"
|
||||
? ROAD_LABELS
|
||||
: LIGHT_LABELS;
|
||||
return labels[normalized] ?? raw;
|
||||
return labels[normalized] ?? (/[a-z]/i.test(raw) ? "ثبت نشده است" : raw);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { buildFileLink } from "src/helpers/urlCreator";
|
||||
import { personDisplayName } from "src/helpers/person-display-name";
|
||||
import type { ReportAttachment } from "./case-expert-report.types";
|
||||
|
||||
const documentLabels: Record<string, string> = {
|
||||
accident_sketch: "کروکی",
|
||||
car_green_card: "برگه سبز خودرو",
|
||||
car_certificate: "سند خودرو",
|
||||
national_card: "کارت ملی",
|
||||
damaged_driving_license_front: "روی گواهینامه زیاندیده",
|
||||
damaged_driving_license_back: "پشت گواهینامه زیاندیده",
|
||||
damaged_chassis_number: "شماره شاسی",
|
||||
damaged_engine_photo: "شماره موتور",
|
||||
damaged_car_card_front: "روی کارت خودروی زیاندیده",
|
||||
damaged_car_card_back: "پشت کارت خودروی زیاندیده",
|
||||
damaged_metal_plate: "پلاک خودروی زیاندیده",
|
||||
guilty_driving_license_front: "روی گواهینامه مقصر",
|
||||
guilty_driving_license_back: "پشت گواهینامه مقصر",
|
||||
guilty_car_card_front: "روی کارت خودروی مقصر",
|
||||
guilty_car_card_back: "پشت کارت خودروی مقصر",
|
||||
guilty_metal_plate: "پلاک خودروی مقصر",
|
||||
guilty_damage_area: "آسیب خودروی مقصر",
|
||||
drivingLicense: "گواهینامه",
|
||||
nationalCertificate: "مدرک هویتی",
|
||||
carCertificate: "سند خودرو",
|
||||
carGreenCard: "برگه سبز خودرو",
|
||||
};
|
||||
const angleLabels: Record<string, string> = {
|
||||
front: "نمای جلو",
|
||||
back: "نمای عقب",
|
||||
left: "نمای چپ",
|
||||
right: "نمای راست",
|
||||
};
|
||||
|
||||
export function buildReportAttachments(
|
||||
claim: any,
|
||||
blame: any,
|
||||
blameDocuments: { path: string; documentType: string }[],
|
||||
invoices: { path: string }[],
|
||||
): ReportAttachment[] {
|
||||
const attachments = new Map<string, ReportAttachment>();
|
||||
function add(label: string, url: unknown) {
|
||||
if (typeof url !== "string" || !/(?:^|\/)files\/[^?#]+/.test(url)) return;
|
||||
const path =
|
||||
url
|
||||
.split(/[?#]/)[0]
|
||||
.split(/(?:^|\/)files\//)
|
||||
.at(-1) ?? "";
|
||||
if (!attachments.has(path)) attachments.set(path, { label, url });
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(claim?.carAngles ?? {})) {
|
||||
const angle = value as { url?: string };
|
||||
add(angleLabels[key] ?? "نمای خودرو", angle.url);
|
||||
}
|
||||
for (const part of claim?.damagedParts ?? []) {
|
||||
const name =
|
||||
typeof part.label_fa === "string" && /[\u0600-\u06ff]/.test(part.label_fa)
|
||||
? part.label_fa
|
||||
: "تصویر قطعه آسیبدیده";
|
||||
add(name, part.url);
|
||||
}
|
||||
for (const [key, value] of Object.entries(claim?.requiredDocuments ?? {})) {
|
||||
add(
|
||||
documentLabels[key] ?? "مدرک خسارت",
|
||||
(value as { fileUrl?: string }).fileUrl,
|
||||
);
|
||||
}
|
||||
for (const party of blame?.parties ?? []) {
|
||||
for (const image of party.evidence?.images ?? []) {
|
||||
if (typeof image === "string" && /(?:^|\/)files\//.test(image)) {
|
||||
add("تصویر حادثه", buildFileLink(image));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const document of blameDocuments) {
|
||||
if (document.path)
|
||||
add(
|
||||
documentLabels[document.documentType] ?? "مدرک حادثه",
|
||||
buildFileLink(document.path),
|
||||
);
|
||||
}
|
||||
|
||||
const evaluation = claim?.evaluation;
|
||||
for (const invoice of invoices) {
|
||||
if (invoice.path) add("فاکتور قطعه", buildFileLink(invoice.path));
|
||||
}
|
||||
for (const invoice of evaluation?.objection?.invoices ?? [])
|
||||
add("فاکتور اعتراض", invoice.url);
|
||||
return [...attachments.values()];
|
||||
}
|
||||
|
||||
export function buildReportSignatures(
|
||||
blame: any,
|
||||
claim: any,
|
||||
): ReportAttachment[] {
|
||||
const parties: any[] = blame?.parties ?? claim?.snapshot?.parties ?? [];
|
||||
const signatures: ReportAttachment[] = [];
|
||||
for (const [index, party] of parties.entries()) {
|
||||
const signature = party.confirmation?.signature;
|
||||
const url =
|
||||
signature?.link ||
|
||||
(signature?.fileUrl ? buildFileLink(signature.fileUrl) : undefined);
|
||||
if (!url) continue;
|
||||
const isSecond = party.role ? party.role === "SECOND" : index === 1;
|
||||
const role = isSecond ? "طرف دوم" : "طرف اول";
|
||||
const name = personDisplayName(party.person);
|
||||
signatures.push({
|
||||
label: name ? `امضای ${role} · ${name}` : `امضای ${role}`,
|
||||
url,
|
||||
});
|
||||
}
|
||||
const ownerSign =
|
||||
claim?.evaluation?.ownerInsurerApproval?.signLink ??
|
||||
claim?.evaluation?.ownerPricedPartsApproval?.signLink;
|
||||
if (ownerSign)
|
||||
signatures.push({
|
||||
label: "امضای زیاندیده برای تأیید خسارت",
|
||||
url: ownerSign,
|
||||
});
|
||||
const expert = claim?.fanavaranExpertSignature;
|
||||
if (expert?.image) {
|
||||
signatures.push({
|
||||
label:
|
||||
expert.name && expert.name !== "کارشناس پرونده"
|
||||
? `امضای کارشناس · ${expert.name}`
|
||||
: "امضای کارشناس",
|
||||
image: expert.image,
|
||||
});
|
||||
}
|
||||
return signatures;
|
||||
}
|
||||
@@ -118,6 +118,7 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz
|
||||
VideoCaptureDbService,
|
||||
ClaimRequiredDocumentDbService,
|
||||
ClaimSignDbService,
|
||||
ClaimFactorsImageDbService,
|
||||
],
|
||||
})
|
||||
export class ClaimRequestManagementModule {}
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
import { REVIEW_REFERRAL_DENIED } from 'src/expert-claim/review-referral/review-referral';
|
||||
import {
|
||||
assertFanavaranExpertSignature,
|
||||
fanavaranSignatureRevision,
|
||||
hasFanavaranExpertSignature,
|
||||
readFanavaranSignatureImage,
|
||||
requiresFanavaranExpertSignature,
|
||||
} from 'src/fanavaran/fanavaran-expert-signature';
|
||||
import { personDisplayName } from 'src/helpers/person-display-name';
|
||||
import { resolveClaimPriceDropAge } from "src/helpers/claim-price-drop";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { unlink } from "node:fs/promises";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
@@ -385,6 +396,7 @@ const FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX =
|
||||
'FANAVARAN_ATTACHMENT_FORMAT_WAIVED:';
|
||||
|
||||
interface FanavaranClaimExpertContext {
|
||||
reviewReferral?: { assigneeId?: unknown };
|
||||
initiatedByFieldExpertId?: unknown;
|
||||
evaluation?: object;
|
||||
workflow?: { assignedForReviewBy?: { actorId?: unknown } };
|
||||
@@ -2821,7 +2833,6 @@ export class ClaimRequestManagementService {
|
||||
parts: any[];
|
||||
claimExpertId: number;
|
||||
submittedAt: Date;
|
||||
priceDropTotal: number;
|
||||
priceDropCarPrice: unknown;
|
||||
warnings: string[];
|
||||
/** Non-blocking notices (factory-bundle fallbacks). Never gates submission. */
|
||||
@@ -2997,7 +3008,7 @@ export class ClaimRequestManagementService {
|
||||
dmgAssessmentDate: this.convertToPersianDate(input.submittedAt),
|
||||
inspectionTime: this.getTime24Hour(input.submittedAt),
|
||||
wage, componentReplacementCost, wasteValue,
|
||||
dropAmount: input.priceDropTotal || 0,
|
||||
dropAmount: 0,
|
||||
vehicleCurrentValue, vehicle, colorId, repairDuration,
|
||||
dmgSections: hullSections,
|
||||
});
|
||||
@@ -3614,7 +3625,7 @@ export class ClaimRequestManagementService {
|
||||
return this.fanavaranLocationService.resolveBusinessLocation({
|
||||
clientKey,
|
||||
requireStaffLocation: true,
|
||||
staffCandidateIds: [
|
||||
staffCandidateIds: (claimCase.reviewReferral ? [claimCase.reviewReferral.assigneeId] : [
|
||||
claimCase.initiatedByFieldExpertId,
|
||||
blame?.initiatedByFieldExpertId,
|
||||
this.fanavaranDamageReplyActorId(claimCase),
|
||||
@@ -3622,7 +3633,7 @@ export class ClaimRequestManagementService {
|
||||
blame?.assignedFileReviewerId,
|
||||
blame?.expert?.assignedExpertId,
|
||||
blame?.expert?.decision?.decidedByExpertId,
|
||||
].map((id) => (id == null ? undefined : String(id))),
|
||||
]).map((id) => (id == null ? undefined : String(id))),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -3756,6 +3767,7 @@ export class ClaimRequestManagementService {
|
||||
const candidateIds = [
|
||||
...new Set(
|
||||
[
|
||||
claimCase?.reviewReferral?.assigneeId,
|
||||
blame.initiatedByFieldExpertId,
|
||||
blame.expert?.assignedExpertId,
|
||||
blame.expert?.decision?.decidedByExpertId,
|
||||
@@ -3861,7 +3873,7 @@ export class ClaimRequestManagementService {
|
||||
type?: BlameRequestType;
|
||||
assignedFileReviewerId?: unknown;
|
||||
},
|
||||
claimCase: { evaluation?: Record<string, unknown> } | null | undefined,
|
||||
claimCase: FanavaranClaimExpertContext | null | undefined,
|
||||
): Promise<{
|
||||
claimExpertId: number | null;
|
||||
code: string | null;
|
||||
@@ -3883,7 +3895,8 @@ export class ClaimRequestManagementService {
|
||||
}
|
||||
|
||||
if (blame.isMadeByFileMaker) {
|
||||
if (!blame.assignedFileReviewerId) {
|
||||
const reviewerId = claimCase?.reviewReferral?.assigneeId ?? blame.assignedFileReviewerId;
|
||||
if (!reviewerId) {
|
||||
return {
|
||||
claimExpertId: null,
|
||||
code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING',
|
||||
@@ -3892,7 +3905,7 @@ export class ClaimRequestManagementService {
|
||||
candidatesTried: [],
|
||||
};
|
||||
}
|
||||
const fileReviewerId = String(blame.assignedFileReviewerId);
|
||||
const fileReviewerId = String(reviewerId);
|
||||
const fileReviewer =
|
||||
await this.fileReviewerDbService.findById(fileReviewerId);
|
||||
if (!fileReviewer) {
|
||||
@@ -3920,7 +3933,7 @@ export class ClaimRequestManagementService {
|
||||
};
|
||||
}
|
||||
|
||||
const actorId = this.fanavaranDamageReplyActorId(claimCase);
|
||||
const actorId = claimCase?.reviewReferral?.assigneeId ?? this.fanavaranDamageReplyActorId(claimCase);
|
||||
if (actorId == null || String(actorId).trim() === '') {
|
||||
return {
|
||||
claimExpertId: null,
|
||||
@@ -3968,7 +3981,7 @@ export class ClaimRequestManagementService {
|
||||
type?: BlameRequestType;
|
||||
assignedFileReviewerId?: unknown;
|
||||
},
|
||||
claimCase: { evaluation?: Record<string, unknown> } | null | undefined,
|
||||
claimCase: FanavaranClaimExpertContext | null | undefined,
|
||||
options?: { required?: boolean },
|
||||
): Promise<number | null> {
|
||||
const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId(
|
||||
@@ -6331,7 +6344,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,
|
||||
@@ -6340,7 +6355,7 @@ export class ClaimRequestManagementService {
|
||||
return this.buildCarBodyFanavaranExpertisePayload({
|
||||
clientKey: input.clientKey, claimCase: input.claimCase,
|
||||
blame: blameForExpertIds, profile, parts, claimExpertId,
|
||||
submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice,
|
||||
submittedAt, priceDropCarPrice: priceDrop?.carPrice,
|
||||
warnings, infoWarnings, replyKey: active?.replyKey,
|
||||
});
|
||||
}
|
||||
@@ -6542,24 +6557,96 @@ export class ClaimRequestManagementService {
|
||||
});
|
||||
}
|
||||
|
||||
async getFanavaranExpertSignatureStatus(
|
||||
id: string,
|
||||
actor: { sub: string; role?: string },
|
||||
) {
|
||||
const claim = await this.claimCaseDbService.findWithFanavaranSignature(id);
|
||||
if (!claim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
|
||||
return {
|
||||
required: true,
|
||||
signed: hasFanavaranExpertSignature(claim, actor),
|
||||
revision: fanavaranSignatureRevision(claim),
|
||||
submitted: claim.expertiseId != null,
|
||||
};
|
||||
}
|
||||
|
||||
async saveFanavaranExpertSignature(
|
||||
id: string,
|
||||
actor: { sub: string; role: string; fullName?: string },
|
||||
body: { revision?: string; image?: string },
|
||||
) {
|
||||
const image = readFanavaranSignatureImage(body?.image);
|
||||
const claim = await this.claimCaseDbService.findWithFanavaranSignature(id);
|
||||
if (!claim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
|
||||
if (claim.expertiseId != null) {
|
||||
throw new ConflictException('ثبت نهایی پرونده در فناوران انجام شده است.');
|
||||
}
|
||||
const revision = fanavaranSignatureRevision(claim);
|
||||
if (revision !== body?.revision) {
|
||||
throw new ConflictException({
|
||||
code: 'FANAVARAN_EXPERT_SIGNATURE_REQUIRED',
|
||||
message: 'اطلاعات پرونده تغییر کرده است. پرونده را دوباره بررسی و امضا کنید.',
|
||||
});
|
||||
}
|
||||
const updated = await this.claimCaseDbService.findOneAndUpdate(
|
||||
{
|
||||
_id: claim._id, expertiseId: null, updatedAt: (claim as any).updatedAt,
|
||||
$or: [
|
||||
{ 'fanavaranExpertSignature.submissionExpiresAt': null },
|
||||
{ 'fanavaranExpertSignature.submissionExpiresAt': { $lte: new Date() } },
|
||||
],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
fanavaranExpertSignature: {
|
||||
image, revision,
|
||||
actorId: String(actor.sub),
|
||||
actorRole: actor.role,
|
||||
name: personDisplayName(actor) || 'کارشناس پرونده',
|
||||
signedAt: new Date(),
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!updated) throw new ConflictException('پرونده تغییر کرده است. دوباره تلاش کنید.');
|
||||
return { required: true, signed: true, revision, submitted: false };
|
||||
}
|
||||
|
||||
async submitFanavaranExpertiseV2(
|
||||
claimCaseId: string,
|
||||
clientKey: FanavaranClientKey,
|
||||
bodyOverride?: Record<string, unknown>,
|
||||
actor?: { sub: string; role?: string },
|
||||
): Promise<any> {
|
||||
try {
|
||||
const manualSubmission =
|
||||
bodyOverride != null && Object.keys(bodyOverride).length > 0;
|
||||
const signatureRequired = requiresFanavaranExpertSignature();
|
||||
if (signatureRequired) {
|
||||
if (manualSubmission) {
|
||||
throw new BadRequestException('با فعال بودن امضای کارشناس، ارسال فقط با اطلاعات ذخیرهشده پرونده انجام میشود.');
|
||||
}
|
||||
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(claimCaseId);
|
||||
if (!signedClaim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
|
||||
if (signedClaim.expertiseId != null) {
|
||||
return signedClaim.fanavaranSync?.expertise?.response ?? { Id: signedClaim.expertiseId };
|
||||
}
|
||||
assertFanavaranExpertSignature(signedClaim, actor);
|
||||
}
|
||||
await this.completeFanavaranExpertisePrerequisites(
|
||||
claimCaseId,
|
||||
clientKey,
|
||||
FanavaranAuditSource.SUBMIT,
|
||||
);
|
||||
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
|
||||
const claimCase = signatureRequired
|
||||
? await this.claimCaseDbService.findWithFanavaranSignature(claimCaseId)
|
||||
: await this.claimCaseDbService.findById(claimCaseId);
|
||||
if (!claimCase) throw new NotFoundException('Claim case not found');
|
||||
if (claimCase.expertiseId != null) {
|
||||
return claimCase.fanavaranSync?.expertise?.response ?? { Id: claimCase.expertiseId };
|
||||
}
|
||||
if (signatureRequired) assertFanavaranExpertSignature(claimCase, actor);
|
||||
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
|
||||
const built = await this.buildFanavaranExpertisePayload({
|
||||
claimCase,
|
||||
@@ -6570,17 +6657,22 @@ export class ClaimRequestManagementService {
|
||||
built.payload,
|
||||
bodyOverride,
|
||||
);
|
||||
if (product === 'car-body') payload.DropAmount = 0;
|
||||
this.assertFanavaranExpertisePayloadReady(
|
||||
payload,
|
||||
manualSubmission ? [] : built.warnings,
|
||||
{ ...hullExpertiseAssertFields(product) },
|
||||
);
|
||||
const signatureArgs: [typeof actor?, string?] = signatureRequired
|
||||
? [actor, fanavaranSignatureRevision(claimCase)]
|
||||
: [];
|
||||
const result = await this.executeFanavaranExpertiseSubmit(
|
||||
claimCaseId,
|
||||
clientKey,
|
||||
payload,
|
||||
FanavaranAuditSource.SUBMIT,
|
||||
manualSubmission,
|
||||
...signatureArgs,
|
||||
);
|
||||
// Surface infoWarnings (e.g. factory-bundle fallbacks) on the success
|
||||
// response so callers are informed, without ever blocking the submit.
|
||||
@@ -6604,6 +6696,8 @@ export class ClaimRequestManagementService {
|
||||
payload: Record<string, unknown>,
|
||||
auditSource: FanavaranAuditSource,
|
||||
preservePayload = false,
|
||||
signingActor?: { sub: string; role?: string },
|
||||
signedRevision?: string,
|
||||
): Promise<any> {
|
||||
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
|
||||
if (!claimCase) throw new NotFoundException('Claim case not found');
|
||||
@@ -6664,6 +6758,38 @@ export class ClaimRequestManagementService {
|
||||
requestMeta: { claimId: claimCase.claimId },
|
||||
});
|
||||
|
||||
let submissionId: string | undefined;
|
||||
if (requiresFanavaranExpertSignature()) {
|
||||
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(claimCaseId);
|
||||
if (!signedClaim) throw new NotFoundException('پرونده خسارت پیدا نشد.');
|
||||
if (signedClaim.expertiseId != null) {
|
||||
return signedClaim.fanavaranSync?.expertise?.response ?? { Id: signedClaim.expertiseId };
|
||||
}
|
||||
assertFanavaranExpertSignature(signedClaim, signingActor);
|
||||
if (signedClaim.fanavaranExpertSignature?.revision !== signedRevision) {
|
||||
throw new ConflictException({
|
||||
code: 'FANAVARAN_EXPERT_SIGNATURE_REQUIRED',
|
||||
message: 'اطلاعات پرونده تغییر کرده است. پرونده را دوباره بررسی کنید.',
|
||||
});
|
||||
}
|
||||
submissionId = randomUUID();
|
||||
const locked = await this.claimCaseDbService.findOneAndUpdate(
|
||||
{
|
||||
_id: signedClaim._id,
|
||||
expertiseId: null,
|
||||
updatedAt: (signedClaim as any).updatedAt,
|
||||
$or: [
|
||||
{ 'fanavaranExpertSignature.submissionExpiresAt': null },
|
||||
{ 'fanavaranExpertSignature.submissionExpiresAt': { $lte: new Date() } },
|
||||
],
|
||||
},
|
||||
{ $set: {
|
||||
'fanavaranExpertSignature.submissionId': submissionId,
|
||||
'fanavaranExpertSignature.submissionExpiresAt': new Date(Date.now() + 5 * 60_000),
|
||||
} },
|
||||
);
|
||||
if (!locked) throw new ConflictException('پرونده در حال ارسال است یا تغییر کرده است. دوباره تلاش کنید.');
|
||||
}
|
||||
try {
|
||||
const response = await this.postFanavaranJson(
|
||||
url,
|
||||
@@ -6725,6 +6851,16 @@ export class ClaimRequestManagementService {
|
||||
durationMs: Date.now() - startedAt,
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
if (submissionId) {
|
||||
await this.claimCaseDbService.findOneAndUpdate(
|
||||
{ _id: claimCaseId, 'fanavaranExpertSignature.submissionId': submissionId },
|
||||
{ $unset: {
|
||||
'fanavaranExpertSignature.submissionId': '',
|
||||
'fanavaranExpertSignature.submissionExpiresAt': '',
|
||||
} },
|
||||
).catch(() => this.logger.warn('Could not release Fanavaran expertise submission lock.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6755,6 +6891,15 @@ export class ClaimRequestManagementService {
|
||||
};
|
||||
}
|
||||
|
||||
if (requiresFanavaranExpertSignature()) {
|
||||
return {
|
||||
attempted: false,
|
||||
submitted: false,
|
||||
skipped: true,
|
||||
skipReason: 'در انتظار امضای کارشناس و ارسال نهایی به فناوران',
|
||||
};
|
||||
}
|
||||
|
||||
// Same ordered soft-ensure as manual expertise submit: base → damage → files.
|
||||
await this.completeFanavaranExpertisePrerequisites(
|
||||
claimCaseId,
|
||||
@@ -8052,6 +8197,21 @@ export class ClaimRequestManagementService {
|
||||
clientKey: FanavaranClientKey,
|
||||
bodyOverride?: Record<string, unknown>,
|
||||
auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT,
|
||||
): Promise<any> {
|
||||
const release = await this.claimCaseDbService.acquireReviewWrite(claimCaseId);
|
||||
if (!release) throw new NotFoundException('Claim case not found');
|
||||
try {
|
||||
return await this.executeFanavaranBaseClaim(claimCaseId, clientKey, bodyOverride, auditSource);
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
}
|
||||
|
||||
private async executeFanavaranBaseClaim(
|
||||
claimCaseId: string,
|
||||
clientKey: FanavaranClientKey,
|
||||
bodyOverride: Record<string, unknown> | undefined,
|
||||
auditSource: FanavaranAuditSource,
|
||||
): Promise<any> {
|
||||
const logPrefix = `[Fanavaran ${clientKey} V2]`;
|
||||
|
||||
@@ -11903,6 +12063,9 @@ export class ClaimRequestManagementService {
|
||||
claimCase: any,
|
||||
blame: any,
|
||||
): Promise<void> {
|
||||
if (claimCase.reviewReferral) {
|
||||
throw new ForbiddenException(REVIEW_REFERRAL_DENIED);
|
||||
}
|
||||
if (
|
||||
claimCase.workflow?.currentStep === ClaimWorkflowStep.SELECT_OUTER_PARTS
|
||||
) {
|
||||
@@ -11943,14 +12106,23 @@ export class ClaimRequestManagementService {
|
||||
);
|
||||
}
|
||||
|
||||
await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), {
|
||||
const update = {
|
||||
$set: {
|
||||
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
|
||||
claimStatus: ClaimStatus.PENDING,
|
||||
'workflow.currentStep': ClaimWorkflowStep.SELECT_OUTER_PARTS,
|
||||
'workflow.nextStep': ClaimWorkflowStep.SELECT_OTHER_PARTS,
|
||||
},
|
||||
});
|
||||
};
|
||||
if (isFileReviewerReentry || claimCase.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT) {
|
||||
const resumed = await this.claimCaseDbService.findOneAndUpdate(
|
||||
{ _id: claimCase._id, status: claimCase.status, reviewReferral: null },
|
||||
update,
|
||||
);
|
||||
if (!resumed) throw new ConflictException('پرونده تغییر کرده است. وضعیت پرونده را دوباره دریافت کنید.');
|
||||
} else {
|
||||
await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), update);
|
||||
}
|
||||
}
|
||||
|
||||
private async assertV3InPersonClaim(claimCase: any) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
Controller,
|
||||
@@ -64,6 +65,7 @@ import { UserObjectionV2Dto } from "./dto/user-objection-v2.dto";
|
||||
import { UserRatingDto } from "./dto/user-rating.dto";
|
||||
|
||||
@ApiTags("claim-request-management (v2)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/claim-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(GlobalGuard, RolesGuard)
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { Injectable, Logger } from "@nestjs/common";
|
||||
import { InjectModel } from "@nestjs/mongoose";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { FilterQuery, Model, Types } from "mongoose";
|
||||
import { ClaimCase, ClaimCaseDocument } from "../schema/claim-cases.schema";
|
||||
|
||||
@Injectable()
|
||||
export class ClaimCaseDbService {
|
||||
private readonly logger = new Logger(ClaimCaseDbService.name);
|
||||
constructor(
|
||||
@InjectModel(ClaimCase.name)
|
||||
private readonly claimCaseModel: Model<ClaimCaseDocument>,
|
||||
@@ -20,6 +22,74 @@ export class ClaimCaseDbService {
|
||||
return this.claimCaseModel.findById(id);
|
||||
}
|
||||
|
||||
findReviewAccess(id: string) {
|
||||
return this.claimCaseModel
|
||||
.findById(id)
|
||||
.select(
|
||||
"reviewReferral owner.clientId owner.userClientKey fileMakerApprovalActorId initiatedByFieldExpertId status",
|
||||
)
|
||||
.lean()
|
||||
.exec();
|
||||
}
|
||||
|
||||
async acquireReviewWrite(
|
||||
id: string,
|
||||
filter: Record<string, Date | Types.ObjectId | null> = {},
|
||||
) {
|
||||
const token = randomUUID();
|
||||
const now = new Date();
|
||||
// Bounded recovery for abandoned requests after an API process stops.
|
||||
const expiresAt = new Date(now.getTime() + 60 * 60_000);
|
||||
const _id = new Types.ObjectId(id);
|
||||
// Internal leases must not change the case's updatedAt or audit timestamp.
|
||||
const acquired = await this.claimCaseModel.collection.findOneAndUpdate(
|
||||
{ ...filter, _id },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
reviewWrites: {
|
||||
$concatArrays: [
|
||||
{
|
||||
$filter: {
|
||||
input: { $ifNull: ["$reviewWrites", []] },
|
||||
as: "write",
|
||||
cond: { $gt: ["$$write.expiresAt", now] },
|
||||
},
|
||||
},
|
||||
[{ token, expiresAt }],
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
{ projection: { _id: 1 } },
|
||||
);
|
||||
if (!acquired) return null;
|
||||
return async () => {
|
||||
try {
|
||||
await this.claimCaseModel.collection.updateOne({ _id }, [
|
||||
{
|
||||
$set: {
|
||||
reviewWrites: {
|
||||
$filter: {
|
||||
input: { $ifNull: ["$reviewWrites", []] },
|
||||
as: "write",
|
||||
cond: { $ne: ["$$write.token", token] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
} catch {
|
||||
this.logger.warn("Could not release review write for claim " + id);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
async findWithFanavaranSignature(id: string | Types.ObjectId) {
|
||||
return this.claimCaseModel.findById(id).select("+fanavaranExpertSignature");
|
||||
}
|
||||
|
||||
async findOne(
|
||||
filter: FilterQuery<ClaimCase>,
|
||||
): Promise<ClaimCaseDocument | null> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectModel } from "@nestjs/mongoose";
|
||||
import { Model } from "mongoose";
|
||||
import { Model, Types } from "mongoose";
|
||||
import { ClaimFactorsImage } from "src/claim-request-management/entites/schema/factor-image.schema";
|
||||
|
||||
@Injectable()
|
||||
@@ -13,6 +13,10 @@ export class ClaimFactorsImageDbService {
|
||||
return await this.model.create(image);
|
||||
}
|
||||
|
||||
async findByClaimId(id: string): Promise<ClaimFactorsImage[]> {
|
||||
return this.model.find({ claimId: new Types.ObjectId(id) }).lean();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<ClaimFactorsImage | null> {
|
||||
return this.model.findById(id).lean();
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
ClaimWorkflowSchema,
|
||||
} from "./claim-case.workflow.schema";
|
||||
import { UserClaimRating } from "./claim-request-management.schema";
|
||||
import type { FanavaranExpertSignature } from "src/fanavaran/fanavaran-expert-signature";
|
||||
import type { FanavaranFieldReview } from "../../fanavaran-stage-fields";
|
||||
import {
|
||||
CaseInquiries,
|
||||
@@ -253,6 +254,29 @@ export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass(
|
||||
FanavaranVehicleReview,
|
||||
);
|
||||
|
||||
@Schema({ _id: false })
|
||||
export class ClaimReviewReferral {
|
||||
@Prop({ type: Types.ObjectId, required: true })
|
||||
assigneeId: Types.ObjectId;
|
||||
|
||||
@Prop({ type: String, required: true })
|
||||
assigneeRole: string;
|
||||
|
||||
@Prop({ type: Date, required: true })
|
||||
referredAt: Date;
|
||||
}
|
||||
const ClaimReviewReferralSchema = SchemaFactory.createForClass(ClaimReviewReferral);
|
||||
|
||||
@Schema({ _id: false })
|
||||
class ClaimReviewWrite {
|
||||
@Prop({ type: String, required: true })
|
||||
token: string;
|
||||
|
||||
@Prop({ type: Date, required: true })
|
||||
expiresAt: Date;
|
||||
}
|
||||
const ClaimReviewWriteSchema = SchemaFactory.createForClass(ClaimReviewWrite);
|
||||
|
||||
@Schema({
|
||||
collection: "claimCases",
|
||||
timestamps: true,
|
||||
@@ -260,6 +284,7 @@ export const FanavaranVehicleReviewSchema = SchemaFactory.createForClass(
|
||||
versionKey: false,
|
||||
})
|
||||
export class ClaimCase {
|
||||
updatedAt?: Date;
|
||||
@Prop({ required: true, unique: true, index: true, trim: true })
|
||||
requestNo: string;
|
||||
|
||||
@@ -311,7 +336,7 @@ export class ClaimCase {
|
||||
@Prop({ type: Types.ObjectId, index: true })
|
||||
initiatedByFieldExpertId?: Types.ObjectId;
|
||||
|
||||
/** Routing branch inherited from the blame (user selection or expert-created branch). */
|
||||
/** Current review branch, initially inherited from the originating blame branch. */
|
||||
@Prop({ type: Types.ObjectId, index: true })
|
||||
branchId?: Types.ObjectId;
|
||||
|
||||
@@ -323,6 +348,12 @@ export class ClaimCase {
|
||||
@Prop({ type: Types.ObjectId, index: true })
|
||||
damagedPartyUserId?: Types.ObjectId;
|
||||
|
||||
@Prop({ type: ClaimReviewReferralSchema })
|
||||
reviewReferral?: ClaimReviewReferral;
|
||||
|
||||
@Prop({ type: [ClaimReviewWriteSchema], select: false, default: undefined })
|
||||
reviewWrites?: ClaimReviewWrite[];
|
||||
|
||||
@Prop({ type: ClaimWorkflowSchema, default: () => ({}) })
|
||||
workflow?: ClaimWorkflow;
|
||||
|
||||
@@ -350,6 +381,9 @@ export class ClaimCase {
|
||||
@Prop({ type: FanavaranSyncStateSchema, default: () => ({}) })
|
||||
fanavaranSync?: FanavaranSyncState;
|
||||
|
||||
@Prop({ type: MongooseSchema.Types.Mixed, select: false })
|
||||
fanavaranExpertSignature?: FanavaranExpertSignature;
|
||||
|
||||
/** Expert-approved Fanavaran vehicle classification used by outbound stages. */
|
||||
@Prop({ type: FanavaranVehicleReviewSchema })
|
||||
fanavaranVehicleReview?: FanavaranVehicleReview;
|
||||
@@ -440,3 +474,4 @@ export class ClaimCase {
|
||||
export type ClaimCaseDocument = HydratedDocument<ClaimCase>;
|
||||
export const ClaimCaseSchema = SchemaFactory.createForClass(ClaimCase);
|
||||
ClaimCaseSchema.index({ status: 1, "workflow.locked": 1 });
|
||||
ClaimCaseSchema.index({ "reviewReferral.assigneeId": 1 }, { sparse: true });
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { extname } from "node:path";
|
||||
@@ -68,6 +69,7 @@ import { Role } from "src/common/auth/enums";
|
||||
* from their own account through the normal user endpoints.
|
||||
*/
|
||||
@ApiTags("expert-initiated claim (mirror v2)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/expert-initiated/claim-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -121,6 +121,7 @@ describe("Fanavaran outgoing Location headers", () => {
|
||||
? { locations: [{ id: "110011", name: "Claim branch" }] }
|
||||
: null,
|
||||
);
|
||||
management.claimCaseDbService.acquireReviewWrite = async () => async () => {};
|
||||
management.assertFanavaranVehicleReviewApproved = jest.fn();
|
||||
management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
|
||||
PolicyId: 1,
|
||||
|
||||
@@ -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 ?? 0 } }),
|
||||
);
|
||||
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(product === "car-body" || age > 10 ? 0 : 999);
|
||||
expect(claimCase.evaluation.priceDrop.total).toBe(999); // Historical data is preserved.
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -4,7 +4,18 @@ import { toFanavaranHullBaseClaimPayload } from "./fanavaran-hull-base-claim";
|
||||
function setup(product = "car-body") {
|
||||
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
|
||||
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) };
|
||||
service.claimCaseDbService = {
|
||||
acquireReviewWrite: async () => async () => {},
|
||||
findById: jest.fn().mockResolvedValue({
|
||||
fanavaranVehicleReview: {
|
||||
approved: true,
|
||||
vehicleGroup: { id: 1 },
|
||||
vehicleUseType: { id: 3 },
|
||||
vehicleSystem: { id: 14 },
|
||||
vehicleKind: { id: 7456 },
|
||||
},
|
||||
}),
|
||||
};
|
||||
service.fanavaranAuditService = { generateTrackingCode: () => "test" };
|
||||
service.fanavaranAuthService = { assertNotInBackoff: jest.fn() };
|
||||
service.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
@@ -63,6 +64,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-
|
||||
* The registrar's job ends here — no reviewing panel is needed.
|
||||
*/
|
||||
@ApiTags("registrar claim (mirror v2)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/registrar/claim-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ClientWorkingHoursService } from "./working-hours/client-working-hours.service";
|
||||
import { UserClaimBranchService } from "./user-claim-branch.service";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MongooseModule } from "@nestjs/mongoose";
|
||||
@@ -34,6 +35,7 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema";
|
||||
ClientDbService,
|
||||
BranchDbService,
|
||||
ExternalInquirySettingsService,
|
||||
ClientWorkingHoursService,
|
||||
],
|
||||
exports: [
|
||||
UserClaimBranchService,
|
||||
@@ -41,6 +43,7 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema";
|
||||
ClientDbService,
|
||||
BranchDbService,
|
||||
ExternalInquirySettingsService,
|
||||
ClientWorkingHoursService,
|
||||
],
|
||||
})
|
||||
export class ClientModule {}
|
||||
|
||||
@@ -56,6 +56,14 @@ export class ClientDbService implements OnModuleInit {
|
||||
return this.clientModel.findOne(client);
|
||||
}
|
||||
|
||||
async findWorkingHours(filter: FilterQuery<ClientModel>) {
|
||||
return this.clientModel
|
||||
.findOne(filter)
|
||||
.select("settings.workingHours")
|
||||
.lean()
|
||||
.exec();
|
||||
}
|
||||
|
||||
async findAll(): Promise<ClientModel[]> {
|
||||
return await this.clientModel.find();
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
|
||||
import type { WorkingHours } from "src/client/working-hours/working-hours";
|
||||
import type { ExternalInquiryFlags } from "src/common/types/external-inquiry.types";
|
||||
|
||||
export type ClientDocument = ClientModel & Document;
|
||||
@@ -68,6 +69,9 @@ export class ClientExternalInquirySettings implements Partial<ExternalInquiryFla
|
||||
* working when a field is missing.
|
||||
*/
|
||||
export class ClientSettings {
|
||||
@Prop({ type: Object, required: false })
|
||||
workingHours?: WorkingHours;
|
||||
|
||||
/**
|
||||
* Max number of days between the accident and the moment a CAR_BODY blame
|
||||
* file is allowed to be submitted. When unset, consumers fall back to the
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
SetMetadata,
|
||||
} from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
import { Types } from "mongoose";
|
||||
import { Observable } from "rxjs";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
|
||||
import {
|
||||
actorWorkingHoursClientId,
|
||||
ClientWorkingHoursService,
|
||||
responsibleBlameInsurer,
|
||||
workingHoursClientId,
|
||||
} from "./client-working-hours.service";
|
||||
|
||||
const CASE_WRITES = Symbol("case-working-hours");
|
||||
type CaseWriteOptions = { genericId?: "blame" };
|
||||
export const EnforceCaseWorkingHours = (options: CaseWriteOptions = {}) =>
|
||||
SetMetadata(CASE_WRITES, options);
|
||||
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
||||
const caseScheduleScope = new AsyncLocalStorage<
|
||||
(clientId: string) => Promise<void>
|
||||
>();
|
||||
|
||||
// An intake inquiry can identify a different insurer before the case is saved.
|
||||
export async function checkDiscoveredCaseInsurer(value: unknown) {
|
||||
const clientId = workingHoursClientId(value);
|
||||
if (clientId) await caseScheduleScope.getStore()?.(clientId);
|
||||
}
|
||||
|
||||
export function checkDiscoveredBlameInsurer(
|
||||
blame: Parameters<typeof responsibleBlameInsurer>[0],
|
||||
) {
|
||||
return checkDiscoveredCaseInsurer(responsibleBlameInsurer(blame));
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class CaseWorkingHoursInterceptor implements NestInterceptor {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly hours: ClientWorkingHoursService,
|
||||
private readonly claims: ClaimCaseDbService,
|
||||
private readonly blames: BlameRequestDbService,
|
||||
) {}
|
||||
|
||||
async intercept(context: ExecutionContext, next: CallHandler) {
|
||||
const rule = this.reflector.getAllAndOverride<CaseWriteOptions>(
|
||||
CASE_WRITES,
|
||||
[context.getHandler(), context.getClass()],
|
||||
);
|
||||
const req = context.switchToHttp().getRequest();
|
||||
if (!rule || !req.user?.sub || !WRITE_METHODS.has(req.method))
|
||||
return next.handle();
|
||||
|
||||
const now = new Date();
|
||||
const scope = await this.resolveScope(req.params ?? {}, rule);
|
||||
if (!scope) return next.handle(); // Keep existing invalid/missing case responses.
|
||||
const checked = new Set<string | undefined>();
|
||||
const check = async (clientId?: string) => {
|
||||
if (checked.has(clientId)) return;
|
||||
await this.hours.assertOpen(clientId, now);
|
||||
checked.add(clientId);
|
||||
};
|
||||
await check(scope.clientId ?? actorWorkingHoursClientId(req.user));
|
||||
|
||||
// Subscribe inside the scope so asynchronous handlers and multipart processing inherit it.
|
||||
return new Observable((subscriber) =>
|
||||
caseScheduleScope.run(check, () => next.handle().subscribe(subscriber)),
|
||||
);
|
||||
}
|
||||
|
||||
private async resolveScope(
|
||||
params: Record<string, string>,
|
||||
rule: CaseWriteOptions,
|
||||
) {
|
||||
const claimId = params.claimRequestId ?? params.claimCaseId;
|
||||
let blameId =
|
||||
params.blameRequestId ??
|
||||
params.requestId ??
|
||||
(rule.genericId === "blame" ? params.id : undefined);
|
||||
if (claimId) {
|
||||
if (!workingHoursClientId(claimId)) return null;
|
||||
const [claim] = (await this.claims.find(
|
||||
{ _id: new Types.ObjectId(claimId) },
|
||||
{
|
||||
lean: true,
|
||||
select: "owner.clientId owner.userClientKey blameRequestId",
|
||||
},
|
||||
)) as Record<string, any>[];
|
||||
if (!claim) return null;
|
||||
const tenant =
|
||||
workingHoursClientId(claim.owner?.clientId) ??
|
||||
workingHoursClientId(claim.owner?.userClientKey);
|
||||
if (tenant) return { clientId: tenant };
|
||||
blameId = claim.blameRequestId ? String(claim.blameRequestId) : undefined;
|
||||
}
|
||||
|
||||
if (!blameId) return {};
|
||||
if (!workingHoursClientId(blameId)) return null;
|
||||
const [blame] = await this.blames.find(
|
||||
{ _id: new Types.ObjectId(blameId) },
|
||||
{
|
||||
lean: true,
|
||||
select:
|
||||
"type blameStatus parties.role parties.person.clientId parties.person.userId parties.statement expert.decision.guiltyPartyId callCenterInitiated workingHoursIntakeClientId",
|
||||
},
|
||||
);
|
||||
if (!blame) return claimId ? {} : null;
|
||||
return {
|
||||
clientId:
|
||||
responsibleBlameInsurer(blame) ??
|
||||
workingHoursClientId(blame.workingHoursIntakeClientId),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { resolveGuiltyPartyClientId } from "src/helpers/tenant-scope";
|
||||
import { ClientDbService } from "../entities/db-service/client.db.service";
|
||||
import {
|
||||
defaultWorkingHours,
|
||||
getNextOpening,
|
||||
parseWorkingHours,
|
||||
workingHoursMessage,
|
||||
} from "./working-hours";
|
||||
|
||||
export function workingHoursClientId(value: unknown): string | undefined {
|
||||
const id = String(value ?? "");
|
||||
return /^[a-f\d]{24}$/i.test(id) ? id.toLowerCase() : undefined;
|
||||
}
|
||||
|
||||
export function actorWorkingHoursClientId(actor: {
|
||||
role?: string;
|
||||
clientKey?: unknown;
|
||||
}) {
|
||||
// The public user's JWT clientKey is not their insurer.
|
||||
return actor?.role && actor.role !== RoleEnum.USER
|
||||
? workingHoursClientId(actor.clientKey)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
type CaseParties = {
|
||||
type?: unknown;
|
||||
blameStatus?: unknown;
|
||||
expert?: { decision?: { guiltyPartyId?: unknown } };
|
||||
callCenterInitiated?: unknown;
|
||||
parties?: Array<{
|
||||
role?: string;
|
||||
person?: { clientId?: unknown; userId?: unknown };
|
||||
statement?: { admitsGuilt?: boolean; claimsDamage?: boolean };
|
||||
}>;
|
||||
};
|
||||
|
||||
export function responsibleBlameInsurer(blame: CaseParties | null | undefined) {
|
||||
if (!blame) return undefined;
|
||||
const first = blame.parties?.find((party) => party.role === "FIRST");
|
||||
if (blame.type === "CAR_BODY")
|
||||
return workingHoursClientId(first?.person?.clientId);
|
||||
if (
|
||||
blame.expert?.decision?.guiltyPartyId ||
|
||||
blame.parties?.some((party) => party.statement?.admitsGuilt)
|
||||
) {
|
||||
return workingHoursClientId(resolveGuiltyPartyClientId(blame));
|
||||
}
|
||||
// AGREED can mean that the first party reported being the injured party.
|
||||
if (blame.blameStatus === "AGREED" && first?.statement?.claimsDamage) {
|
||||
const second = blame.parties?.find((party) => party.role === "SECOND");
|
||||
return workingHoursClientId(second?.person?.clientId);
|
||||
}
|
||||
return blame.blameStatus === "AGREED" || blame.callCenterInitiated
|
||||
? workingHoursClientId(first?.person?.clientId)
|
||||
: undefined;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
export class ClientWorkingHoursService {
|
||||
constructor(private readonly clients: ClientDbService) {}
|
||||
|
||||
async read(clientId: string) {
|
||||
const id = this.requireClientId(clientId);
|
||||
const client = await this.clients.findWorkingHours({ _id: id });
|
||||
if (!client) throw new NotFoundException("شرکت بیمه یافت نشد.");
|
||||
return client.settings?.workingHours ?? defaultWorkingHours();
|
||||
}
|
||||
|
||||
async update(clientId: string, body: unknown) {
|
||||
const id = this.requireClientId(clientId);
|
||||
const schedule = parseWorkingHours(body);
|
||||
const updated = await this.clients.findByIdAndUpdate(id, {
|
||||
$set: { "settings.workingHours": schedule },
|
||||
});
|
||||
if (!updated) throw new NotFoundException("شرکت بیمه یافت نشد.");
|
||||
return schedule;
|
||||
}
|
||||
|
||||
async assertOpen(clientId: string | undefined, now: Date) {
|
||||
const deploymentCode = process.env.CLIENT_ID?.trim();
|
||||
const filter = clientId
|
||||
? { _id: clientId }
|
||||
: deploymentCode && /^\d+$/.test(deploymentCode)
|
||||
? { clientCode: Number(deploymentCode) }
|
||||
: null;
|
||||
if (!filter) return;
|
||||
|
||||
const client = await this.clients.findWorkingHours(filter);
|
||||
const policy = client?.settings?.workingHours;
|
||||
if (!policy) return;
|
||||
const nextOpening = getNextOpening(policy, now);
|
||||
if (nextOpening === null) return;
|
||||
throw new ForbiddenException({
|
||||
code: "OUTSIDE_WORKING_HOURS",
|
||||
message: workingHoursMessage(nextOpening),
|
||||
...(nextOpening ? { nextOpening } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
private requireClientId(value: unknown) {
|
||||
const id = workingHoursClientId(value);
|
||||
if (!id) throw new BadRequestException("شرکت بیمه معتبر نیست.");
|
||||
return id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { ExecutionContextHost } from "@nestjs/core/helpers/execution-context-host";
|
||||
import { lastValueFrom, defer, of } from "rxjs";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import {
|
||||
CaseWorkingHoursInterceptor,
|
||||
checkDiscoveredBlameInsurer,
|
||||
EnforceCaseWorkingHours,
|
||||
} from "./case-working-hours.interceptor";
|
||||
import {
|
||||
ClientWorkingHoursService,
|
||||
responsibleBlameInsurer,
|
||||
} from "./client-working-hours.service";
|
||||
import { getNextOpening, parseWorkingHours } from "./working-hours";
|
||||
|
||||
const open = { alwaysOpen: true, windows: [] };
|
||||
const saturday = { weekday: 6, opensAt: "08:00", closesAt: "16:00" };
|
||||
const schedule = { alwaysOpen: false, windows: [saturday] };
|
||||
const afterClosing = new Date("2026-11-21T12:30:00Z");
|
||||
|
||||
describe("Tehran working hours", () => {
|
||||
it("includes the opening minute, excludes closing, and reports the next open day", () => {
|
||||
expect(getNextOpening(open, afterClosing)).toBeNull();
|
||||
expect(getNextOpening(schedule, new Date("2026-11-21T04:29:59Z"))).toEqual({
|
||||
weekday: 6,
|
||||
time: "08:00",
|
||||
});
|
||||
expect(
|
||||
getNextOpening(schedule, new Date("2026-11-21T04:30:00Z")),
|
||||
).toBeNull();
|
||||
expect(
|
||||
getNextOpening(schedule, new Date("2026-11-21T12:29:59Z")),
|
||||
).toBeNull();
|
||||
expect(getNextOpening(schedule, afterClosing)).toEqual({
|
||||
weekday: 6,
|
||||
time: "08:00",
|
||||
});
|
||||
});
|
||||
|
||||
it("handles the overnight week boundary and a day ending at midnight", () => {
|
||||
const overnight = {
|
||||
alwaysOpen: false,
|
||||
windows: [{ weekday: 6, opensAt: "23:00", closesAt: "02:00" }],
|
||||
};
|
||||
expect(getNextOpening(overnight, new Date("2026-11-21T19:29:59Z"))).toEqual(
|
||||
{ weekday: 6, time: "23:00" },
|
||||
);
|
||||
expect(
|
||||
getNextOpening(overnight, new Date("2026-11-21T21:30:00Z")),
|
||||
).toBeNull();
|
||||
expect(getNextOpening(overnight, new Date("2026-11-21T22:30:00Z"))).toEqual(
|
||||
{ weekday: 6, time: "23:00" },
|
||||
);
|
||||
const allSaturday = parseWorkingHours({
|
||||
alwaysOpen: false,
|
||||
windows: [{ weekday: 6, opensAt: "00:00", closesAt: "24:00" }],
|
||||
});
|
||||
expect(
|
||||
getNextOpening(allSaturday, new Date("2026-11-21T20:29:59Z")),
|
||||
).toBeNull();
|
||||
expect(
|
||||
getNextOpening(allSaturday, new Date("2026-11-21T20:30:00Z")),
|
||||
).toEqual({ weekday: 6, time: "00:00" });
|
||||
});
|
||||
|
||||
it("rejects duplicate, invalid, and empty restricted schedules", () => {
|
||||
for (const value of [
|
||||
{ alwaysOpen: false, windows: [] },
|
||||
{ ...schedule, windows: [saturday, saturday] },
|
||||
{ ...schedule, windows: [{ ...saturday, weekday: 7 }] },
|
||||
{ ...schedule, windows: [{ ...saturday, opensAt: "24:00" }] },
|
||||
{ ...schedule, windows: [{ ...saturday, closesAt: "08:00" }] },
|
||||
{ ...schedule, windows: [{ ...saturday, closesAt: "25:00" }] },
|
||||
{ ...schedule, clientId: "another insurer" },
|
||||
]) {
|
||||
expect(() => parseWorkingHours(value)).toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@EnforceCaseWorkingHours()
|
||||
class CaseController {
|
||||
write() {}
|
||||
}
|
||||
|
||||
const first = "aaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const second = "bbbbbbbbbbbbbbbbbbbbbbbb";
|
||||
const caseId = "cccccccccccccccccccccccc";
|
||||
|
||||
function context(
|
||||
params: Record<string, string> = {},
|
||||
role = RoleEnum.USER,
|
||||
method = "POST",
|
||||
) {
|
||||
const req = { method, params, user: { sub: "user", role, clientKey: first } };
|
||||
return new ExecutionContextHost(
|
||||
[req],
|
||||
CaseController,
|
||||
CaseController.prototype.write,
|
||||
);
|
||||
}
|
||||
|
||||
describe("case working-hours enforcement", () => {
|
||||
const findWorkingHours = jest.fn();
|
||||
const findByIdAndUpdate = jest.fn();
|
||||
const hours = new ClientWorkingHoursService({
|
||||
findWorkingHours,
|
||||
findByIdAndUpdate,
|
||||
} as any);
|
||||
const assertOpen = jest.spyOn(hours, "assertOpen");
|
||||
const claims = { find: jest.fn() };
|
||||
const blames = { find: jest.fn() };
|
||||
const interceptor = new CaseWorkingHoursInterceptor(
|
||||
new Reflector(),
|
||||
hours,
|
||||
claims as any,
|
||||
blames as any,
|
||||
);
|
||||
let deployment: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
deployment = process.env.CLIENT_ID;
|
||||
jest.useFakeTimers({ now: afterClosing });
|
||||
findWorkingHours.mockImplementation(async (filter) =>
|
||||
filter._id === first
|
||||
? { settings: {} }
|
||||
: { settings: { workingHours: schedule } },
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (deployment === undefined) delete process.env.CLIENT_ID;
|
||||
else process.env.CLIENT_ID = deployment;
|
||||
jest.useRealTimers();
|
||||
});
|
||||
|
||||
it("uses the second party's insurer when the first party reports being injured", () => {
|
||||
const injured = {
|
||||
role: "FIRST",
|
||||
person: { clientId: first },
|
||||
statement: { claimsDamage: true },
|
||||
};
|
||||
const atFault = { role: "SECOND", person: { clientId: second } };
|
||||
expect(
|
||||
responsibleBlameInsurer({
|
||||
type: "THIRD_PARTY",
|
||||
blameStatus: "AGREED",
|
||||
parties: [injured],
|
||||
}),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
responsibleBlameInsurer({
|
||||
type: "THIRD_PARTY",
|
||||
blameStatus: "AGREED",
|
||||
parties: [injured, atFault],
|
||||
}),
|
||||
).toBe(second);
|
||||
});
|
||||
|
||||
it("blocks public intake using the deployment insurer instead of the public JWT key", async () => {
|
||||
process.env.CLIENT_ID = "8";
|
||||
const handle = jest.fn(() => of(true));
|
||||
await expect(
|
||||
interceptor.intercept(context(), { handle }),
|
||||
).rejects.toMatchObject({
|
||||
status: 403,
|
||||
response: {
|
||||
code: "OUTSIDE_WORKING_HOURS",
|
||||
nextOpening: { weekday: 6, time: "08:00" },
|
||||
},
|
||||
});
|
||||
expect(findWorkingHours).toHaveBeenCalledWith({ clientCode: 8 });
|
||||
expect(handle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses a case's payer over the actor's insurer, including Fanavaran writes", async () => {
|
||||
claims.find.mockResolvedValue([{ owner: { clientId: second } }]);
|
||||
const handle = jest.fn(() => of(true));
|
||||
await expect(
|
||||
interceptor.intercept(
|
||||
context({ claimCaseId: caseId }, RoleEnum.DAMAGE_EXPERT),
|
||||
{ handle },
|
||||
),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(findWorkingHours).toHaveBeenCalledWith({ _id: second });
|
||||
expect(handle).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the initiating insurer for a call-center case before policy details are known", async () => {
|
||||
blames.find.mockResolvedValue([
|
||||
{ type: "CAR_BODY", workingHoursIntakeClientId: second },
|
||||
]);
|
||||
await expect(
|
||||
interceptor.intercept(context({ requestId: caseId }), {
|
||||
handle: () => of(true),
|
||||
}),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(findWorkingHours).toHaveBeenCalledWith({ _id: second });
|
||||
});
|
||||
|
||||
it("checks a newly discovered payer inside the handler before it persists a transition", async () => {
|
||||
const save = jest.fn();
|
||||
const result = await interceptor.intercept(
|
||||
context({}, RoleEnum.FIELD_EXPERT),
|
||||
{
|
||||
handle: () =>
|
||||
defer(async () => {
|
||||
await checkDiscoveredBlameInsurer({
|
||||
type: "THIRD_PARTY",
|
||||
parties: [
|
||||
{ role: "FIRST", person: { clientId: first } },
|
||||
{
|
||||
role: "SECOND",
|
||||
person: { clientId: second },
|
||||
statement: { admitsGuilt: true },
|
||||
},
|
||||
],
|
||||
});
|
||||
save();
|
||||
}),
|
||||
},
|
||||
);
|
||||
await expect(lastValueFrom(result)).rejects.toBeInstanceOf(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(assertOpen).toHaveBeenNthCalledWith(1, first, afterClosing);
|
||||
expect(assertOpen).toHaveBeenNthCalledWith(2, second, afterClosing);
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("defaults old insurers to always open and updates only the schedule", async () => {
|
||||
expect(await hours.read(first)).toEqual(open);
|
||||
findByIdAndUpdate.mockResolvedValueOnce({
|
||||
settings: { workingHours: schedule },
|
||||
});
|
||||
expect(await hours.update(first, schedule)).toEqual(schedule);
|
||||
expect(findByIdAndUpdate).toHaveBeenCalledWith(first, {
|
||||
$set: { "settings.workingHours": schedule },
|
||||
});
|
||||
});
|
||||
|
||||
it("leaves reads and the existing missing-case error path alone", async () => {
|
||||
blames.find.mockResolvedValue([]);
|
||||
const read = await interceptor.intercept(
|
||||
context({ requestId: caseId }, RoleEnum.USER, "GET"),
|
||||
{
|
||||
handle: () => of("read"),
|
||||
},
|
||||
);
|
||||
expect(await lastValueFrom(read)).toBe("read");
|
||||
expect(blames.find).not.toHaveBeenCalled();
|
||||
const missing = await interceptor.intercept(
|
||||
context({ requestId: caseId }),
|
||||
{
|
||||
handle: () => of("existing not found handling"),
|
||||
},
|
||||
);
|
||||
expect(await lastValueFrom(missing)).toBe("existing not found handling");
|
||||
expect(assertOpen).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
|
||||
export const WORKING_HOURS_TIMEZONE = "Asia/Tehran";
|
||||
const DAYS = [
|
||||
"یکشنبه",
|
||||
"دوشنبه",
|
||||
"سهشنبه",
|
||||
"چهارشنبه",
|
||||
"پنجشنبه",
|
||||
"جمعه",
|
||||
"شنبه",
|
||||
];
|
||||
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
|
||||
const DAY = 1440;
|
||||
const WEEK = 7 * DAY;
|
||||
const timeFormat = new Intl.DateTimeFormat("en-GB", {
|
||||
timeZone: WORKING_HOURS_TIMEZONE,
|
||||
weekday: "short",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hourCycle: "h23",
|
||||
});
|
||||
const timePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||||
|
||||
export type WorkingHoursWindow = {
|
||||
weekday: number;
|
||||
opensAt: string;
|
||||
closesAt: string;
|
||||
};
|
||||
export type WorkingHours = {
|
||||
alwaysOpen: boolean;
|
||||
windows: WorkingHoursWindow[];
|
||||
};
|
||||
export const defaultWorkingHours = (): WorkingHours => ({
|
||||
alwaysOpen: true,
|
||||
windows: [],
|
||||
});
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return !!value && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function parseWorkingHours(value: unknown): WorkingHours {
|
||||
if (
|
||||
!isRecord(value) ||
|
||||
Object.keys(value).some(
|
||||
(key) => !["alwaysOpen", "windows"].includes(key),
|
||||
) ||
|
||||
typeof value.alwaysOpen !== "boolean" ||
|
||||
!Array.isArray(value.windows) ||
|
||||
value.windows.length > 7
|
||||
) {
|
||||
throw new BadRequestException("برنامه ساعات کاری معتبر نیست.");
|
||||
}
|
||||
|
||||
const days = new Set<number>();
|
||||
const windows = value.windows.map((window: unknown) => {
|
||||
if (
|
||||
!isRecord(window) ||
|
||||
Object.keys(window).some(
|
||||
(key) => !["weekday", "opensAt", "closesAt"].includes(key),
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException("برنامه روز کاری معتبر نیست.");
|
||||
}
|
||||
const { weekday, opensAt, closesAt } = window;
|
||||
if (
|
||||
typeof weekday !== "number" ||
|
||||
!Number.isInteger(weekday) ||
|
||||
weekday < 0 ||
|
||||
weekday > 6 ||
|
||||
days.has(weekday)
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
"برای هر روز هفته فقط یک بازه کاری تعریف کنید.",
|
||||
);
|
||||
}
|
||||
if (
|
||||
typeof opensAt !== "string" ||
|
||||
!timePattern.test(opensAt) ||
|
||||
typeof closesAt !== "string" ||
|
||||
!(timePattern.test(closesAt) || closesAt === "24:00") ||
|
||||
opensAt === closesAt
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
`ساعت شروع و پایان روز ${DAYS[weekday]} را بهدرستی وارد کنید.`,
|
||||
);
|
||||
}
|
||||
days.add(weekday);
|
||||
return { weekday, opensAt, closesAt };
|
||||
});
|
||||
if (!value.alwaysOpen && windows.length === 0) {
|
||||
throw new BadRequestException(
|
||||
"حداقل یک روز کاری انتخاب کنید یا دسترسی شبانهروزی را فعال کنید.",
|
||||
);
|
||||
}
|
||||
return {
|
||||
alwaysOpen: value.alwaysOpen,
|
||||
windows: windows.sort((a, b) => a.weekday - b.weekday),
|
||||
};
|
||||
}
|
||||
|
||||
function minutes(time: string) {
|
||||
const [hour, minute] = time.split(":").map(Number);
|
||||
return hour * 60 + minute;
|
||||
}
|
||||
|
||||
/** Null means open. The opening minute is included and the closing minute is excluded. */
|
||||
export function getNextOpening(policy: WorkingHours, now: Date) {
|
||||
if (policy.alwaysOpen) return null;
|
||||
const parts = Object.fromEntries(
|
||||
timeFormat.formatToParts(now).map(({ type, value }) => [type, value]),
|
||||
);
|
||||
const weekday = WEEKDAYS.indexOf(parts.weekday);
|
||||
const current =
|
||||
weekday * DAY + Number(parts.hour) * 60 + Number(parts.minute);
|
||||
const spans = policy.windows.map((window) => {
|
||||
const open = minutes(window.opensAt);
|
||||
const close = minutes(window.closesAt);
|
||||
return {
|
||||
start: window.weekday * DAY + open,
|
||||
duration: close > open ? close - open : DAY + close - open,
|
||||
window,
|
||||
};
|
||||
});
|
||||
if (
|
||||
spans.some((span) => (current - span.start + WEEK) % WEEK < span.duration)
|
||||
)
|
||||
return null;
|
||||
|
||||
const next = spans.reduce<(typeof spans)[number] | undefined>(
|
||||
(earliest, span) => {
|
||||
const delay = (span.start - current + WEEK) % WEEK;
|
||||
return !earliest || delay < (earliest.start - current + WEEK) % WEEK
|
||||
? span
|
||||
: earliest;
|
||||
},
|
||||
undefined,
|
||||
);
|
||||
return next
|
||||
? { weekday: next.window.weekday, time: next.window.opensAt }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function workingHoursMessage(next: ReturnType<typeof getNextOpening>) {
|
||||
const message =
|
||||
"ثبت و ادامه پرونده فقط در ساعات کاری شرکت بیمه امکانپذیر است.";
|
||||
if (!next) return message;
|
||||
const time = next.time.replace(/\d/g, (digit) => "۰۱۲۳۴۵۶۷۸۹"[Number(digit)]);
|
||||
return `${message} شروع بعدی: ${DAYS[next.weekday]} ساعت ${time} به وقت تهران.`;
|
||||
}
|
||||
@@ -20,6 +20,10 @@ export enum Environment {
|
||||
}
|
||||
|
||||
export class EnvironmentVariables {
|
||||
@IsOptional()
|
||||
@IsBooleanString()
|
||||
FANAVARAN_REQUIRE_EXPERT_SIGNATURE?: string;
|
||||
|
||||
@IsEnum(Environment, {
|
||||
message: "NODE_ENV should be development or production",
|
||||
})
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import {
|
||||
Controller,
|
||||
Get,
|
||||
@@ -38,6 +39,7 @@ import { ExpertBlameService } from "./expert-blame.service";
|
||||
|
||||
@ApiExcludeController()
|
||||
// @ApiTags("expert-blame-panel")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("expert-blame")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { checkDiscoveredBlameInsurer } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
@@ -2034,6 +2035,11 @@ export class ExpertBlameService {
|
||||
},
|
||||
};
|
||||
|
||||
await checkDiscoveredBlameInsurer({
|
||||
type: request.type,
|
||||
parties: request.parties,
|
||||
expert: { decision: decisionPayload },
|
||||
});
|
||||
const updatePayload = {
|
||||
$set: {
|
||||
"workflow.locked": false,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -35,6 +36,7 @@ import { SubmitReplyDto } from "./dto/reply.dto";
|
||||
import { ResendRequestDto } from "./dto/resend.dto";
|
||||
|
||||
@ApiTags("expert-blame-panel (v2)")
|
||||
@EnforceCaseWorkingHours({ genericId: "blame" })
|
||||
@Controller("v2/expert-blame")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
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: "THIRD_PARTY",
|
||||
expert: { decision: { guiltyPartyId: "other-party" } },
|
||||
parties: [
|
||||
{
|
||||
role: "FIRST",
|
||||
person: { userId: "beneficiary" },
|
||||
vehicle: { inquiry: { mapped: { ModelField: "1402" } } },
|
||||
statement: { accidentDate: "2026-11-23" },
|
||||
},
|
||||
{ role: "SECOND", person: { userId: "other-party" } },
|
||||
],
|
||||
};
|
||||
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("does not provide depreciation options or save depreciation for car-body claims", async () => {
|
||||
const { service, blame, body, id } = setup();
|
||||
blame.type = "CAR_BODY";
|
||||
await expect(service.getPriceDropContextV2(id, {})).rejects.toThrow("افت قیمت برای پرونده بیمه بدنه");
|
||||
await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow("افت قیمت برای پرونده بیمه بدنه");
|
||||
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns the Fanavaran catalog and age at accident without changing the saved assessment", async () => {
|
||||
const { service, claim, id } = setup();
|
||||
claim.evaluation.priceDrop = { total: 123, partLines: [] };
|
||||
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;
|
||||
|
||||
@@ -2,13 +2,15 @@ import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Type } from "class-transformer";
|
||||
import {
|
||||
IsArray,
|
||||
ArrayMinSize,
|
||||
ArrayUnique,
|
||||
IsEnum,
|
||||
IsInt,
|
||||
IsOptional,
|
||||
IsString,
|
||||
ValidateNested,
|
||||
} from "class-validator";
|
||||
import { IsRepairLineAmountToman } from "src/common/validators/repair-line-amount-toman.validator";
|
||||
import { IsMoneyAmountString } from "src/common/validators/money-amount-string.validator";
|
||||
import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum";
|
||||
|
||||
class FactorDecisionDto {
|
||||
@@ -51,35 +53,36 @@ class FactorDecisionV2Dto {
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Part price (Toman). With totalPayment or price+salary for APPROVED/REJECTED factor lines. Use 0 if unused.",
|
||||
"Part price (Rial). With totalPayment or price+salary for APPROVED/REJECTED factor lines. Use 0 if unused.",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsRepairLineAmountToman({ allowZero: true })
|
||||
@IsMoneyAmountString()
|
||||
price?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Salary in Toman. Send with price when not using only totalPayment. Use 0 if unused.",
|
||||
"Salary in Rial. Send with price when not using only totalPayment. Use 0 if unused.",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsRepairLineAmountToman({ allowZero: true })
|
||||
@IsMoneyAmountString()
|
||||
salary?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Line total in Toman; or send both price and salary.",
|
||||
description: "Line total in Rial; or send both price and salary.",
|
||||
})
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@IsRepairLineAmountToman()
|
||||
@IsMoneyAmountString()
|
||||
totalPayment?: string;
|
||||
}
|
||||
|
||||
export class FactorValidationV2Dto {
|
||||
@ApiProperty({ type: [FactorDecisionV2Dto] })
|
||||
@IsArray()
|
||||
@ArrayMinSize(1)
|
||||
@ArrayUnique((decision: FactorDecisionV2Dto) => decision.partId)
|
||||
@ValidateNested({ each: true })
|
||||
@Type(() => FactorDecisionV2Dto)
|
||||
decisions: FactorDecisionV2Dto[];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
"use strict";
|
||||
|
||||
import {
|
||||
assertReferredReviewer,
|
||||
isOriginalFileMaker,
|
||||
isReferredReviewer,
|
||||
reviewReferralActorFilter,
|
||||
} from "./review-referral/review-referral";
|
||||
|
||||
import { hasReviewedTejaratNotifier } from "src/fanavaran/tejarat-notifier";
|
||||
import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config";
|
||||
|
||||
@@ -55,9 +62,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,
|
||||
@@ -313,6 +329,10 @@ export class ExpertClaimService {
|
||||
claim: any,
|
||||
actor: any,
|
||||
): Promise<void> {
|
||||
if (claim.reviewReferral) {
|
||||
assertReferredReviewer(claim, actor);
|
||||
return;
|
||||
}
|
||||
const blame = await this.loadBlameForClaim(claim);
|
||||
// FILE_REVIEWER: by the time we reach this method the caller has already
|
||||
// verified that actor.sub === blame.assignedFileReviewerId (Phase 2 of
|
||||
@@ -391,6 +411,8 @@ export class ExpertClaimService {
|
||||
? String((damageExpert as any).branchId)
|
||||
: undefined;
|
||||
if (!actorBranchId) {
|
||||
const referred = claims.filter((claim) => isReferredReviewer(claim, actor));
|
||||
if (referred.length) return referred;
|
||||
throw new ForbiddenException(
|
||||
"DamageExpert account is not assigned to a branch.",
|
||||
);
|
||||
@@ -441,6 +463,7 @@ export class ExpertClaimService {
|
||||
);
|
||||
|
||||
return claims.filter((claim) => {
|
||||
if (claim.reviewReferral) return isReferredReviewer(claim, actor);
|
||||
let caseBranchId = claim?.branchId ? String(claim.branchId) : undefined;
|
||||
if (!caseBranchId && claim?.blameRequestId) {
|
||||
const blame = blameById.get(String(claim.blameRequestId));
|
||||
@@ -980,7 +1003,7 @@ export class ExpertClaimService {
|
||||
|
||||
if (!claimIsAwaitingExpertFactorValidationV2(claim)) {
|
||||
throw new BadRequestException(
|
||||
"Claim is not awaiting expert factor validation (UNDER_REVIEW at EXPERT_COST_EVALUATION).",
|
||||
"پرونده در مرحله بررسی فاکتور توسط کارشناس نیست. وضعیت پرونده را دوباره دریافت کنید.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -993,76 +1016,160 @@ export class ExpertClaimService {
|
||||
: claim.evaluation?.damageExpertReply;
|
||||
|
||||
if (!finalReply?.parts?.length) {
|
||||
throw new BadRequestException("No expert reply found in this claim.");
|
||||
throw new BadRequestException("پاسخ کارشناسی برای بررسی فاکتور در این پرونده یافت نشد.");
|
||||
}
|
||||
|
||||
const requiredFactors = finalReply.parts.filter((p) => p.factorNeeded);
|
||||
if (requiredFactors.length === 0) {
|
||||
throw new BadRequestException("No parts require factor validation.");
|
||||
throw new BadRequestException("در این پاسخ کارشناسی قطعهای نیازمند بررسی فاکتور نیست.");
|
||||
}
|
||||
if (!requiredFactors.every((p) => !!p.factorLink)) {
|
||||
throw new BadRequestException(
|
||||
"Not all required factors have been uploaded yet.",
|
||||
"هنوز همه فاکتورهای موردنیاز بارگذاری نشدهاند.",
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(body.decisions) || body.decisions.length === 0) {
|
||||
throw new BadRequestException("حداقل یک فاکتور را بررسی کنید.");
|
||||
}
|
||||
const $set: Record<string, unknown> = {};
|
||||
const seen = new Set<string>();
|
||||
const proposedParts = finalReply.parts.map((part: any) => ({
|
||||
...(typeof part.toObject === "function" ? part.toObject() : part),
|
||||
}));
|
||||
for (const decision of body.decisions) {
|
||||
const partIndex = finalReply.parts.findIndex((p) =>
|
||||
sameCatalogPartId(p.partId, decision.partId),
|
||||
const partIndex = proposedParts.findIndex((part) =>
|
||||
sameCatalogPartId(part.partId, decision.partId),
|
||||
);
|
||||
if (partIndex === -1) {
|
||||
this.logger.warn(
|
||||
`Part ${decision.partId} not found in claim ${claimRequestId}, skipping.`,
|
||||
const id = String(decision.partId);
|
||||
if (seen.has(id))
|
||||
throw new BadRequestException(
|
||||
"برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const part = finalReply.parts[partIndex];
|
||||
if (!part.factorNeeded) {
|
||||
this.logger.warn(
|
||||
`Part ${decision.partId} is not factor-needed, skipping.`,
|
||||
seen.add(id);
|
||||
if (partIndex < 0 || !proposedParts[partIndex].factorNeeded) {
|
||||
throw new BadRequestException(
|
||||
"قطعه انتخابشده در فهرست فاکتورهای موردنیاز پرونده وجود ندارد.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const base = `evaluation.${replyField}.parts.${partIndex}`;
|
||||
$set[`${base}.factorStatus`] = decision.status;
|
||||
$set[`${base}.rejectionReason`] = decision.rejectionReason ?? null;
|
||||
if (decision.price !== undefined) {
|
||||
$set[`${base}.price`] = decision.price;
|
||||
}
|
||||
if (decision.salary !== undefined) {
|
||||
$set[`${base}.salary`] = decision.salary;
|
||||
}
|
||||
if (decision.totalPayment !== undefined) {
|
||||
$set[`${base}.totalPayment`] = decision.totalPayment;
|
||||
}
|
||||
|
||||
if (
|
||||
decision.status === FactorStatus.APPROVED ||
|
||||
decision.status === FactorStatus.REJECTED
|
||||
![FactorStatus.APPROVED, FactorStatus.REJECTED].includes(
|
||||
decision.status,
|
||||
)
|
||||
) {
|
||||
if (!this.expertFactorValidationDecisionHasLinePricing(decision)) {
|
||||
throw new BadRequestException(
|
||||
"نتیجه بررسی فاکتور باید تأیید یا عدم تأیید باشد.",
|
||||
);
|
||||
}
|
||||
if (
|
||||
decision.status === FactorStatus.REJECTED &&
|
||||
!String(decision.rejectionReason ?? "").trim()
|
||||
) {
|
||||
throw new BadRequestException("دلیل عدم تأیید فاکتور را وارد کنید.");
|
||||
}
|
||||
const providedTotal =
|
||||
decision.totalPayment != null &&
|
||||
String(decision.totalPayment).trim() !== "";
|
||||
const price = parseMoneyAmountToman(decision.price);
|
||||
const salary = parseMoneyAmountToman(decision.salary);
|
||||
const lineTotal = providedTotal
|
||||
? parseMoneyAmountToman(decision.totalPayment)
|
||||
: price != null && salary != null
|
||||
? price + salary
|
||||
: NaN;
|
||||
if (
|
||||
!this.expertFactorValidationDecisionHasLinePricing(decision) ||
|
||||
!Number.isSafeInteger(lineTotal) ||
|
||||
lineTotal < 1_000_000 ||
|
||||
lineTotal > 100_000_000_000
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
"مبلغ نهایی قطعه با احتساب اجرت باید بین ۱٬۰۰۰٬۰۰۰ و ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
|
||||
);
|
||||
}
|
||||
const base = `evaluation.${replyField}.parts.${partIndex}`;
|
||||
const updates: Record<string, unknown> = {
|
||||
factorStatus: decision.status,
|
||||
rejectionReason:
|
||||
decision.status === FactorStatus.REJECTED
|
||||
? decision.rejectionReason.trim()
|
||||
: null,
|
||||
totalPayment: String(lineTotal),
|
||||
};
|
||||
for (const field of ["price", "salary"] as const) {
|
||||
if (decision[field] === undefined) continue;
|
||||
const amount = parseMoneyAmountToman(decision[field]);
|
||||
if (
|
||||
!Number.isSafeInteger(amount) ||
|
||||
amount < 0 ||
|
||||
amount > 100_000_000_000
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
`Part ${decision.partId}: ${decision.status === FactorStatus.APPROVED ? "approved" : "rejected"} factor lines require expert totalPayment (or both price and salary).`,
|
||||
"قیمت قطعه و اجرت باید مبلغ صحیح و نامنفی به ریال باشند.",
|
||||
);
|
||||
}
|
||||
updates[field] = String(amount);
|
||||
}
|
||||
Object.assign(proposedParts[partIndex], updates);
|
||||
for (const [field, value] of Object.entries(updates))
|
||||
$set[`${base}.${field}`] = value;
|
||||
}
|
||||
const reqParts = proposedParts.filter((part) => part.factorNeeded);
|
||||
const anyRejected = reqParts.some(
|
||||
(part) => part.factorStatus === FactorStatus.REJECTED,
|
||||
);
|
||||
const anyStillPending = reqParts.some(
|
||||
(part) =>
|
||||
!part.factorStatus || part.factorStatus === FactorStatus.PENDING,
|
||||
);
|
||||
if (!anyStillPending) {
|
||||
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
|
||||
const priceCap =
|
||||
configuredPriceCap !== null &&
|
||||
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
|
||||
? configuredPriceCap
|
||||
: null;
|
||||
if (priceCap !== null) {
|
||||
let totalPrice = 0;
|
||||
for (const part of proposedParts || []) {
|
||||
const line = this.claimReplyPartLineTotalForCap(part);
|
||||
if (isNaN(line)) {
|
||||
throw new BadRequestException({
|
||||
message: `مبلغ قطعه ${String(part.partId ?? "")} معتبر نیست. مبلغ نهایی یا قیمت قطعه و اجرت را ثبت کنید.`,
|
||||
error: "PRICE_CAP_ERROR",
|
||||
});
|
||||
}
|
||||
totalPrice += line;
|
||||
}
|
||||
if (totalPrice > priceCap) {
|
||||
throw new BadRequestException({
|
||||
message: `مجموع مبلغ قطعات و فاکتورها (${totalPrice.toLocaleString("fa-IR")} ریال) از سقف مجاز پرونده (${priceCap.toLocaleString("fa-IR")} ریال) بیشتر است.`,
|
||||
error: "PRICE_CAP_ERROR",
|
||||
totalPrice,
|
||||
priceCap,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (Object.keys($set).length === 0) {
|
||||
throw new BadRequestException("No valid factor decisions to apply.");
|
||||
}
|
||||
|
||||
if (factorValidationSnapshot) {
|
||||
if (factorValidationSnapshot)
|
||||
$set["evaluation.factorValidationExpertProfileSnapshot"] =
|
||||
factorValidationSnapshot;
|
||||
}
|
||||
|
||||
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
|
||||
$set,
|
||||
});
|
||||
|
||||
const updatedClaim = await this.claimCaseDbService.findOneAndUpdate(
|
||||
{
|
||||
_id: claim._id,
|
||||
status: claim.status,
|
||||
claimStatus: claim.claimStatus,
|
||||
"workflow.currentStep": claim.workflow.currentStep,
|
||||
...((claim as any).updatedAt != null
|
||||
? { updatedAt: (claim as any).updatedAt }
|
||||
: { [`evaluation.${replyField}.parts`]: finalReply.parts }),
|
||||
},
|
||||
{ $set },
|
||||
);
|
||||
if (!updatedClaim)
|
||||
throw new ConflictException(
|
||||
"اطلاعات فاکتورها هنگام بررسی تغییر کرده است. پرونده را دوباره دریافت و تلاش کنید.",
|
||||
);
|
||||
await this.recordClaimExpertActivity({
|
||||
expertId: String(actor.sub),
|
||||
tenantId: this.claimActivityTenantId(claim, actor),
|
||||
@@ -1070,59 +1177,15 @@ export class ExpertClaimService {
|
||||
eventType: ExpertFileActivityType.CHECKED,
|
||||
idempotencyKey: `claim:${claimRequestId}:checked:${actor.sub}`,
|
||||
});
|
||||
|
||||
const updatedClaim = await this.claimCaseDbService.findById(claimRequestId);
|
||||
const updatedReply =
|
||||
replyField === "damageExpertReplyFinal"
|
||||
? updatedClaim!.evaluation!.damageExpertReplyFinal!
|
||||
: updatedClaim!.evaluation!.damageExpertReply!;
|
||||
|
||||
const reqParts = updatedReply.parts.filter((p) => p.factorNeeded);
|
||||
const anyRejected = reqParts.some(
|
||||
(p) => p.factorStatus === FactorStatus.REJECTED,
|
||||
);
|
||||
const anyStillPending = reqParts.some(
|
||||
(p) => !p.factorStatus || p.factorStatus === FactorStatus.PENDING,
|
||||
);
|
||||
|
||||
const baseMessage = "Factor validation updated.";
|
||||
if (anyStillPending) {
|
||||
if (anyStillPending)
|
||||
return {
|
||||
message: `${baseMessage} Some factors are still pending review.`,
|
||||
message:
|
||||
"نتیجه بررسی فاکتور ثبت شد. فاکتورهای باقیمانده را نیز بررسی کنید.",
|
||||
claimRequestId,
|
||||
claimStatus: updatedClaim!.claimStatus,
|
||||
caseStatus: updatedClaim!.status,
|
||||
claimStatus: updatedClaim.claimStatus,
|
||||
caseStatus: updatedClaim.status,
|
||||
pendingFactorValidation: true,
|
||||
};
|
||||
}
|
||||
|
||||
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
|
||||
const priceCap =
|
||||
configuredPriceCap !== null &&
|
||||
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
|
||||
? configuredPriceCap
|
||||
: null;
|
||||
if (priceCap !== null) {
|
||||
let totalPrice = 0;
|
||||
for (const part of updatedReply.parts || []) {
|
||||
const line = this.claimReplyPartLineTotalForCap(part);
|
||||
if (isNaN(line)) {
|
||||
throw new BadRequestException({
|
||||
message: `Part ${String(part.partId ?? "")}: invalid amount for price total — use totalPayment or price and salary.`,
|
||||
error: "PRICE_CAP_ERROR",
|
||||
});
|
||||
}
|
||||
totalPrice += line;
|
||||
}
|
||||
if (totalPrice > priceCap) {
|
||||
throw new BadRequestException({
|
||||
message: `You have reached the maximum acceptable total price (Rial). The sum of priced parts and factor lines (${totalPrice.toLocaleString()}) exceeds the limit (${priceCap.toLocaleString()}).`,
|
||||
error: "PRICE_CAP_ERROR",
|
||||
totalPrice,
|
||||
priceCap,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const historyActor = {
|
||||
actorId: new Types.ObjectId(actor.sub),
|
||||
@@ -1340,7 +1403,7 @@ export class ExpertClaimService {
|
||||
// so they can perform damage assessment. Fall through to the
|
||||
// damage-expert path below; assertExpertActorOnClaim will verify
|
||||
// tenant scope via the reviewer's clientKey.
|
||||
if ((actor as any).role === RoleEnum.FILE_REVIEWER) {
|
||||
if (actor.role === RoleEnum.FILE_REVIEWER && !claim.reviewReferral) {
|
||||
if (!claim.blameRequestId) {
|
||||
throw new BadRequestException({
|
||||
success: false,
|
||||
@@ -1421,7 +1484,8 @@ export class ExpertClaimService {
|
||||
|
||||
const isFieldExpertOwner =
|
||||
(actor as any).role === RoleEnum.FIELD_EXPERT &&
|
||||
(await this.fieldExpertOwnsClaim(claim, actor));
|
||||
(isReferredReviewer(claim, actor) ||
|
||||
(await this.fieldExpertOwnsClaim(claim, actor)));
|
||||
const isFactorValidationLock =
|
||||
claimIsAwaitingExpertFactorValidationV2(claim);
|
||||
const isDamageReviewLock =
|
||||
@@ -1436,6 +1500,7 @@ export class ExpertClaimService {
|
||||
claim.status === ClaimCaseStatus.CANCELLED;
|
||||
const isFieldExpertPortfolioLock =
|
||||
isFieldExpertOwner &&
|
||||
!claim.reviewReferral &&
|
||||
!isTerminalClaim &&
|
||||
!isDamageReviewLock &&
|
||||
!isFactorValidationLock &&
|
||||
@@ -1584,6 +1649,7 @@ export class ExpertClaimService {
|
||||
|
||||
const assignFilter: Record<string, unknown> = {
|
||||
_id: new Types.ObjectId(claimRequestId),
|
||||
"reviewReferral.referredAt": claim.reviewReferral?.referredAt ?? null,
|
||||
$and: [
|
||||
{
|
||||
$or: [
|
||||
@@ -1807,7 +1873,7 @@ export class ExpertClaimService {
|
||||
if (existingResend?.fulfilledAt) {
|
||||
throw new BusinessRuleException(
|
||||
BusinessErrorCode.DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED,
|
||||
"The owner has already fulfilled a damage-expert resend for this claim. You cannot request another resend.",
|
||||
"کاربر درخواست قبلی تکمیل اطلاعات را انجام داده است. برای این پرونده امکان درخواست مجدد وجود ندارد؛ پاسخ کارشناسی را ثبت کنید یا مراجعه حضوری درخواست دهید.",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2439,11 +2505,17 @@ export class ExpertClaimService {
|
||||
async getStatusReportBucketsV2(actor: any): Promise<Record<string, number>> {
|
||||
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
||||
const rows = (await this.claimCaseDbService.find(
|
||||
{ initiatedByFieldExpertId: new Types.ObjectId(actor.sub) },
|
||||
{
|
||||
$or: [
|
||||
{ initiatedByFieldExpertId: new Types.ObjectId(actor.sub) },
|
||||
reviewReferralActorFilter(actor),
|
||||
],
|
||||
},
|
||||
{ lean: true },
|
||||
)) as any[];
|
||||
const buckets = initialClaimExpertReportBuckets();
|
||||
for (const doc of rows) {
|
||||
if (doc.reviewReferral && !isReferredReviewer(doc, actor)) continue;
|
||||
const key = claimCaseStatusToReportBucket(String(doc.status ?? ""));
|
||||
buckets.all++;
|
||||
buckets[key] = (buckets[key] ?? 0) + 1;
|
||||
@@ -2471,6 +2543,7 @@ export class ExpertClaimService {
|
||||
expertPortfolioFileIdsFromActivityEvents(activityEvents);
|
||||
|
||||
const orClauses: Record<string, unknown>[] = [
|
||||
reviewReferralActorFilter(actor),
|
||||
{ "workflow.lockedBy.actorId": expertOid },
|
||||
{ "evaluation.damageExpertReply.actorDetail.actorId": expertOid },
|
||||
{ "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid },
|
||||
@@ -2495,7 +2568,9 @@ export class ExpertClaimService {
|
||||
const id = String(doc._id ?? "");
|
||||
if (seen.has(id)) continue;
|
||||
if (
|
||||
!claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
|
||||
doc.reviewReferral && actor.role !== RoleEnum.FILE_MAKER
|
||||
? !isReferredReviewer(doc, actor)
|
||||
: !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -2581,6 +2656,7 @@ export class ExpertClaimService {
|
||||
)
|
||||
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
||||
const claimOr: Record<string, unknown>[] = [
|
||||
reviewReferralActorFilter(actor),
|
||||
{
|
||||
initiatedByFieldExpertId: expertOid,
|
||||
requiresFileMakerApproval: { $ne: true },
|
||||
@@ -2589,7 +2665,8 @@ export class ExpertClaimService {
|
||||
if (expertBlameIds.length > 0) {
|
||||
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
||||
}
|
||||
claims = (await this.claimCaseDbService.find({ $or: claimOr })) as any[];
|
||||
claims = (await this.claimCaseDbService.find({ $or: claimOr }))
|
||||
.filter((c) => !c.reviewReferral || isReferredReviewer(c, actor));
|
||||
} else {
|
||||
const clientKey = requireActorClientKey(actor);
|
||||
const expertId = String(actor.sub);
|
||||
@@ -2602,6 +2679,7 @@ export class ExpertClaimService {
|
||||
const activityFileIds =
|
||||
expertPortfolioFileIdsFromActivityEvents(activityEvents);
|
||||
const orClauses: Record<string, unknown>[] = [
|
||||
reviewReferralActorFilter(actor),
|
||||
{ "workflow.lockedBy.actorId": expertOid },
|
||||
{ "evaluation.damageExpertReply.actorDetail.actorId": expertOid },
|
||||
{ "evaluation.damageExpertReplyFinal.actorDetail.actorId": expertOid },
|
||||
@@ -2623,7 +2701,9 @@ export class ExpertClaimService {
|
||||
const id = String(doc._id ?? "");
|
||||
if (seen.has(id)) continue;
|
||||
if (
|
||||
!claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
|
||||
doc.reviewReferral && actor.role !== RoleEnum.FILE_MAKER
|
||||
? !isReferredReviewer(doc, actor)
|
||||
: !claimDocInExpertPortfolio(doc, expertId, activityFileIds, clientKey)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
@@ -2817,6 +2897,7 @@ export class ExpertClaimService {
|
||||
|
||||
// Post-filter: remove files that belong to another expert after reconciliation
|
||||
const finalFiltered = filtered.filter((c) => {
|
||||
if (c.reviewReferral) return isReferredReviewer(c, actor);
|
||||
const assignedId = String(c.workflow?.assignedForReviewBy?.actorId ?? "");
|
||||
const lockEnforced =
|
||||
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c);
|
||||
@@ -2940,6 +3021,7 @@ export class ExpertClaimService {
|
||||
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
||||
|
||||
const claimOr: Record<string, unknown>[] = [
|
||||
reviewReferralActorFilter(actor),
|
||||
// Direct claim link: exclude V5 claims that require FileMaker approval
|
||||
{
|
||||
initiatedByFieldExpertId: expertOid,
|
||||
@@ -2976,7 +3058,10 @@ export class ExpertClaimService {
|
||||
blames.map((b) => [String(b._id), b]),
|
||||
);
|
||||
|
||||
const list = claims.map((c) => {
|
||||
const visibleClaims = claims.filter(
|
||||
(claim) => !claim.reviewReferral || isReferredReviewer(claim, actor),
|
||||
);
|
||||
const list = visibleClaims.map((c) => {
|
||||
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
|
||||
const blame = c.blameRequestId
|
||||
? blameById.get(c.blameRequestId.toString())
|
||||
@@ -3044,6 +3129,15 @@ export class ExpertClaimService {
|
||||
const clientKey = requireActorClientKey(actor);
|
||||
const reviewerOid = new Types.ObjectId(actor.sub);
|
||||
|
||||
const referred = await this.claimCaseDbService.find(reviewReferralActorFilter(actor), {
|
||||
lean: true,
|
||||
select: "blameRequestId owner reviewReferral",
|
||||
});
|
||||
const referredBlameIds = referred
|
||||
.filter((claim) => isReferredReviewer(claim, actor) && claim.blameRequestId)
|
||||
.map((claim) => claim.blameRequestId);
|
||||
const referredBlames = new Set(referredBlameIds.map(String));
|
||||
|
||||
// Find V4 and V5 blame files visible to this reviewer
|
||||
const blames = (await this.blameRequestDbService.find(
|
||||
{
|
||||
@@ -3051,6 +3145,7 @@ export class ExpertClaimService {
|
||||
expertInitiated: true,
|
||||
creationMethod: "IN_PERSON",
|
||||
$or: [
|
||||
{ _id: { $in: referredBlameIds } },
|
||||
// Open: sealed by FileMaker, not yet taken by any reviewer
|
||||
{
|
||||
status: "WAITING_FOR_FILE_REVIEWER",
|
||||
@@ -3076,11 +3171,12 @@ export class ExpertClaimService {
|
||||
|
||||
// Scope to this reviewer's insurer via blame party clientId
|
||||
const tenantScopedBlames = blames.filter((b) =>
|
||||
blameCaseTouchesClient(b, clientKey),
|
||||
referredBlames.has(String(b._id)) || blameCaseTouchesClient(b, clientKey),
|
||||
);
|
||||
const scopedBlames = (
|
||||
await Promise.all(
|
||||
tenantScopedBlames.map(async (blame) => {
|
||||
if (referredBlames.has(String(blame._id))) return blame;
|
||||
try {
|
||||
await this.fanavaranLocationService.assertMakerReviewerBranchCompatible(
|
||||
{
|
||||
@@ -3112,7 +3208,10 @@ export class ExpertClaimService {
|
||||
scopedBlames.map((b) => [String(b._id), b]),
|
||||
);
|
||||
|
||||
const list = claims.map((c) => {
|
||||
const visibleClaims = claims.filter(
|
||||
(claim) => !claim.reviewReferral || isReferredReviewer(claim, actor),
|
||||
);
|
||||
const list = visibleClaims.map((c) => {
|
||||
const blame = c.blameRequestId
|
||||
? blameById.get(c.blameRequestId.toString())
|
||||
: undefined;
|
||||
@@ -3122,8 +3221,9 @@ export class ExpertClaimService {
|
||||
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
|
||||
);
|
||||
const assignedToMe =
|
||||
blame?.assignedFileReviewerId &&
|
||||
String(blame.assignedFileReviewerId) === actor.sub;
|
||||
c.reviewReferral
|
||||
? isReferredReviewer(c, actor)
|
||||
: String(blame?.assignedFileReviewerId ?? "") === actor.sub;
|
||||
return {
|
||||
claimRequestId: c._id.toString(),
|
||||
publicId: c.publicId,
|
||||
@@ -3153,9 +3253,10 @@ export class ExpertClaimService {
|
||||
createdAt: c.createdAt,
|
||||
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
|
||||
needsFileReviewerCompletion:
|
||||
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
|
||||
(!!blame?.isMadeByFileMaker &&
|
||||
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
|
||||
!c.reviewReferral &&
|
||||
(String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
|
||||
(!!blame?.isMadeByFileMaker &&
|
||||
String(blame?.status ?? "") === "WAITING_FOR_EXPERT")),
|
||||
assignedToMe: !!assignedToMe,
|
||||
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
|
||||
fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0,
|
||||
@@ -3553,10 +3654,9 @@ export class ExpertClaimService {
|
||||
"workflow.preLockQueueSnapshot": "",
|
||||
};
|
||||
|
||||
const assigneeToPersist = claimWorkflowAssigneeToPersistOnLockExpiry(
|
||||
claim.workflow,
|
||||
claim,
|
||||
);
|
||||
const assigneeToPersist = claim.reviewReferral
|
||||
? claim.workflow?.assignedForReviewBy
|
||||
: claimWorkflowAssigneeToPersistOnLockExpiry(claim.workflow, claim);
|
||||
const expireLockSet: Record<string, unknown> = { "workflow.locked": false };
|
||||
if (assigneeToPersist) {
|
||||
expireLockSet["workflow.assignedForReviewBy"] = assigneeToPersist;
|
||||
@@ -3627,10 +3727,12 @@ export class ExpertClaimService {
|
||||
// FILE_REVIEWER access is validated by the role-specific gate below
|
||||
// (isAssignedToMe || isOpen). Skip the generic tenant-scope assert which
|
||||
// would incorrectly reject them via the initiatedByFieldExpertId path.
|
||||
if (actor.role !== RoleEnum.FILE_REVIEWER) {
|
||||
assertClaimCaseForExpertActor(claim, actor, linkedBlame);
|
||||
if (!claim.reviewReferral) {
|
||||
if (actor.role !== RoleEnum.FILE_REVIEWER) {
|
||||
assertClaimCaseForExpertActor(claim, actor, linkedBlame);
|
||||
}
|
||||
await this.assertActorBranchAccess(claim, actor, linkedBlame);
|
||||
}
|
||||
await this.assertActorBranchAccess(claim, actor, linkedBlame);
|
||||
|
||||
// Variables used both in the gate block and in the detail-build section below
|
||||
const isDamageExpertPhase =
|
||||
@@ -3641,7 +3743,9 @@ export class ExpertClaimService {
|
||||
|
||||
// FileMaker: can view any file they created (both during filing and approval phase).
|
||||
// The list endpoint already filters to V5-only; detail access is scoped by ownership.
|
||||
if (actor.role === RoleEnum.FILE_MAKER) {
|
||||
if (claim.reviewReferral) {
|
||||
if (!isOriginalFileMaker(claim, actor)) assertReferredReviewer(claim, actor);
|
||||
} else if (actor.role === RoleEnum.FILE_MAKER) {
|
||||
const isOwn = claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame);
|
||||
if (!isOwn) {
|
||||
throw new ForbiddenException(
|
||||
@@ -3927,6 +4031,9 @@ export class ExpertClaimService {
|
||||
|
||||
let evaluationForApi: Record<string, unknown> | undefined;
|
||||
if (enrichedEvaluation) {
|
||||
if (blameFileContext.blameRequestType === BlameRequestType.CAR_BODY) {
|
||||
delete enrichedEvaluation.priceDrop;
|
||||
}
|
||||
evaluationForApi = {};
|
||||
// damageExpertReply / damageExpertReplyFinal: include whenever present.
|
||||
// Previously these were gated on isFactorValidationPending, which hid the
|
||||
@@ -4023,6 +4130,18 @@ export class ExpertClaimService {
|
||||
};
|
||||
}
|
||||
|
||||
async assertCanSignFanavaranClaim(id: string, actor: any) {
|
||||
if (!Types.ObjectId.isValid(id)) throw new BadRequestException("شناسه پرونده معتبر نیست.");
|
||||
const roles = [
|
||||
RoleEnum.DAMAGE_EXPERT, RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER, RoleEnum.REGISTRAR,
|
||||
];
|
||||
if (!actor?.sub || !roles.includes(actor.role)) {
|
||||
throw new ForbiddenException("فقط کارشناس مجاز پرونده میتواند آن را امضا کند.");
|
||||
}
|
||||
await this.getClaimDetailV2(id, actor);
|
||||
}
|
||||
|
||||
private asFanavaranLookupRows(value: unknown): Array<Record<string, any>> {
|
||||
if (Array.isArray(value)) return value as Array<Record<string, any>>;
|
||||
if (value && typeof value === "object") {
|
||||
@@ -4439,6 +4558,12 @@ export class ExpertClaimService {
|
||||
return { version: fields.review.version };
|
||||
}
|
||||
|
||||
private assertPriceDropProduct(type: unknown) {
|
||||
if (type === BlameRequestType.CAR_BODY) {
|
||||
throw new BadRequestException("افت قیمت برای پرونده بیمه بدنه قابل ثبت نیست.");
|
||||
}
|
||||
}
|
||||
|
||||
/** V2 price-drop: claim locked by this expert during damage assessment. */
|
||||
private async assertExpertCanEditClaimDuringReviewV2(
|
||||
claim: any,
|
||||
@@ -4472,29 +4597,40 @@ 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;
|
||||
this.assertPriceDropProduct(blame?.type);
|
||||
suggestedCarModelYear = resolveVehicleModelYearFromBlame(
|
||||
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 +4640,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 +4680,72 @@ 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",
|
||||
},
|
||||
);
|
||||
this.assertPriceDropProduct(blameRows[0]?.type);
|
||||
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 +4769,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 +4786,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 +4812,7 @@ export class ExpertClaimService {
|
||||
body.partSeverities.map((p) => ({
|
||||
partId: p.partId,
|
||||
severity: p.severity,
|
||||
fanavaranPartId: p.fanavaranPartId,
|
||||
})),
|
||||
carType,
|
||||
);
|
||||
@@ -4634,14 +4825,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,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { GuardClaimReview } from "src/expert-claim/review-referral/claim-review.interceptor";
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { AiPricingRequestDto } from "src/ai/ai-pricing-request.dto";
|
||||
import { ValidationPipe } from "@nestjs/common";
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
@@ -68,6 +70,8 @@ class InPersonVisitV2Dto {
|
||||
}
|
||||
|
||||
@ApiTags("expert-claim-panel (v2)")
|
||||
@GuardClaimReview("review")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/expert-claim")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
@@ -277,7 +281,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 +299,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 })
|
||||
@@ -455,7 +459,7 @@ export class ExpertClaimV2Controller {
|
||||
@ApiBody({ type: FactorValidationV2Dto })
|
||||
async validateClaimFactorsV2(
|
||||
@Param("claimRequestId") claimRequestId: string,
|
||||
@Body() body: FactorValidationV2Dto,
|
||||
@Body(submitExpertReplyValidationPipe) body: FactorValidationV2Dto,
|
||||
@CurrentUser() actor,
|
||||
) {
|
||||
return await this.expertClaimService.validateClaimFactorsV2(
|
||||
|
||||
@@ -734,6 +734,7 @@ describe("Expert Fanavaran stage fields", () => {
|
||||
});
|
||||
management.logger = { log: jest.fn() };
|
||||
management.claimCaseDbService = {
|
||||
acquireReviewWrite: async () => async () => {},
|
||||
findById: jest.fn().mockResolvedValue(claim),
|
||||
};
|
||||
management.previewFanavaranSubmitV2 = jest.fn();
|
||||
|
||||
@@ -148,7 +148,7 @@ describe("Fanavaran vehicle review", () => {
|
||||
it("blocks a new manual base submission before building or posting its payload", async () => {
|
||||
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||
service.logger = { log: jest.fn() };
|
||||
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) };
|
||||
service.claimCaseDbService = { acquireReviewWrite: async () => async () => {}, findById: jest.fn().mockResolvedValue({}) };
|
||||
service.previewFanavaranSubmitV2 = jest.fn();
|
||||
await expect(service.executeFanavaranV2Submit("case", "moallem", { PolicyId: 1 }))
|
||||
.rejects.toMatchObject({ response: { code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED" } });
|
||||
@@ -159,7 +159,7 @@ describe("Fanavaran vehicle review", () => {
|
||||
it("reuses the existing base without requiring review or creating another base", async () => {
|
||||
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||
service.logger = { log: jest.fn() };
|
||||
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({ claimId: 12378660 }) };
|
||||
service.claimCaseDbService = { acquireReviewWrite: async () => async () => {}, findById: jest.fn().mockResolvedValue({ claimId: 12378660 }) };
|
||||
await expect(service.executeFanavaranV2Submit("case", "moallem"))
|
||||
.resolves.toMatchObject({ Id: 12378660 });
|
||||
});
|
||||
|
||||
@@ -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,20 @@ 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: field === "decisions" && constraint === "arrayMinSize"
|
||||
? "حداقل یک فاکتور را بررسی کنید."
|
||||
: field === "decisions" && constraint === "arrayUnique"
|
||||
? "برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید."
|
||||
: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
|
||||
}),
|
||||
);
|
||||
return [
|
||||
...ownErrors,
|
||||
...flattenValidationErrors(error.children ?? [], field),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
@@ -49,10 +58,12 @@ export const submitExpertReplyValidationPipe = new ValidationPipe({
|
||||
whitelist: true,
|
||||
exceptionFactory: (errors: ValidationError[]) => {
|
||||
const validationErrors = flattenValidationErrors(errors);
|
||||
const invoiceReview = errors.some(error => error.property === "decisions");
|
||||
const code = invoiceReview ? "FACTOR_VALIDATION_ERROR" : "EXPERT_REPLY_VALIDATION_ERROR";
|
||||
return new BadRequestException({
|
||||
message: "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
|
||||
error: "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
code: "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
message: invoiceReview ? "اطلاعات بررسی فاکتور معتبر نیست. فیلدهای مشخصشده را بررسی کنید." : "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
|
||||
error: code,
|
||||
code,
|
||||
validationErrors,
|
||||
});
|
||||
},
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ConflictException,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
SetMetadata,
|
||||
} from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { Types } from "mongoose";
|
||||
import { defer, lastValueFrom } from "rxjs";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { claimCaseTouchesClient } from "src/helpers/tenant-scope";
|
||||
import {
|
||||
assertReferredReviewer,
|
||||
isOriginalFileMaker,
|
||||
REVIEW_REFERRAL_CONFLICT,
|
||||
} from "./review-referral";
|
||||
|
||||
type Scope = "review" | "integration" | "approval";
|
||||
const SCOPE = Symbol("claim-review");
|
||||
export const GuardClaimReview = (scope: Scope) => SetMetadata(SCOPE, scope);
|
||||
const writes = new Set(["POST", "PUT", "PATCH", "DELETE"]);
|
||||
|
||||
@Injectable()
|
||||
export class ClaimReviewInterceptor implements NestInterceptor {
|
||||
constructor(
|
||||
private readonly reflector: Reflector,
|
||||
private readonly claims: ClaimCaseDbService,
|
||||
) {}
|
||||
|
||||
async intercept(context: ExecutionContext, next: CallHandler) {
|
||||
const scope = this.reflector.getAllAndOverride<Scope>(SCOPE, [
|
||||
context.getHandler(),
|
||||
context.getClass(),
|
||||
]);
|
||||
if (!scope) return next.handle();
|
||||
const req = context.switchToHttp().getRequest();
|
||||
const id =
|
||||
req.params?.claimRequestId ?? req.params?.claimCaseId ?? req.params?.id;
|
||||
if (!Types.ObjectId.isValid(id) || !req.user?.sub) return next.handle();
|
||||
|
||||
const actor = req.user;
|
||||
const claim = await this.claims.findReviewAccess(id);
|
||||
if (!claim) return next.handle();
|
||||
const mutating = writes.has(req.method);
|
||||
const ownMaker = isOriginalFileMaker(claim, actor);
|
||||
const retainsApprovalAccess =
|
||||
ownMaker &&
|
||||
(scope === "approval" ||
|
||||
(scope === "review" && !mutating) ||
|
||||
(scope === "integration" &&
|
||||
claim.status === ClaimCaseStatus.COMPLETED));
|
||||
const insurerIntegration =
|
||||
scope === "integration" &&
|
||||
(actor.role === RoleEnum.SUPER_ADMIN ||
|
||||
(actor.role === RoleEnum.COMPANY &&
|
||||
!!actor.clientKey &&
|
||||
claimCaseTouchesClient(claim, actor.clientKey)));
|
||||
if (!retainsApprovalAccess && !insurerIntegration)
|
||||
assertReferredReviewer(claim, actor);
|
||||
if (!mutating) return next.handle();
|
||||
|
||||
// A referral can interrupt a review session, but may not interleave with a
|
||||
// write already accepted from that session. The database fence spans replicas.
|
||||
return defer(async () => {
|
||||
const release = await this.claims.acquireReviewWrite(id, {
|
||||
"reviewReferral.referredAt": claim.reviewReferral?.referredAt ?? null,
|
||||
"reviewReferral.assigneeId": claim.reviewReferral?.assigneeId ?? null,
|
||||
});
|
||||
if (!release) throw new ConflictException(REVIEW_REFERRAL_CONFLICT);
|
||||
try {
|
||||
return await lastValueFrom(next.handle());
|
||||
} finally {
|
||||
await release();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,519 @@
|
||||
import {
|
||||
ConflictException,
|
||||
ForbiddenException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Reflector } from "@nestjs/core";
|
||||
import { ExecutionContextHost } from "@nestjs/core/helpers/execution-context-host";
|
||||
import { Types } from "mongoose";
|
||||
import { defer, lastValueFrom, of } from "rxjs";
|
||||
import { ClaimCaseStatus as Status } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
|
||||
import { ClaimWorkflowStep as Step } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
||||
import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { ClaimReviewReferralService } from "src/expert-insurer/claim-review-referral.service";
|
||||
import { getEventFaDescription } from "src/expert-insurer/helper/timeline-fa-labels";
|
||||
import {
|
||||
ClaimReviewInterceptor,
|
||||
GuardClaimReview,
|
||||
} from "./claim-review.interceptor";
|
||||
import {
|
||||
assertReferredReviewer,
|
||||
isReferredReviewer,
|
||||
referralIneligibility,
|
||||
reviewReferralRole,
|
||||
} from "./review-referral";
|
||||
import { ExpertClaimService } from "../expert-claim.service";
|
||||
import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature";
|
||||
|
||||
const tenant = "650000000000000000000001";
|
||||
const otherTenant = "650000000000000000000002";
|
||||
const previousBranchId = "650000000000000000000003";
|
||||
const nextBranchId = "650000000000000000000004";
|
||||
const previousExpertId = "650000000000000000000005";
|
||||
const nextExpertId = "650000000000000000000006";
|
||||
const insurerId = "650000000000000000000007";
|
||||
const makerId = "650000000000000000000008";
|
||||
const claimId = "650000000000000000000009";
|
||||
const blameId = "650000000000000000000010";
|
||||
const readyClaim = {
|
||||
_id: new Types.ObjectId(claimId),
|
||||
publicId: "REF100",
|
||||
updatedAt: new Date("2026-11-20T08:00:00Z"),
|
||||
status: Status.WAITING_FOR_DAMAGE_EXPERT,
|
||||
workflow: { currentStep: Step.USER_SUBMISSION_COMPLETE },
|
||||
owner: { clientId: new Types.ObjectId(tenant) },
|
||||
branchId: new Types.ObjectId(previousBranchId),
|
||||
blameRequestId: new Types.ObjectId(blameId),
|
||||
};
|
||||
const complete = {
|
||||
_id: readyClaim.blameRequestId,
|
||||
status: "COMPLETED",
|
||||
branchId: readyClaim.branchId,
|
||||
};
|
||||
const split = {
|
||||
...complete,
|
||||
isMadeByFileMaker: true,
|
||||
expertInitiated: true,
|
||||
initiatedByFieldExpertId: makerId,
|
||||
assignedFileReviewerId: previousExpertId,
|
||||
creationMethod: "IN_PERSON",
|
||||
};
|
||||
const cases = [
|
||||
["v1", complete, RoleEnum.DAMAGE_EXPERT],
|
||||
["v2", { ...complete, expertInitiated: true }, RoleEnum.FIELD_EXPERT],
|
||||
["v3", { ...complete, expertInitiated: true }, RoleEnum.FIELD_EXPERT],
|
||||
["v4", split, RoleEnum.FILE_REVIEWER],
|
||||
["v5", { ...split, requiresFileMakerApproval: true }, RoleEnum.FILE_REVIEWER],
|
||||
["v6", { ...complete, callCenterInitiated: true }, RoleEnum.DAMAGE_EXPERT],
|
||||
] as const;
|
||||
|
||||
describe("review-only referral eligibility", () => {
|
||||
it.each(cases)(
|
||||
"%s can refer the completed intake to the role that runs assessment",
|
||||
(_, blame, role) => {
|
||||
expect(reviewReferralRole(readyClaim, blame)).toBe(role);
|
||||
expect(referralIneligibility(readyClaim, blame)).toBeNull();
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{ ...readyClaim, status: Status.UPLOADING_REQUIRED_DOCUMENTS },
|
||||
blame,
|
||||
),
|
||||
).toBeTruthy();
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{ ...readyClaim, status: Status.WAITING_FOR_USER_RESEND },
|
||||
blame,
|
||||
),
|
||||
).toBeTruthy();
|
||||
},
|
||||
);
|
||||
it.each(["baseClaim", "damageCase", "attachments", "expertise"])(
|
||||
"blocks a successful %s stage",
|
||||
(stage) => {
|
||||
const claim = {
|
||||
...readyClaim,
|
||||
fanavaranSync: { [stage]: { status: "success" } },
|
||||
};
|
||||
expect(referralIneligibility(claim, complete)).toContain("فناوران");
|
||||
},
|
||||
);
|
||||
it("blocks legacy remote IDs and successful attachment receipts, and permits a failed base submission", () => {
|
||||
expect(
|
||||
referralIneligibility({ ...readyClaim, claimNo: 12 }, complete),
|
||||
).toContain("فناوران");
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{
|
||||
...readyClaim,
|
||||
fanavaranSync: { attachments: { files: [{ fileId: 4 }] } },
|
||||
},
|
||||
complete,
|
||||
),
|
||||
).toContain("فناوران");
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{ ...readyClaim, fanavaranSync: { baseClaim: { status: "failed" } } },
|
||||
complete,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
it("blocks sealed files still waiting for capture, and permits a V5 assessment correction", () => {
|
||||
const waiting = {
|
||||
...split,
|
||||
status: "WAITING_FOR_FILE_REVIEWER",
|
||||
requiresFileMakerApproval: true,
|
||||
};
|
||||
expect(referralIneligibility(readyClaim, waiting)).not.toBeNull();
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{
|
||||
...readyClaim,
|
||||
fileMakerRejectionCount: 1,
|
||||
workflow: { currentStep: Step.EXPERT_DAMAGE_ASSESSMENT },
|
||||
},
|
||||
waiting,
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{ ...readyClaim, status: Status.WAITING_FOR_FILE_MAKER_APPROVAL },
|
||||
complete,
|
||||
),
|
||||
).not.toBeNull();
|
||||
});
|
||||
it("allows mid-review and factor validation after all invoices have been uploaded", () => {
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{
|
||||
...readyClaim,
|
||||
status: Status.EXPERT_REVIEWING,
|
||||
workflow: { currentStep: Step.EXPERT_DAMAGE_ASSESSMENT },
|
||||
},
|
||||
complete,
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
referralIneligibility(
|
||||
{
|
||||
...readyClaim,
|
||||
status: Status.EXPERT_VALIDATING_REPAIR_FACTORS,
|
||||
claimStatus: ClaimStatus.UNDER_REVIEW,
|
||||
workflow: { currentStep: Step.EXPERT_COST_EVALUATION },
|
||||
},
|
||||
complete,
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
function setup() {
|
||||
const previousActor = {
|
||||
actorId: new Types.ObjectId(previousExpertId),
|
||||
actorRole: RoleEnum.FILE_REVIEWER,
|
||||
actorName: "سارا احمدی",
|
||||
};
|
||||
const claim = {
|
||||
...readyClaim,
|
||||
initiatedByFieldExpertId: new Types.ObjectId(makerId),
|
||||
fileMakerApprovalActorId: new Types.ObjectId(makerId),
|
||||
status: Status.EXPERT_REVIEWING,
|
||||
workflow: {
|
||||
currentStep: Step.EXPERT_DAMAGE_ASSESSMENT,
|
||||
assignedForReviewBy: previousActor,
|
||||
locked: true,
|
||||
lockedBy: previousActor,
|
||||
},
|
||||
evaluation: { damageExpertReply: { description: "ارزیابی اولیه" } },
|
||||
history: [],
|
||||
};
|
||||
const prevBranch = {
|
||||
_id: previousBranchId,
|
||||
name: "شعبه قبلی",
|
||||
city: "تهران",
|
||||
clientKey: tenant,
|
||||
};
|
||||
const nextBranch = {
|
||||
_id: nextBranchId,
|
||||
name: "شعبه جدید",
|
||||
city: "کرج",
|
||||
clientKey: tenant,
|
||||
};
|
||||
const nextExpert = {
|
||||
_id: nextExpertId,
|
||||
firstName: "رضا",
|
||||
lastName: "کریمی",
|
||||
clientKey: tenant,
|
||||
branchId: new Types.ObjectId(nextBranchId),
|
||||
isActive: true,
|
||||
};
|
||||
const repo = {
|
||||
findOne: jest.fn(async (filter) =>
|
||||
filter.publicId === claim.publicId &&
|
||||
String(filter.$or[0]["owner.clientId"]) === tenant
|
||||
? claim
|
||||
: null,
|
||||
),
|
||||
findOneAndUpdate: jest.fn().mockResolvedValue(claim),
|
||||
};
|
||||
const reviewers = {
|
||||
findById: jest.fn().mockResolvedValue(nextExpert),
|
||||
findReviewCandidates: jest.fn().mockResolvedValue([nextExpert]),
|
||||
};
|
||||
const branches = {
|
||||
findById: jest.fn(async (id) =>
|
||||
[prevBranch, nextBranch].find((branch) => branch._id === id),
|
||||
),
|
||||
findAll: jest.fn().mockResolvedValue([prevBranch, nextBranch]),
|
||||
};
|
||||
const service = new ClaimReviewReferralService(
|
||||
repo as any,
|
||||
{ findById: async () => split } as any,
|
||||
branches as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
reviewers as any,
|
||||
);
|
||||
const insurer = { sub: insurerId, clientKey: tenant, fullName: "مدیر بیمه" };
|
||||
const body = {
|
||||
expertId: nextExpertId,
|
||||
revision: String(claim.updatedAt.getTime()),
|
||||
};
|
||||
return {
|
||||
claim,
|
||||
repo,
|
||||
reviewers,
|
||||
service,
|
||||
insurer,
|
||||
body,
|
||||
branches,
|
||||
nextExpert,
|
||||
nextBranch,
|
||||
};
|
||||
}
|
||||
|
||||
describe("insurer claim review referral", () => {
|
||||
it("updates the assignee and review branch atomically with a before/after audit entry", async () => {
|
||||
const { claim, repo, service, body, insurer } = setup();
|
||||
const options = await service.options(tenant, claim.publicId);
|
||||
expect(options.candidates).toEqual([
|
||||
{
|
||||
id: nextExpertId,
|
||||
name: "رضا کریمی",
|
||||
branchId: nextBranchId,
|
||||
branchName: "شعبه جدید",
|
||||
city: "کرج",
|
||||
},
|
||||
]);
|
||||
await expect(service.refer(insurer, claim.publicId, body)).resolves.toEqual(
|
||||
{
|
||||
expertName: "رضا کریمی",
|
||||
branchName: "شعبه جدید",
|
||||
},
|
||||
);
|
||||
const [filter, update] = repo.findOneAndUpdate.mock.calls[0];
|
||||
expect(filter).toMatchObject({
|
||||
status: Status.EXPERT_REVIEWING,
|
||||
updatedAt: claim.updatedAt,
|
||||
claimId: null,
|
||||
"fanavaranSync.baseClaim.status": { $ne: "success" },
|
||||
reviewWrites: {
|
||||
$not: { $elemMatch: { expiresAt: { $gt: expect.any(Date) } } },
|
||||
},
|
||||
});
|
||||
expect(String(update.$set.branchId)).toBe(nextBranchId);
|
||||
expect(String(update.$set.reviewReferral.assigneeId)).toBe(nextExpertId);
|
||||
expect(update.$set["workflow.locked"]).toBe(false);
|
||||
expect(update.$unset).toHaveProperty(["workflow.lockedBy"]);
|
||||
expect(update.$push.history.metadata).toMatchObject({
|
||||
previousExpertId,
|
||||
previousExpertName: "سارا احمدی",
|
||||
previousBranchId,
|
||||
previousBranchName: "شعبه قبلی",
|
||||
expertId: nextExpertId,
|
||||
branchId: nextBranchId,
|
||||
});
|
||||
expect(getEventFaDescription(update.$push.history)).toContain("شعبه قبلی");
|
||||
expect(getEventFaDescription(update.$push.history)).toContain("شعبه جدید");
|
||||
expect(update.$set).not.toHaveProperty("status");
|
||||
expect(update.$set).not.toHaveProperty("evaluation");
|
||||
expect(update.$set).not.toHaveProperty("initiatedByFieldExpertId");
|
||||
});
|
||||
|
||||
it("allows a same-branch reassignment", async () => {
|
||||
const { claim, service, body, insurer, nextExpert } = setup();
|
||||
nextExpert.branchId = new Types.ObjectId(previousBranchId);
|
||||
await expect(
|
||||
service.refer(insurer, claim.publicId, body),
|
||||
).resolves.toMatchObject({ branchName: "شعبه قبلی" });
|
||||
});
|
||||
|
||||
it("rejects another insurer, inactive experts or branches, and stale decisions", async () => {
|
||||
const { claim, service, body, insurer, repo, nextExpert, nextBranch } =
|
||||
setup();
|
||||
await expect(
|
||||
service.refer(
|
||||
{ ...insurer, clientKey: otherTenant },
|
||||
claim.publicId,
|
||||
body,
|
||||
),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
service.refer(insurer, claim.publicId, { ...body, revision: "0" }),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
nextExpert.isActive = false;
|
||||
await expect(
|
||||
service.refer(insurer, claim.publicId, body),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
nextExpert.isActive = true;
|
||||
Object.assign(nextBranch, { isActive: false });
|
||||
await expect(
|
||||
service.refer(insurer, claim.publicId, body),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
expect(repo.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not overwrite a concurrent review, referral, or Fanavaran submission", async () => {
|
||||
const { claim, service, body, insurer, repo } = setup();
|
||||
repo.findOneAndUpdate.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.refer(insurer, claim.publicId, body),
|
||||
).rejects.toBeInstanceOf(ConflictException);
|
||||
});
|
||||
});
|
||||
|
||||
@GuardClaimReview("review")
|
||||
class TestReviewRoute {
|
||||
review() {}
|
||||
}
|
||||
@GuardClaimReview("approval")
|
||||
class TestMakerApprovalRoute {
|
||||
review() {}
|
||||
}
|
||||
|
||||
describe("referred expert review access", () => {
|
||||
const newReviewer = {
|
||||
sub: nextExpertId,
|
||||
role: RoleEnum.FILE_REVIEWER,
|
||||
clientKey: tenant,
|
||||
};
|
||||
const claim = {
|
||||
...readyClaim,
|
||||
fileMakerApprovalActorId: new Types.ObjectId(makerId),
|
||||
reviewReferral: {
|
||||
assigneeId: new Types.ObjectId(nextExpertId),
|
||||
assigneeRole: RoleEnum.FILE_REVIEWER,
|
||||
referredAt: new Date(),
|
||||
},
|
||||
};
|
||||
const context = (actor: any, method = "PUT", route = TestReviewRoute) =>
|
||||
new ExecutionContextHost(
|
||||
[{ user: actor, method, params: { claimRequestId: claimId } }],
|
||||
route,
|
||||
route.prototype.review,
|
||||
);
|
||||
const release = jest.fn();
|
||||
const repo = {
|
||||
findReviewAccess: jest.fn().mockResolvedValue(claim),
|
||||
acquireReviewWrite: jest.fn().mockResolvedValue(release),
|
||||
};
|
||||
const interceptor = new ClaimReviewInterceptor(new Reflector(), repo as any);
|
||||
|
||||
it("requires the exact expert, role and insurer", () => {
|
||||
expect(isReferredReviewer(claim, newReviewer)).toBe(true);
|
||||
for (const actor of [
|
||||
{ ...newReviewer, sub: previousExpertId },
|
||||
{ ...newReviewer, clientKey: otherTenant },
|
||||
{ ...newReviewer, role: RoleEnum.DAMAGE_EXPERT },
|
||||
])
|
||||
expect(() => assertReferredReviewer(claim, actor)).toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks the old expert before the handler and fences writes from the new expert", async () => {
|
||||
const handle = jest.fn(() => of("done"));
|
||||
await expect(
|
||||
interceptor.intercept(
|
||||
context({ ...newReviewer, sub: previousExpertId }),
|
||||
{ handle },
|
||||
),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(handle).not.toHaveBeenCalled();
|
||||
const result = await interceptor.intercept(context(newReviewer), {
|
||||
handle,
|
||||
});
|
||||
expect(await lastValueFrom(result)).toBe("done");
|
||||
expect(repo.acquireReviewWrite).toHaveBeenCalledWith(claimId, {
|
||||
"reviewReferral.referredAt": claim.reviewReferral.referredAt,
|
||||
"reviewReferral.assigneeId": claim.reviewReferral.assigneeId,
|
||||
});
|
||||
expect(release).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("releases the write fence when the handler rejects", async () => {
|
||||
release.mockClear();
|
||||
const result = await interceptor.intercept(context(newReviewer), {
|
||||
handle: () =>
|
||||
defer(async () => {
|
||||
throw new Error("write failed");
|
||||
}),
|
||||
});
|
||||
await expect(lastValueFrom(result)).rejects.toThrow("write failed");
|
||||
expect(release).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("preserves the original FileMaker's approval, while restricting review writes", async () => {
|
||||
const maker = {
|
||||
sub: makerId,
|
||||
role: RoleEnum.FILE_MAKER,
|
||||
clientKey: tenant,
|
||||
};
|
||||
const handle = () => of("allowed");
|
||||
await expect(
|
||||
interceptor.intercept(context(maker), { handle }),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
const reply = await interceptor.intercept(
|
||||
context(maker, "POST", TestMakerApprovalRoute),
|
||||
{ handle },
|
||||
);
|
||||
expect(await lastValueFrom(reply)).toBe("allowed");
|
||||
});
|
||||
|
||||
it("admits the referred reviewer for assessment without granting original intake ownership", async () => {
|
||||
const expert = Object.create(ExpertClaimService.prototype);
|
||||
expert.loadBlameForClaim = jest.fn();
|
||||
await expert.assertExpertActorOnClaim(claim, newReviewer);
|
||||
await expect(
|
||||
expert.assertExpertActorOnClaim(claim, {
|
||||
...newReviewer,
|
||||
sub: previousExpertId,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(ForbiddenException);
|
||||
expect(expert.loadBlameForClaim).not.toHaveBeenCalled();
|
||||
expect(fanavaranSignatureRevision(claim)).not.toBe(
|
||||
fanavaranSignatureRevision(readyClaim),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expert queues after a referral", () => {
|
||||
it.each([RoleEnum.FIELD_EXPERT, RoleEnum.FILE_REVIEWER])(
|
||||
"lists the case for the %s destination and removes it from the original queue",
|
||||
async (role) => {
|
||||
const expert = Object.create(ExpertClaimService.prototype);
|
||||
const ready = {
|
||||
...readyClaim,
|
||||
branchId: new Types.ObjectId(nextBranchId),
|
||||
initiatedByFieldExpertId: new Types.ObjectId(previousExpertId),
|
||||
reviewReferral: {
|
||||
assigneeId: new Types.ObjectId(nextExpertId),
|
||||
assigneeRole: role,
|
||||
referredAt: new Date(),
|
||||
},
|
||||
};
|
||||
const intake = {
|
||||
...split,
|
||||
_id: readyClaim.blameRequestId,
|
||||
isMadeByFileMaker: role === RoleEnum.FILE_REVIEWER,
|
||||
};
|
||||
expert.blameRequestDbService = { find: async () => [intake] };
|
||||
expert.claimCaseDbService = {
|
||||
find: jest.fn(async (filter) => {
|
||||
const filterId = filter["reviewReferral.assigneeId"];
|
||||
return filterId && filterId !== nextExpertId ? [] : [ready];
|
||||
}),
|
||||
};
|
||||
expert.fanavaranLocationService = {
|
||||
assertMakerReviewerBranchCompatible: jest.fn(
|
||||
async ({ fileReviewerId }) => {
|
||||
if (fileReviewerId === nextExpertId)
|
||||
throw new Error("different intake branch");
|
||||
},
|
||||
),
|
||||
};
|
||||
expert.vehicleForExpertFromClaimAndBlameMap = jest.fn();
|
||||
expert.blameFileContextForExpert = jest.fn(() => ({}));
|
||||
expert.paginateClaimListV2 = (rows) => rows;
|
||||
const newQueue = await expert.getClaimListV2({
|
||||
sub: nextExpertId,
|
||||
clientKey: tenant,
|
||||
role,
|
||||
});
|
||||
expect(newQueue).toHaveLength(1);
|
||||
if (role === RoleEnum.FILE_REVIEWER) {
|
||||
expect(newQueue[0].needsFileReviewerCompletion).toBe(false);
|
||||
expect(newQueue[0].assignedToMe).toBe(true);
|
||||
expect(
|
||||
expert.fanavaranLocationService.assertMakerReviewerBranchCompatible,
|
||||
).not.toHaveBeenCalled();
|
||||
}
|
||||
const previousQueue = await expert.getClaimListV2({
|
||||
sub: previousExpertId,
|
||||
clientKey: tenant,
|
||||
role,
|
||||
});
|
||||
expect(previousQueue).toEqual([]);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,127 @@
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
|
||||
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { claimIsAwaitingExpertFactorValidationV2 } from "src/helpers/claim-v2-expert-reply-workflow";
|
||||
import { claimCaseTouchesClient } from "src/helpers/tenant-scope";
|
||||
|
||||
export const CLAIM_REVIEW_REFERRED = "CLAIM_REVIEW_REFERRED";
|
||||
export const REVIEW_REFERRAL_CONFLICT =
|
||||
"پرونده در حال تغییر است. اطلاعات ارجاع را دوباره دریافت کنید.";
|
||||
export const REVIEW_REFERRAL_DENIED =
|
||||
"بررسی این پرونده به کارشناس دیگری ارجاع شده است.";
|
||||
export const REVIEW_REFERRAL_ROLES = [
|
||||
RoleEnum.DAMAGE_EXPERT,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
] as const;
|
||||
export type ReviewReferralRole = (typeof REVIEW_REFERRAL_ROLES)[number];
|
||||
|
||||
const fanavaranStages = [
|
||||
"baseClaim",
|
||||
"damageCase",
|
||||
"attachments",
|
||||
"expertise",
|
||||
] as const;
|
||||
const remoteIds = ["claimId", "claimNo", "dmgCaseId", "expertiseId"] as const;
|
||||
const remoteFields = [
|
||||
...remoteIds,
|
||||
...fanavaranStages.flatMap((stage) =>
|
||||
remoteIds.map((id) => `fanavaranSync.${stage}.${id}`),
|
||||
),
|
||||
];
|
||||
export const noFanavaranSubmission = {
|
||||
...Object.fromEntries(remoteFields.map((field) => [field, null])),
|
||||
...Object.fromEntries(
|
||||
fanavaranStages.map((stage) => [
|
||||
`fanavaranSync.${stage}.status`,
|
||||
{ $ne: "success" },
|
||||
]),
|
||||
),
|
||||
"fanavaranSync.attachments.files.0": { $exists: false },
|
||||
};
|
||||
|
||||
export function referralIneligibility(claim: any, blame: any): string | null {
|
||||
if (!claim) return "پرونده خسارت هنوز تشکیل نشده است.";
|
||||
if (
|
||||
remoteIds.some((id) => claim[id] != null) ||
|
||||
fanavaranStages.some((stage) => {
|
||||
const sync = claim.fanavaranSync?.[stage];
|
||||
return (
|
||||
sync?.status === "success" || remoteIds.some((id) => sync?.[id] != null)
|
||||
);
|
||||
}) ||
|
||||
claim.fanavaranSync?.attachments?.files?.length
|
||||
)
|
||||
return "پرونده در فناوران ثبت شده و امکان ارجاع آن وجود ندارد.";
|
||||
|
||||
const step = claim.workflow?.currentStep;
|
||||
const assessmentReady =
|
||||
(claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT &&
|
||||
[
|
||||
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
|
||||
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
|
||||
].includes(step)) ||
|
||||
(claim.status === ClaimCaseStatus.EXPERT_REVIEWING &&
|
||||
step === ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT) ||
|
||||
claimIsAwaitingExpertFactorValidationV2(claim);
|
||||
// A V5 correction reopens the blame record after the original capture was completed.
|
||||
const v5Correction =
|
||||
blame?.isMadeByFileMaker === true &&
|
||||
blame.requiresFileMakerApproval === true &&
|
||||
claim.fileMakerRejectionCount > 0 &&
|
||||
blame.status === "WAITING_FOR_FILE_REVIEWER";
|
||||
if (
|
||||
!assessmentReady ||
|
||||
!blame ||
|
||||
(blame.status !== "COMPLETED" && !v5Correction)
|
||||
) {
|
||||
return "ارجاع پس از تکمیل اطلاعات و ورود پرونده به مرحله ارزیابی خسارت امکانپذیر است.";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export function reviewReferralRole(claim: any, blame: any): ReviewReferralRole {
|
||||
if (blame?.isMadeByFileMaker === true) return RoleEnum.FILE_REVIEWER;
|
||||
if (claim?.initiatedByFieldExpertId || blame?.expertInitiated === true)
|
||||
return RoleEnum.FIELD_EXPERT;
|
||||
return RoleEnum.DAMAGE_EXPERT;
|
||||
}
|
||||
|
||||
export function isReferredReviewer(claim: any, actor: any): boolean {
|
||||
const referral = claim?.reviewReferral;
|
||||
return (
|
||||
!!referral &&
|
||||
referral.assigneeRole === actor?.role &&
|
||||
String(referral.assigneeId) === String(actor?.sub) &&
|
||||
!!actor?.clientKey &&
|
||||
claimCaseTouchesClient(claim, String(actor.clientKey))
|
||||
);
|
||||
}
|
||||
|
||||
/** V5 approval remains with the file maker who created the case. */
|
||||
export function isOriginalFileMaker(claim: any, actor: any) {
|
||||
const makerId =
|
||||
claim?.fileMakerApprovalActorId ?? claim?.initiatedByFieldExpertId;
|
||||
return (
|
||||
actor?.role === RoleEnum.FILE_MAKER &&
|
||||
!!makerId &&
|
||||
String(makerId) === String(actor?.sub)
|
||||
);
|
||||
}
|
||||
|
||||
export function assertReferredReviewer(claim: any, actor: any): void {
|
||||
if (claim?.reviewReferral && !isReferredReviewer(claim, actor)) {
|
||||
throw new ForbiddenException({
|
||||
code: "CLAIM_REVIEW_REFERRED",
|
||||
message: REVIEW_REFERRAL_DENIED,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function reviewReferralActorFilter(actor: any) {
|
||||
return {
|
||||
"reviewReferral.assigneeId": actor.sub,
|
||||
"reviewReferral.assigneeRole": actor.role,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import {
|
||||
ConflictException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { Types } from "mongoose";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { ClaimCaseDocument } from "src/claim-request-management/entites/schema/claim-cases.schema";
|
||||
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
|
||||
import {
|
||||
CLAIM_REVIEW_REFERRED,
|
||||
noFanavaranSubmission,
|
||||
referralIneligibility,
|
||||
REVIEW_REFERRAL_CONFLICT,
|
||||
reviewReferralRole,
|
||||
ReviewReferralRole,
|
||||
} from "src/expert-claim/review-referral/review-referral";
|
||||
import { personDisplayName } from "src/helpers/person-display-name";
|
||||
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
|
||||
import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service";
|
||||
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
|
||||
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
|
||||
import { ReferClaimReviewDto } from "./dto/refer-claim-review.dto";
|
||||
|
||||
type InsurerActor = { sub: string; clientKey: string; fullName?: string };
|
||||
type Staff = {
|
||||
_id?: unknown;
|
||||
branchId?: unknown;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
};
|
||||
type Branch = {
|
||||
_id?: unknown;
|
||||
name: string;
|
||||
code?: string;
|
||||
city: string;
|
||||
isActive?: boolean;
|
||||
};
|
||||
const revision = (claim: ClaimCaseDocument) =>
|
||||
String(claim.updatedAt?.getTime() ?? 0);
|
||||
|
||||
@Injectable()
|
||||
export class ClaimReviewReferralService {
|
||||
constructor(
|
||||
private readonly claims: ClaimCaseDbService,
|
||||
private readonly blames: BlameRequestDbService,
|
||||
private readonly branches: BranchDbService,
|
||||
private readonly damageExperts: DamageExpertDbService,
|
||||
private readonly fieldExperts: FieldExpertDbService,
|
||||
private readonly fileReviewers: FileReviewerDbService,
|
||||
) {}
|
||||
|
||||
private async context(clientKey: string, publicId: string) {
|
||||
if (!Types.ObjectId.isValid(clientKey))
|
||||
throw new NotFoundException("پرونده خسارت یافت نشد.");
|
||||
const tenantFilter = {
|
||||
$or: [
|
||||
{ "owner.clientId": new Types.ObjectId(clientKey) },
|
||||
{ "owner.clientId": null, "owner.userClientKey": clientKey },
|
||||
],
|
||||
};
|
||||
const claim = await this.claims.findOne({ publicId, ...tenantFilter });
|
||||
if (!claim) throw new NotFoundException("پرونده خسارت یافت نشد.");
|
||||
const blame = claim.blameRequestId
|
||||
? await this.blames.findById(claim.blameRequestId)
|
||||
: null;
|
||||
const role = reviewReferralRole(claim, blame);
|
||||
const current =
|
||||
claim.workflow?.assignedForReviewBy ?? claim.workflow?.lockedBy;
|
||||
const currentExpertId =
|
||||
claim.reviewReferral?.assigneeId ??
|
||||
current?.actorId ??
|
||||
(role === RoleEnum.FILE_REVIEWER
|
||||
? blame?.assignedFileReviewerId
|
||||
: role === RoleEnum.FIELD_EXPERT
|
||||
? (claim.initiatedByFieldExpertId ?? blame?.initiatedByFieldExpertId)
|
||||
: undefined);
|
||||
const branchId = claim.branchId ?? blame?.branchId;
|
||||
return {
|
||||
claim,
|
||||
blame,
|
||||
role,
|
||||
current,
|
||||
currentExpertId,
|
||||
branchId,
|
||||
tenantFilter,
|
||||
};
|
||||
}
|
||||
|
||||
private getStaff(role: ReviewReferralRole) {
|
||||
if (role === RoleEnum.FILE_REVIEWER) return this.fileReviewers;
|
||||
if (role === RoleEnum.FIELD_EXPERT) return this.fieldExperts;
|
||||
return this.damageExperts;
|
||||
}
|
||||
|
||||
private async getBranch(id?: unknown): Promise<Branch | null> {
|
||||
return id ? this.branches.findById(String(id)) : null;
|
||||
}
|
||||
|
||||
async options(clientKey: string, publicId: string) {
|
||||
const c = await this.context(clientKey, publicId);
|
||||
const reason = referralIneligibility(c.claim, c.blame);
|
||||
const [branches, staff, currentStaff] = await Promise.all([
|
||||
this.branches.findAll(clientKey) as Promise<Branch[]>,
|
||||
reason ? [] : this.getStaff(c.role).findReviewCandidates(clientKey),
|
||||
c.currentExpertId && !c.current?.actorName
|
||||
? this.getStaff(c.role).findById(String(c.currentExpertId))
|
||||
: null,
|
||||
]);
|
||||
const activeBranches = new Map(
|
||||
branches
|
||||
.filter((branch) => branch.isActive !== false)
|
||||
.map((branch) => [String(branch._id), branch]),
|
||||
);
|
||||
const candidates = staff.flatMap((expert: Staff) => {
|
||||
const id = String(expert._id);
|
||||
const branchId = String(expert.branchId ?? "");
|
||||
const branch = activeBranches.get(branchId);
|
||||
if (
|
||||
!branch ||
|
||||
(id === String(c.currentExpertId) && branchId === String(c.branchId))
|
||||
)
|
||||
return [];
|
||||
return [
|
||||
{
|
||||
id,
|
||||
name: personDisplayName(expert),
|
||||
branchId,
|
||||
branchName: branch.name,
|
||||
city: branch.city,
|
||||
},
|
||||
];
|
||||
});
|
||||
return {
|
||||
eligible: !reason,
|
||||
reason,
|
||||
role: c.role,
|
||||
revision: revision(c.claim),
|
||||
current: {
|
||||
expertName: c.current?.actorName || personDisplayName(currentStaff),
|
||||
branchName: branches.find(
|
||||
(branch) => String(branch._id) === String(c.branchId),
|
||||
)?.name,
|
||||
},
|
||||
candidates,
|
||||
};
|
||||
}
|
||||
|
||||
async refer(
|
||||
actor: InsurerActor,
|
||||
publicId: string,
|
||||
body: ReferClaimReviewDto,
|
||||
) {
|
||||
const c = await this.context(actor.clientKey, publicId);
|
||||
const reason = referralIneligibility(c.claim, c.blame);
|
||||
if (reason) throw new ConflictException(reason);
|
||||
if (body.revision !== revision(c.claim))
|
||||
throw new ConflictException(REVIEW_REFERRAL_CONFLICT);
|
||||
const repo = this.getStaff(c.role);
|
||||
const expert = await repo.findById(body.expertId);
|
||||
if (
|
||||
!expert ||
|
||||
String(expert.clientKey) !== actor.clientKey ||
|
||||
expert.isActive === false ||
|
||||
!expert.branchId
|
||||
) {
|
||||
throw new NotFoundException("کارشناس فعال در این شرکت بیمه یافت نشد.");
|
||||
}
|
||||
const [branch, previousBranch, previousExpert] = await Promise.all([
|
||||
this.branches.findById(String(expert.branchId)),
|
||||
this.getBranch(c.branchId),
|
||||
c.currentExpertId && !c.current?.actorName
|
||||
? repo.findById(String(c.currentExpertId))
|
||||
: null,
|
||||
]);
|
||||
if (
|
||||
!branch ||
|
||||
String(branch.clientKey) !== actor.clientKey ||
|
||||
branch.isActive === false
|
||||
) {
|
||||
throw new ConflictException("شعبه کارشناس انتخابشده فعال نیست.");
|
||||
}
|
||||
if (
|
||||
String(c.currentExpertId) === body.expertId &&
|
||||
String(c.branchId) === String(expert.branchId)
|
||||
) {
|
||||
throw new ConflictException(
|
||||
"این پرونده در همین شعبه به کارشناس انتخابشده ارجاع شده است.",
|
||||
);
|
||||
}
|
||||
|
||||
const now = new Date();
|
||||
const expertId = new Types.ObjectId(body.expertId);
|
||||
const name = personDisplayName(expert);
|
||||
const updated = await this.claims.findOneAndUpdate(
|
||||
{
|
||||
_id: c.claim._id,
|
||||
...c.tenantFilter,
|
||||
...noFanavaranSubmission,
|
||||
updatedAt: c.claim.updatedAt ?? null,
|
||||
status: c.claim.status,
|
||||
"workflow.currentStep": c.claim.workflow?.currentStep ?? null,
|
||||
"workflow.assignedForReviewBy.actorId":
|
||||
c.claim.workflow?.assignedForReviewBy?.actorId ?? null,
|
||||
"reviewReferral.referredAt": c.claim.reviewReferral?.referredAt ?? null,
|
||||
reviewWrites: { $not: { $elemMatch: { expiresAt: { $gt: now } } } },
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
branchId: expert.branchId,
|
||||
reviewReferral: {
|
||||
assigneeId: expertId,
|
||||
assigneeRole: c.role,
|
||||
referredAt: now,
|
||||
},
|
||||
"workflow.assignedForReviewBy": {
|
||||
actorId: expertId,
|
||||
actorName: name,
|
||||
actorRole: c.role,
|
||||
},
|
||||
"workflow.locked": false,
|
||||
},
|
||||
$unset: {
|
||||
"workflow.lockedBy": "",
|
||||
"workflow.lockedAt": "",
|
||||
"workflow.expiredAt": "",
|
||||
"workflow.preLockQueueSnapshot": "",
|
||||
},
|
||||
$push: {
|
||||
history: {
|
||||
type: CLAIM_REVIEW_REFERRED,
|
||||
timestamp: now,
|
||||
actor: {
|
||||
actorId: new Types.ObjectId(actor.sub),
|
||||
actorType: RoleEnum.COMPANY,
|
||||
actorName: actor.fullName,
|
||||
},
|
||||
metadata: {
|
||||
previousExpertId: c.currentExpertId
|
||||
? String(c.currentExpertId)
|
||||
: null,
|
||||
previousExpertName:
|
||||
c.current?.actorName ||
|
||||
personDisplayName(previousExpert) ||
|
||||
null,
|
||||
previousBranchId: c.branchId ? String(c.branchId) : null,
|
||||
previousBranchName: previousBranch?.name ?? null,
|
||||
previousBranchCode: previousBranch?.code ?? null,
|
||||
expertId: String(expertId),
|
||||
expertName: name,
|
||||
expertRole: c.role,
|
||||
branchId: String(expert.branchId),
|
||||
branchName: branch.name,
|
||||
branchCode: branch.code,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!updated) throw new ConflictException(REVIEW_REFERRAL_CONFLICT);
|
||||
return { expertName: name, branchName: branch.name };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsMongoId, Matches } from "class-validator";
|
||||
|
||||
export class ReferClaimReviewDto {
|
||||
@ApiProperty()
|
||||
@IsMongoId()
|
||||
expertId: string;
|
||||
|
||||
@ApiProperty({ description: "Revision from the referral options endpoint." })
|
||||
@Matches(/^\d{1,16}$/)
|
||||
revision: string;
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { ClaimReviewReferralService } from "./claim-review-referral.service";
|
||||
import { ReferClaimReviewDto } from "./dto/refer-claim-review.dto";
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { currentAiCaptures } from "src/ai/ai-captures";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
@@ -7,11 +9,14 @@ import {
|
||||
Controller,
|
||||
Get,
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UnauthorizedException,
|
||||
UseGuards,
|
||||
UsePipes,
|
||||
ValidationPipe,
|
||||
} from "@nestjs/common";
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
@@ -62,6 +67,7 @@ export class ExpertInsurerController {
|
||||
private readonly expertInsurerService: ExpertInsurerService,
|
||||
private readonly reportsService: ReportsService,
|
||||
private readonly aiService: AiService,
|
||||
private readonly claimReviewReferralService: ClaimReviewReferralService,
|
||||
private readonly claimCaseDbService: ClaimCaseDbService,
|
||||
) {}
|
||||
|
||||
@@ -428,6 +434,22 @@ export class ExpertInsurerController {
|
||||
return this.aiService.retry(id, currentAiCaptures(claim), false);
|
||||
}
|
||||
|
||||
@Get("files/:publicId/review-referral")
|
||||
getReviewReferral(@CurrentUser() insurer, @Param("publicId") publicId: string) {
|
||||
return this.claimReviewReferralService.options(insurer.clientKey, publicId);
|
||||
}
|
||||
|
||||
@Patch("files/:publicId/review-referral")
|
||||
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
|
||||
@ApiBody({ type: ReferClaimReviewDto })
|
||||
referClaimReview(
|
||||
@CurrentUser() insurer,
|
||||
@Param("publicId") publicId: string,
|
||||
@Body() body: ReferClaimReviewDto,
|
||||
) {
|
||||
return this.claimReviewReferralService.refer(insurer, publicId, body);
|
||||
}
|
||||
|
||||
@Get("files/:publicId")
|
||||
@ApiParam({ name: "publicId" })
|
||||
async getFileDetailsByPublicId(@CurrentUser() insurer, @Param("publicId") publicId: string) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ClaimReviewReferralService } from "./claim-review-referral.service";
|
||||
import { AiModule } from "src/ai/ai.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MongooseModule } from "@nestjs/mongoose";
|
||||
@@ -48,7 +49,7 @@ import { HashModule } from "src/utils/hash/hash.module";
|
||||
},
|
||||
]),
|
||||
],
|
||||
providers: [ExpertInsurerService],
|
||||
providers: [ExpertInsurerService, ClaimReviewReferralService],
|
||||
controllers: [ExpertInsurerController],
|
||||
exports: [ExpertInsurerService],
|
||||
})
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import { referralIneligibility } from "src/expert-claim/review-referral/review-referral";
|
||||
import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature";
|
||||
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
@@ -269,7 +272,7 @@ export class ExpertInsurerService {
|
||||
if (!Array.isArray(parties) || !parties.length) return undefined;
|
||||
return parties.map((p: any) => ({
|
||||
role: p?.role,
|
||||
fullName: p?.person?.fullName,
|
||||
fullName: personDisplayName(p?.person),
|
||||
vehicle: {
|
||||
carName: p?.vehicle?.carName ?? p?.vehicle?.name,
|
||||
carModel: p?.vehicle?.carModel ?? p?.vehicle?.model,
|
||||
@@ -524,11 +527,24 @@ export class ExpertInsurerService {
|
||||
}
|
||||
}
|
||||
|
||||
private async personForDisplay(person: any, cache: Map<string, Promise<any>>) {
|
||||
if (!person) return person;
|
||||
const id = String(person.userId ?? "");
|
||||
let profile: any;
|
||||
if (Types.ObjectId.isValid(id) && this.userDbService?.findOne) {
|
||||
if (!cache.has(id)) cache.set(id, this.userDbService.findOne({_id:new Types.ObjectId(id)}));
|
||||
profile = await cache.get(id);
|
||||
}
|
||||
return {...person,fullName:personDisplayName(profile,person),phoneNumber:person.phoneNumber || profile?.mobile || ""};
|
||||
}
|
||||
|
||||
private async buildInsurerBlameDetail(
|
||||
blameLean: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const doc: Record<string, unknown> = { ...blameLean };
|
||||
const parties = (Array.isArray(doc.parties) ? doc.parties : []) as any[];
|
||||
const displayCache = new Map<string, Promise<any>>();
|
||||
await Promise.all(parties.map(async party => { party.person = await this.personForDisplay(party.person,displayCache); }));
|
||||
await this.enrichBlamePartyEvidenceUrls(parties);
|
||||
doc.parties = enrichBlamePartiesForAgreementView(doc);
|
||||
|
||||
@@ -571,6 +587,11 @@ export class ExpertInsurerService {
|
||||
claim: Record<string, unknown>,
|
||||
blameForContext: Record<string, unknown> | null,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const displayCache = new Map<string, Promise<any>>();
|
||||
claim = {...claim,owner:await this.personForDisplay(claim.owner,displayCache)};
|
||||
if (Array.isArray(blameForContext?.parties)) {
|
||||
blameForContext = {...blameForContext,parties:await Promise.all(blameForContext.parties.map(async (party:any) => ({...party,person:await this.personForDisplay(party.person,displayCache)})))};
|
||||
}
|
||||
// Add at the top of buildInsurerClaimDetail, before the return:
|
||||
const carType = (claim as any).vehicle?.carType as
|
||||
| ClaimVehicleTypeV2
|
||||
@@ -679,6 +700,9 @@ export class ExpertInsurerService {
|
||||
|
||||
const evaluationEnriched =
|
||||
await this.enrichClaimEvaluationForInsurer(evaluation);
|
||||
if (blameForContext?.type === BlameRequestType.CAR_BODY && evaluationEnriched) {
|
||||
delete evaluationEnriched.priceDrop;
|
||||
}
|
||||
const vehicleSanitized = claim.vehicle
|
||||
? this.sanitizeVehicleInquiry(claim.vehicle as any)
|
||||
: undefined;
|
||||
@@ -1823,7 +1847,7 @@ export class ExpertInsurerService {
|
||||
};
|
||||
}
|
||||
|
||||
async retrieveFileDetailsByPublicId(insurerId: string, publicId: string) {
|
||||
async retrieveFileDetailsByPublicId(insurerId: string, publicId: string, includeReportMedia = false) {
|
||||
if (!publicId?.trim()) {
|
||||
throw new BadRequestException("publicId is required");
|
||||
}
|
||||
@@ -1898,10 +1922,29 @@ export class ExpertInsurerService {
|
||||
? await this.buildInsurerClaimDetail(claimFull, blameForClaimContext)
|
||||
: undefined;
|
||||
|
||||
const reviewReferralAvailable = !!claimFull && !referralIneligibility(claimFull, blameForClaimContext);
|
||||
const reviewBranch = claimFull?.reviewReferral && claimFull?.branchId
|
||||
? await this.branchDbService.findById(String(claimFull.branchId))
|
||||
: null;
|
||||
|
||||
const reportBlame = includeReportMedia
|
||||
? blameDetails ?? (blameForClaimContext ? await this.buildInsurerBlameDetail(blameForClaimContext) : undefined)
|
||||
: undefined;
|
||||
if (includeReportMedia && claimDetails && claimFull?._id) {
|
||||
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(String(claimFull._id));
|
||||
const signature = signedClaim?.fanavaranExpertSignature;
|
||||
if (signature && (signedClaim.expertiseId != null || signature.revision === fanavaranSignatureRevision(signedClaim))) {
|
||||
claimDetails.fanavaranExpertSignature = { name: signature.name, image: signature.image };
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
overview,
|
||||
blame: blameDetails,
|
||||
claim: claimDetails,
|
||||
reviewReferralAvailable,
|
||||
reviewBranchName: reviewBranch?.name,
|
||||
...(includeReportMedia ? { reportBlame } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2511,25 +2554,14 @@ export class ExpertInsurerService {
|
||||
]);
|
||||
|
||||
private static getDisplayNameFromRecord(record: any): string | null {
|
||||
if (!record) return null;
|
||||
|
||||
const fullName =
|
||||
typeof record.fullName === "string" ? record.fullName.trim() : "";
|
||||
if (fullName) return fullName;
|
||||
|
||||
const firstName =
|
||||
typeof record.firstName === "string" ? record.firstName.trim() : "";
|
||||
const lastName =
|
||||
typeof record.lastName === "string" ? record.lastName.trim() : "";
|
||||
const combined = [firstName, lastName].filter(Boolean).join(" ").trim();
|
||||
return combined || null;
|
||||
return personDisplayName(record) || null;
|
||||
}
|
||||
|
||||
private static isMeaningfulTimelineActorName(
|
||||
name: string | undefined,
|
||||
): boolean {
|
||||
const trimmed = typeof name === "string" ? name.trim() : "";
|
||||
if (!trimmed) return false;
|
||||
if (!meaningfulPersonName(trimmed)) return false;
|
||||
return !ExpertInsurerService.TIMELINE_PLACEHOLDER_ACTOR_NAMES.has(
|
||||
trimmed.toLowerCase(),
|
||||
);
|
||||
@@ -2552,11 +2584,11 @@ export class ExpertInsurerService {
|
||||
)
|
||||
: null;
|
||||
|
||||
const matchedName = matchedParty?.person?.fullName?.trim?.();
|
||||
const matchedName = personDisplayName(matchedParty?.person);
|
||||
if (matchedName) return matchedName;
|
||||
|
||||
if (parties.length === 1) {
|
||||
return parties[0]?.person?.fullName?.trim?.() || null;
|
||||
return personDisplayName(parties[0]?.person) || null;
|
||||
}
|
||||
|
||||
return null;
|
||||
@@ -2711,7 +2743,7 @@ export class ExpertInsurerService {
|
||||
): Promise<string | null> {
|
||||
const explicitName =
|
||||
typeof actor?.actorName === "string" ? actor.actorName.trim() : "";
|
||||
if (ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) {
|
||||
if (actorType !== "user" && ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) {
|
||||
return explicitName;
|
||||
}
|
||||
|
||||
@@ -2721,16 +2753,6 @@ export class ExpertInsurerService {
|
||||
return ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
|
||||
}
|
||||
|
||||
if (actorType === "user") {
|
||||
const ownerName = sourceDoc?.owner?.fullName?.trim?.();
|
||||
if (ownerName) return ownerName;
|
||||
|
||||
const blamePartyName = ExpertInsurerService.resolveBlamePartyName(
|
||||
sourceDoc,
|
||||
event?.metadata?.partyRole,
|
||||
);
|
||||
if (blamePartyName) return blamePartyName;
|
||||
}
|
||||
|
||||
const actorId = actor?.actorId ? String(actor.actorId).trim() : "";
|
||||
if (actorId) {
|
||||
@@ -2745,14 +2767,13 @@ export class ExpertInsurerService {
|
||||
);
|
||||
|
||||
if (!resolvedName && actorType === "user") {
|
||||
resolvedName =
|
||||
sourceDoc?.owner?.fullName?.trim?.() ??
|
||||
ExpertInsurerService.resolveBlamePartyName(
|
||||
sourceDoc,
|
||||
event?.metadata?.partyRole,
|
||||
);
|
||||
const parties = Array.isArray(sourceDoc?.parties) ? sourceDoc.parties : [];
|
||||
const party = parties.find((row:any) => String(row?.person?.userId ?? "") === actorId);
|
||||
resolvedName = personDisplayName(party?.person,
|
||||
String(sourceDoc?.owner?.userId ?? "") === actorId ? sourceDoc.owner : undefined) || null;
|
||||
}
|
||||
|
||||
if (!resolvedName && ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) resolvedName = explicitName;
|
||||
if (!resolvedName) {
|
||||
resolvedName =
|
||||
ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
|
||||
@@ -2762,6 +2783,7 @@ export class ExpertInsurerService {
|
||||
return resolvedName ?? null;
|
||||
}
|
||||
|
||||
if (actorType === "user") return personDisplayName(sourceDoc?.owner) || ExpertInsurerService.resolveBlamePartyName(sourceDoc,event?.metadata?.partyRole);
|
||||
return ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { CLAIM_REVIEW_REFERRED } from "src/expert-claim/review-referral/review-referral";
|
||||
/**
|
||||
* Persian (Farsi) display labels for every timeline event `type` that can
|
||||
* appear in a blame or claim history array.
|
||||
@@ -104,6 +105,7 @@ export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
|
||||
CLAIM_CREATED: "پرونده خسارت ایجاد شد",
|
||||
|
||||
// Expert assignment (claim)
|
||||
[CLAIM_REVIEW_REFERRED]: "ارجاع ارزیابی خسارت",
|
||||
CLAIM_ASSIGNED: "پرونده خسارت به کارشناس ارزیابی تخصیص داده شد",
|
||||
|
||||
// Expert actions on claim
|
||||
@@ -263,6 +265,14 @@ export function getEventFaDescription(event: {
|
||||
type: string;
|
||||
metadata?: any;
|
||||
}): string {
|
||||
if (event.type === CLAIM_REVIEW_REFERRED) {
|
||||
const { previousExpertName, previousBranchName, expertName, branchName } = event.metadata ?? {};
|
||||
const from = [previousExpertName, previousBranchName].filter(Boolean).join("، ");
|
||||
const to = [expertName, branchName].filter(Boolean).join("، ");
|
||||
if (to) return from
|
||||
? `ارزیابی خسارت از ${from} به ${to} ارجاع شد.`
|
||||
: `ارزیابی خسارت به ${to} ارجاع شد.`;
|
||||
}
|
||||
const stepKey: string | undefined = event.metadata?.stepKey;
|
||||
if (stepKey && STEP_KEY_FA_DESCRIPTIONS[stepKey]) {
|
||||
return STEP_KEY_FA_DESCRIPTIONS[stepKey];
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import { fanavaranSignatureRevision } from "./fanavaran-expert-signature";
|
||||
|
||||
describe("Fanavaran expert signature gate", () => {
|
||||
const actor = {
|
||||
sub: "expert-1",
|
||||
role: "damage_expert",
|
||||
fullName: "کارشناس نمونه",
|
||||
};
|
||||
const image =
|
||||
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j3ZkAAAAASUVORK5CYII=";
|
||||
let service: any;
|
||||
let claim: any;
|
||||
let old: string | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
old = process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE;
|
||||
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = "true";
|
||||
claim = {
|
||||
_id: "claim-1",
|
||||
vehicle: { carName: "پژو" },
|
||||
updatedAt: new Date(),
|
||||
evaluation: {},
|
||||
};
|
||||
service = Object.create(ClaimRequestManagementService.prototype);
|
||||
service.claimCaseDbService = {
|
||||
findById: jest.fn(async () => claim),
|
||||
findWithFanavaranSignature: jest.fn(async () => claim),
|
||||
findOneAndUpdate: jest.fn(async (_query, update) => {
|
||||
Object.assign(claim, update.$set);
|
||||
return claim;
|
||||
}),
|
||||
};
|
||||
service.completeFanavaranExpertisePrerequisites = jest.fn();
|
||||
service.resolveFanavaranClaimProduct = jest.fn(async () => "third-party");
|
||||
service.buildFanavaranExpertisePayload = jest.fn(async () => ({
|
||||
payload: {},
|
||||
warnings: [],
|
||||
infoWarnings: [],
|
||||
}));
|
||||
service.assertFanavaranExpertisePayloadReady = jest.fn();
|
||||
service.executeFanavaranExpertiseSubmit = jest.fn(async () => ({
|
||||
Id: 123,
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (old === undefined)
|
||||
delete process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE;
|
||||
else process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = old;
|
||||
});
|
||||
|
||||
it("requires a signature before running prerequisites and leaves automatic final submission pending", async () => {
|
||||
await expect(
|
||||
service.submitFanavaranExpertiseV2(
|
||||
"claim-1",
|
||||
"parsian",
|
||||
undefined,
|
||||
actor,
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
response: { code: "FANAVARAN_EXPERT_SIGNATURE_REQUIRED" },
|
||||
});
|
||||
await expect(
|
||||
service.autoSubmitFanavaranExpertiseOnExpertReply("claim-1"),
|
||||
).resolves.toMatchObject({ skipped: true });
|
||||
expect(
|
||||
service.completeFanavaranExpertisePrerequisites,
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores the authenticated signer's signature, rejects stale or mismatched signatures and accepts retry", async () => {
|
||||
const revision = fanavaranSignatureRevision(claim);
|
||||
await expect(
|
||||
service.saveFanavaranExpertSignature("claim-1", actor, {
|
||||
revision,
|
||||
image: "invalid",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
await expect(
|
||||
service.saveFanavaranExpertSignature("claim-1", actor, {
|
||||
revision: "stale",
|
||||
image,
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
service.saveFanavaranExpertSignature("claim-1", actor, {
|
||||
revision,
|
||||
image,
|
||||
}),
|
||||
).resolves.toMatchObject({ signed: true });
|
||||
expect(claim.fanavaranExpertSignature).toMatchObject({
|
||||
actorId: actor.sub,
|
||||
actorRole: actor.role,
|
||||
revision,
|
||||
image,
|
||||
});
|
||||
await expect(
|
||||
service.submitFanavaranExpertiseV2("claim-1", "parsian", undefined, {
|
||||
...actor,
|
||||
sub: "other",
|
||||
}),
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
await expect(
|
||||
service.submitFanavaranExpertiseV2(
|
||||
"claim-1",
|
||||
"parsian",
|
||||
{ ClaimExpertId: 12 },
|
||||
actor,
|
||||
),
|
||||
).rejects.toMatchObject({ status: 400 });
|
||||
expect(
|
||||
service.completeFanavaranExpertisePrerequisites,
|
||||
).not.toHaveBeenCalled();
|
||||
claim.fanavaranSync = { baseClaim: { status: "success" } };
|
||||
await expect(
|
||||
service.submitFanavaranExpertiseV2(
|
||||
"claim-1",
|
||||
"parsian",
|
||||
undefined,
|
||||
actor,
|
||||
),
|
||||
).resolves.toEqual({ Id: 123 });
|
||||
claim.evaluation.priceDrop = { total: 123 };
|
||||
await expect(
|
||||
service.submitFanavaranExpertiseV2(
|
||||
"claim-1",
|
||||
"parsian",
|
||||
undefined,
|
||||
actor,
|
||||
),
|
||||
).rejects.toMatchObject({ status: 409 });
|
||||
});
|
||||
|
||||
it("retains unsigned submission when the deployment disables the feature", async () => {
|
||||
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = "false";
|
||||
await expect(
|
||||
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
|
||||
).resolves.toEqual({ Id: 123 });
|
||||
expect(
|
||||
service.claimCaseDbService.findWithFanavaranSignature,
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,107 @@
|
||||
import { BadRequestException, ConflictException } from "@nestjs/common";
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
export type FanavaranExpertSignature = {
|
||||
actorId: string;
|
||||
actorRole: string;
|
||||
name: string;
|
||||
signedAt: Date;
|
||||
revision: string;
|
||||
image: string;
|
||||
};
|
||||
|
||||
export function requiresFanavaranExpertSignature(): boolean {
|
||||
return ["true", "1"].includes(
|
||||
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE?.trim().toLowerCase() ?? "",
|
||||
);
|
||||
}
|
||||
|
||||
export function fanavaranSignatureRevision(claim: any): string {
|
||||
const row = claim.toObject?.({ flattenMaps: true }) ?? claim;
|
||||
const {
|
||||
status,
|
||||
claimStatus,
|
||||
evaluation,
|
||||
vehicle,
|
||||
damage,
|
||||
owner,
|
||||
money,
|
||||
fanavaranVehicleReview,
|
||||
fanavaranFieldReview,
|
||||
snapshot,
|
||||
requiredDocuments,
|
||||
media,
|
||||
} = row;
|
||||
return createHash("sha256")
|
||||
.update(
|
||||
JSON.stringify({
|
||||
status,
|
||||
claimStatus,
|
||||
evaluation,
|
||||
vehicle,
|
||||
damage,
|
||||
owner,
|
||||
money,
|
||||
fanavaranVehicleReview,
|
||||
fanavaranFieldReview,
|
||||
snapshot,
|
||||
requiredDocuments,
|
||||
media,
|
||||
...(row.reviewReferral ? { reviewReferral: row.reviewReferral, branchId: row.branchId } : {}),
|
||||
}),
|
||||
)
|
||||
.digest("hex");
|
||||
}
|
||||
|
||||
export function hasFanavaranExpertSignature(
|
||||
claim: any,
|
||||
actor?: { sub: string; role?: string },
|
||||
): boolean {
|
||||
const signature: FanavaranExpertSignature | undefined =
|
||||
claim.fanavaranExpertSignature;
|
||||
return (
|
||||
!!actor &&
|
||||
!!signature?.image &&
|
||||
signature.actorId === String(actor.sub) &&
|
||||
signature.actorRole === actor.role &&
|
||||
signature.revision === fanavaranSignatureRevision(claim)
|
||||
);
|
||||
}
|
||||
|
||||
export function assertFanavaranExpertSignature(
|
||||
claim: any,
|
||||
actor?: { sub: string; role?: string },
|
||||
): void {
|
||||
if (!hasFanavaranExpertSignature(claim, actor)) {
|
||||
throw new ConflictException({
|
||||
code: "FANAVARAN_EXPERT_SIGNATURE_REQUIRED",
|
||||
message: "ابتدا نسخه فعلی پرونده را امضا کنید و سپس به فناوران بفرستید.",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export function readFanavaranSignatureImage(value: unknown): string {
|
||||
const invalid = () =>
|
||||
new BadRequestException("تصویر امضا معتبر نیست. امضا را دوباره ثبت کنید.");
|
||||
if (
|
||||
typeof value !== "string" ||
|
||||
value.length > 100_000 ||
|
||||
!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(value)
|
||||
)
|
||||
throw invalid();
|
||||
const png = Buffer.from(
|
||||
value.slice("data:image/png;base64,".length),
|
||||
"base64",
|
||||
);
|
||||
if (
|
||||
png.length < 45 ||
|
||||
png.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a" ||
|
||||
png.toString("ascii", 12, 16) !== "IHDR" ||
|
||||
png.subarray(-12).toString("hex") !== "0000000049454e44ae426082"
|
||||
)
|
||||
throw invalid();
|
||||
const width = png.readUInt32BE(16);
|
||||
const height = png.readUInt32BE(20);
|
||||
if (!width || !height || width > 900 || height > 400) throw invalid();
|
||||
return value;
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
import { GuardClaimReview } from "src/expert-claim/review-referral/claim-review.interceptor";
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import {
|
||||
BadRequestException,
|
||||
Body,
|
||||
Controller,
|
||||
Get,
|
||||
Patch,
|
||||
Param,
|
||||
Post,
|
||||
Query,
|
||||
@@ -16,6 +19,9 @@ import {
|
||||
ApiQuery,
|
||||
ApiTags,
|
||||
} from "@nestjs/swagger";
|
||||
import { CurrentUser } from "src/decorators/user.decorator";
|
||||
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
|
||||
import { requiresFanavaranExpertSignature } from "./fanavaran-expert-signature";
|
||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import {
|
||||
@@ -28,12 +34,15 @@ import {
|
||||
} from "src/core/config/fanavaran-client.config";
|
||||
|
||||
@ApiTags("fanavaran")
|
||||
@GuardClaimReview("integration")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/fanavaran")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard)
|
||||
export class FanavaranController {
|
||||
constructor(
|
||||
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
||||
private readonly expertClaimService: ExpertClaimService,
|
||||
) {}
|
||||
|
||||
@Get("clients")
|
||||
@@ -279,6 +288,26 @@ export class FanavaranController {
|
||||
);
|
||||
}
|
||||
|
||||
@Get("claim-cases/:claimCaseId/expert-signature")
|
||||
async expertSignatureStatus(@Param("claimCaseId") id: string, @CurrentUser() actor: any) {
|
||||
if (!requiresFanavaranExpertSignature()) return { required: false, signed: false };
|
||||
await this.expertClaimService.assertCanSignFanavaranClaim(id, actor);
|
||||
return this.claimRequestManagementService.getFanavaranExpertSignatureStatus(id, actor);
|
||||
}
|
||||
|
||||
@Patch("claim-cases/:claimCaseId/expert-signature")
|
||||
async saveExpertSignature(
|
||||
@Param("claimCaseId") id: string,
|
||||
@CurrentUser() actor: any,
|
||||
@Body() body: { revision?: string; image?: string },
|
||||
) {
|
||||
if (!requiresFanavaranExpertSignature()) {
|
||||
throw new BadRequestException("ثبت امضای کارشناس در این سامانه فعال نیست.");
|
||||
}
|
||||
await this.expertClaimService.assertCanSignFanavaranClaim(id, actor);
|
||||
return this.claimRequestManagementService.saveFanavaranExpertSignature(id, actor, body);
|
||||
}
|
||||
|
||||
@Post(":client/claim-cases/:claimCaseId/expertise/submit")
|
||||
@ApiOperation({
|
||||
summary: "Submit Fanavaran expertise request",
|
||||
@@ -303,13 +332,21 @@ export class FanavaranController {
|
||||
async submitExpertise(
|
||||
@Param("client") client: string,
|
||||
@Param("claimCaseId") claimCaseId: string,
|
||||
@CurrentUser() actor: any,
|
||||
@Body() body?: Record<string, unknown>,
|
||||
) {
|
||||
const clientKey = this.parseClientParam(client);
|
||||
if (requiresFanavaranExpertSignature()) {
|
||||
if (clientKey !== resolveFanavaranClientKey()) {
|
||||
throw new BadRequestException("شرکت بیمه با تنظیمات این سامانه مطابقت ندارد.");
|
||||
}
|
||||
await this.expertClaimService.assertCanSignFanavaranClaim(claimCaseId, actor);
|
||||
}
|
||||
return await this.claimRequestManagementService.submitFanavaranExpertiseV2(
|
||||
claimCaseId,
|
||||
clientKey,
|
||||
body && Object.keys(body).length > 0 ? body : undefined,
|
||||
actor,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@ import { HttpModule } from "@nestjs/axios";
|
||||
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
|
||||
import { ExpertClaimModule } from "src/expert-claim/expert-claim.module";
|
||||
import { FanavaranAuditModule } from "./fanavaran-audit.module";
|
||||
import { FanavaranController } from "./fanavaran.controller";
|
||||
import { FanavaranLookupModule } from "./fanavaran-lookup.module";
|
||||
@@ -12,6 +13,7 @@ import { FanavaranHullReadController } from "./fanavaran-hull-read.controller";
|
||||
@Module({
|
||||
imports: [
|
||||
ClaimRequestManagementModule,
|
||||
ExpertClaimModule,
|
||||
FanavaranAuditModule,
|
||||
FanavaranLookupModule,
|
||||
HttpModule.registerAsync({
|
||||
|
||||
@@ -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,83 @@
|
||||
import { meaningfulPersonName, personDisplayName } from "./person-display-name";
|
||||
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||
|
||||
describe("person labels in panels/reports", () => {
|
||||
it.each([
|
||||
"1234567890",
|
||||
"۱۲۳۴۵۶۷۸۹۰",
|
||||
"650000000000000000000001",
|
||||
"Unknown User",
|
||||
"User",
|
||||
"user@example.com",
|
||||
])("never uses an identifier or placeholder as a name: %s", (name) => {
|
||||
expect(meaningfulPersonName(name)).toBe("");
|
||||
expect(
|
||||
personDisplayName({
|
||||
fullName: name,
|
||||
mobile: "09120000000",
|
||||
nationalCode: "1234567890",
|
||||
}),
|
||||
).toBe("09120000000");
|
||||
});
|
||||
it("prefers saved names across records and combines first/last names", () => {
|
||||
expect(
|
||||
personDisplayName(
|
||||
{ fullName: "1234567890", mobile: "09120000000" },
|
||||
{ firstName: "علی", lastName: "رضایی" },
|
||||
),
|
||||
).toBe("علی رضایی");
|
||||
expect(personDisplayName({ firstName: "علی" })).toBe("علی");
|
||||
expect(
|
||||
personDisplayName({ fullName: "9123456789", nationalCode: "9123456789" }),
|
||||
).toBe("");
|
||||
expect(personDisplayName({ fullName: "نامشخص" })).toBe("");
|
||||
});
|
||||
it("hydrates current profile names without changing stored case data and caches lookups", async () => {
|
||||
const service = Object.create(ExpertInsurerService.prototype) as any;
|
||||
service.userDbService = {
|
||||
findOne: jest.fn(async () => ({
|
||||
fullName: "علی رضایی",
|
||||
mobile: "09120000000",
|
||||
})),
|
||||
};
|
||||
const person = {
|
||||
userId: "650000000000000000000001",
|
||||
fullName: "1234567890",
|
||||
};
|
||||
const cache = new Map();
|
||||
expect(await service.personForDisplay(person, cache)).toMatchObject({
|
||||
fullName: "علی رضایی",
|
||||
phoneNumber: "09120000000",
|
||||
});
|
||||
await service.personForDisplay(person, cache);
|
||||
expect(service.userDbService.findOne).toHaveBeenCalledTimes(1);
|
||||
expect(person.fullName).toBe("1234567890");
|
||||
});
|
||||
it("timeline identifies the actual user, rather than the other party or a legacy ID name", async () => {
|
||||
const service = Object.create(ExpertInsurerService.prototype) as any;
|
||||
service.userDbService = {
|
||||
findOne: jest.fn(async () => ({
|
||||
fullName: "علی رضایی",
|
||||
mobile: "09120000000",
|
||||
})),
|
||||
};
|
||||
const actor = {
|
||||
actorId: "650000000000000000000001",
|
||||
actorName: "1234567890",
|
||||
};
|
||||
const document = {
|
||||
owner: { userId: "650000000000000000000002", fullName: "شخص دیگر" },
|
||||
};
|
||||
expect(
|
||||
await service.resolveTimelineActorName(actor, "user", document),
|
||||
).toBe("علی رضایی");
|
||||
service.userDbService.findOne.mockResolvedValue({ mobile: "09120000000" });
|
||||
expect(
|
||||
await service.resolveTimelineActorName(actor, "user", document),
|
||||
).toBe("09120000000");
|
||||
service.userDbService.findOne.mockResolvedValue(null);
|
||||
expect(
|
||||
await service.resolveTimelineActorName(actor, "user", document),
|
||||
).not.toBe("شخص دیگر");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
type PersonRecord = object | null | undefined;
|
||||
|
||||
const placeholders = new Set([
|
||||
"user",
|
||||
"actor",
|
||||
"expert",
|
||||
"unknown",
|
||||
"unknown user",
|
||||
"unknown expert",
|
||||
"system",
|
||||
"null",
|
||||
"undefined",
|
||||
"نامشخص",
|
||||
"کاربر",
|
||||
"موجود نیست",
|
||||
]);
|
||||
const englishDigits = (value: string) =>
|
||||
value.replace(/[۰-۹٠-٩]/g, (digit) =>
|
||||
String("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩".indexOf(digit) % 10),
|
||||
);
|
||||
export function meaningfulPersonName(value: unknown): string {
|
||||
if (typeof value !== "string") return "";
|
||||
const name = value.trim().replace(/\s+/g, " ");
|
||||
const normalized = englishDigits(name);
|
||||
if (
|
||||
!name ||
|
||||
placeholders.has(name.toLowerCase()) ||
|
||||
/^\+?[\d\s()-]+$/.test(normalized) ||
|
||||
/^[a-f\d]{24}$/i.test(normalized) ||
|
||||
/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(normalized) ||
|
||||
/@/.test(name)
|
||||
)
|
||||
return "";
|
||||
return name;
|
||||
}
|
||||
function phone(value: unknown): string {
|
||||
if (typeof value !== "string" && typeof value !== "number") return "";
|
||||
const text = String(value).trim();
|
||||
return /^\+?[\d۰-۹٠-٩][\d۰-۹٠-٩ ()-]{6,17}$/.test(text) ? text : "";
|
||||
}
|
||||
/** Names first, then explicitly recorded phone numbers. IDs/national codes are never names. */
|
||||
export function personDisplayName(...records: PersonRecord[]): string {
|
||||
for (const source of records) {
|
||||
if (!source) continue;
|
||||
const record = source as Record<string, unknown>;
|
||||
const joined = [
|
||||
meaningfulPersonName(record.firstName),
|
||||
meaningfulPersonName(record.lastName),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join(" ");
|
||||
const name =
|
||||
meaningfulPersonName(record.fullName) ||
|
||||
joined ||
|
||||
meaningfulPersonName(record.name);
|
||||
if (name) return name;
|
||||
}
|
||||
for (const source of records) {
|
||||
if (!source) continue;
|
||||
const record = source as Record<string, unknown>;
|
||||
for (const key of ["phoneNumber", "mobile", "mobileNumber", "phone"]) {
|
||||
const value = phone(record[key]);
|
||||
if (value) return value;
|
||||
}
|
||||
const legacy = englishDigits(
|
||||
String(record.fullName ?? record.username ?? ""),
|
||||
).replace(/[\s()-]/g, "");
|
||||
if (/^(?:\+98|0098|98|0)9\d{9}$/.test(legacy)) return legacy;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ClientWorkingHoursService } from "src/client/working-hours/client-working-hours.service";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -42,7 +43,19 @@ const validation = new ValidationPipe({
|
||||
@UsePipes(validation)
|
||||
@Controller("super-admin/management")
|
||||
export class SuperAdminManagementController {
|
||||
constructor(private management: ManagementService) {}
|
||||
constructor(
|
||||
private management: ManagementService,
|
||||
private readonly workingHours: ClientWorkingHoursService,
|
||||
) {}
|
||||
@Get("working-hours")
|
||||
readHours(@Query("clientId") clientId: string) {
|
||||
return this.workingHours.read(clientId);
|
||||
}
|
||||
@Patch("working-hours")
|
||||
updateHours(@Query("clientId") clientId: string, @Body() body: unknown) {
|
||||
return this.workingHours.update(clientId, body);
|
||||
}
|
||||
|
||||
@Get("clients") clients() {
|
||||
return this.management.listClients();
|
||||
}
|
||||
@@ -129,7 +142,19 @@ export class SuperAdminManagementController {
|
||||
@UsePipes(validation)
|
||||
@Controller("expert-insurer/management")
|
||||
export class InsurerManagementController {
|
||||
constructor(private management: ManagementService) {}
|
||||
constructor(
|
||||
private management: ManagementService,
|
||||
private readonly workingHours: ClientWorkingHoursService,
|
||||
) {}
|
||||
@Get("working-hours")
|
||||
readHours(@CurrentUser() actor: { clientKey: string }) {
|
||||
return this.workingHours.read(actor.clientKey);
|
||||
}
|
||||
@Patch("working-hours")
|
||||
updateHours(@CurrentUser() actor: { clientKey: string }, @Body() body: unknown) {
|
||||
return this.workingHours.update(actor.clientKey, body);
|
||||
}
|
||||
|
||||
@Get("staff") staff(
|
||||
@CurrentUser() actor,
|
||||
@Query() query: ManagedListQueryDto,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { ClientModule } from "src/client/client.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MongooseModule } from "@nestjs/mongoose";
|
||||
import { AuthModule } from "src/auth/auth.module";
|
||||
@@ -47,6 +48,7 @@ import {
|
||||
@Module({
|
||||
imports: [
|
||||
AuthModule,
|
||||
ClientModule,
|
||||
HashModule,
|
||||
MongooseModule.forFeature([
|
||||
{ name: ClientModel.name, schema: ClientDbSchema },
|
||||
|
||||
@@ -28,6 +28,7 @@ import {
|
||||
SetManagedStaffActiveDto,
|
||||
} from "./management.dto";
|
||||
import { ClientDbSchema } from "src/client/entities/schema/client.schema";
|
||||
import { ClientWorkingHoursService } from "src/client/working-hours/client-working-hours.service";
|
||||
import { BranchSchema } from "src/client/entities/schema/branch.schema";
|
||||
import { ExpertDbSchema } from "src/users/entities/schema/expert.schema";
|
||||
import { DamageExpertDbSchema } from "src/users/entities/schema/damage-expert.schema";
|
||||
@@ -478,6 +479,16 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
};
|
||||
}
|
||||
actorAuth.clientDbService = { findOne: async () => repos[0].records[0] };
|
||||
const workingHours = new ClientWorkingHoursService({
|
||||
findWorkingHours: (filter) => repos[0].findOne(filter).lean(),
|
||||
findByIdAndUpdate: async (id, update) => {
|
||||
const client = await repos[0].findOne({ _id: id }).lean();
|
||||
if (client) {
|
||||
client.settings = { ...client.settings, workingHours: update.$set["settings.workingHours"] };
|
||||
}
|
||||
return client;
|
||||
},
|
||||
} as any);
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [JwtModule.register({})],
|
||||
controllers: [
|
||||
@@ -489,6 +500,7 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
SuperAdminGuard,
|
||||
LocalActorAuthGuard,
|
||||
{ provide: ManagementService, useValue: service },
|
||||
{ provide: ClientWorkingHoursService, useValue: workingHours },
|
||||
{ provide: ActorAuthService, useValue: actorAuth },
|
||||
{
|
||||
provide: CaptchaChallengeService,
|
||||
@@ -550,6 +562,46 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
).body.access_token;
|
||||
expect(jwt.decode(makerToken).sub).toBe(maker._id);
|
||||
expect(jwt.decode(reviewerToken).sub).toBe(reviewer._id);
|
||||
const ownHours = `/expert-insurer/management/working-hours?clientId=${foreign}`;
|
||||
const otherHours = `/super-admin/management/working-hours?clientId=${foreign}`;
|
||||
const alwaysOpen = { alwaysOpen: true, windows: [] };
|
||||
const restricted = {
|
||||
alwaysOpen: false,
|
||||
windows: [{ weekday: 6, opensAt: "08:00", closesAt: "16:00" }],
|
||||
};
|
||||
await request(app.getHttpServer())
|
||||
.patch(otherHours)
|
||||
.auth(companyToken, { type: "bearer" })
|
||||
.send(restricted)
|
||||
.expect(401);
|
||||
await request(app.getHttpServer())
|
||||
.patch(ownHours)
|
||||
.auth(makerToken, { type: "bearer" })
|
||||
.send(restricted)
|
||||
.expect(403);
|
||||
await request(app.getHttpServer())
|
||||
.patch(ownHours)
|
||||
.auth(companyToken, { type: "bearer" })
|
||||
.send(restricted)
|
||||
.expect(200, restricted);
|
||||
await request(app.getHttpServer())
|
||||
.get(otherHours)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.expect(200, alwaysOpen);
|
||||
await request(app.getHttpServer())
|
||||
.patch(otherHours)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.send(restricted)
|
||||
.expect(200, restricted);
|
||||
await request(app.getHttpServer())
|
||||
.patch(ownHours)
|
||||
.auth(companyToken, { type: "bearer" })
|
||||
.send(alwaysOpen)
|
||||
.expect(200, alwaysOpen);
|
||||
await request(app.getHttpServer())
|
||||
.get(otherHours)
|
||||
.auth(adminToken, { type: "bearer" })
|
||||
.expect(200, restricted);
|
||||
const statusUrl = `/super-admin/management/staff/file_maker/${maker._id}/status?clientId=${tenant}`;
|
||||
await request(app.getHttpServer())
|
||||
.patch(statusUrl)
|
||||
@@ -734,7 +786,8 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
listBranches: jest.fn(),
|
||||
saveBranch: jest.fn(),
|
||||
};
|
||||
const controller = new InsurerManagementController(mocked as any);
|
||||
const workingHours = { read: jest.fn(), update: jest.fn() };
|
||||
const controller = new InsurerManagementController(mocked as any, workingHours as any);
|
||||
const actor = { clientKey: tenant };
|
||||
controller.staff(actor, { clientId: foreign });
|
||||
controller.createStaff(actor, staff("file_maker"));
|
||||
@@ -742,8 +795,12 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
|
||||
controller.branches(actor);
|
||||
controller.createBranch(actor, {} as any);
|
||||
controller.updateBranch(actor, branchId, {});
|
||||
controller.readHours(actor);
|
||||
controller.updateHours(actor, { alwaysOpen: true, windows: [] });
|
||||
for (const method of Object.values(mocked))
|
||||
expect(method.mock.calls[0][0]).toBe(tenant);
|
||||
expect(workingHours.read).toHaveBeenCalledWith(tenant);
|
||||
expect(workingHours.update).toHaveBeenCalledWith(tenant, { alwaysOpen: true, windows: [] });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
@@ -40,6 +41,7 @@ import {
|
||||
* as normal after the blame link is opened.
|
||||
*/
|
||||
@ApiTags("call-center-blame (v6)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v6/call-center-blame")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Injectable } from "@nestjs/common";
|
||||
import { InjectModel } from "@nestjs/mongoose";
|
||||
import { Model } from "mongoose";
|
||||
import { Model, Types } from "mongoose";
|
||||
import { BlameDocumentModel } from "../schema/blame-document.schema";
|
||||
|
||||
@Injectable()
|
||||
@@ -17,6 +17,10 @@ export class BlameDocumentDbService {
|
||||
return newDocument.save();
|
||||
}
|
||||
|
||||
async findByRequestId(id: string): Promise<BlameDocumentModel[]> {
|
||||
return this.blameDocumentModel.find({ requestId: new Types.ObjectId(id) }).lean();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<BlameDocumentModel | null> {
|
||||
return this.blameDocumentModel.findById(id).lean();
|
||||
}
|
||||
|
||||
@@ -98,6 +98,10 @@ export class BlameRequest {
|
||||
@Prop({ type: Types.ObjectId, index: true })
|
||||
branchId?: Types.ObjectId;
|
||||
|
||||
/** Insurer of the staff member who started intake, before liability is established. */
|
||||
@Prop({ type: String })
|
||||
workingHoursIntakeClientId?: string;
|
||||
|
||||
/** True when this blame was created by a registrar. */
|
||||
@Prop({ default: false })
|
||||
registrarInitiated?: boolean;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
Body,
|
||||
@@ -69,6 +70,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-managemen
|
||||
* CAR_BODY: same but single party — omit second-party OTP/inquiries/sign steps.
|
||||
*/
|
||||
@ApiTags("expert-initiated blame (mirror v3 in-person)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v3/expert-initiated/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
Body,
|
||||
@@ -63,6 +64,7 @@ import { PartyRole } from "./entities/schema/partyRole.enum";
|
||||
* second party steps -> sign FIRST + sign SECOND -> COMPLETED.
|
||||
*/
|
||||
@ApiTags("expert-initiated blame (mirror v2)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/expert-initiated/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common";
|
||||
import { ApiBearerAuth, ApiExcludeController } from "@nestjs/swagger";
|
||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||
@@ -10,6 +11,7 @@ import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto";
|
||||
import { RequestManagementService } from "./request-management.service";
|
||||
|
||||
@ApiExcludeController()
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("expert-initiated-blame")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
Controller,
|
||||
@@ -47,6 +48,7 @@ import { PartyRole } from "./entities/schema/partyRole.enum";
|
||||
* Only the initiating field expert can see/review these files.
|
||||
*/
|
||||
// @ApiTags("expert-initiated-blame (v2)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/expert-initiated-blame")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
Body,
|
||||
@@ -70,6 +71,7 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||
* CAR_BODY sequence: same but single party — omit second-party steps.
|
||||
*/
|
||||
@ApiTags("v4 FileMaker — blame file creation")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v4/file-maker/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
Body,
|
||||
@@ -71,6 +72,7 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||
* → sign (damaged) ← FileMaker job done here
|
||||
*/
|
||||
@ApiTags("v5 FileMaker — blame file creation (with FinancialExpert approval)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v5/file-maker/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { GuardClaimReview } from "src/expert-claim/review-referral/claim-review.interceptor";
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common";
|
||||
import {
|
||||
ApiBearerAuth,
|
||||
@@ -44,6 +46,8 @@ class FileMakerRejectDto {
|
||||
* the claimRequestId from the original blame request ID.
|
||||
*/
|
||||
@ApiTags("v5 FileMaker — claim approval before fanavaran")
|
||||
@GuardClaimReview("approval")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v5/file-maker/claim-approval")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
@@ -74,6 +75,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-managemen
|
||||
* NOTE: upload-video is a no-op for V4 (blame is already COMPLETED by car-capture).
|
||||
*/
|
||||
@ApiTags("v4 FileReviewer — blame file review & capture")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v4/file-reviewer/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
@@ -72,6 +73,7 @@ import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
|
||||
* NOTE: upload-video is a no-op for V5 (blame is already COMPLETED by car-capture).
|
||||
*/
|
||||
@ApiTags("v5 FileReviewer — blame file review & capture (with FinancialExpert approval)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v5/file-reviewer/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import {
|
||||
BadRequestException,
|
||||
@@ -59,6 +60,7 @@ import { PartyRole } from "./entities/schema/partyRole.enum";
|
||||
* add-accident-fields -> sign FIRST + sign SECOND -> COMPLETED.
|
||||
*/
|
||||
@ApiTags("registrar blame (mirror v2)")
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/registrar/blame-request-management")
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
checkDiscoveredBlameInsurer,
|
||||
checkDiscoveredCaseInsurer,
|
||||
} from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { actorWorkingHoursClientId } from "src/client/working-hours/client-working-hours.service";
|
||||
import { normalizeAccidentConditions } from "./accident-conditions";
|
||||
import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service";
|
||||
import { normalizeAccidentLocation } from "./accident-location";
|
||||
@@ -2252,6 +2257,7 @@ export class RequestManagementService {
|
||||
party.person.clientId = await this.resolveCarBodyPolicyClientId(m);
|
||||
}
|
||||
|
||||
await checkDiscoveredBlameInsurer(req);
|
||||
// Advance workflow
|
||||
await this.advanceWorkflowToNext(req, stepKey);
|
||||
|
||||
@@ -2656,6 +2662,7 @@ export class RequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
await checkDiscoveredBlameInsurer(req);
|
||||
// Advance workflow
|
||||
await this.advanceWorkflowToNext(req, stepKey);
|
||||
|
||||
@@ -3628,6 +3635,7 @@ export class RequestManagementService {
|
||||
locked: false,
|
||||
},
|
||||
history: [],
|
||||
workingHoursIntakeClientId: actorWorkingHoursClientId(registrar),
|
||||
registrarInitiated: true,
|
||||
initiatedByRegistrarId: registrarId,
|
||||
creationMethod: CreationMethod.IN_PERSON,
|
||||
@@ -3758,6 +3766,7 @@ export class RequestManagementService {
|
||||
locked: false,
|
||||
},
|
||||
history: [],
|
||||
workingHoursIntakeClientId: actorWorkingHoursClientId(expert),
|
||||
expertInitiated: true,
|
||||
initiatedByFieldExpertId: expertId,
|
||||
...(expertBranchId ? { branchId: expertBranchId } : {}),
|
||||
@@ -5219,6 +5228,7 @@ export class RequestManagementService {
|
||||
});
|
||||
const carBodyClientId =
|
||||
await this.resolveCarBodyPolicyClientId(carBodyInfo);
|
||||
await checkDiscoveredCaseInsurer(carBodyClientId);
|
||||
if (!inquirySubmission.participants.legacy) {
|
||||
const options = carBodyClientId
|
||||
? { clientId: String(carBodyClientId) }
|
||||
@@ -5624,6 +5634,7 @@ export class RequestManagementService {
|
||||
decidedByExpertId: new Types.ObjectId(expert.sub),
|
||||
fields: { ...MUTUAL_AGREEMENT_EXPERT_DECISION_FIELDS },
|
||||
} as any;
|
||||
await checkDiscoveredBlameInsurer(req);
|
||||
req.workflow = {
|
||||
currentStep: WorkflowStep.FIRST_LOCATION as any,
|
||||
nextStep: WorkflowStep.SECOND_LOCATION as any,
|
||||
@@ -7086,6 +7097,15 @@ export class RequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
// The first party's policy funds the interim third-party claim in this flow.
|
||||
if (
|
||||
req.type === BlameRequestType.THIRD_PARTY &&
|
||||
partyRole === PartyRole.FIRST
|
||||
) {
|
||||
await checkDiscoveredCaseInsurer(party.person?.clientId);
|
||||
} else {
|
||||
await checkDiscoveredBlameInsurer(req);
|
||||
}
|
||||
await this.runParticipantPersonalInquiries(
|
||||
req,
|
||||
partyRole,
|
||||
@@ -7293,6 +7313,7 @@ export class RequestManagementService {
|
||||
payingClientId = guiltyClientId ? String(guiltyClientId) : undefined;
|
||||
}
|
||||
|
||||
await checkDiscoveredCaseInsurer(payingClientId);
|
||||
const claimNo = `CL${Math.floor(10000 + Math.random() * 90000)}`;
|
||||
const newClaimData: any = {
|
||||
requestNo: claimNo,
|
||||
@@ -8024,6 +8045,14 @@ export class RequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
req.type === BlameRequestType.THIRD_PARTY &&
|
||||
partyRole === PartyRole.FIRST
|
||||
) {
|
||||
await checkDiscoveredCaseInsurer(party.person?.clientId);
|
||||
} else {
|
||||
await checkDiscoveredBlameInsurer(req);
|
||||
}
|
||||
await this.runParticipantPersonalInquiries(
|
||||
req,
|
||||
partyRole,
|
||||
@@ -9257,6 +9286,7 @@ export class RequestManagementService {
|
||||
locked: false,
|
||||
},
|
||||
history: [],
|
||||
workingHoursIntakeClientId: actorWorkingHoursClientId(agent),
|
||||
callCenterInitiated: true,
|
||||
initiatedByCallCenterId: agentId,
|
||||
creationMethod: CreationMethod.LINK,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
|
||||
import { extname } from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdirSync } from "node:fs";
|
||||
@@ -55,6 +56,7 @@ import { GetUserBlameListV2ResponseDto } from "./dto/blame-list-user-v2.dto";
|
||||
* Versioning strategy: prefix the controller route with `v2/` so
|
||||
* all endpoints under this controller are automatically V2.
|
||||
*/
|
||||
@EnforceCaseWorkingHours()
|
||||
@Controller("v2/blame-request-management")
|
||||
@ApiTags("blame-request-management (v2)")
|
||||
@ApiBearerAuth()
|
||||
|
||||
@@ -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";
|
||||
@@ -21,6 +21,14 @@ export class DamageExpertDbService {
|
||||
return await this.damageExpertModel.findOne(user);
|
||||
}
|
||||
|
||||
async findReviewCandidates(clientKey: string) {
|
||||
return this.damageExpertModel.find({
|
||||
clientKey,
|
||||
isActive: { $ne: false },
|
||||
branchId: { $ne: null },
|
||||
}).select("firstName lastName branchId").sort({ firstName: 1, lastName: 1 }).lean().exec();
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<DamageExpertModel> {
|
||||
return await this.damageExpertModel.findOne({
|
||||
_id: new Types.ObjectId(userId),
|
||||
|
||||
@@ -38,6 +38,14 @@ export class FieldExpertDbService {
|
||||
return await this.fieldExpertModel.findOne({ $or: or });
|
||||
}
|
||||
|
||||
async findReviewCandidates(clientKey: string) {
|
||||
return this.fieldExpertModel.find({
|
||||
clientKey,
|
||||
isActive: { $ne: false },
|
||||
branchId: { $ne: null },
|
||||
}).select("firstName lastName branchId").sort({ firstName: 1, lastName: 1 }).lean().exec();
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<FieldExpertModel | null> {
|
||||
return await this.fieldExpertModel.findOne({
|
||||
_id: new Types.ObjectId(userId),
|
||||
|
||||
@@ -38,6 +38,14 @@ export class FileReviewerDbService {
|
||||
return await this.fileReviewerModel.findOne({ $or: or });
|
||||
}
|
||||
|
||||
async findReviewCandidates(clientKey: string) {
|
||||
return this.fileReviewerModel.find({
|
||||
clientKey,
|
||||
isActive: { $ne: false },
|
||||
branchId: { $ne: null },
|
||||
}).select("firstName lastName branchId").sort({ firstName: 1, lastName: 1 }).lean().exec();
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<FileReviewerModel | null> {
|
||||
return await this.fileReviewerModel.findOne({
|
||||
_id: new Types.ObjectId(userId),
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
/** HTTP regression suite from expert assessment through owner signing/uploads and invoice review.
|
||||
* Real controllers, guards, validation pipes and workflow services; in-memory persistence and no external delivery.
|
||||
*/
|
||||
import "reflect-metadata";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { JwtModule, JwtService } from "@nestjs/jwt";
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { HttpAdapterHost } from "@nestjs/core";
|
||||
import * as request from "supertest";
|
||||
import { mkdir, unlink } from "node:fs/promises";
|
||||
import { Types } from "mongoose";
|
||||
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
|
||||
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
|
||||
import { ClaimRequestManagementV2Controller } from "src/claim-request-management/claim-request-management.v2.controller";
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { MediaPolicyService } from "src/media-policy/media-policy.service";
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
import { GlobalGuard } from "src/auth/guards/global.guard";
|
||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||
import { RolesGuard } from "src/auth/guards/role.guard";
|
||||
import { PersianErrorFilter } from "src/common/errors/persian-error.filter";
|
||||
|
||||
const id = "650000000000000000000001",
|
||||
actorId = "650000000000000000000002",
|
||||
ownerId = "650000000000000000000003",
|
||||
tenant = "650000000000000000000004";
|
||||
const clone = (v: any) => (v == null ? v : JSON.parse(JSON.stringify(v)));
|
||||
const png = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jTncAAAAASUVORK5CYII=",
|
||||
"base64",
|
||||
);
|
||||
function get(obj: any, path: string) {
|
||||
return path.split(".").reduce((o, k) => o?.[k], obj);
|
||||
}
|
||||
function set(obj: any, path: string, value: any) {
|
||||
const keys = path.split(".");
|
||||
const last = keys.pop();
|
||||
const parent = keys.reduce(
|
||||
(o, k) => (o[k] ??= /^\d+$/.test(k) ? [] : {}),
|
||||
obj,
|
||||
);
|
||||
parent[last] = clone(value);
|
||||
}
|
||||
function unset(obj: any, path: string) {
|
||||
const keys = path.split(".");
|
||||
const last = keys.pop();
|
||||
const parent = keys.reduce((o, k) => o?.[k], obj);
|
||||
if (parent) delete parent[last];
|
||||
}
|
||||
|
||||
describe("claim resend and invoice lifecycle through HTTP", () => {
|
||||
let app: INestApplication,
|
||||
jwt: JwtService,
|
||||
claim: any,
|
||||
blame: any,
|
||||
expert: any,
|
||||
owner: any;
|
||||
let forceStale = false;
|
||||
const writes: any[] = [];
|
||||
const files: string[] = [];
|
||||
const priorSecret = process.env.JWT_SECRET,
|
||||
priorCap = process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
const repo = {
|
||||
findById: jest.fn(async () => clone(claim)),
|
||||
findByIdAndUpdate: jest.fn(async (_id, update) => apply(update)),
|
||||
findOneAndUpdate: jest.fn(async (filter, update) => {
|
||||
if (forceStale) {
|
||||
forceStale = false;
|
||||
return null;
|
||||
}
|
||||
for (const [key, value] of Object.entries(filter)) {
|
||||
if (key.endsWith(".partId")) continue;
|
||||
const actual = get(claim, key);
|
||||
if (
|
||||
value === null
|
||||
? actual != null
|
||||
: JSON.stringify(actual) !== JSON.stringify(clone(value))
|
||||
)
|
||||
return null;
|
||||
}
|
||||
let normalized = clone(update);
|
||||
if (Object.keys(filter).some((k) => k.endsWith(".partId"))) {
|
||||
const key = Object.keys(filter).find((k) => k.endsWith(".partId"));
|
||||
const path = key.slice(0, -7);
|
||||
const index = get(claim, path).findIndex(
|
||||
(p) => String(p.partId) === String(filter[key]),
|
||||
);
|
||||
normalized.$set = Object.fromEntries(
|
||||
Object.entries(normalized.$set).map(([k, v]) => [
|
||||
k.replace(".$.", `.${index}.`),
|
||||
v,
|
||||
]),
|
||||
);
|
||||
}
|
||||
return apply(normalized);
|
||||
}),
|
||||
};
|
||||
function apply(update: any) {
|
||||
writes.push(clone(update));
|
||||
for (const [key, value] of Object.entries({
|
||||
...Object.fromEntries(
|
||||
Object.entries(update).filter(([k]) => !k.startsWith("$")),
|
||||
),
|
||||
...update.$set,
|
||||
}))
|
||||
set(claim, key, value);
|
||||
for (const key of Object.keys(update.$unset ?? {})) unset(claim, key);
|
||||
for (const [key, value] of Object.entries(update.$push ?? {})) {
|
||||
let list = get(claim, key);
|
||||
if (!list) {
|
||||
set(claim, key, []);
|
||||
list = get(claim, key);
|
||||
}
|
||||
list.push(clone(value));
|
||||
}
|
||||
return clone(claim);
|
||||
}
|
||||
const actorToken = (flow = "v1") =>
|
||||
jwt.sign(
|
||||
{
|
||||
sub: actorId,
|
||||
role: ["v1", "v6"].includes(flow)
|
||||
? "damage_expert"
|
||||
: ["v2", "v3"].includes(flow)
|
||||
? "field_expert"
|
||||
: "file_reviewer",
|
||||
clientKey: tenant,
|
||||
fullName: "کارشناس آزمایشی",
|
||||
},
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const userToken = () =>
|
||||
jwt.sign(
|
||||
{ sub: ownerId, role: "user", fullName: "مالک آزمایشی" },
|
||||
{ secret: process.env.JWT_SECRET },
|
||||
);
|
||||
const act = (method: "put" | "patch", path: string, flow = "v1") =>
|
||||
request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set("Authorization", `Bearer ${actorToken(flow)}`);
|
||||
const user = (method: "put" | "patch", path: string) =>
|
||||
request(app.getHttpServer())
|
||||
[method](path)
|
||||
.set("Authorization", `Bearer ${userToken()}`);
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = "invoice-regression-test-secret";
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
await mkdir("files/claim-sign", { recursive: true });
|
||||
await mkdir("files/claim-factors", { recursive: true });
|
||||
expert = Object.create(ExpertClaimService.prototype);
|
||||
owner = Object.create(ClaimRequestManagementService.prototype);
|
||||
Object.assign(expert, {
|
||||
claimCaseDbService: repo,
|
||||
blameRequestDbService: { findById: async () => clone(blame) },
|
||||
assertExpertActorOnClaim: jest.fn(async () => {}),
|
||||
snapshotDamageExpert: jest.fn(async () => undefined),
|
||||
recordClaimExpertActivity: jest.fn(async () => {}),
|
||||
resolveClaimOwnerPhone: jest.fn(async () => null),
|
||||
logger: { warn: jest.fn(), error: jest.fn(), log: jest.fn() },
|
||||
loadBlameForClaim: async () => clone(blame),
|
||||
});
|
||||
Object.assign(owner, {
|
||||
claimCaseDbService: repo,
|
||||
resolveClaimEffectiveUserId: async () => ownerId,
|
||||
assertEffectiveUserIsDamagedPartyOnClaim: async () => {},
|
||||
autoSubmitFanavaranExpertiseOnExpertReply: async () => ({submitted:false,attempted:false}),
|
||||
autoSubmitToFanavaranV2OnClaimCompleted: async () => ({submitted:false,attempted:false}),
|
||||
claimSignDbService: {
|
||||
create: async () => ({ _id: new Types.ObjectId() }),
|
||||
},
|
||||
claimFactorsImageDbService: {
|
||||
create: async () => ({ _id: new Types.ObjectId() }),
|
||||
},
|
||||
logger: { warn: jest.fn(), error: jest.fn(), log: jest.fn() },
|
||||
});
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [JwtModule.register({})],
|
||||
controllers: [
|
||||
ExpertClaimV2Controller,
|
||||
ClaimRequestManagementV2Controller,
|
||||
],
|
||||
providers: [
|
||||
LocalActorAuthGuard,
|
||||
GlobalGuard,
|
||||
RolesGuard,
|
||||
{
|
||||
provide: ActorAuthService,
|
||||
useValue: { assertActorActive: async () => {} },
|
||||
},
|
||||
{ provide: ExpertClaimService, useValue: expert },
|
||||
{ provide: ClaimRequestManagementService, useValue: owner },
|
||||
{ provide: ClaimCaseDbService, useValue: repo },
|
||||
{ provide: AiService, useValue: {} },
|
||||
{
|
||||
provide: MediaPolicyService,
|
||||
useValue: {
|
||||
assertForClaim: async (file) => {
|
||||
if (file?.path) files.push(file.path);
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
app = module.createNestApplication({ logger: false });
|
||||
app.useGlobalFilters(new PersianErrorFilter(app.get(HttpAdapterHost)));
|
||||
await app.init();
|
||||
jwt = app.get(JwtService);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
await Promise.all(files.map((file) => unlink(file).catch(() => {})));
|
||||
if (priorSecret === undefined) delete process.env.JWT_SECRET;
|
||||
else process.env.JWT_SECRET = priorSecret;
|
||||
if (priorCap === undefined)
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
else process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED = priorCap;
|
||||
});
|
||||
function fixture(flow = "v1", type = "THIRD_PARTY") {
|
||||
writes.length = 0;
|
||||
forceStale = false;
|
||||
blame = {
|
||||
type,
|
||||
flowVersion: flow,
|
||||
expertInitiated: ["v2", "v3"].includes(flow),
|
||||
registrarInitiated: ["v4", "v5"].includes(flow),
|
||||
callCenterInitiated: flow === "v6",
|
||||
creationMethod:
|
||||
flow === "v1" ? "NORMAL" : flow === "v6" ? "LINK" : "IN_PERSON",
|
||||
};
|
||||
claim = {
|
||||
_id: id,
|
||||
publicId: "QA-1",
|
||||
blameRequestId: "650000000000000000000005",
|
||||
status: "EXPERT_REVIEWING",
|
||||
owner: { userId: ownerId, clientId: tenant },
|
||||
requiresFileMakerApproval: flow === "v5",
|
||||
workflow: {
|
||||
locked: true,
|
||||
lockedBy: { actorId },
|
||||
currentStep: "EXPERT_DAMAGE_ASSESSMENT",
|
||||
},
|
||||
vehicle: { carType: "sedan" },
|
||||
evaluation: {},
|
||||
damage: {
|
||||
selectedParts: [30, 31, 15].map((part) => ({
|
||||
id: part,
|
||||
name: String(part),
|
||||
side: "",
|
||||
label_fa: String(part),
|
||||
catalogKey: String(part),
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
function quote(partId: number, factorNeeded: boolean) {
|
||||
return {
|
||||
partId,
|
||||
typeOfDamage: "تعویض",
|
||||
...(factorNeeded ? {} : { price: "1000000" }),
|
||||
salary: "1000000",
|
||||
totalPayment: factorNeeded ? "1000000" : "2000000",
|
||||
factorNeeded,
|
||||
daghi: { option: "فاقد ارزش" },
|
||||
};
|
||||
}
|
||||
function readyForReview() {
|
||||
fixture();
|
||||
claim.status = "EXPERT_VALIDATING_REPAIR_FACTORS";
|
||||
claim.claimStatus = "UNDER_REVIEW";
|
||||
claim.workflow.currentStep = "EXPERT_COST_EVALUATION";
|
||||
claim.evaluation.damageExpertReply = {
|
||||
submittedAt: new Date().toISOString(),
|
||||
parts: [
|
||||
{
|
||||
...quote(30, true),
|
||||
factorLink: "test-factor",
|
||||
factorStatus: "PENDING",
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
for (const flow of ["v1", "v2", "v3", "v4", "v5", "v6"])
|
||||
for (const type of ["THIRD_PARTY", "CAR_BODY"])
|
||||
for (const shape of ["mixed", "all-factor", "priced"]) {
|
||||
it(`${flow} ${type} ${shape}: assessment → signature if needed → uploads → per-invoice review`, async () => {
|
||||
fixture(flow, type);
|
||||
const parts = [
|
||||
quote(30, shape !== "priced"),
|
||||
quote(31, shape === "all-factor"),
|
||||
];
|
||||
const reply = await act(
|
||||
"put",
|
||||
`/v2/expert-claim/reply/submit/${id}`,
|
||||
flow,
|
||||
).send({
|
||||
parts,
|
||||
...(type === "CAR_BODY" ? { carPrice: "1000000000" } : {}),
|
||||
});
|
||||
expect(reply.status).toBe(200);
|
||||
if (shape === "priced") {
|
||||
if (claim.status === "INSURER_REVIEW_AWAITING_OWNER_SIGN") {
|
||||
const signature = await user("put", `/v2/claim-request-management/request/${id}/owner-insurer-approval/sign`)
|
||||
.field("agree", "true").attach("sign", png, {filename:"signature.png",contentType:"image/png"});
|
||||
expect(signature.status).toBe(200);
|
||||
}
|
||||
expect(claim.status).toBe(flow === "v5" ? "WAITING_FOR_FILE_MAKER_APPROVAL" : "COMPLETED");
|
||||
return;
|
||||
}
|
||||
const upload = (part: number) =>
|
||||
user(
|
||||
"patch",
|
||||
`/v2/claim-request-management/request/reply/${id}/${part}/upload-factor`,
|
||||
).attach("file", png, {
|
||||
filename: "factor.png",
|
||||
contentType: "image/png",
|
||||
});
|
||||
if (shape === "mixed") {
|
||||
expect((await upload(30)).status).toBe(400);
|
||||
const sign = await user(
|
||||
"put",
|
||||
`/v2/claim-request-management/request/${id}/owner-insurer-approval/sign`,
|
||||
)
|
||||
.field("agree", "true")
|
||||
.attach("sign", png, {
|
||||
filename: "signature.png",
|
||||
contentType: "image/png",
|
||||
});
|
||||
expect(sign.status).toBe(200);
|
||||
expect(sign.body.currentStep).toBe("OWNER_UPLOAD_FACTOR_DOCUMENTS");
|
||||
} else
|
||||
expect(claim.workflow.currentStep).toBe(
|
||||
"OWNER_UPLOAD_FACTOR_DOCUMENTS",
|
||||
);
|
||||
expect((await upload(30)).status).toBe(200);
|
||||
expect((await upload(30)).status).toBe(409);
|
||||
if (shape === "all-factor")
|
||||
expect((await upload(31)).status).toBe(200);
|
||||
expect(claim.status).toBe("EXPERT_VALIDATING_REPAIR_FACTORS");
|
||||
for (const part of parts.filter((p) => p.factorNeeded)) {
|
||||
const result = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
flow,
|
||||
).send({
|
||||
decisions: [
|
||||
{
|
||||
partId: part.partId,
|
||||
status: "APPROVED",
|
||||
totalPayment: "3000000",
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(result.status).toBe(200);
|
||||
}
|
||||
expect(claim.status).toBe(
|
||||
flow === "v5" ? "WAITING_FOR_FILE_MAKER_APPROVAL" : "COMPLETED",
|
||||
);
|
||||
expect(
|
||||
claim.evaluation.damageExpertReply.parts
|
||||
.filter((p) => p.factorNeeded)
|
||||
.every((p) => p.factorStatus === "APPROVED"),
|
||||
).toBe(true);
|
||||
});
|
||||
}
|
||||
it("accepts the exact reported resend body on its first cycle and exposes the Persian rule on a second cycle", async () => {
|
||||
fixture();
|
||||
const body = {
|
||||
resendDescription: "gjjjjjjg",
|
||||
resendDocuments: [],
|
||||
resendCarParts: [
|
||||
{
|
||||
key: "چراغ عقب چپ",
|
||||
label_fa: "چراغ عقب چپ",
|
||||
label_en: "15",
|
||||
side: "",
|
||||
id: 15,
|
||||
captured: false,
|
||||
name: "15",
|
||||
},
|
||||
],
|
||||
};
|
||||
const first = await act("put", `/v2/expert-claim/reply/resend/${id}`).send(
|
||||
body,
|
||||
);
|
||||
expect(first.status).toBe(200);
|
||||
expect(claim.evaluation.damageExpertResend.resendCarParts[0].id).toBe(15);
|
||||
claim.status = "EXPERT_REVIEWING";
|
||||
claim.workflow.locked = true;
|
||||
claim.workflow.lockedBy = { actorId };
|
||||
claim.evaluation.damageExpertResend.fulfilledAt = new Date().toISOString();
|
||||
const before = clone(claim);
|
||||
const second = await act("put", `/v2/expert-claim/reply/resend/${id}`).send(
|
||||
body,
|
||||
);
|
||||
expect(second.status).toBe(422);
|
||||
expect(second.body.errorCode).toBe("DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED");
|
||||
expect(second.body.message).toContain("درخواست قبلی");
|
||||
expect(claim).toEqual(before);
|
||||
});
|
||||
it.each(
|
||||
[
|
||||
[],
|
||||
[{ partId: 30, status: "PENDING", totalPayment: "3000000" }],
|
||||
[{ partId: 30, status: "APPROVED", totalPayment: "factor" }],
|
||||
[{ partId: 30, status: "APPROVED" }],
|
||||
[{ partId: 30, status: "REJECTED", totalPayment: "3000000" }],
|
||||
[{ partId: 99, status: "APPROVED", totalPayment: "3000000" }],
|
||||
[
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "3000000" },
|
||||
{
|
||||
partId: 30,
|
||||
status: "REJECTED",
|
||||
totalPayment: "3000000",
|
||||
rejectionReason: "خطا",
|
||||
},
|
||||
],
|
||||
].map((decisions) => [decisions]),
|
||||
)("invalid invoice decision makes no writes: %j", async (decisions) => {
|
||||
readyForReview();
|
||||
const before = clone(claim);
|
||||
const res = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
).send({ decisions });
|
||||
expect(res.status).toBe(400);
|
||||
expect(claim).toEqual(before);
|
||||
expect(writes).toHaveLength(0);
|
||||
});
|
||||
it("a cap failure preserves pending invoice data and a corrected retry completes", async () => {
|
||||
readyForReview();
|
||||
blame.expertInitiated = false;
|
||||
blame.registrarInitiated = false;
|
||||
blame.creationMethod = "NORMAL";
|
||||
process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED = "true";
|
||||
const before = clone(claim);
|
||||
const res = await act(
|
||||
"patch",
|
||||
`/v2/expert-claim/validate-factors/${id}`,
|
||||
).send({
|
||||
decisions: [
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "600000000" },
|
||||
],
|
||||
});
|
||||
expect(res.status).toBe(400);
|
||||
expect(claim).toEqual(before);
|
||||
expect(writes).toHaveLength(0);
|
||||
expect(
|
||||
(
|
||||
await act("patch", `/v2/expert-claim/validate-factors/${id}`).send({
|
||||
decisions: [
|
||||
{ partId: 30, status: "APPROVED", totalPayment: "3000000" },
|
||||
],
|
||||
})
|
||||
).status,
|
||||
).toBe(200);
|
||||
delete process.env.CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED;
|
||||
});
|
||||
it("rejecting an invoice with a corrected amount completes with its reason, and stale writes return 409", async () => {
|
||||
readyForReview();
|
||||
forceStale = true;
|
||||
const body = {
|
||||
decisions: [
|
||||
{
|
||||
partId: 30,
|
||||
status: "REJECTED",
|
||||
totalPayment: "۳٬۰۰۰٬۰۰۰",
|
||||
rejectionReason: "اصلاح مبلغ فاکتور",
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(
|
||||
(await act("patch", `/v2/expert-claim/validate-factors/${id}`).send(body))
|
||||
.status,
|
||||
).toBe(409);
|
||||
expect(writes).toHaveLength(0);
|
||||
expect(
|
||||
(await act("patch", `/v2/expert-claim/validate-factors/${id}`).send(body))
|
||||
.status,
|
||||
).toBe(200);
|
||||
expect(claim.evaluation.damageExpertReply.parts[0]).toMatchObject({
|
||||
factorStatus: "REJECTED",
|
||||
totalPayment: "3000000",
|
||||
rejectionReason: "اصلاح مبلغ فاکتور",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { INestApplication } from "@nestjs/common";
|
||||
import { APP_INTERCEPTOR } from "@nestjs/core";
|
||||
import { JwtModule, JwtService } from "@nestjs/jwt";
|
||||
import { Test } from "@nestjs/testing";
|
||||
import { Types } from "mongoose";
|
||||
import * as request from "supertest";
|
||||
import { AiService } from "src/ai/ai.service";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
|
||||
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
|
||||
import { ClaimReviewInterceptor } from "src/expert-claim/review-referral/claim-review.interceptor";
|
||||
import { ClaimReviewReferralService } from "src/expert-insurer/claim-review-referral.service";
|
||||
import { ExpertInsurerController } from "src/expert-insurer/expert-insurer.controller";
|
||||
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||
import { ReportsService } from "src/reports/reports.service";
|
||||
|
||||
const tenant = "650000000000000000000001";
|
||||
const other = "650000000000000000000002";
|
||||
const insurer = "650000000000000000000003";
|
||||
const before = "650000000000000000000004";
|
||||
const after = "650000000000000000000005";
|
||||
const branch = "650000000000000000000006";
|
||||
const priorBranch = "650000000000000000000007";
|
||||
const claimId = "650000000000000000000008";
|
||||
const blameId = "650000000000000000000009";
|
||||
|
||||
describe("insurer referral through HTTP", () => {
|
||||
let app: INestApplication;
|
||||
let jwt: JwtService;
|
||||
const secretBefore = process.env.JWT_SECRET;
|
||||
const secret = "local-referral-test-only";
|
||||
const activeWrites = new Set<string>();
|
||||
let claim: any;
|
||||
const findClaim = async () => claim;
|
||||
const repo = {
|
||||
findOne: jest.fn(async (filter) =>
|
||||
filter.publicId === claim.publicId &&
|
||||
String(filter.$or[0]["owner.clientId"]) === tenant
|
||||
? claim
|
||||
: null,
|
||||
),
|
||||
findReviewAccess: findClaim,
|
||||
acquireReviewWrite: jest.fn(async () => {
|
||||
const marker = String(activeWrites.size + 1);
|
||||
activeWrites.add(marker);
|
||||
return async () => {
|
||||
activeWrites.delete(marker);
|
||||
};
|
||||
}),
|
||||
findOneAndUpdate: jest.fn(async (filter, update) => {
|
||||
if (
|
||||
activeWrites.size ||
|
||||
filter.updatedAt !== claim.updatedAt ||
|
||||
claim.claimId != null
|
||||
)
|
||||
return null;
|
||||
claim = {
|
||||
...claim,
|
||||
branchId: update.$set.branchId,
|
||||
reviewReferral: update.$set.reviewReferral,
|
||||
updatedAt: new Date(claim.updatedAt.getTime() + 1),
|
||||
history: [...claim.history, update.$push.history],
|
||||
};
|
||||
return claim;
|
||||
}),
|
||||
};
|
||||
const staff = {
|
||||
findById: async (id) =>
|
||||
id === after
|
||||
? {
|
||||
_id: after,
|
||||
clientKey: tenant,
|
||||
branchId: branch,
|
||||
firstName: "علی",
|
||||
lastName: "کریمی",
|
||||
}
|
||||
: null,
|
||||
findReviewCandidates: async () => [await staff.findById(after)],
|
||||
};
|
||||
const branches = {
|
||||
findById: async (id) => ({
|
||||
_id: id,
|
||||
clientKey: tenant,
|
||||
name: id === branch ? "کرج" : "تهران",
|
||||
}),
|
||||
findAll: async () =>
|
||||
Promise.all([priorBranch, branch].map(branches.findById)),
|
||||
};
|
||||
|
||||
const detail = jest.fn(async () => ({ claimRequestId: claimId }));
|
||||
const reply = jest.fn(async () => ({ saved: true }));
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.JWT_SECRET = secret;
|
||||
const referrals = new ClaimReviewReferralService(
|
||||
repo as any,
|
||||
{
|
||||
findById: async () => ({
|
||||
status: "COMPLETED",
|
||||
branchId: new Types.ObjectId(priorBranch),
|
||||
}),
|
||||
} as any,
|
||||
branches as any,
|
||||
staff as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
);
|
||||
const module = await Test.createTestingModule({
|
||||
imports: [JwtModule.register({})],
|
||||
controllers: [ExpertInsurerController, ExpertClaimV2Controller],
|
||||
providers: [
|
||||
{ provide: APP_INTERCEPTOR, useClass: ClaimReviewInterceptor },
|
||||
{ provide: ClaimCaseDbService, useValue: repo },
|
||||
{ provide: AiService, useValue: {} },
|
||||
{
|
||||
provide: ActorAuthService,
|
||||
useValue: { assertActorActive: async () => {} },
|
||||
},
|
||||
{ provide: ClaimRequestManagementService, useValue: {} },
|
||||
{
|
||||
provide: ExpertClaimService,
|
||||
useValue: { getClaimDetailV2: detail, submitExpertReplyV2: reply },
|
||||
},
|
||||
{ provide: ExpertInsurerService, useValue: {} },
|
||||
{ provide: ClaimReviewReferralService, useValue: referrals },
|
||||
{ provide: ReportsService, useValue: {} },
|
||||
],
|
||||
}).compile();
|
||||
app = module.createNestApplication({ logger: false });
|
||||
jwt = module.get(JwtService);
|
||||
await app.init();
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
activeWrites.clear();
|
||||
claim = {
|
||||
_id: new Types.ObjectId(claimId),
|
||||
publicId: "REF100",
|
||||
owner: { clientId: tenant },
|
||||
status: "EXPERT_REVIEWING",
|
||||
blameRequestId: new Types.ObjectId(blameId),
|
||||
branchId: new Types.ObjectId(priorBranch),
|
||||
updatedAt: new Date(),
|
||||
workflow: {
|
||||
currentStep: "EXPERT_DAMAGE_ASSESSMENT",
|
||||
assignedForReviewBy: { actorId: before, actorName: "کارشناس قبلی" },
|
||||
},
|
||||
history: [],
|
||||
};
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
if (secretBefore === undefined) delete process.env.JWT_SECRET;
|
||||
else process.env.JWT_SECRET = secretBefore;
|
||||
});
|
||||
|
||||
const referralUrl = "/expert-insurer/files/REF100/review-referral";
|
||||
const reviewUrl = `/v2/expert-claim/request/${claimId}`;
|
||||
const token = (sub, role, clientKey = tenant) =>
|
||||
jwt.sign({ sub, role, clientKey }, { secret });
|
||||
const authorize = (req, sub, role, clientKey = tenant) =>
|
||||
req.auth(token(sub, role, clientKey), { type: "bearer" });
|
||||
|
||||
it("authorizes only the insurer, rejects a stale transfer, and switches review detail access", async () => {
|
||||
const server = app.getHttpServer();
|
||||
await authorize(
|
||||
request(server).get(referralUrl),
|
||||
before,
|
||||
"damage_expert",
|
||||
).expect(403);
|
||||
await authorize(
|
||||
request(server).get(referralUrl),
|
||||
insurer,
|
||||
"company",
|
||||
other,
|
||||
).expect(404);
|
||||
const options = await authorize(
|
||||
request(server).get(referralUrl),
|
||||
insurer,
|
||||
"company",
|
||||
).expect(200);
|
||||
const body = { expertId: after, revision: options.body.revision };
|
||||
expect(options.body.candidates).toEqual([
|
||||
expect.objectContaining({ id: after, branchId: branch }),
|
||||
]);
|
||||
|
||||
await authorize(request(server).patch(referralUrl), insurer, "company")
|
||||
.send({ ...body, branchId: priorBranch })
|
||||
.expect(400);
|
||||
activeWrites.add("review in progress");
|
||||
await authorize(request(server).patch(referralUrl), insurer, "company")
|
||||
.send(body)
|
||||
.expect(409);
|
||||
activeWrites.clear();
|
||||
await authorize(request(server).patch(referralUrl), insurer, "company")
|
||||
.send(body)
|
||||
.expect(200);
|
||||
await authorize(request(server).patch(referralUrl), insurer, "company")
|
||||
.send(body)
|
||||
.expect(409);
|
||||
await authorize(
|
||||
request(server).get(reviewUrl),
|
||||
before,
|
||||
"damage_expert",
|
||||
).expect(403);
|
||||
await authorize(
|
||||
request(server).get(reviewUrl),
|
||||
after,
|
||||
"damage_expert",
|
||||
other,
|
||||
).expect(403);
|
||||
await authorize(
|
||||
request(server).get(reviewUrl),
|
||||
after,
|
||||
"damage_expert",
|
||||
).expect(200);
|
||||
await authorize(
|
||||
request(server).put(`/v2/expert-claim/reply/submit/${claimId}`),
|
||||
before,
|
||||
"damage_expert",
|
||||
)
|
||||
.send({})
|
||||
.expect(403);
|
||||
expect(reply).not.toHaveBeenCalled();
|
||||
expect(claim.history).toHaveLength(1);
|
||||
expect(claim.history[0].metadata).toMatchObject({
|
||||
previousBranchId: priorBranch,
|
||||
branchId: branch,
|
||||
previousExpertId: before,
|
||||
expertId: after,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -301,6 +301,18 @@
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "ExpertInsurerController",
|
||||
"method": "GET",
|
||||
"path": "/expert-insurer/files/:publicId/review-referral",
|
||||
"guards": [
|
||||
"LocalActorAuthGuard",
|
||||
"RolesGuard"
|
||||
],
|
||||
"roles": [
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "ExpertInsurerController",
|
||||
"method": "GET",
|
||||
@@ -337,6 +349,18 @@
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "InsurerManagementController",
|
||||
"method": "GET",
|
||||
"path": "/expert-insurer/management/working-hours",
|
||||
"guards": [
|
||||
"LocalActorAuthGuard",
|
||||
"RolesGuard"
|
||||
],
|
||||
"roles": [
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "ExpertInsurerController",
|
||||
"method": "GET",
|
||||
@@ -1072,6 +1096,15 @@
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "SuperAdminManagementController",
|
||||
"method": "GET",
|
||||
"path": "/super-admin/management/working-hours",
|
||||
"guards": [
|
||||
"SuperAdminGuard"
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "SuperAdminController",
|
||||
"method": "GET",
|
||||
@@ -1645,6 +1678,15 @@
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "FanavaranController",
|
||||
"method": "GET",
|
||||
"path": "/v2/fanavaran/claim-cases/:claimCaseId/expert-signature",
|
||||
"guards": [
|
||||
"LocalActorAuthGuard"
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "FanavaranController",
|
||||
"method": "GET",
|
||||
@@ -2012,6 +2054,18 @@
|
||||
"expert"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "ExpertInsurerController",
|
||||
"method": "PATCH",
|
||||
"path": "/expert-insurer/files/:publicId/review-referral",
|
||||
"guards": [
|
||||
"LocalActorAuthGuard",
|
||||
"RolesGuard"
|
||||
],
|
||||
"roles": [
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "InsurerManagementController",
|
||||
"method": "PATCH",
|
||||
@@ -2036,6 +2090,18 @@
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "InsurerManagementController",
|
||||
"method": "PATCH",
|
||||
"path": "/expert-insurer/management/working-hours",
|
||||
"guards": [
|
||||
"LocalActorAuthGuard",
|
||||
"RolesGuard"
|
||||
],
|
||||
"roles": [
|
||||
"company"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "SuperAdminController",
|
||||
"method": "PATCH",
|
||||
@@ -2090,6 +2156,15 @@
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "SuperAdminManagementController",
|
||||
"method": "PATCH",
|
||||
"path": "/super-admin/management/working-hours",
|
||||
"guards": [
|
||||
"SuperAdminGuard"
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "SuperAdminController",
|
||||
"method": "PATCH",
|
||||
@@ -2305,6 +2380,15 @@
|
||||
"file_reviewer"
|
||||
]
|
||||
},
|
||||
{
|
||||
"controller": "FanavaranController",
|
||||
"method": "PATCH",
|
||||
"path": "/v2/fanavaran/claim-cases/:claimCaseId/expert-signature",
|
||||
"guards": [
|
||||
"LocalActorAuthGuard"
|
||||
],
|
||||
"roles": []
|
||||
},
|
||||
{
|
||||
"controller": "RegistrarClaimMirrorController",
|
||||
"method": "PATCH",
|
||||
|
||||
Reference in New Issue
Block a user