Compare commits

...

36 Commits

Author SHA1 Message Date
6e5b7cb1fd Merge pull request 'Fixed type fixes and errors' (#312) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#312
2026-09-14 12:52:02 +03:30
SepehrYahyaee
51166a8d0d Fixed type fixes and errors 2026-09-14 12:49:46 +03:30
4f301d1d03 Merge pull request 'Fix V4 FileMaker workflow re-entry' (#311) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#311
2026-09-14 11:43:41 +03:30
SepehrYahyaee
1b69da38ff Fix V4 FileMaker workflow re-entry 2026-09-14 11:42:48 +03:30
1941013b00 Merge pull request 'Route inquiries by participant role' (#310) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#310
2026-09-14 10:51:40 +03:30
SepehrYahyaee
98c7ebb83a Route inquiries by participant role 2026-09-14 10:43:57 +03:30
461afbb6b9 Merge pull request 'Implement role-complete inquiry participants + Bug fixes' (#309) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#309
2026-09-13 16:23:42 +03:30
SepehrYahyaee
6a26811555 Calculate insurer report review duration 2026-09-13 16:15:12 +03:30
SepehrYahyaee
f9d4b5df9a Localize timeline system reasons 2026-09-13 16:04:51 +03:30
SepehrYahyaee
0eaf55e73c Document structured inquiry payload for frontend 2026-09-13 14:35:45 +03:30
SepehrYahyaee
5b77241f28 Require structured inquiry participant inputs 2026-09-13 14:13:05 +03:30
SepehrYahyaee
cc8a96c875 Persist inquiry audit on client resolution failures 2026-09-13 12:59:39 +03:30
SepehrYahyaee
5812637a1e Mark rejected inquiry results as failed 2026-09-13 12:55:55 +03:30
SepehrYahyaee
287978a555 Retain inquiry audit context on failure 2026-09-13 11:42:20 +03:30
SepehrYahyaee
fe22e69351 Persist failed inquiry audit trails 2026-09-13 11:36:03 +03:30
SepehrYahyaee
b5b18114d8 Complete inquiry participant flow coverage 2026-09-13 11:29:43 +03:30
SepehrYahyaee
d060b6d9e2 Harden inquiry participant edge cases 2026-09-13 11:18:37 +03:30
SepehrYahyaee
c64f23091a Implement role-complete inquiry participants 2026-09-13 10:59:00 +03:30
SepehrYahyaee
401ad6a143 Added Docs 2026-09-12 17:02:12 +03:30
ed9ef3bac3 Merge pull request 'Removed unncessary data from PDF' (#308) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#308
2026-09-12 14:35:33 +03:30
SepehrYahyaee
bc9c217d8a Removed unncessary data from PDF 2026-09-12 14:35:01 +03:30
48c8290f9c Merge pull request 'YARA-1258' (#307) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#307
2026-09-12 14:24:00 +03:30
SepehrYahyaee
7fd60df1d6 YARA-1258 2026-09-12 14:23:23 +03:30
7f50b75c64 Merge pull request 'Preserved FE contact' (#306) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#306
2026-09-12 12:20:26 +03:30
SepehrYahyaee
9e51fdcdaf Preserved FE contact 2026-09-12 12:20:03 +03:30
58e374d502 Merge pull request 'Fixed FaLabels in Timeline' (#305) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#305
2026-09-12 11:59:03 +03:30
SepehrYahyaee
0bab93e983 Fixed seed data 2026-09-12 11:58:24 +03:30
SepehrYahyaee
fc37dd78a4 Fixed FaLabels 2026-09-12 11:58:07 +03:30
795ecbae96 Merge pull request 'YARA-1257, YARA-1272, YARA-985' (#304) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#304
2026-09-12 11:21:01 +03:30
SepehrYahyaee
15342e16d8 YARA-1257, YARA-1272, YARA-985 2026-09-12 11:19:57 +03:30
2dc25100ea Merge pull request 'fixed branch being mandatory' (#303) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#303
2026-09-12 10:19:37 +03:30
SepehrYahyaee
ebe45646c1 fixed branch being mandatory 2026-09-12 10:18:17 +03:30
bf515f3011 Merge pull request 'YARA-1267, YARA-1268' (#302) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#302
2026-09-08 14:53:15 +03:30
SepehrYahyaee
55da8188a9 YARA-1267, YARA-1268 2026-09-08 14:51:51 +03:30
20aa6957e9 Merge pull request 'Better error handling and validation and min/max prices added for expert submit' (#301) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#301
2026-09-08 13:12:20 +03:30
SepehrYahyaee
0e861ff6d1 Better error handling and validation and min/max prices added for expert submit 2026-09-08 13:11:24 +03:30
58 changed files with 7318 additions and 1625 deletions

103
docs/architecture.md Normal file
View File

@@ -0,0 +1,103 @@
docs/
│
├── README.md
│
├── architecture/
│ ├── overview.md
│ ├── principles.md
│ ├── layers.md
│ ├── modules.md
│ ├── workflow-engine.md
│ ├── event-driven.md
│ ├── database.md
│ ├── caching.md
│ ├── authentication.md
│ ├── authorization.md
│ ├── file-storage.md
│ ├── id-generation.md
│ ├── error-handling.md
│ ├── logging.md
│ └── diagrams/
│
├── adr/
│ ├── 0001-use-mongodb.md
│ ├── 0002-use-workflow-engine.md
│ ├── ...
│
├── engineering/
│ ├── structure.md
│ ├── coding-style.md
│ ├── naming.md
│ ├── comments.md
│ ├── exceptions.md
│ ├── validation.md
│ ├── dto-guidelines.md
│ ├── repositories.md
│ ├── services.md
│ ├── controllers.md
│ ├── testing.md
│ ├── code-review.md
│ ├── gitflow.md
│ ├── commit-convention.md
│ ├── branching.md
│ ├── dependency-rules.md
│ ├── security.md
│ └── performance.md
│
├── domain/
│ ├── glossary.md
│ ├── insurance-concepts.md
│ ├── entities.md
│ ├── events.md
│ ├── workflows.md
│ ├── business-rules.md
│ └── state-transitions.md
│
├── flows/
│ ├── company-a/
│ ├── company-b/
│ ├── company-c/
│ └── common/
│
├── api/
│ ├── rest.md
│ ├── versioning.md
│ ├── pagination.md
│ ├── errors.md
│ └── examples/
│
├── deployment/
│ ├── docker.md
│ ├── environments.md
│ ├── ci.md
│ ├── cd.md
│ ├── backups.md
│ └── monitoring.md
│
├── onboarding/
│ ├── setup.md
│ ├── first-day.md
│ ├── debugging.md
│ ├── faq.md
│ └── common-mistakes.md
│
├── operations/
│ ├── runbooks.md
│ ├── incident-response.md
│ ├── rca/
│ ├── postmortems/
│ └── troubleshooting.md
│
├── backlog/
│ ├── ideas.md
│ ├── technical-debt.md
│ ├── future-features.md
│ └── experiments.md
│
├── decisions/
│ ├── rejected-ideas.md
│ ├── deprecated.md
│ └── migration-plans.md
│
├── changelog.md
└── roadmap.md

View File

@@ -0,0 +1,228 @@
# راهنمای فرانت‌اند: ثبت پاسخ کارشناس خسارت (V2)
این مستند قرارداد API زیر را توضیح می‌دهد، به‌ویژه اعتبارسنجی مبلغ‌ها و ساختار خطاهایی که باید در فرم نمایش داده شوند.
```http
PUT /v2/expert-claim/reply/submit/:claimRequestId
Authorization: Bearer <actor-token>
Content-Type: application/json
```
اگر محیط شما API را زیر پیشوند `/api` منتشر می‌کند، مسیر نهایی به‌صورت `/api/v2/expert-claim/reply/submit/:claimRequestId` است.
## پیش‌نیازها
- کاربر باید نقش کارشناس مجاز داشته باشد.
- پرونده باید پیش از ارسال توسط همین کارشناس قفل شده باشد.
- `partId` هر ردیف باید از `damagedParts[].partId` در جزئیات پرونده انتخاب شود؛ شناسه دلخواه ارسال نکنید.
- دست‌کم یک ردیف در `parts` لازم است.
## بدنه درخواست
تمام مبلغ‌ها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته می‌شوند؛ برای نمونه هر دو مقدار `"100000"` و `"۱۰۰,۰۰۰"` معتبرند.
```json
{
"description": "تعویض درب جلو لازم است",
"parts": [
{
"partId": 201,
"typeOfDamage": "تعویض",
"price": "2500000",
"salary": "400000",
"totalPayment": "2900000",
"factorNeeded": false,
"daghi": {
"option": "ارزش لوازم بازیافتی",
"price": "300000"
}
}
]
}
```
### فیلدهای سطح بالا
| فیلد | الزامی | توضیح |
| --- | --- | --- |
| `description` | خیر | یادداشت متنی کارشناس. می‌تواند ارسال نشود. |
| `parts` | بله | آرایه‌ای با حداقل یک ردیف قیمت‌گذاری. |
### فیلدهای هر ردیف `parts[i]`
| فیلد | الزامی | مقدار و قاعده |
| --- | --- | --- |
| `partId` | بله | عدد صحیح؛ باید متعلق به قطعات آسیب‌دیده همان پرونده باشد. |
| `typeOfDamage` | بله | دقیقاً یکی از `"تعمیر"` یا `"تعویض"`. |
| `price` | برای `"تعویض"` بله؛ برای `"تعمیر"` اختیاری | در صورت ارسال، مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `salary` | بله | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `totalPayment` | بله | مبلغ بین 100,000 تا 10,000,000,000 تومان. مجموع این فیلدها در کل پرونده نباید از 53,000,000 تومان بیشتر شود. |
| `factorNeeded` | بله | مقدار Boolean واقعی (`true` یا `false`)؛ رشته ارسال نکنید. |
| `daghi` | برای `"تعویض"` بله | برای `"تعمیر"` لازم نیست و در ثبت نهایی حذف می‌شود. |
| `daghi.option` | در صورت وجود `daghi` بله | یکی از `"ارزش لوازم بازیافتی"`، `"تحویل داغی"`، `"فاقد ارزش"` یا `"با احتساب داغی"`. |
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `daghi.branchId` | فقط وقتی `option` برابر `"تحویل داغی"` است | Mongo ObjectId معتبرِ شعبه. |
نکته‌ها:
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 100,000 تومان است.
- محدودیت 10 میلیارد مربوط به **هر فیلد مبلغ** است؛ سقف 53 میلیون مربوط به **مجموع `totalPayment` تمام ردیف‌ها** است و همچنان اعمال می‌شود.
- فیلدهای ناشناخته در body حذف می‌شوند. فرانت‌اند نباید برای انتقال داده به آن‌ها تکیه کند.
## پاسخ موفق
پاسخ `200` شامل مسیر بعدی workflow است. نمونه:
```json
{
"claimRequestId": "66c...",
"status": "COMPLETED",
"claimStatus": "APPROVED",
"currentStep": "CLAIM_COMPLETED",
"workflowNextStep": "CLAIM_COMPLETED",
"factorNeeded": false,
"mixedPricingAndFactors": false,
"allPartsFactorNeeded": false,
"isFinalReplyAfterObjection": false
}
```
مقادیر `status` و step به این وابسته‌اند که ردیف factor داشته باشید یا نه؛ فرانت‌اند باید از مقادیر پاسخ استفاده کند، نه اینکه مسیر بعدی را فقط از payload حدس بزند.
## قرارداد خطا
همه خطاهای این endpoint JSON هستند و NestJS مقدار `statusCode` را نیز به پاسخ اضافه می‌کند. برای نمایش پیام به کاربر از `message` استفاده کنید و برای منطق برنامه از `code` استفاده کنید؛ متن فارسی را با متن ثابت در فرانت‌اند جایگزین نکنید.
### 1. خطای ساختار DTO — `400`
برای نبودن فیلد الزامی، نوع اشتباه، enum نامعتبر، آرایه خالی، یا فرمت مبلغ نامعتبر، پاسخ زیر برمی‌گردد:
```json
{
"statusCode": 400,
"message": "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
"error": "EXPERT_REPLY_VALIDATION_ERROR",
"code": "EXPERT_REPLY_VALIDATION_ERROR",
"validationErrors": [
{
"field": "parts[0].salary",
"message": "باید مبلغ صحیح و غیرمنفی به تومان باشد."
},
{
"field": "parts[0].factorNeeded",
"message": "باید درست یا نادرست باشد."
}
]
}
```
`validationErrors` ممکن است چند خطا داشته باشد. کلید `field` دقیقاً برای اتصال به کنترل فرم است؛ مانند `parts[0].daghi.price` یا `parts[2].partId`.
### 2. خطای قواعد مبلغ و قیمت‌گذاری — `400`
این خطاها پس از اعتبارسنجی ساختار و پیش از تغییر وضعیت پرونده بررسی می‌شوند. برای مثال، مبلغ کمتر از حداقل:
```json
{
"statusCode": 400,
"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
}
```
`rule` یکی از این مقادیر است:
| مقدار | معنی |
| --- | --- |
| `required` | فیلد لازم ارسال نشده است. |
| `invalid_value` | مقدار enum یا شناسه معتبر نیست. |
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به تومان نیست. |
| `amount_out_of_range` | مبلغ خارج از بازه `minAmount` و `maxAmount` است. |
در صورت `amount_out_of_range`، برای نمایش محدوده از اعداد `minAmount` و `maxAmount` استفاده کنید، نه از parse کردن متن `message`.
### 3. سقف مجموع مبلغ‌ها — `400`
```json
{
"statusCode": 400,
"message": "مجموع مبلغ قطعات (۵۴٬۰۰۰٬۰۰۰) از سقف مجاز (۵۳٬۰۰۰٬۰۰۰) تومان بیشتر است.",
"error": "PRICE_CAP_ERROR",
"code": "PRICE_CAP_ERROR",
"totalPrice": 54000000,
"priceCap": 53000000
}
```
این خطا به یک ردیف مشخص وصل نیست. آن را در بالای جدول قیمت‌ها نمایش دهید و در صورت نیاز از `priceCap` برای پیام UI استفاده کنید.
### 4. خطاهای قواعد پرونده و workflow
این خطاها ساختار مشترک زیر را دارند:
```json
{
"statusCode": 400,
"message": "قطعه با شناسه 201 در فهرست قطعات آسیب‌دیده پرونده وجود ندارد.",
"error": "EXPERT_REPLY_SUBMISSION_ERROR",
"code": "PART_NOT_ON_CLAIM",
"field": "partId",
"partId": 201
}
```
کدهای مهم:
| HTTP | `code` | رفتار پیشنهادی فرانت‌اند |
| --- | --- | --- |
| 404 | `CLAIM_NOT_FOUND` | پیام خطا و بازگشت به فهرست پرونده‌ها. |
| 400 | `CLAIM_NOT_REVIEWABLE` | جزئیات پرونده را refresh کنید؛ ثبت در وضعیت فعلی مجاز نیست. |
| 403 | `CLAIM_NOT_LOCKED` | کاربر باید ابتدا پرونده را قفل کند. |
| 403 | `CLAIM_LOCKED_BY_ANOTHER_EXPERT` | فرم را read-only کنید و پیام مناسب نمایش دهید. |
| 400 | `PART_NOT_ON_CLAIM` | داده قطعات را refresh کنید و ردیف خطادار را اصلاح/حذف کنید. |
| 400 | `PART_INVALID` / `PART_ID_INVALID` | ردیف دارای `partId` را اصلاح کنید. |
| 400 | `DUPLICATE_PART` | ردیف تکراری را حذف کنید. |
| 400 | `DAGHI_OPTION_REQUIRED` | فیلد `daghi.option` همان ردیف را نشان‌دار کنید. |
| 400 | `DAGHI_PRICE_REQUIRED` | فیلد `daghi.price` همان ردیف را نشان‌دار کنید. |
| 400 | `DAGHI_BRANCH_REQUIRED` / `DAGHI_BRANCH_INVALID` | فیلد `daghi.branchId` همان ردیف را نشان‌دار کنید. |
| 409 | `FINAL_REPLY_ALREADY_SUBMITTED` | ثبت مجدد ممنوع است؛ داده پرونده را refresh کنید. |
برای خطاهای داغی که از سرویس برمی‌گردند، `field` به شکل `parts[<index>].daghi.<property>` است.
## الگوی پیشنهادی هندل کردن خطا در فرانت‌اند
```ts
type ApiErrorBody = {
message?: string;
code?: string;
field?: string;
validationErrors?: Array<{ field: string; message: string }>;
minAmount?: number;
maxAmount?: number;
priceCap?: number;
};
function applySubmitError(body: ApiErrorBody) {
if (body.validationErrors?.length) {
for (const issue of body.validationErrors) {
setFieldError(issue.field, issue.message);
}
return;
}
if (body.field) {
setFieldError(body.field, body.message ?? "مقدار واردشده معتبر نیست.");
return;
}
setFormError(body.message ?? "ثبت پاسخ کارشناسی انجام نشد.");
}
```
قبل از ارسال، فرانت‌اند می‌تواند همین بازه مبلغ را برای تجربه کاربری بهتر بررسی کند؛ با این حال اعتبار نهایی همیشه پاسخ API است. برای جلوگیری از خطای سقف مجموع، جمع `totalPayment` ردیف‌ها را نیز پیش از ارسال محاسبه و نمایش دهید.

View File

@@ -0,0 +1,237 @@
# راهنمای فرانت‌اند برای ارسال اطلاعات استعلام
این سند قرارداد نهایی فرانت‌اند برای مرحله استعلام است. از این به بعد اطلاعات اشخاص و خودرو باید با ساختار نقش‌محور زیر ارسال شود. فیلدهای تخت قدیمی مانند `nationalCodeOfDriver` و `nationalCodeOfInsurer` دیگر ورودی معتبر نیستند.
## پاسخ کوتاه درباره `unknown`
`unknown` فقط برای یک حالت استثنایی لازم است: وقتی در مرحله طرف زیان‌دیده یک پرونده `THIRD_PARTY`، هویت بیمه‌گذار شخص ثالث واقعاً مشخص نیست.
```json
{
"thirdPartyPolicyholder": { "unknown": true }
}
```
قواعد آن:
- فقط برای طرف زیان‌دیده (`SECOND`) مجاز است؛ برای طرف مقصر (`FIRST`) خطا برمی‌گردد.
- فقط برای `thirdPartyPolicyholder` مجاز است؛ برای راننده، مالک یا بیمه‌گذار بدنه مجاز نیست.
- وقتی `unknown: true` ارسال می‌شود، هیچ فیلد هویتی دیگری در همان آبجکت نفرستید.
- در استعلام شخص ثالث با پلاک یا VIN، استعلام بیمه‌گذار عمداً skip می‌شود و سیستم نباید کد ملی راننده یا مالک را جایگزین کند.
- استعلام‌های راننده، مالکیت خودرو و اطلاعات افراد شناخته‌شده همچنان اجرا می‌شوند.
- اگر هویت بیمه‌گذار مشخص است، اصلاً از `unknown` استفاده نکنید و اطلاعات واقعی یا `sameAs` را بفرستید.
## ساختار کلی درخواست
برای پرونده `THIRD_PARTY`:
```json
{
"driver": {
"nationalCode": "0012345678",
"birthday": "1370/01/01",
"hasDrivingLicense": true,
"licenseNumber": "123456789",
"licenseType": "1"
},
"vehicleOwner": { "sameAs": "DRIVER" },
"thirdPartyPolicyholder": { "sameAs": "VEHICLE_OWNER" },
"vehicle": {
"registrationState": "CURRENT",
"currentPlate": {
"leftDigits": "44",
"centerAlphabet": "ب",
"centerDigits": "111",
"ir": "22"
},
"isNewCar": false
},
"sheba": "IR123456789012345678901234"
}
```
برای پرونده `CAR_BODY`، نقش بیمه‌گذار بدنه هم الزامی است:
```json
{
"driver": {
"nationalCode": "0012345678",
"birthday": "1370/01/01",
"hasDrivingLicense": false
},
"vehicleOwner": { "sameAs": "DRIVER" },
"thirdPartyPolicyholder": {
"nationalCode": "0023456789",
"birthday": "1360/02/02"
},
"carBodyPolicyholder": {
"nationalCode": "0034567890",
"birthday": "1350/03/03"
},
"vehicle": {
"currentPlate": {
"leftDigits": "44",
"centerAlphabet": "ب",
"centerDigits": "111",
"ir": "22"
},
"isNewCar": false
},
"sheba": "IR123456789012345678901234"
}
```
`sheba` فقط در routeهایی که قبلاً اطلاعات بانکی را در مرحله استعلام دریافت می‌کردند ارسال می‌شود؛ در V6 مرکز تماس، شماره شبا در این body نیست و بعداً توسط کاربر دریافت می‌شود.
## هر استعلام با اطلاعات کدام نقش انجام می‌شود؟
فرانت‌اند فقط اشخاص را با ساختار نقش‌محور ارسال می‌کند؛ انتخاب کد ملی مناسب برای هر سرویس در بک‌اند انجام می‌شود:
| استعلام | کد ملی مورد استفاده | شناسه خودرو/بانکی |
| --- | --- | --- |
| بیمه شخص ثالث با پلاک یا VIN | `thirdPartyPolicyholder.nationalCode` | پلاک یا `vehicle.vin` |
| بیمه بدنه با پلاک یا VIN | `carBodyPolicyholder.nationalCode` | پلاک یا `vehicle.vin` |
| تطبیق شبا | `vehicleOwner.nationalCode` | `sheba` |
| گواهینامه | `driver.nationalCode` | `driver.licenseNumber` |
بنابراین کد ملی راننده نباید به‌جای بیمه‌گذار یا مالک ارسال یا تکرار شود. اگر چند نقش متعلق به یک نفر است، `sameAs` ارتباط را مشخص می‌کند و بک‌اند همان شخص را برای استعلام مربوط به هر نقش انتخاب می‌کند.
در مرحله بانکی بعدی جریان V6، برای پرونده‌های جدید فقط `sheba` لازم است. بک‌اند کد ملی مالک خودرو را از `participants` و `participantRoles` ذخیره‌شده در پرونده تقصیر می‌خواند. فیلدهای قدیمی `nationalCodeOfInsurer` یا `nationalCodeOfOwner` فقط برای پرونده‌های تاریخی فاقد اطلاعات نقش‌محور fallback هستند؛ اگر همراه پرونده جدید ارسال شوند باید با مالک ذخیره‌شده یکسان باشند.
پنل‌های کارشناسی اطلاعات کامل اشخاص را در `parties[].participants` و نگاشت نقش‌ها را در `parties[].participantRoles` دریافت می‌کنند. اطلاعات راننده حتی اگر در استعلام بیمه یا شبا استفاده نشود در همین ساختار ذخیره و نمایش داده می‌شود.
## نقش‌ها و فیلدهای هر شخص
هر نقش باید یکی از این دو حالت را داشته باشد، نه هر دو را:
1. اطلاعات یک شخص جدید؛ یا
2. ارجاع با `sameAs` به شخصی که قبلاً در همین درخواست معرفی شده است.
| فیلد | کاربرد | وضعیت |
| --- | --- | --- |
| `nationalCode` | کد ملی شخص | برای شخص جدید الزامی |
| `birthday` | تاریخ تولد جلالی | برای شخص جدید الزامی |
| `fullName` | نام نمایشی شخص | اختیاری |
| `sameAs` | اتصال این نقش به نقش دیگر | به‌جای اطلاعات شخص جدید |
| `unknown` | نامشخص بودن بیمه‌گذار ثالث | فقط `SECOND` در `THIRD_PARTY` |
| `hasDrivingLicense` | داشتن گواهینامه راننده | برای نقش راننده الزامی |
| `licenseNumber` | شماره گواهینامه | اگر `hasDrivingLicense=true` الزامی |
| `licenseType` | نوع گواهینامه | اگر `hasDrivingLicense=true` الزامی |
مقادیر مجاز `sameAs` عبارت‌اند از:
- `DRIVER`
- `VEHICLE_OWNER`
- `THIRD_PARTY_POLICYHOLDER`
- `CAR_BODY_POLICYHOLDER`
برای `sameAs` هیچ‌کدام از `nationalCode`، `birthday`، `fullName`، اطلاعات گواهینامه یا `phoneNumber` را در همان آبجکت نفرستید.
شماره تلفن بخشی از هویت استعلام نیست و در این DTOها وجود ندارد. احراز هویت پیامکی و شماره تماس طرفین از این مرحله جداست.
## اطلاعات خودرو و پلاک
| فیلد | کاربرد | وضعیت |
| --- | --- | --- |
| `vehicle.registrationState` | وضعیت ثبت رسمی خودرو | `CURRENT` یا `RECENTLY_TRANSFERRED`؛ پیش‌فرض `CURRENT` |
| `vehicle.currentPlate` | پلاک رسمی فعلی و شناسه اصلی خودرو | الزامی |
| `vehicle.previousPlate` | پلاک قبلی در انتقال اخیر | فقط در `RECENTLY_TRANSFERRED` |
| `vehicle.vin` | شماره شاسی/VIN | در انتقال اخیر الزامی؛ حداکثر ۱۷ کاراکتر |
| `vehicle.isNewCar` | نو بودن خودرو | اختیاری |
اجزای پلاک:
```json
{
"leftDigits": "44",
"centerAlphabet": "ب",
"centerDigits": "111",
"ir": "22"
}
```
`leftDigits`، `centerDigits` و `ir` را می‌توان به‌صورت string یا number فرستاد؛ ارسال string پیشنهاد می‌شود تا صفرهای ابتدایی از بین نروند. `centerAlphabet` باید حرف فارسی پلاک باشد.
### انتقال اخیر
```json
{
"vehicle": {
"registrationState": "RECENTLY_TRANSFERRED",
"currentPlate": {
"leftDigits": "44",
"centerAlphabet": "ب",
"centerDigits": "111",
"ir": "22"
},
"previousPlate": {
"leftDigits": "55",
"centerAlphabet": "ج",
"centerDigits": "222",
"ir": "33"
},
"vin": "NAAM01E15HK123456"
}
}
```
سیستم ابتدا پلاک فعلی را استعلام می‌کند. اگر نتیجه ناموجود، منقضی یا فاقد بیمه‌نامه مرتبط باشد، پلاک قبلی را امتحان می‌کند. نتیجه پلاک قبلی فقط در صورت تطبیق VIN پذیرفته می‌شود؛ پلاک قبلی هرگز جایگزین پلاک فعلی نمی‌شود.
حتی در route مربوط به VIN، آبجکت `vehicle` از قرارداد مشترک استفاده می‌کند و `currentPlate` در قرارداد فعلی الزامی است. مقدار VIN در `vehicle.vin` قرار می‌گیرد، نه در فیلد سطح بالای `vin`.
## ترتیب پیشنهادی نمایش فرم
1. پلاک فعلی و وضعیت انتقال خودرو را بگیرید.
2. اگر انتقال اخیر بود، پلاک قبلی و VIN را بگیرید.
3. اطلاعات راننده و وضعیت گواهینامه را بگیرید.
4. بپرسید مالک خودرو همان راننده است یا شخص دیگری؛ در حالت یکسان از `sameAs` استفاده کنید.
5. بیمه‌گذار شخص ثالث را از بین راننده، مالک یا شخص دیگر انتخاب کنید.
6. در `CAR_BODY` همین کار را برای بیمه‌گذار بدنه انجام دهید.
7. خلاصه اطلاعات را به کاربر نشان دهید و سپس درخواست استعلام را ارسال کنید.
## مسیرهای اصلی
بدنه درخواست در همه این مسیرها همین ساختار را دارد:
| جریان | مسیر پلاک | مسیر VIN |
| --- | --- | --- |
| کاربر V2 | `/v2/blame-request-management/initial-form/:requestId` | `/v2/blame-request-management/initial-form-vin/:requestId` |
| کارشناس/پرونده‌ساز V3 تا V5 | `.../run-inquiries/:requestId` | `.../run-inquiries-vin/:requestId` |
| مرکز تماس V6 | `/v6/call-center-blame/run-inquiry/:requestId` | `/v6/call-center-blame/run-inquiry-vin/:requestId` |
در جریان‌های V3 تا V5، فراخوان اول برای طرف مقصر (`FIRST`) و فراخوان دوم، فقط در `THIRD_PARTY`، برای طرف زیان‌دیده (`SECOND`) است. همین تفاوت تعیین می‌کند که `unknown` مجاز است یا نه.
## فیلدهایی که نباید ارسال شوند
این فیلدها دیگر بخشی از قرارداد ورودی نیستند و ارسال آن‌ها باعث خطای اعتبارسنجی می‌شود:
```text
nationalCodeOfDriver
driverBirthday
driverLicense
licenseType // در سطح بالا؛ مقدار صحیح داخل driver است
nationalCodeOfInsurer
insurerBirthday
insurerLicense
driverIsInsurer
userNoCertificate
plate // در سطح بالا؛ مقدار صحیح داخل vehicle.currentPlate است
plateId
vin // در سطح بالا؛ مقدار صحیح داخل vehicle.vin است
isNewCar // در سطح بالا؛ مقدار صحیح داخل vehicle.isNewCar است
phoneNumber // در participantها
```
## خطاهای رایج فرانت‌اند
- ارسال `vehicleOwner` به‌صورت خالی؛ باید شخص جدید یا `sameAs` باشد.
- استفاده از `sameAs` همراه با `nationalCode` یا `birthday`.
- ارسال `carBodyPolicyholder` برای `THIRD_PARTY`.
- ارسال `unknown` برای طرف مقصر یا برای نقشی غیر از بیمه‌گذار ثالث.
- فرستادن `previousPlate` بدون `registrationState=RECENTLY_TRANSFERRED`.
- فرستادن `RECENTLY_TRANSFERRED` بدون `previousPlate` یا `vin`.
- قرار دادن VIN یا پلاک در سطح بالای body.
- ارسال شماره تلفن در آبجکت شخص.
- تکرار کد ملی راننده یا بیمه‌گذار در مرحله شبا؛ تطبیق شبا همیشه با مالک خودرو انجام می‌شود.
مستند مدل دامنه و جزئیات تصمیم معماری در [inquiry-participants-proposal.fa.md](./inquiry-participants-proposal.fa.md) قرار دارد.

View File

@@ -0,0 +1,116 @@
# پیشنهاد مدل اشخاص در مرحله استعلام
وضعیت: پیاده‌سازی‌شده در ۱۴۰۵/۰۶/۲۲
دامنه: تمام جریان‌های استعلام کاربر، کارشناس، پرونده‌ساز و مرکز تماس
نسخه انگلیسی: [inquiry-participants-proposal.md](./inquiry-participants-proposal.md)
## interface پیاده‌سازی‌شده
فیلدهای نقش‌ها و آبجکت الزامی `vehicle` که در ادامه آمده‌اند، مستقیماً در body تمام درخواست‌های استعلام فعلی پذیرفته می‌شوند. این تغییر شامل فرم اولیه کاربر و mirror کارشناس/ثبت‌کننده در V2، جریان کارشناس V3، جریان‌های پرونده‌ساز V4/V5، مرکز تماس V6 و مسیرهای تک‌درخواستی حضوری است. routeهای پلاک و VIN از قوانین مشترک اشخاص استفاده می‌کنند. فیلدهای تخت راننده/بیمه‌گذار و شماره تلفن، ورودی استعلام نیستند.
پاسخ‌ها و جزئیات پرونده برای نقش‌های عملیاتی، در صورت وجود داده، فیلدهای نرمال‌شده `participants`، `participantRoles`، `vehicle.registrationState` و `vehicle.previousPlateId` را نمایش می‌دهند.
## مسئله
قرارداد فعلی استعلام عمدتاً فقط راننده و شخصی با عنوان `insurer` را نگه می‌دارد. این مدل کامل نیست و نام‌گذاری نیز دقیق نیست: شخص، **بیمه‌گذار** است و **بیمه‌گر** شرکت بیمه است.
برای هر وسیله نقلیه در یک `Party` نقش‌های هویتی زیر وجود دارد:
| نوع پرونده | نقش‌های الزامی |
| ------------- | ------------------------------------------------------------ |
| `THIRD_PARTY` | راننده، مالک وسیله نقلیه، بیمه‌گذار شخص ثالث |
| `CAR_BODY` | راننده، مالک وسیله نقلیه، بیمه‌گذار شخص ثالث، بیمه‌گذار بدنه |
ممکن است یک شخص چند نقش را داشته باشد، اما سیستم نباید یکسان بودن آن‌ها را فرض کند.
## پیشنهاد
پیش از اجرای استعلام، یک **مرحله کوتاه تعیین اشخاص** اضافه شود. ابتدا نسبت اشخاص پرسیده شود و اطلاعات فقط برای افراد متفاوت دریافت شود. دریافت بدون شرط اطلاعات کامل همه اشخاص مناسب نیست. همچنین افزودن فلگ‌های دوتایی متعدد مانند `driverIsOwner` و `ownerIsPolicyholder` باعث ابهام، تناقض و رشد سریع حالت‌ها می‌شود.
به‌جای آن، هر نقش یا اطلاعات یک شخص جدید را داشته باشد یا به نقش قبلی ارجاع دهد:
```json
{
"driver": {
"nationalCode": "0012345678",
"birthday": "1370/01/01",
"hasDrivingLicense": true,
"licenseNumber": "123456789",
"licenseType": "1"
},
"vehicleOwner": { "sameAs": "DRIVER" },
"thirdPartyPolicyholder": { "sameAs": "VEHICLE_OWNER" },
"carBodyPolicyholder": {
"nationalCode": "0098765432",
"birthday": "1365/02/03"
}
}
```
فیلد `carBodyPolicyholder` برای `THIRD_PARTY` مجاز نیست و برای `CAR_BODY` الزامی است. هر نقش باید فقط یکی از دو حالت «اطلاعات شخص» یا `sameAs` را داشته باشد. بک‌اند این ورودی را به فهرست اشخاص یکتا و اتصال نقش‌ها به آن‌ها تبدیل می‌کند.
فقط برای طرف زیان‌دیده در پرونده `THIRD_PARTY` می‌توان نامشخص بودن بیمه‌گذار را به‌صورت صریح با `"thirdPartyPolicyholder": { "unknown": true }` ارسال کرد. این حالت برای طرف مقصر پذیرفته نمی‌شود. استعلام بیمه شخص ثالث با پلاک یا VIN ــ چون هر دو به کد ملی بیمه‌گذار نیاز دارند ــ به‌شکل قابل‌ممیزی «عمداً اجرا نشد» ثبت می‌شود و بک‌اند نباید کد ملی راننده یا مالک را جایگزین کند. اعتبارسنجی راننده و مالک و استعلام‌های هویت، مالکیت و گواهینامه همچنان انجام می‌شوند.
برای راننده، `hasDrivingLicense` الزامی است. اگر مقدار آن `true` باشد، هر دو فیلد `licenseNumber` و `licenseType` نیز الزامی هستند؛ اگر مقدار آن `false` باشد، استعلام گواهینامه عمداً اجرا نمی‌شود.
## انتقال مالکیت اخیر و پلاک قبلی
نقش اشخاص و شناسه‌های خودرو دو موضوع جدا هستند. اگر خودرو به‌تازگی فروخته یا خریداری شده باشد، ممکن است اطلاعات رسمی یا بیمه‌نامه هنوز به پلاک قبلی متصل باشد. این وضعیت باید صریح ثبت شود و پلاک قبلی نباید جایگزین پلاک فعلی شود:
```json
{
"vehicle": {
"registrationState": "RECENTLY_TRANSFERRED",
"currentPlate": {
"leftDigits": "44",
"centerAlphabet": "ب",
"centerDigits": "111",
"ir": "22"
},
"previousPlate": {
"leftDigits": "55",
"centerAlphabet": "ج",
"centerDigits": "222",
"ir": "33"
},
"vin": "NAAM01E15HK123456"
}
}
```
مقدار پیش‌فرض `registrationState` برابر `CURRENT` است و برای این مسیر استثنایی مقدار `RECENTLY_TRANSFERRED` استفاده می‌شود. `previousPlate` فقط در حالت انتقال اخیر الزامی است. پلاک فعلی همچنان شناسه اصلی خودرو است. هماهنگ‌کننده استعلام باید ابتدا پلاک فعلی را بررسی کند و اگر نتیجه ناموجود، قدیمی یا فاقد بیمه‌نامه مرتبط بود، پلاک قبلی را به‌صورت خودکار استعلام کند.
پیش از پذیرش نتیجه پلاک قبلی، بک‌اند باید یکسان بودن VIN/شماره شاسی را بررسی کند. در صورت مغایرت، انتخاب خودکار متوقف و اصلاح اطلاعات یا بررسی دستی الزامی شود. هر دو پلاک و تمام تلاش‌های استعلام برای ممیزی نگه‌داری شوند، اما پلاک قبلی هیچ‌گاه نباید روی پلاک فعلی نوشته شود.
## ترتیب پیشنهادی فرم
1. پلاک فعلی دریافت و درباره انتقال مالکیت اخیر پرسیده شود. در صورت انتقال اخیر، پلاک قبلی و VIN/شماره شاسی نیز دریافت شوند.
2. اطلاعات هویتی و گواهینامه راننده دریافت شود.
3. پرسیده شود آیا مالک خودرو همان راننده است؛ فقط در صورت تفاوت، اطلاعات مالک دریافت شود.
4. برای بیمه‌گذار شخص ثالث یکی از «راننده»، «مالک» یا «شخص دیگر» انتخاب شود؛ فقط برای شخص دیگر فرم جدید نمایش داده شود.
5. در `CAR_BODY` همین انتخاب برای بیمه‌گذار بدنه انجام شود و امکان انتخاب هر شخص ثبت‌شده یا شخص دیگر وجود داشته باشد.
6. خلاصه اشخاص نمایش داده شود و سپس استعلام‌ها اجرا شوند.
به این ترتیب مسیر رایج کوتاه می‌ماند و همه ترکیب‌های معتبر نیز پشتیبانی می‌شوند.
## محل منطق در بک‌اند
یک resolver مشترک برای اشخاص ساخته شود و تمام routeهای استعلام از آن استفاده کنند. interface این ماژول باید:
- نقش‌های لازم را بر اساس نوع پرونده اعتبارسنجی و ارجاع‌های نامعتبر یا حلقوی `sameAs` را رد کند؛
- شخص نهایی هر نقش را برگرداند؛
- هویت درست را به استعلام مرتبط بدهد: گواهینامه ← راننده، مالکیت و تطبیق شبا ← مالک خودرو، بیمه شخص ثالث با پلاک/VIN ← بیمه‌گذار شخص ثالث، بیمه بدنه با پلاک/VIN ← بیمه‌گذار بدنه؛
- بر اساس یک قاعده مشخص، پلاک فعلی یا قبلی را انتخاب و نتیجه پلاک قبلی را با VIN/شماره شاسی تطبیق دهد؛
- استعلام هویت را برای هر شخص یکتا فقط یک بار اجرا کند؛
- اشخاص نرمال‌شده و نقش‌های آن‌ها را در `Party` مربوط ذخیره کند.
- `participants` و `participantRoles` ذخیره‌شده را بدون حذف اطلاعات در جزئیات پرونده پنل‌های کارشناسی و پرونده خسارت متصل نمایش دهد تا اطلاعات راننده و سایر نقش‌ها برای بررسی در دسترس بماند.
جریان‌های V2 کاربر/کارشناس، V3، V4، V5 و V6 باید adapter همین قوانین مشترک باشند و منطق نسبت اشخاص را جداگانه پیاده‌سازی نکنند.
## مرز قرارداد
ورودی استعلام فقط شامل آبجکت‌های ساختاریافته اشخاص و خودرو است. بک‌اند فیلدهای تختی مانند `nationalCodeOfDriver`، `nationalCodeOfInsurer`، `driverIsInsurer`، `plate`/`vin` سطح بالا و `phoneNumber` را با خطای اعتبارسنجی رد می‌کند. احراز هویت تلفنی و جریان‌های تماس با طرفین از جمع‌آوری هویت برای استعلام جدا هستند.
## تصمیم پیشنهادی
راه‌حل مناسب، **دریافت شرطی اطلاعات همراه با اتصال صریح نقش‌ها** است. این روش بدون طولانی کردن مسیر اکثر کاربران، اطلاعات کامل فراهم می‌کند، از تناقض فلگ‌ها جلوگیری می‌کند و یک مدل یکسان برای همه جریان‌های استعلام می‌سازد.

View File

@@ -0,0 +1,116 @@
# Inquiry participant identity proposal
Status: implemented on 2026-09-13
Scope: every user, expert, FileMaker, and call-center inquiry flow
Persian version: [inquiry-participants-proposal.fa.md](./inquiry-participants-proposal.fa.md)
## Implemented interface
The role fields and required `vehicle` object shown below are accepted directly in every existing inquiry request body. This covers V2 user and expert/registrar mirror initial forms, V3 expert flow, V4/V5 FileMaker flows, V6 call-center flow, and the one-shot in-person completion paths. Plate and VIN routes share the same participant rules. Flat driver/insurer fields and phone numbers are not inquiry inputs.
Responses and file-detail views for operational actors expose normalized `participants`, `participantRoles`, `vehicle.registrationState`, and `vehicle.previousPlateId` where available.
## Problem
The current inquiry contract mainly models a driver and a value named `insurer`. That is incomplete and the name is misleading: a person is the **policyholder**; the **insurer** is the insurance company.
Each vehicle-side `Party` can have these identity roles:
| Case type | Required roles |
| ------------- | ---------------------------------------------------------------------- |
| `THIRD_PARTY` | Driver, vehicle owner, third-party policyholder |
| `CAR_BODY` | Driver, vehicle owner, third-party policyholder, car-body policyholder |
One person may hold several roles, but the system must not assume that they do.
## Recommendation
Add a short **participant-identification step before inquiry**. Ask relationship questions and collect details only for distinct people. Do not ask for every person's complete data unconditionally, and do not add pairwise flags such as `driverIsOwner`, `ownerIsPolicyholder`, and `driverIsBodyPolicyholder`; that becomes ambiguous and grows combinatorially.
Use explicit role references instead:
```json
{
"driver": {
"nationalCode": "0012345678",
"birthday": "1370/01/01",
"hasDrivingLicense": true,
"licenseNumber": "123456789",
"licenseType": "1"
},
"vehicleOwner": { "sameAs": "DRIVER" },
"thirdPartyPolicyholder": { "sameAs": "VEHICLE_OWNER" },
"carBodyPolicyholder": {
"nationalCode": "0098765432",
"birthday": "1365/02/03"
}
}
```
`carBodyPolicyholder` is forbidden for `THIRD_PARTY` and required for `CAR_BODY`. A role is either a new person's identity or a `sameAs` reference, never both. The backend should normalize this input into unique participants plus role assignments.
For the damaged party of a `THIRD_PARTY` case only, the policyholder can be explicitly unresolved with `"thirdPartyPolicyholder": { "unknown": true }`. This is not accepted for the guilty party. Third-party-policy inquiry by either plate or VIN is recorded as intentionally skipped because both routes require the policyholder national code; the backend must not substitute the driver or owner. The driver, owner, personal, ownership, and licence rules remain enforced.
For Driver, `hasDrivingLicense` is required. When it is `true`, both `licenseNumber` and `licenseType` are required; when it is `false`, the licence inquiry is intentionally skipped.
## Recent ownership transfer and previous plate
Participant roles and vehicle identifiers are separate concerns. When a vehicle has recently been sold or purchased, the current official record or policy may still be connected to its previous plate. Model this explicitly instead of replacing the current plate:
```json
{
"vehicle": {
"registrationState": "RECENTLY_TRANSFERRED",
"currentPlate": {
"leftDigits": "44",
"centerAlphabet": "ب",
"centerDigits": "111",
"ir": "22"
},
"previousPlate": {
"leftDigits": "55",
"centerAlphabet": "ج",
"centerDigits": "222",
"ir": "33"
},
"vin": "NAAM01E15HK123456"
}
}
```
`registrationState` is `CURRENT` by default or `RECENTLY_TRANSFERRED` for this exceptional path. `previousPlate` is required only when `registrationState=RECENTLY_TRANSFERRED`. The current plate remains the vehicle's primary identifier. The inquiry orchestrator should query the current plate first and automatically try the previous plate when the current result is missing, stale, or does not find the relevant policy.
Before accepting a previous-plate result, the backend must correlate it to the same VIN/chassis. A mismatch must stop automatic selection and require correction or manual review. Both identifiers and every attempted inquiry should be retained for audit, but a previous plate must never overwrite the current plate.
## Suggested UI sequence
1. Collect the current plate and ask whether the vehicle was recently transferred. If yes, collect the previous plate and VIN/chassis.
2. Collect driver identity and licence details.
3. Ask whether the vehicle owner is the driver; collect owner identity only when different.
4. Ask whether the third-party policyholder is the driver, the owner, or another person; collect identity only for “another person”.
5. For `CAR_BODY`, ask the same question for the car-body policyholder, allowing any already entered person or another person.
6. Show a short review, then run the inquiries.
This keeps the common case fast while representing all valid combinations.
## Backend seam
Create one shared participant resolver used by every inquiry route. Its interface should:
- validate required roles by case type and reject circular/invalid `sameAs` references;
- return the resolved person for each role;
- route the correct identity to each inquiry: driver licence → Driver, ownership and Sheba validation → Vehicle Owner, third-party policy by plate/VIN → Third-party Policyholder, car-body policy by plate/VIN → Car-body Policyholder;
- choose the current or previous plate deterministically and verify previous-plate results against VIN/chassis;
- run personal identity inquiry once per distinct person;
- persist normalized participants and role assignments on the relevant `Party`.
- expose the persisted `participants` and `participantRoles` unchanged in expert-facing blame and linked-claim details so driver and other role data remain available for review.
V2 user/expert routes, V3, V4, V5, and V6 should be adapters over this shared rule set rather than implementing their own relationship logic.
## Contract boundary
The structured participant and vehicle objects are the only accepted inquiry input. The backend rejects flat fields such as `nationalCodeOfDriver`, `nationalCodeOfInsurer`, `driverIsInsurer`, top-level `plate`/`vin`, and `phoneNumber` with a validation error. Phone-based authentication and party contact flows remain separate from inquiry identity collection.
## Decision
Prefer **conditional collection plus explicit role assignments**. It provides complete data without burdening most users, prevents contradictory booleans, and gives all inquiry flows one consistent domain model.

View File

@@ -0,0 +1,26 @@
# اطلاعات پنل‌ها و PDF
## مواردی که نبود و اضافه شد
- نام شخص در پنل‌های فلو ۴ و ۵
- کد ملی بیمه‌گذار و راننده در پنل‌های فلو ۴ و ۵
- مشخص‌بودن یکسان‌بودن راننده و بیمه‌گذار در فلو ۴ و ۵
- نوع، شماره و تاریخ گواهینامه در پنل‌های فلو ۴ و ۵
- تاریخ تولد بیمه‌گذار و راننده در پنل‌های فلو ۴ و ۵
- پلاک و VIN در پنل‌های فلو ۴ و ۵
- شماره شبا در پنل‌های فلو ۴ و ۵
- کدهای تکمیلی فناوران در پنل‌ها: بیمه‌نامه، راننده، نوع خودرو، نوع/نمونه پلاک، کاربری خودرو و شرکت بیمه
- نمایش نوع واقعی گواهینامه، مثل «پایه یک»، در PDF
## مواردی که از قبل وجود داشت
- نام و کد ملی افراد در پنل‌های کارشناس و بیمه‌گر
- کد ملی راننده، در صورت متفاوت‌بودن با بیمه‌گذار
- شماره شبا در پنل بیمه‌گر و PDF
- اطلاعات راننده در PDF، وقتی راننده با بیمه‌گذار متفاوت است
- پلاک خودرو در API؛ فرانت باید از `vehicle.plateId` بخواند
- کدهای اصلی فناوران: شماره خسارت، شماره پرونده، شناسه پرونده خسارت و شناسه کارشناسی
## موردی که هنوز نداریم
- `expedited` → در بک‌اند فیلد و قرارداد API ندارد.

View File

@@ -367,7 +367,7 @@
<tr><td><span class="method post">POST</span></td><td><code>v2/expert-claim/assign/:claimRequestId</code></td><td>Lock claim to this expert. Returns <code>assigned</code>, <code>already_assigned_to_you</code>, or 409.</td></tr>
<tr><td><span class="method get">GET</span></td><td><code>v2/expert-claim/request/:claimRequestId/price-drop</code></td><td>Price-drop context: severity labels, coefficient catalog, damaged parts + mapping, suggested car year from blame inquiry.</td></tr>
<tr><td><span class="method put">PUT</span></td><td><code>v2/expert-claim/request/:claimRequestId/price-drop</code></td><td>Calculate and persist price-drop: carPrice × yearCoeff × sumOfCoeffs ÷ 400.</td></tr>
<tr><td><span class="method put">PUT</span></td><td><code>v2/expert-claim/reply/submit/:claimRequestId</code></td><td>Submit damage assessment reply (priced parts list, daghi, branchId). Cap: total ≤ 53 000 000 Toman. A priced-only claim completes immediately; factor claims continue through factor collection/validation. No final owner signature or automatic Fanavaran submission.</td></tr>
<tr><td><span class="method put">PUT</span></td><td><code>v2/expert-claim/reply/submit/:claimRequestId</code></td><td>Submit damage assessment reply (priced parts list and daghi). <code>daghi.branchId</code> is used only with the <code>تحویل داغی</code> option. Cap: total ≤ 53 000 000 Toman. A priced-only claim completes immediately; factor claims continue through factor collection/validation. No final owner signature or automatic Fanavaran submission.</td></tr>
<tr><td><span class="method put">PUT</span></td><td><code>v2/expert-claim/reply/resend/:claimRequestId</code></td><td>Request user to resend documents/photos. One resend per claim lifecycle; returns 422 if already fulfilled.</td></tr>
<tr><td><span class="method patch">PATCH</span></td><td><code>v2/expert-claim/:claimRequestId/visit</code></td><td>Ask user to come in person. Unlocks claim, sets claimStatus to NEEDS_REVISION.</td></tr>
<tr><td><span class="method patch">PATCH</span></td><td><code>v2/expert-claim/validate-factors/:claimRequestId</code></td><td>Validate uploaded repair factor invoices. Approve or reject each factor line with totalPayment. Cap applies across all lines (≤ 53 000 000 Toman). Auto-completes when all lines are decided.</td></tr>
@@ -552,7 +552,7 @@
<tr><th style="width:70px">Method</th><th>Route</th><th>What it does</th></tr>
<tr><td><span class="method post">POST</span></td><td><code>create-from-blame/:blameId</code></td><td>Create claim from a completed blame file.</td></tr>
<tr><td><span class="method get">GET</span></td><td><code>outer-parts-catalog</code> / <code>car-other-part</code></td><td>Parts catalogs (outer body parts + other parts JSON).</td></tr>
<tr><td><span class="method get">GET</span></td><td><code>branches/:insuranceId</code></td><td>Insurer branch list (for branch selection in claim sign step).</td></tr>
<tr><td><span class="method get">GET</span></td><td><code>branches/:insuranceId</code></td><td>Insurer branch list for <code>daghi.branchId</code> when the expert selects the <code>تحویل داغی</code> option.</td></tr>
<tr><td><span class="method patch">PATCH</span></td><td><code>select-outer-parts/:claimId</code></td><td>Select outer damaged parts.</td></tr>
<tr><td><span class="method patch">PATCH</span></td><td><code>select-other-parts/:claimId</code></td><td>Select other damaged parts + bank info.</td></tr>
<tr><td><span class="method post">POST</span></td><td><code>upload-document/:claimId</code></td><td>Upload claim documents (licences, car card).</td></tr>

View File

@@ -0,0 +1,402 @@
# مستند فرانت‌اند API گزارش PDF پرونده
## هدف API
این API داده‌ی ساخت‌یافته‌ی لازم برای تولید PDF پرونده در پنل بیمه‌گر را برمی‌گرداند.
خروجی آن ترکیبی از اطلاعات پرونده‌ی تقصیر (`blame`) و پرونده‌ی خسارت (`claim`) است و طوری طراحی شده که فرانت‌اند بدون وابستگی به مدل‌های داخلی بک‌اند، فقط با `sections` و `fields` بتواند PDF را رندر کند.
---
## آدرس API
```http
GET /expert-insurer/files/:publicId/report
```
### پارامتر مسیر
- `publicId`: شناسه عمومی پرونده
---
## ساختار کلی پاسخ
```json
{
"title": "گزارش پرونده بیمه گر",
"publicId": "RPT832-00406",
"requestNo": "BL-RPT832-000406",
"sections": []
}
```
### فیلدهای سطح بالا
#### `title`
عنوان کلی گزارش.
#### `publicId`
شناسه عمومی پرونده.
#### `requestNo`
شماره درخواست، اگر در داده‌های پرونده موجود باشد.
#### `sections`
آرایه‌ای از سکشن‌های گزارش.
هر سکشن یک عنوان دارد و شامل تعدادی ردیف اطلاعات (`fields`) است.
---
## ساختار هر سکشن
```json
{
"title": "زمان‌بندی پرونده",
"fields": [
{
"label": "تاریخ و ساعت ثبت پرونده",
"value": "1405/06/02 07:02"
}
]
}
```
### `title`
عنوان فارسی سکشن، آماده‌ی نمایش در PDF.
### `fields`
لیست ردیف‌های اطلاعاتی همان سکشن.
---
## ساختار هر فیلد
```json
{
"label": "شماره بیمه‌نامه",
"value": "POL-12345"
}
```
### `label`
عنوان فارسی فیلد.
### `value`
مقدار فیلد.
برای نمایش مستقیم در PDF استفاده می‌شود.
---
## سکشن‌های ممکن در پاسخ
سکشن‌ها معمولاً با ترتیب زیر برمی‌گردند، ولی فرانت‌اند بهتر است به‌جای تکیه بر ایندکس آرایه، سکشن را با `title` پیدا کند:
1. `زمان‌بندی پرونده`
2. `مالک خودروی زیان دیده`
3. `مالک خودروی مقصر`
4. `راننده خودروی زیان دیده`
5. `بیمه شخص ثالث زیان‌دیده`
6. `بیمه بدنه زیان‌دیده`
7. `بیمه شخص ثالث مقصر`
8. `بیمه بدنه مقصر`
9. `اطلاعات خودروی زیان‌دیده`
10. `اطلاعات خودروی مقصر`
11. `اظهارات و اقرار زیان‌دیده`
12. `اظهارات و اقرار مقصر`
13. `کدهای فناوران`
14. `نتیجه ارزیابی`
15. `گزارش حادثه`
نکته:
- بعضی سکشن‌ها بسته به نوع پرونده ممکن است وجود نداشته باشند.
- در پرونده‌های بدنه (`CAR_BODY`) اگر طرفین عملاً یک نفر باشند، سکشن‌های مربوط به مقصر ممکن است حذف شوند.
- در پرونده‌های شخص ثالث (`THIRD_PARTY`) انتظار می‌رود اطلاعات هر دو طرف به‌صورت تفکیک‌شده برگردد.
---
# توضیح سکشن‌ها
## 1) `زمان‌بندی پرونده`
برای نمایش زمان‌های مهم پرونده.
فیلدهای مهم:
- `تاریخ و ساعت ثبت پرونده`
- `تاریخ و ساعت ثبت نتیجه ارزیابی`
نکته:
- این تاریخ‌ها در بک‌اند فرمت شده‌اند و آماده‌ی نمایش هستند.
---
## 2) `مالک خودروی زیان دیده`
اطلاعات مالک یا صاحب خودروی زیان‌دیده.
فیلدهای رایج:
- `نام`
- `شماره تلفن`
- `کد ملی`
- `تاریخ تولد`
- `شماره شبا`
نکته:
- `شماره شبا` معمولاً برای زیان‌دیده مهم است و ممکن است فقط در همین سکشن وجود داشته باشد.
---
## 3) `مالک خودروی مقصر`
اطلاعات مالک خودروی مقصر.
فیلدهای رایج:
- `نام`
- `شماره تلفن`
- `کد ملی`
- `تاریخ تولد`
نکته:
- این سکشن مخصوص پرونده‌های شخص ثالث اهمیت دارد تا اطلاعات مالک هر دو طرف در PDF موجود باشد.
---
## 4) `راننده خودروی زیان دیده`
اگر راننده با مالک/بیمه‌گذار متفاوت باشد، این سکشن برمی‌گردد.
فیلدهای رایج:
- `نام`
- `نوع گواهینامه`
- `تاریخ گواهینامه`
- `شماره تلفن`
- `کد ملی`
- `تاریخ تولد`
- `شماره گواهینامه`
نکته:
- اگر راننده و مالک یکی باشند، این سکشن ممکن است وجود نداشته باشد.
---
## 5) `بیمه شخص ثالث زیان‌دیده`
اطلاعات بیمه شخص ثالث طرف زیان‌دیده.
فیلدهای رایج:
- `شماره بیمه‌نامه`
- `شرکت بیمه`
- `تاریخ شروع بیمه‌نامه`
- `تاریخ پایان بیمه‌نامه`
- `سقف تعهد مالی`
- `پوشش‌ها`
---
## 6) `بیمه بدنه زیان‌دیده`
اطلاعات بیمه بدنه‌ی طرف زیان‌دیده.
فیلدهای رایج:
- `شماره بیمه‌نامه`
- `شرکت بیمه`
- `تاریخ شروع بیمه‌نامه`
- `تاریخ پایان بیمه‌نامه`
- `پوشش‌ها`
---
## 7) `بیمه شخص ثالث مقصر`
اطلاعات بیمه شخص ثالث طرف مقصر.
فیلدهای رایج:
- `شماره بیمه‌نامه`
- `شرکت بیمه`
- `تاریخ شروع بیمه‌نامه`
- `تاریخ پایان بیمه‌نامه`
- `سقف تعهد مالی`
- `پوشش‌ها`
---
## 8) `بیمه بدنه مقصر`
اطلاعات بیمه بدنه‌ی طرف مقصر.
فیلدهای رایج:
- `شماره بیمه‌نامه`
- `شرکت بیمه`
- `تاریخ شروع بیمه‌نامه`
- `تاریخ پایان بیمه‌نامه`
- `پوشش‌ها`
---
## 9) `اطلاعات خودروی زیان‌دیده`
جزئیات خودروی زیان‌دیده.
فیلدها می‌توانند شامل موارد زیر باشند:
- `خودرو / پلاک`
- `خودرو / نام خودرو`
- `خودرو / مدل خودرو`
- `خودرو / نوع خودرو`
- `VIN`
- `شماره موتور`
- `شماره شاسی`
- `رنگ اصلی`
- `رنگ فرعی`
- `سیستم`
- `تیپ`
- `کاربری`
- `ظرفیت`
- `تعداد سیلندر`
نکته:
- بسته به منبع داده، ممکن است بعضی فیلدها با برچسب‌های نزدیک به هم ولی از دو منبع مختلف برگردند.
---
## 10) `اطلاعات خودروی مقصر`
جزئیات خودروی طرف مقصر.
فیلدها مشابه سکشن خودروی زیان‌دیده هستند.
---
## 11) `اظهارات و اقرار زیان‌دیده`
اطلاعات مربوط به اظهارات طرف زیان‌دیده.
فیلدهای رایج:
- `نقش طرف`
- `نام`
- `ادعای خسارت`
- `پذیرش نظر کارشناس`
- `توضیحات طرف`
نکته:
- معمولاً `اقرار به تقصیر` برای زیان‌دیده نمایش داده نمی‌شود.
---
## 12) `اظهارات و اقرار مقصر`
اطلاعات مربوط به اظهارات طرف مقصر.
فیلدهای رایج:
- `نقش طرف`
- `نام`
- `اقرار به تقصیر`
- `پذیرش نظر کارشناس`
- `توضیحات طرف`
نکته:
- معمولاً `ادعای خسارت` برای مقصر نمایش داده نمی‌شود.
---
## 13) `کدهای فناوران`
کدها و شناسه‌های فنی مرتبط با پرونده در فناوران.
فیلدهای ممکن:
- `شماره پرونده فناوران`
- `کد پرونده فناوران`
- `کد کیس خسارت فناوران`
- `کد کارشناسی فناوران`
- `کد بیمه‌نامه فناوران`
- `کد راننده فناوران`
- `کد نوع خودرو فناوران`
- `کد شرکت بیمه فناوران`
---
## 14) `نتیجه ارزیابی`
اطلاعات نتیجه‌ی ارزیابی کارشناس خسارت.
فیلدهای مهم:
- `نتیجه ارزیابی`
- `کارشناس ارزیاب`
- `تاریخ و ساعت ثبت ارزیابی`
- `پاسخ / توضیحات کارشناس`
---
## 15) `گزارش حادثه`
خلاصه‌ی اطلاعات حادثه، وضعیت پرونده و برخی خروجی‌های کارشناسی.
فیلدهای رایج:
- `تاریخ حادثه`
- `ساعت حادثه`
- `کارشناس(ان)`
- `موقعیت (عرض و طول جغرافیایی)`
- `وضعیت آب و هوا`
- `وضعیت جاده`
- `وضعیت نور`
- `وضعیت مقصر`
- `وضعیت خسارت`
- `نظر کارشناس مقصر`
- `نحوه برخورد`
- `علت حادثه`
- `نوع حادثه`
- `توضیحات طرف`
---
## نکات مهم برای فرانت‌اند
### 1) فقط بر اساس `sections` و `fields` رندر کنید
ساختار اصلی خروجی این است:
```ts
response.sections[].title
response.sections[].fields[].label
response.sections[].fields[].value
```
---
### 2) به ایندکس سکشن‌ها وابسته نشوید
ممکن است بعضی سکشن‌ها در بعضی پرونده‌ها وجود نداشته باشند.
بهتر است سکشن را با `title` پیدا کنید.
---
### 3) نبودن بعضی سکشن‌ها طبیعی است
مثلاً:
- `راننده خودروی زیان دیده`
- سکشن‌های مربوط به مقصر در بعضی پرونده‌های بدنه
- بعضی داده‌های فناوران
---
### 4) مقدار `-` یعنی داده‌ای برای نمایش وجود نداشته
اگر سکشنی داده‌ی واقعی نداشته باشد، ممکن است فقط این مقدار را داشته باشد:
```json
{
"label": "اطلاعات",
"value": "-"
}
```
---
### 5) برچسب‌ها فارسی و آماده‌ی نمایش هستند
فیلدهای `title` و `label` نیازی به ترجمه‌ی مجدد در فرانت‌اند ندارند.
---
## نمونه‌ی ساده‌ی رندر در فرانت‌اند
```ts
for (const section of response.sections) {
renderSectionTitle(section.title)
for (const field of section.fields) {
renderRow(field.label, field.value ?? "-")
}
}
```
---
## خلاصه
این API برای تولید PDF پرونده، داده‌ها را به‌صورت کامل و تفکیک‌شده برمی‌گرداند، از جمله:
- زمان‌بندی پرونده
- اطلاعات مالک زیان‌دیده
- اطلاعات مالک مقصر
- اطلاعات راننده در صورت متفاوت بودن
- بیمه‌نامه‌های تفکیک‌شده‌ی ثالث و بدنه برای هر طرف
- اطلاعات خودرو برای هر دو طرف
- اظهارات و اقرار هر دو طرف
- کدهای فناوران
- نتیجه ارزیابی و توضیحات کارشناس
- گزارش حادثه

View File

@@ -22,6 +22,8 @@
* SEED_REPORTS_TAG=reports-load-v1
* SEED_REPORTS_PUBLIC_PREFIX=RPT1
* SEED_REPORTS_DEFAULT_PASSWORD=Reports@724
* SEED_REPORTS_PURGE_ONLY=true # remove seeded data; do not insert it again
* SEED_REPORTS_PURGE_ALL=true # with PURGE_ONLY, remove every reports seed tag
*/
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
@@ -652,24 +654,31 @@ function randNationalBase(prefix: string): string {
return n.padEnd(6, "7");
}
async function purgeSeedPortfolio(db: mongoose.mongo.Db, seedTag: string) {
async function purgeSeedPortfolio(
db: mongoose.mongo.Db,
seedTag?: string,
) {
const blameCases = db.collection("blameCases");
const claimCases = db.collection("claimCases");
const expertFileActivities = db.collection("expertFileActivities");
const fixtureFilter = {
"seedMeta.script": SCRIPT_NAME,
...(seedTag ? { "seedMeta.tag": seedTag } : {}),
};
const [existingBlames, existingClaims] = await Promise.all([
blameCases.find({ "seedMeta.script": SCRIPT_NAME, "seedMeta.tag": seedTag }, { projection: { _id: 1 } }).toArray(),
claimCases.find({ "seedMeta.script": SCRIPT_NAME, "seedMeta.tag": seedTag }, { projection: { _id: 1 } }).toArray(),
blameCases.find(fixtureFilter, { projection: { _id: 1 } }).toArray(),
claimCases.find(fixtureFilter, { projection: { _id: 1 } }).toArray(),
]);
const fileIds = [...existingBlames, ...existingClaims].map((d) => asObjectId(d._id));
const [deletedBlames, deletedClaims, deletedActivities] = await Promise.all([
blameCases.deleteMany({ "seedMeta.script": SCRIPT_NAME, "seedMeta.tag": seedTag }),
claimCases.deleteMany({ "seedMeta.script": SCRIPT_NAME, "seedMeta.tag": seedTag }),
blameCases.deleteMany(fixtureFilter),
claimCases.deleteMany(fixtureFilter),
expertFileActivities.deleteMany({
$or: [
{ "seedMeta.script": SCRIPT_NAME, "seedMeta.tag": seedTag },
fixtureFilter,
...(fileIds.length ? [{ fileId: { $in: fileIds } }] : []),
],
}),
@@ -682,6 +691,32 @@ async function purgeSeedPortfolio(db: mongoose.mongo.Db, seedTag: string) {
};
}
/**
* The portfolio seed creates a shared synthetic roster and three report-only
* branches. Remove those too once no fixture portfolio remains, so a purge
* actually returns the insurer tenant to its pre-fixture state.
*/
async function purgeSeedSupportData(db: mongoose.mongo.Db) {
const collectionNames = [
"branches",
"expert",
"damage-expert",
"field-expert",
"file-maker",
"file-reviewer",
"call-center-agents",
];
const deleted = await Promise.all(
collectionNames.map(async (collectionName) => {
const result = await db
.collection(collectionName)
.deleteMany({ "seedMeta.script": SCRIPT_NAME });
return [collectionName, result.deletedCount ?? 0] as const;
}),
);
return Object.fromEntries(deleted);
}
function scaleBucketCounts(total: number): Record<UnifiedBucket, number> {
const keys = Object.keys(BUCKET_WEIGHTS) as UnifiedBucket[];
const raw = keys.map((key) => ({ key, exact: BUCKET_WEIGHTS[key] * total }));
@@ -2307,6 +2342,8 @@ async function main() {
const mongoUri = resolveMongoUri();
const count = Math.max(1, Number(process.env.SEED_REPORTS_COUNT?.trim() || "1000"));
const seedTag = process.env.SEED_REPORTS_TAG?.trim() || "reports-load-v1";
const purgeOnly = process.env.SEED_REPORTS_PURGE_ONLY?.trim() === "true";
const purgeAll = process.env.SEED_REPORTS_PURGE_ALL?.trim() === "true";
const publicPrefix =
process.env.SEED_REPORTS_PUBLIC_PREFIX?.trim() || `RPT${shortHash(seedTag, 3)}`;
const defaultPassword =
@@ -2325,6 +2362,29 @@ async function main() {
const clientLabel =
client?.clientName?.persian || client?.clientName?.english || String(client._id);
if (purgeOnly) {
const purge = await purgeSeedPortfolio(db, purgeAll ? undefined : seedTag);
const remainingPortfolio = await Promise.all([
db.collection("blameCases").countDocuments({ "seedMeta.script": SCRIPT_NAME }),
db.collection("claimCases").countDocuments({ "seedMeta.script": SCRIPT_NAME }),
]);
const supportData =
remainingPortfolio[0] + remainingPortfolio[1] === 0
? await purgeSeedSupportData(db)
: null;
console.log("\n=== Insurer reports seed purge complete ===");
console.log(`Client : ${clientLabel} (${clientId.toHexString()})`);
console.log(`Seed scope : ${purgeAll ? "all tags" : seedTag}`);
console.log(`Removed : ${purge.deletedBlames} blame, ${purge.deletedClaims} claim, ${purge.deletedActivities} activities`);
if (supportData) {
console.log("Support data :", supportData);
} else {
console.log("Support data : retained because other report-fixture portfolios remain");
}
return;
}
const rng = mulberry32(seedToInt(`${seedTag}:${clientId.toHexString()}:${count}`));
const passwordHash = await hashPassword(defaultPassword);
const branches = await ensureBranches(db, clientId, String(clientLabel));

View File

@@ -1,6 +1,5 @@
import { buildInsurerFileReport } from "./case-expert-report.builder";
import { PR } from "./persian-report-labels";
import { toJalaliDateAndTime } from "../helpers/date-jalali";
describe("buildInsurerFileReport", () => {
const getFieldValue = (
@@ -18,9 +17,6 @@ describe("buildInsurerFileReport", () => {
it("separates insurance blocks and exposes Fanavaran/timeline/evaluation data", () => {
const fileCreatedAt = new Date("2026-08-10T09:53:23.588Z");
const evaluationSubmittedAt = new Date("2026-08-10T12:30:45.000Z");
const [fileDate, fileTime] = toJalaliDateAndTime(fileCreatedAt);
const [evaluationDate, evaluationTime] =
toJalaliDateAndTime(evaluationSubmittedAt);
const report = buildInsurerFileReport({
overview: {
@@ -74,6 +70,26 @@ describe("buildInsurerFileReport", () => {
},
{
role: "SECOND",
participants: [
{
participantId: "DRIVER",
fullName: "راننده نمونه",
nationalCode: "0012345678",
birthday: "1370/01/01",
licenseNumber: "LIC-1",
},
{
participantId: "VEHICLE_OWNER",
fullName: "زیان دیده نمونه",
nationalCode: "1234567890",
birthday: "1370/01/01",
},
],
participantRoles: {
driver: "DRIVER",
vehicleOwner: "VEHICLE_OWNER",
thirdPartyPolicyholder: "VEHICLE_OWNER",
},
person: {
userId: "damaged-user-id",
fullName: "زیان دیده نمونه",
@@ -152,82 +168,298 @@ describe("buildInsurerFileReport", () => {
submittedAt: evaluationSubmittedAt,
description: "نیاز به تعویض سپر جلو",
actorDetail: { actorName: "کارشناس خسارت نمونه" },
parts: [
{
partId: 12,
carPartDamage: { label_fa: "سپر جلو" },
typeOfDamage: "تعویض",
price: 2_500_000,
salary: 500_000,
totalPayment: 3_000_000,
factorNeeded: false,
daghi: { option: "تحویل داغی" },
},
],
},
},
},
});
expect(getFieldValue(report, PR.ownerSection, PR.name)).toBe("زیان دیده نمونه");
expect(getFieldValue(report, PR.guiltyOwnerSection, PR.name)).toBe("مقصر نمونه");
expect(getFieldValue(report, PR.guiltyOwnerSection, PR.phone)).toBe("09120000000");
expect(getFieldValue(report, PR.ownerSection, PR.name)).toBe(
"زیان دیده نمونه",
);
expect(
getFieldValue(report, PR.damagedParticipantsSection, PR.driverRole),
).toContain("راننده نمونه");
expect(
getFieldValue(
report,
PR.damagedParticipantsSection,
PR.thirdPartyPolicyholderRole,
),
).toContain("1234567890");
expect(getFieldValue(report, PR.guiltyOwnerSection, PR.name)).toBe(
"مقصر نمونه",
);
expect(getFieldValue(report, PR.guiltyOwnerSection, PR.phone)).toBe(
"09120000000",
);
expect(getFieldValue(report, PR.guiltyOwnerSection, PR.nationalCode)).toBe(
"0987654321",
);
expect(getFieldValue(report, PR.damagedThirdPartyInsuranceSection, PR.policyNumber)).toBe(
"TP-DAMAGED-001",
);
expect(getFieldValue(report, PR.guiltyThirdPartyInsuranceSection, PR.policyNumber)).toBe(
"TP-GUILTY-001",
);
expect(getFieldValue(report, PR.damagedCarBodyInsuranceSection, PR.policyNumber)).toBe(
"CB-DAMAGED-001",
);
expect(getFieldValue(report, PR.guiltyCarBodyInsuranceSection, PR.policyNumber)).toBe(
"CB-GUILTY-001",
);
expect(getFieldValue(report, PR.damagedVehicleSection, "خودرو / نام خودرو")).toBe(
"207",
);
expect(getFieldValue(report, PR.guiltyVehicleSection, "خودرو / نام خودرو")).toBe(
"206",
);
expect(getFieldValue(report, PR.damagedStatementSection, PR.partyDescription)).toBe(
"توضیحات زیان‌دیده",
);
expect(getFieldValue(report, PR.damagedStatementSection, PR.claimsDamage)).toBe(
"بله",
);
expect(
getFieldValue(report, PR.damagedStatementSection, PR.acceptsExpertOpinion),
getFieldValue(
report,
PR.damagedThirdPartyInsuranceSection,
PR.policyNumber,
),
).toBe("TP-DAMAGED-001");
expect(
getFieldValue(
report,
PR.guiltyThirdPartyInsuranceSection,
PR.policyNumber,
),
).toBe("TP-GUILTY-001");
expect(
getFieldValue(report, PR.damagedCarBodyInsuranceSection, PR.policyNumber),
).toBe("CB-DAMAGED-001");
expect(
getFieldValue(report, PR.guiltyCarBodyInsuranceSection, PR.policyNumber),
).toBe("CB-GUILTY-001");
expect(
getFieldValue(report, PR.damagedVehicleSection, "خودرو / نام خودرو"),
).toBe("207");
expect(
getFieldValue(report, PR.guiltyVehicleSection, "خودرو / نام خودرو"),
).toBe("206");
expect(
getFieldValue(report, PR.damagedStatementSection, PR.partyDescription),
).toBe("توضیحات زیان‌دیده");
expect(
getFieldValue(report, PR.damagedStatementSection, PR.claimsDamage),
).toBe("بله");
expect(
getFieldValue(
report,
PR.damagedStatementSection,
PR.acceptsExpertOpinion,
),
).toBe("خیر");
expect(getFieldValue(report, PR.guiltyStatementSection, PR.partyDescription)).toBe(
"توضیحات مقصر",
);
expect(getFieldValue(report, PR.guiltyStatementSection, PR.admitsGuilt)).toBe(
"بله",
);
expect(
getFieldValue(report, PR.guiltyStatementSection, PR.partyDescription),
).toBe("توضیحات مقصر");
expect(
getFieldValue(report, PR.guiltyStatementSection, PR.admitsGuilt),
).toBe("بله");
expect(
getFieldValue(report, PR.guiltyStatementSection, PR.acceptsExpertOpinion),
).toBe("بله");
expect(getFieldValue(report, PR.fanavaranSection, PR.fanavaranClaimNo)).toBe(
"111",
);
expect(
getFieldValue(report, PR.fanavaranSection, PR.fanavaranClaimNo),
).toBe("111");
expect(
getFieldValue(report, PR.fanavaranSection, PR.fanavaranExpertiseId),
).toBe("444");
expect(getFieldValue(report, PR.fanavaranSection, PR.fanavaranPolicyId)).toBe(
"555",
);
expect(
getFieldValue(report, PR.fanavaranSection, PR.fanavaranPolicyId),
).toBe("555");
expect(getFieldValue(report, PR.timelineSection, PR.fileRegisteredAt)).toBe(
`${fileDate} ${fileTime}`,
"1405/05/19 13:23",
);
expect(
getFieldValue(report, PR.timelineSection, PR.evaluationRegisteredAt),
).toBe(`${evaluationDate} ${evaluationTime}`);
).toBe("1405/05/19 16:00");
expect(getFieldValue(report, PR.evaluationSection, PR.evaluationResult)).toBe(
"تأیید شده",
expect(
getFieldValue(report, PR.evaluationSection, PR.evaluationResult),
).toBe("تأیید شده");
expect(
getFieldValue(report, PR.evaluationSection, PR.evaluationExpert),
).toBe("کارشناس خسارت نمونه");
expect(
getFieldValue(report, PR.evaluationSection, PR.evaluationResponse),
).toBe("نیاز به تعویض سپر جلو");
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / نام قطعه")).toBe(
"سپر جلو",
);
expect(getFieldValue(report, PR.evaluationSection, PR.evaluationExpert)).toBe(
"کارشناس خسارت نمونه",
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
"۲٬۵۰۰٬۰۰۰ تومان",
);
expect(getFieldValue(report, PR.evaluationSection, PR.evaluationResponse)).toBe(
"نیاز به تعویض سپر جلو",
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / مبلغ کل")).toBe(
"۳٬۰۰۰٬۰۰۰ تومان",
);
});
it("localizes legacy English car-body environmental conditions", () => {
const report = buildInsurerFileReport({
overview: { publicId: "A00012" },
blame: {
type: "CAR_BODY",
parties: [
{
role: "FIRST",
person: { userId: "damaged", fullName: "بیمه‌گذار" },
statement: {
weatherCondition: "CLEAR",
roadCondition: "wet",
lightCondition: "LOW_LIGHT",
},
},
],
},
});
expect(getFieldValue(report, PR.accidentSection, PR.weather)).toBe("صاف");
expect(getFieldValue(report, PR.accidentSection, PR.road)).toBe("مرطوب");
expect(getFieldValue(report, PR.accidentSection, PR.light)).toBe("کم‌نور");
});
it("exposes the damage expert part-price result as a separate section", () => {
const report = buildInsurerFileReport({
overview: { publicId: "A00013" },
claim: {
claimStatus: "APPROVED",
evaluation: {
damageExpertReply: {
description: "تعویض قطعه ضروری است",
parts: [
{
carPartDamage: { label_fa: "چراغ جلو" },
price: 4_000_000,
totalPayment: 4_000_000,
},
],
},
},
},
});
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / نام قطعه")).toBe(
"چراغ جلو",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
"۴٬۰۰۰٬۰۰۰ تومان",
);
});
it("falls back to claim history for the evaluation submission time", () => {
const report = buildInsurerFileReport({
overview: { publicId: "A00014" },
claim: {
evaluation: {
damageExpertReply: { description: "ارزیابی ثبت شد" },
},
history: [
{
type: "EXPERT_REPLY_SUBMITTED",
timestamp: "2026-08-10T12:30:45.000Z",
},
],
},
});
expect(
getFieldValue(report, PR.timelineSection, PR.evaluationRegisteredAt),
).toBe("1405/05/19 16:00");
expect(
getFieldValue(report, PR.evaluationSection, PR.evaluationSubmittedAt),
).toBe("1405/05/19 16:00");
});
it("localizes every boolean value", () => {
const report = buildInsurerFileReport({
overview: { publicId: "A00015" },
blame: {
type: "CAR_BODY",
parties: [
{
role: "FIRST",
person: { userId: "damaged", fullName: "بیمه‌گذار" },
vehicle: {
isNew: true,
hasEndorsement: false,
source: "ESG_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
},
},
],
},
});
const fields = report.sections.flatMap((section) => section.fields);
expect(
fields.find((field) => field.label === "خودرو / خودرو نو")?.value,
).toBe("بله");
expect(fields.some((field) => field.value === "خیر")).toBe(true);
expect(fields.some((field) => field.value === "true")).toBe(false);
expect(fields.some((field) => field.value === "false")).toBe(false);
});
it("hides ESG and TEJARAT inquiry source details", () => {
const report = buildInsurerFileReport({
overview: { publicId: "A00016" },
blame: {
type: "CAR_BODY",
parties: [
{
role: "FIRST",
person: { userId: "damaged", fullName: "بیمه‌گذار" },
vehicle: {
source: "ESG_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
},
},
],
},
});
const fields = report.sections.flatMap((section) => section.fields);
expect(fields.some((field) => String(field.value).includes("ESG"))).toBe(
false,
);
expect(
fields.some((field) => String(field.value).includes("TEJARAT")),
).toBe(false);
expect(fields.some((field) => field.label.includes("منبع"))).toBe(false);
});
it("uses the stored V4 licence type for a driver who differs from the policyholder", () => {
const report = buildInsurerFileReport({
overview: { publicId: "A00011" },
blame: {
type: "THIRD_PARTY",
parties: [
{
role: "FIRST",
person: { userId: "guilty", fullName: "مقصر" },
},
{
role: "SECOND",
person: {
userId: "damaged",
fullName: "بیمه‌گذار زیان‌دیده",
driverIsInsurer: false,
nationalCodeOfDriver: "0123456789",
driverLicense: "L-123",
licenseType: "پایه یک",
},
},
],
expert: { decision: { guiltyPartyId: "guilty" } },
},
});
expect(getFieldValue(report, PR.driverSection, PR.nationalCode)).toBe(
"0123456789",
);
expect(getFieldValue(report, PR.driverSection, PR.licenseType)).toBe(
"پایه یک",
);
});
});

View File

@@ -9,7 +9,12 @@ import {
InsurerFileReportSection,
InsurerFileReportViewModel,
} from "./case-expert-report.types";
import { PR, persianFieldPath, persianStatus } from "./persian-report-labels";
import {
PR,
persianAccidentCondition,
persianFieldPath,
persianStatus,
} from "./persian-report-labels";
const SKIP_FLATTEN_KEYS = new Set([
"_id",
@@ -20,6 +25,7 @@ const SKIP_FLATTEN_KEYS = new Set([
"confirmation",
"inquiries",
"raw",
"source",
]);
type ReportRecord = Record<string, unknown>;
@@ -30,10 +36,13 @@ type ReportParty = ReportRecord & {
vehicle?: ReportRecord;
statement?: ReportRecord;
location?: { lat?: number; lon?: number };
participants?: ReportRecord[];
participantRoles?: ReportRecord;
};
function asString(value: unknown): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
if (typeof value === "boolean") return value ? "بله" : "خیر";
if (value instanceof Date) {
const [d, t] = toJalaliDateAndTime(value);
return `${d} ${t}`;
@@ -59,12 +68,39 @@ function formatBirthDate(value: unknown): string | undefined {
function formatDateTime(value: unknown): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
const date = value instanceof Date ? value : new Date(value as string | number);
const date =
value instanceof Date ? value : new Date(value as string | number);
if (Number.isNaN(date.getTime())) return asString(value);
const [d, t] = toJalaliDateAndTime(date);
return `${d} ${t}`;
}
const PERSIAN_NUMBER_FORMATTER = new Intl.NumberFormat("fa-IR", {
maximumFractionDigits: 0,
});
function normalizeNumber(value: unknown): number | undefined {
if (typeof value === "number") {
return Number.isFinite(value) ? value : undefined;
}
if (typeof value !== "string" || !value.trim()) return undefined;
const normalized = value
.trim()
.replace(/[۰-۹]/g, (digit) => String("۰۱۲۳۴۵۶۷۸۹".indexOf(digit)))
.replace(/[٠-٩]/g, (digit) => String("٠١٢٣٤٥٦٧٨٩".indexOf(digit)))
.replace(/[٬,\s]/g, "");
const parsed = Number(normalized);
return Number.isFinite(parsed) ? parsed : undefined;
}
function formatToman(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)} تومان`;
}
function firstDefined(...values: unknown[]): string | undefined {
for (const value of values) {
const str = asString(value);
@@ -93,13 +129,13 @@ function flattenObject(
if (Array.isArray(obj)) {
const value = normalizeListValue(obj);
return value
? [{ label: persianFieldPath(prefix || "items"), value }]
: [];
return value ? [{ label: persianFieldPath(prefix || "items"), value }] : [];
}
if (typeof obj !== "object") {
return [{ label: persianFieldPath(prefix || "value"), value: asString(obj) }];
return [
{ label: persianFieldPath(prefix || "value"), value: asString(obj) },
];
}
const rows: InsurerFileReportField[] = [];
@@ -127,7 +163,9 @@ function flattenObject(
return rows;
}
function dedupeFields(fields: InsurerFileReportField[]): InsurerFileReportField[] {
function dedupeFields(
fields: InsurerFileReportField[],
): InsurerFileReportField[] {
const seen = new Set<string>();
const out: InsurerFileReportField[] = [];
@@ -147,7 +185,8 @@ function filterEmptySections(
sections: Array<InsurerFileReportSection | undefined>,
): InsurerFileReportSection[] {
return sections.filter(
(section): section is InsurerFileReportSection => !!section && section.fields.length > 0,
(section): section is InsurerFileReportSection =>
!!section && section.fields.length > 0,
);
}
@@ -171,7 +210,9 @@ function expertNameFromSnapshot(snapshot?: {
lastName?: string;
}): string | undefined {
if (!snapshot) return undefined;
const name = [snapshot.firstName, snapshot.lastName].filter(Boolean).join(" ");
const name = [snapshot.firstName, snapshot.lastName]
.filter(Boolean)
.join(" ");
return name || undefined;
}
@@ -181,9 +222,8 @@ function collectExpertNames(
): string | undefined {
const names = new Set<string>();
const blameDecision = (
blame?.expert as Record<string, unknown> | undefined
)?.decision as Record<string, unknown> | undefined;
const blameDecision = (blame?.expert as Record<string, unknown> | undefined)
?.decision as Record<string, unknown> | undefined;
const blameExpert = expertNameFromSnapshot(
blameDecision?.expertProfileSnapshot as
| { firstName?: string; lastName?: string }
@@ -247,13 +287,16 @@ function resolveReportBlameContext(
(claim?.blameFileContext as Record<string, unknown> | undefined)
?.blameRequestType ??
(snapshot.accident as Record<string, unknown> | undefined)?.type,
blameStatus: (claim?.blameFileContext as Record<string, unknown> | undefined)
?.blameStatus,
blameStatus: (
claim?.blameFileContext as Record<string, unknown> | undefined
)?.blameStatus,
parties: snapshot.parties,
};
}
function getPartyRole(party: ReportParty | null | undefined): string | undefined {
function getPartyRole(
party: ReportParty | null | undefined,
): string | undefined {
const role = party?.role;
return typeof role === "string" ? role : undefined;
}
@@ -285,7 +328,8 @@ function sameParty(
second: ReportParty | null | undefined,
): boolean {
if (!first || !second) return false;
const firstUserId = first.person?.userId != null ? String(first.person.userId) : "";
const firstUserId =
first.person?.userId != null ? String(first.person.userId) : "";
const secondUserId =
second.person?.userId != null ? String(second.person.userId) : "";
if (firstUserId && secondUserId) return firstUserId === secondUserId;
@@ -297,11 +341,30 @@ function resolveEvaluationReply(
): Record<string, unknown> | undefined {
const evaluation = claim?.evaluation as Record<string, unknown> | undefined;
return (
(evaluation?.damageExpertReplyFinal as Record<string, unknown> | undefined) ??
(evaluation?.damageExpertReplyFinal as
| Record<string, unknown>
| undefined) ??
(evaluation?.damageExpertReply as Record<string, unknown> | undefined)
);
}
function resolveEvaluationSubmittedAt(
claim: Record<string, unknown> | null | undefined,
reply: Record<string, unknown> | undefined,
): unknown {
if (reply?.submittedAt != null) return reply.submittedAt;
const history = Array.isArray(claim?.history) ? claim.history : [];
const submittedEvent = [...history]
.reverse()
.find((event) =>
["EXPERT_REPLY_SUBMITTED", "EXPERT_FINAL_REPLY_SUBMITTED"].includes(
String((event as Record<string, unknown>)?.type ?? ""),
),
) as Record<string, unknown> | undefined;
return submittedEvent?.timestamp;
}
function insuranceValueFromCandidates(
...values: unknown[]
): string | undefined {
@@ -325,10 +388,18 @@ function buildThirdPartyInsuranceFields(
const role = getPartyRole(party);
const direct = (party?.insurance ?? {}) as Record<string, unknown>;
const blameInquiry = pickInquiryReportPayload(
inquiryRoleData(blame?.inquiries as Record<string, unknown> | undefined, "thirdParty", role),
inquiryRoleData(
blame?.inquiries as Record<string, unknown> | undefined,
"thirdParty",
role,
),
);
const claimInquiry = pickInquiryReportPayload(
inquiryRoleData(claim?.inquiries as Record<string, unknown> | undefined, "thirdParty", role),
inquiryRoleData(
claim?.inquiries as Record<string, unknown> | undefined,
"thirdParty",
role,
),
);
return [
@@ -412,12 +483,23 @@ function buildCarBodyInsuranceFields(
party?.insurance?.carBody ??
{}) as Record<string, unknown>;
const blameInquiry = pickInquiryReportPayload(
inquiryRoleData(blame?.inquiries as Record<string, unknown> | undefined, "carBody", role),
inquiryRoleData(
blame?.inquiries as Record<string, unknown> | undefined,
"carBody",
role,
),
);
const claimInquiry = pickInquiryReportPayload(
inquiryRoleData(claim?.inquiries as Record<string, unknown> | undefined, "carBody", role),
inquiryRoleData(
claim?.inquiries as Record<string, unknown> | undefined,
"carBody",
role,
),
);
const legacy = (blame?.carBodyInsuranceDetail ?? {}) as Record<string, unknown>;
const legacy = (blame?.carBodyInsuranceDetail ?? {}) as Record<
string,
unknown
>;
return [
{
@@ -506,7 +588,10 @@ function buildPartyOwnerSection(
{
label: PR.nationalCode,
value: options?.useClaimOwnerFallback
? firstDefined(person?.nationalCodeOfInsurer, money?.nationalCodeOfInsurer)
? firstDefined(
person?.nationalCodeOfInsurer,
money?.nationalCodeOfInsurer,
)
: firstDefined(person?.nationalCodeOfInsurer, person?.nationalCode),
},
{
@@ -522,9 +607,55 @@ function buildPartyOwnerSection(
]);
}
function licenseFieldsFromInquiry(
inquiry?: Record<string, unknown>,
): { licenseType?: string; licenseDate?: string } {
function buildParticipantRolesSection(
title: string,
party: ReportParty | null | undefined,
): InsurerFileReportSection | undefined {
const participants = Array.isArray(party?.participants)
? party.participants
: [];
const assignments = party?.participantRoles;
if (!assignments || participants.length === 0) return undefined;
const roleLabels: Record<string, string> = {
driver: PR.driverRole,
vehicleOwner: PR.vehicleOwnerRole,
thirdPartyPolicyholder: PR.thirdPartyPolicyholderRole,
carBodyPolicyholder: PR.carBodyPolicyholderRole,
};
const fields = Object.entries(assignments).map(([role, participantId]) => {
const participant = participants.find(
(candidate) => String(candidate.participantId) === String(participantId),
);
const value = participant?.unknown
? PR.unknown
: [
asString(participant?.fullName),
participant?.nationalCode
? `${PR.nationalCode}: ${asString(participant.nationalCode)}`
: undefined,
participant?.birthday
? `${PR.birthDate}: ${formatBirthDate(participant.birthday)}`
: undefined,
participant?.licenseNumber
? `${PR.licenseNumber}: ${asString(participant.licenseNumber)}`
: undefined,
]
.filter(Boolean)
.join("، ");
return {
label: roleLabels[role] ?? persianFieldPath(role),
value: value || PR.empty,
};
});
return buildSection(title, fields, false);
}
function licenseFieldsFromInquiry(inquiry?: Record<string, unknown>): {
licenseType?: string;
licenseDate?: string;
} {
if (!inquiry) return {};
return {
licenseType: firstDefined(
@@ -565,7 +696,10 @@ function buildDriverSection(
{ label: PR.name, value: asString(person.fullName) },
{
label: PR.licenseType,
value: licenseType ?? (person.driverLicense ? PR.driverLicense : undefined),
value:
licenseType ??
asString(person.licenseType) ??
(person.driverLicense ? PR.driverLicense : undefined),
},
{
label: PR.licenseDate,
@@ -647,7 +781,9 @@ function buildCaseTimelineSection(
},
{
label: PR.evaluationRegisteredAt,
value: formatDateTime(evaluationReply?.submittedAt),
value: formatDateTime(
resolveEvaluationSubmittedAt(claim, evaluationReply),
),
},
]);
}
@@ -656,10 +792,14 @@ function buildFanavaranCodesSection(
claim?: Record<string, unknown> | null,
): InsurerFileReportSection | undefined {
if (!claim) return undefined;
const sync = (claim.fanavaranSync as Record<string, unknown> | undefined) ?? {};
const baseClaim = (sync.baseClaim as Record<string, unknown> | undefined) ?? {};
const damageCase = (sync.damageCase as Record<string, unknown> | undefined) ?? {};
const expertise = (sync.expertise as Record<string, unknown> | undefined) ?? {};
const sync =
(claim.fanavaranSync as Record<string, unknown> | undefined) ?? {};
const baseClaim =
(sync.baseClaim as Record<string, unknown> | undefined) ?? {};
const damageCase =
(sync.damageCase as Record<string, unknown> | undefined) ?? {};
const expertise =
(sync.expertise as Record<string, unknown> | undefined) ?? {};
return buildSection(PR.fanavaranSection, [
{
@@ -672,7 +812,11 @@ function buildFanavaranCodesSection(
},
{
label: PR.fanavaranDamageCaseId,
value: firstDefined(claim.dmgCaseId, damageCase.dmgCaseId, expertise.dmgCaseId),
value: firstDefined(
claim.dmgCaseId,
damageCase.dmgCaseId,
expertise.dmgCaseId,
),
},
{
label: PR.fanavaranExpertiseId,
@@ -720,7 +864,7 @@ function buildEvaluationSection(
},
{
label: PR.evaluationSubmittedAt,
value: formatDateTime(reply?.submittedAt),
value: formatDateTime(resolveEvaluationSubmittedAt(claim, reply)),
},
{
label: PR.evaluationResponse,
@@ -729,6 +873,78 @@ function buildEvaluationSection(
]);
}
function evaluationPartName(part: ReportRecord): string | undefined {
const damage = part.carPartDamage;
if (damage && typeof damage === "object" && !Array.isArray(damage)) {
const record = damage as ReportRecord;
return firstDefined(
record.label_fa,
record.name,
record.part,
record.label,
part.partId != null ? `${PR.part} ${part.partId}` : undefined,
);
}
return firstDefined(
damage,
part.partName,
part.partId != null ? `${PR.part} ${part.partId}` : undefined,
);
}
function evaluationDaghiValue(value: unknown): string | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return asString(value);
}
const daghi = value as ReportRecord;
const option = asString(daghi.option);
const price = formatToman(daghi.price);
return [option, price].filter(Boolean).join(" - ") || undefined;
}
function buildEvaluationPartsSection(
claim?: Record<string, unknown> | null,
): InsurerFileReportSection | undefined {
const reply = resolveEvaluationReply(claim);
const parts = Array.isArray(reply?.parts)
? (reply.parts as ReportRecord[])
: [];
if (!parts.length) return undefined;
const fields = parts.flatMap((part, index) => {
const prefix = `${PR.part} ${PERSIAN_NUMBER_FORMATTER.format(index + 1)}`;
return [
{ label: `${prefix} / ${PR.partName}`, value: evaluationPartName(part) },
{
label: `${prefix} / ${PR.damageType}`,
value: asString(part.typeOfDamage),
},
{ label: `${prefix} / ${PR.partPrice}`, value: formatToman(part.price) },
{
label: `${prefix} / ${PR.repairSalary}`,
value: formatToman(part.salary),
},
{
label: `${prefix} / ${PR.totalPayment}`,
value: formatToman(part.totalPayment),
},
{
label: `${prefix} / ${PR.factorNeeded}`,
value:
typeof part.factorNeeded === "boolean"
? persianStatus(part.factorNeeded)
: undefined,
},
{
label: `${prefix} / ${PR.daghi}`,
value: evaluationDaghiValue(part.daghi),
},
];
});
return buildSection(PR.evaluationPartsSection, fields, false);
}
function buildAccidentReportSection(
blame?: Record<string, unknown> | null,
claim?: Record<string, unknown> | null,
@@ -739,10 +955,11 @@ function buildAccidentReportSection(
const snapshotAccident = (
claim?.snapshot as { accident?: Record<string, unknown> } | undefined
)?.accident;
const blameDecision = (
blame?.expert as Record<string, unknown> | undefined
)?.decision as Record<string, unknown> | undefined;
const decisionFields = blameDecision?.fields as Record<string, unknown> | undefined;
const blameDecision = (blame?.expert as Record<string, unknown> | undefined)
?.decision as Record<string, unknown> | undefined;
const decisionFields = blameDecision?.fields as
| Record<string, unknown>
| undefined;
return buildSection(PR.accidentSection, [
{
@@ -755,7 +972,8 @@ function buildAccidentReportSection(
},
{
label: PR.accidentTime,
value: asString(statement?.accidentTime) ?? asString(snapshotAccident?.time),
value:
asString(statement?.accidentTime) ?? asString(snapshotAccident?.time),
},
{
label: PR.experts,
@@ -770,21 +988,24 @@ function buildAccidentReportSection(
},
{
label: PR.weather,
value:
asString(statement?.weatherCondition) ??
asString(snapshotAccident?.weatherCondition),
value: persianAccidentCondition(
"weather",
statement?.weatherCondition ?? snapshotAccident?.weatherCondition,
),
},
{
label: PR.road,
value:
asString(statement?.roadCondition) ??
asString(snapshotAccident?.roadCondition),
value: persianAccidentCondition(
"road",
statement?.roadCondition ?? snapshotAccident?.roadCondition,
),
},
{
label: PR.light,
value:
asString(statement?.lightCondition) ??
asString(snapshotAccident?.lightCondition),
value: persianAccidentCondition(
"light",
statement?.lightCondition ?? snapshotAccident?.lightCondition,
),
},
{
label: PR.blameStatus,
@@ -798,7 +1019,8 @@ function buildAccidentReportSection(
{
label: PR.accidentWay,
value: asString(
(decisionFields?.accidentWay as { label?: string } | undefined)?.label ??
(decisionFields?.accidentWay as { label?: string } | undefined)
?.label ??
(
snapshotAccident?.classification as {
accidentWay?: { label?: string };
@@ -809,7 +1031,8 @@ function buildAccidentReportSection(
{
label: PR.accidentReason,
value: asString(
(decisionFields?.accidentReason as { label?: string } | undefined)?.label ??
(decisionFields?.accidentReason as { label?: string } | undefined)
?.label ??
(
snapshotAccident?.classification as {
accidentReason?: { label?: string };
@@ -820,7 +1043,8 @@ function buildAccidentReportSection(
{
label: PR.accidentType,
value: asString(
(decisionFields?.accidentType as { label?: string } | undefined)?.label ??
(decisionFields?.accidentType as { label?: string } | undefined)
?.label ??
(
snapshotAccident?.classification as {
accidentType?: { label?: string };
@@ -852,12 +1076,17 @@ export function buildInsurerFileReport(file: {
: null;
const isCarBody =
String((blameContext?.type as string | undefined) ?? "") === "CAR_BODY";
const includeGuiltySections = !!guiltyParty && !(isCarBody && sameParty(damagedParty, guiltyParty));
const includeGuiltySections =
!!guiltyParty && !(isCarBody && sameParty(damagedParty, guiltyParty));
const claimVehicle = claim?.vehicle as Record<string, unknown> | undefined;
const sections = filterEmptySections([
buildCaseTimelineSection(overview, claim),
buildParticipantRolesSection(PR.damagedParticipantsSection, damagedParty),
includeGuiltySections
? buildParticipantRolesSection(PR.guiltyParticipantsSection, guiltyParty)
: undefined,
buildPartyOwnerSection(PR.ownerSection, damagedParty, {
claim,
useClaimOwnerFallback: true,
@@ -887,7 +1116,11 @@ export function buildInsurerFileReport(file: {
buildCarBodyInsuranceFields(guiltyParty, blameContext, claim),
)
: undefined,
buildPartyVehicleSection(PR.damagedVehicleSection, damagedParty, claimVehicle),
buildPartyVehicleSection(
PR.damagedVehicleSection,
damagedParty,
claimVehicle,
),
includeGuiltySections
? buildPartyVehicleSection(PR.guiltyVehicleSection, guiltyParty)
: undefined,
@@ -907,6 +1140,7 @@ export function buildInsurerFileReport(file: {
: undefined,
buildFanavaranCodesSection(claim),
buildEvaluationSection(claim),
buildEvaluationPartsSection(claim),
buildAccidentReportSection(blameContext, claim, damagedParty),
]);

View File

@@ -5,6 +5,8 @@ export const PR = {
empty: "-",
ownerSection: "مالک خودروی زیان دیده",
guiltyOwnerSection: "مالک خودروی مقصر",
damagedParticipantsSection: "اشخاص و نقش‌های خودروی زیان‌دیده",
guiltyParticipantsSection: "اشخاص و نقش‌های خودروی مقصر",
driverSection: "راننده خودروی زیان دیده",
damagedThirdPartyInsuranceSection: "بیمه شخص ثالث زیان‌دیده",
damagedCarBodyInsuranceSection: "بیمه بدنه زیان‌دیده",
@@ -48,10 +50,24 @@ export const PR = {
evaluationExpert: "کارشناس ارزیاب",
evaluationSubmittedAt: "تاریخ و ساعت ثبت ارزیابی",
evaluationResponse: "پاسخ / توضیحات کارشناس",
evaluationPartsSection: "قیمت قطعات",
part: "قطعه",
partName: "نام قطعه",
damageType: "نوع خسارت",
partPrice: "قیمت قطعه",
repairSalary: "اجرت تعمیر",
totalPayment: "مبلغ کل",
factorNeeded: "نیازمند فاکتور",
daghi: "داغی",
admitsGuilt: "اقرار به تقصیر",
claimsDamage: "ادعای خسارت",
acceptsExpertOpinion: "پذیرش نظر کارشناس",
partyRole: "نقش طرف",
driverRole: "راننده",
vehicleOwnerRole: "مالک وسیله نقلیه",
thirdPartyPolicyholderRole: "بیمه‌گذار شخص ثالث",
carBodyPolicyholderRole: "بیمه‌گذار بدنه",
unknown: "نامشخص",
data: "اطلاعات",
date: "تاریخ",
time: "زمان",
@@ -194,6 +210,32 @@ const STATUS_LABELS: Record<string, string> = {
false: "خیر",
};
const WEATHER_LABELS: Record<string, string> = {
clear: "صاف",
sunny: "صاف",
rainy: "بارانی",
rain: "بارانی",
snowy: "برفی",
snow: "برفی",
foggy: "مه‌آلود",
fog: "مه‌آلود",
};
const ROAD_LABELS: Record<string, string> = {
muddy: "گلی",
icy: "یخ‌زده",
wet: "مرطوب",
dry: "خشک",
};
const LIGHT_LABELS: Record<string, string> = {
daylight: "روز",
day: "روز",
night: "شب",
low_light: "کم‌نور",
lowlight: "کم‌نور",
};
/** Turn `party.insurance.policyNumber` into a Persian label. */
export function persianFieldPath(path: string): string {
if (!path) return PR.data;
@@ -231,3 +273,19 @@ export function persianStatus(value: unknown): string | undefined {
const key = String(value);
return STATUS_LABELS[key] ?? key;
}
export function persianAccidentCondition(
kind: "weather" | "road" | "light",
value: unknown,
): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
const raw = String(value).trim();
const normalized = raw.toLowerCase().replace(/[\s-]+/g, "_");
const labels =
kind === "weather"
? WEATHER_LABELS
: kind === "road"
? ROAD_LABELS
: LIGHT_LABELS;
return labels[normalized] ?? raw;
}

View File

@@ -37,7 +37,6 @@ import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-managem
import { CarDamagePartDto, OtherCarDamagePartDto } from "./dto/car-part.dto";
import { UserCommentDto } from "./dto/user-comment.dto";
import { UserObjectionDto } from "./dto/user-objection.dto";
import { InPersonVisitDto } from "./dto/in-person-visit.dto";
import { UserRatingDto } from "./dto/user-rating.dto";
@ApiExcludeController()
@@ -464,29 +463,27 @@ export class ClaimRequestManagementController {
);
}
// @ApiBody({ type: InPersonVisitDto })
// @ApiParam({ name: "id" })
// @ApiOperation({ deprecated: true })
@Patch(":id/visit")
async inPersonVisit(
@Param("id") requestId: string,
@Body() body: InPersonVisitDto,
@CurrentUser() actor,
) {
// Pass the branchId from the body to the service
return await this.claimRequestManagementService.inPersonVisit(
requestId,
body.branchId,
actor,
);
return await this.claimRequestManagementService.inPersonVisit(requestId, actor);
}
// @ApiOperation({ deprecated: true })
@Get("branches/:insuranceId")
// @ApiParam({ name: "insuranceId" })
async insuranceBranches(@Param("insuranceId") insuranceId: string) {
return await this.claimRequestManagementService.retrieveInsuranceBranches(insuranceId);
}
// Legacy V1 owner branch picker — intentionally disabled.
// A claim is handled by an expert assigned to the insurer branch, so the
// owner must not choose an insurer branch while signing. This does not apply
// to the separate expert-only `daghi.branchId` choice in pricing flows.
//
// @Get("branches/:insuranceId")
// async insuranceBranches(@Param("insuranceId") insuranceId: string) {
// return await this.claimRequestManagementService.retrieveInsuranceBranches(
// insuranceId,
// );
// }
// @ApiOperation({ deprecated: true })
@Get("fanavaran-submit/:claimRequestId")

View File

@@ -78,6 +78,7 @@ import {
blameDamagedPartyMatchesUser,
resolveClaimOwnerFieldsFromBlame,
resolveClaimOwnerParty,
resolveDamagedPartyRow,
resolveDamagedPartyUserId,
} from "src/helpers/blame-damaged-party";
import { claimCaseInitiatedByFieldExpert } from "src/helpers/tenant-scope";
@@ -115,6 +116,8 @@ import { BranchDbService } from "src/client/entities/db-service/branch.db.servic
import { CreationMethod } from "src/request-management/entities/schema/request-management.schema";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { PartyRole } from "src/request-management/entities/schema/partyRole.enum";
import { InquiryParticipantRole } from "src/common/dto/inquiry-participants.dto";
import { participantForStoredPartyRole } from "src/request-management/inquiry-participant-resolver";
import { UserRatingDto } from "./dto/user-rating.dto";
import {
canFinalizeExpertResend,
@@ -622,6 +625,20 @@ export class ClaimRequestManagementService {
return this.parsePlateFromCompactString(compactPlateId);
}
private resolveVehicleOwnerNationalCodeForClaim(
blameRequest: any,
): string | undefined {
const damagedParty = resolveDamagedPartyRow(blameRequest as any);
const owner = damagedParty
? participantForStoredPartyRole(
damagedParty as any,
InquiryParticipantRole.VEHICLE_OWNER,
)
: undefined;
const nationalCode = String(owner?.nationalCode ?? "").trim();
return nationalCode || undefined;
}
private delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
@@ -2526,7 +2543,7 @@ export class ClaimRequestManagementService {
/**
* V2 response mapper:
* - convert factorLink ObjectId -> public URL
* - enrich daghi.branchId with branchName when available
* - enrich legacy daghi.branchId with branchName when available
*/
private async mapEvaluationForClient(
evaluation: any,
@@ -3381,29 +3398,17 @@ export class ClaimRequestManagementService {
return updated.objection;
}
async inPersonVisit(requestId: string, branchId: string, actorDetail: any) {
async inPersonVisit(requestId: string, actorDetail: any) {
const request =
await this.claimRequestManagementDbService.findOne(requestId);
if (!request) {
throw new NotFoundException("Claim not found");
}
const branch = await this.branchDbService.findById(branchId);
if (!branch) {
throw new NotFoundException(`Branch with ID ${branchId} not found.`);
}
if (String(request.userClientKey) !== String(branch.clientKey)) {
throw new ForbiddenException(
"This branch does not belong to the insurer of this claim.",
);
}
const updated = await this.claimRequestManagementDbService.findAndUpdate(
requestId,
{
claimStatus: ReqClaimStatus.InPersonVisit,
visitLocation: `Branch ${branch.name} at ${branch.address}`,
},
);
@@ -3523,27 +3528,6 @@ export class ClaimRequestManagementService {
return amount > 0 ? amount : FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT;
}
/** Branch ids referenced on expert-priced parts (`daghi` object with `branchId`). */
private collectBranchIdsFromClaimExpertReply(reply: {
parts?: unknown[];
}): Set<string> {
const ids = new Set<string>();
const parts = reply?.parts;
if (!Array.isArray(parts)) {
return ids;
}
for (const p of parts) {
const d = (p as { daghi?: unknown })?.daghi;
if (d && typeof d === "object" && d !== null && "branchId" in d) {
const bid = (d as { branchId?: unknown }).branchId;
if (bid != null && Types.ObjectId.isValid(String(bid))) {
ids.add(String(bid));
}
}
}
return ids;
}
private getTejaratnoFanavaranConfig() {
return {
appName: this.APP_NAME,
@@ -9228,7 +9212,7 @@ export class ClaimRequestManagementService {
const shebaDigits = shebaInput.replace(/^IR/i, "");
const shebaNumber = `IR${shebaDigits}`;
const nationalCode = String(
const submittedNationalCode = String(
((body as any).nationalCodeOfOwner ??
(body as any).nationalCodeOfInsurer ??
"") as string,
@@ -9238,17 +9222,28 @@ export class ClaimRequestManagementService {
"shebaNumber is required and must be valid (IR + 24 digits or only 24 digits)",
);
}
if (!/^[0-9]{10}$/.test(nationalCode)) {
throw new BadRequestException(
"nationalCodeOfOwner is required and must be exactly 10 digits",
);
}
const blameRequest = claimCase.blameRequestId
? await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
)
: null;
const storedOwnerNationalCode =
this.resolveVehicleOwnerNationalCodeForClaim(blameRequest);
if (
storedOwnerNationalCode &&
submittedNationalCode &&
submittedNationalCode !== storedOwnerNationalCode
) {
throw new BadRequestException(
"Submitted national code does not match the vehicle owner saved on the blame case.",
);
}
const nationalCode = storedOwnerNationalCode ?? submittedNationalCode;
if (!/^[0-9]{10}$/.test(nationalCode)) {
throw new BadRequestException(
"Vehicle owner national code is unavailable; a 10-digit nationalCodeOfOwner is required only for legacy claims.",
);
}
const ownershipPlate = this.resolveOwnershipPlateForClaim(
claimCase,
blameRequest,
@@ -11012,7 +11007,6 @@ export class ClaimRequestManagementService {
async submitOwnerInsurerApprovalSignV2(
claimRequestId: string,
agree: boolean,
branchId: string,
signFile: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string; fullName?: string },
@@ -11072,12 +11066,6 @@ export class ClaimRequestManagementService {
}
const shape = classifyV2ExpertPricingParts(active.parts ?? []);
const pricedBranchReply = {
parts: (active.parts ?? []).filter(
(p: { factorNeeded?: boolean }) => !p.factorNeeded,
),
};
const isMixedPartialGate =
shape.mixedFactorAndPrice &&
claimCase.claimStatus === ClaimStatus.NEEDS_REVISION &&
@@ -11112,39 +11100,6 @@ export class ClaimRequestManagementService {
);
}
const rawBranchId = (branchId ?? "").trim();
if (!rawBranchId || !Types.ObjectId.isValid(rawBranchId)) {
throw new BadRequestException(
"branchId is required and must be a valid MongoDB ObjectId.",
);
}
const branchDoc = await this.branchDbService.findById(rawBranchId);
if (!branchDoc) {
throw new NotFoundException(`Branch with ID ${rawBranchId} not found.`);
}
const ownerClientId = claimCase.owner?.clientId;
if (
!ownerClientId ||
String(branchDoc.clientKey) !== String(ownerClientId)
) {
throw new ForbiddenException(
"This branch does not belong to the insurer for this claim.",
);
}
const branchIdsOnPricing = isMixedPartialGate
? this.collectBranchIdsFromClaimExpertReply(pricedBranchReply)
: this.collectBranchIdsFromClaimExpertReply(
active as { parts?: unknown[] },
);
if (
branchIdsOnPricing.size > 0 &&
!branchIdsOnPricing.has(String(rawBranchId))
) {
throw new BadRequestException(
"branchId must match a branch used in the expert pricing for this claim.",
);
}
const signDoc = await this.claimSignDbService.create({
fileName: signFile.filename,
userId: effectiveUserId,
@@ -11155,7 +11110,6 @@ export class ClaimRequestManagementService {
const signedAt = new Date();
const scopedApprovalPayload = {
agree,
branchId: new Types.ObjectId(rawBranchId),
signDetailId: signId,
signedAt,
};
@@ -11181,7 +11135,7 @@ export class ClaimRequestManagementService {
type: "OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS",
actor: historyActor,
timestamp: signedAt,
metadata: { branchId: rawBranchId },
metadata: {},
},
},
});
@@ -11210,7 +11164,7 @@ export class ClaimRequestManagementService {
type: "OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD",
actor: historyActor,
timestamp: signedAt,
metadata: { branchId: rawBranchId },
metadata: {},
},
},
});
@@ -11241,7 +11195,7 @@ export class ClaimRequestManagementService {
type: "OWNER_REJECTED_INSURER_APPROVAL_PRICING",
actor: historyActor,
timestamp: signedAt,
metadata: { branchId: rawBranchId },
metadata: {},
},
},
});
@@ -11275,7 +11229,7 @@ export class ClaimRequestManagementService {
type: "OWNER_SIGNED_INSURER_APPROVAL",
actor: historyActor,
timestamp: signedAt,
metadata: { branchId: rawBranchId },
metadata: {},
},
},
});

View File

@@ -335,16 +335,16 @@ export class ClaimRequestManagementV2Controller {
@ApiOperation({
summary: "Sign priced lines before factor uploads (owner; final phase is legacy only)",
description:
"Multipart: `sign`, `agree`, `branchId`. Requires `ClaimCaseStatus` **`INSURER_REVIEW_AWAITING_OWNER_SIGN`**, **`INSURER_REVIEW_MIXED_FACTORS_PENDING`**, or legacy **`WAITING_FOR_INSURER_APPROVAL`**, and `workflow.currentStep=INSURER_REVIEW` (not during owner factor upload or `EXPERT_COST_EVALUATION`).\n\n" +
"Multipart: `sign`, `agree`. Requires `ClaimCaseStatus` **`INSURER_REVIEW_AWAITING_OWNER_SIGN`**, **`INSURER_REVIEW_MIXED_FACTORS_PENDING`**, or legacy **`WAITING_FOR_INSURER_APPROVAL`**, and `workflow.currentStep=INSURER_REVIEW` (not during owner factor upload or `EXPERT_COST_EVALUATION`).\n\n" +
"**Phase A — Mixed reply, priced lines only:** `claimStatus=NEEDS_REVISION`, no `evaluation.ownerPricedPartsApproval` yet. `agree=true` records that signature and moves to `OWNER_UPLOAD_FACTOR_DOCUMENTS` for factor uploads; `agree=false` rejects the whole case (`REJECTED`).\n\n" +
"**Phase B — Legacy final phase only:** pre-existing rows with `claimStatus=APPROVED` may still be accepted or rejected through this endpoint. New V2–V5 claims complete after expert work (and V5 FileMaker approval) without a final owner signature.\n\n" +
"Response may include `phase`: `PRICED_PARTS_FOR_FACTORS` or legacy `FINAL_APPROVAL` for UI state.",
})
@ApiBody({
description: "Signature file, agreement, and branch",
description: "Signature file and agreement",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
required: ["sign", "agree"],
properties: {
sign: {
type: "string",
@@ -355,12 +355,6 @@ export class ClaimRequestManagementV2Controller {
type: "boolean",
description: "true to accept expert pricing and complete the claim",
},
branchId: {
type: "string",
description:
"Insurer branch id (must belong to the claim owner's insurer; if pricing lists branch options, must match one of them)",
example: "507f1f77bcf86cd799439011",
},
},
},
})
@@ -392,7 +386,6 @@ export class ClaimRequestManagementV2Controller {
async submitOwnerInsurerApprovalSignV2(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() user: any,
@UploadedFile() sign: Express.Multer.File,
) {
@@ -408,7 +401,6 @@ export class ClaimRequestManagementV2Controller {
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
user.sub,
user,
@@ -467,7 +459,7 @@ export class ClaimRequestManagementV2Controller {
@ApiOperation({
summary: "Get insurer branches (V2)",
description:
"Returns branch list for a given insurer/client id so frontend can render branch options (name/code/address/city/state) and submit selected branchId in daghi part options.",
"Returns branch list for a given insurer/client id. Claim pricing and owner approval no longer require branch selection.",
})
@ApiParam({
name: "insuranceId",

View File

@@ -1,12 +0,0 @@
import { ApiProperty } from "@nestjs/swagger";
import { IsMongoId, IsNotEmpty } from "class-validator";
export class InPersonVisitDto {
@ApiProperty({
example: "60d5ec49e7b2f8001c8e4d2a",
description: "The unique ID of the branch the user is being sent to.",
})
@IsNotEmpty()
@IsMongoId()
branchId: string;
}

View File

@@ -56,20 +56,21 @@ export class SelectOtherPartsV2Dto {
@IsString()
shebaNumber?: string;
@ApiProperty({
description: 'National code of insurer/owner - 10 digits',
@ApiPropertyOptional({
description:
'Legacy fallback for claims created before participant roles were stored. New claims derive the vehicle owner national code from the linked blame case.',
example: '1234567890',
pattern: '^[0-9]{10}$',
minLength: 10,
maxLength: 10,
})
@IsNotEmpty({ message: 'nationalCodeOfInsurer is required' })
@IsOptional()
@IsString({ message: 'National code must be a string' })
@Length(10, 10, { message: 'National code must be exactly 10 digits' })
@Matches(/^[0-9]{10}$/, {
message: 'National code must contain exactly 10 digits',
})
nationalCodeOfInsurer: string;
nationalCodeOfInsurer?: string;
@ApiPropertyOptional({
description: 'Legacy alias for backward compatibility',

View File

@@ -83,10 +83,6 @@ export class ClaimOwnerInsurerApproval {
@Prop({ type: Boolean, required: true })
agree: boolean;
/** Branch the owner is signing for (must belong to their insurer; aligned with expert daghi options when present). */
@Prop({ type: Types.ObjectId })
branchId?: Types.ObjectId;
@Prop({ type: Types.ObjectId })
signDetailId?: Types.ObjectId;
@@ -102,9 +98,6 @@ export class ClaimOwnerPricedPartsApproval {
@Prop({ type: Boolean, required: true })
agree: boolean;
@Prop({ type: Types.ObjectId })
branchId?: Types.ObjectId;
@Prop({ type: Types.ObjectId })
signDetailId?: Types.ObjectId;
@@ -349,4 +342,3 @@ export class ClaimEvaluation {
}
export const ClaimEvaluationSchema =
SchemaFactory.createForClass(ClaimEvaluation);

View File

@@ -533,10 +533,10 @@ Returns status of each item (uploaded/captured or not).
@ApiParam({ name: "claimRequestId" })
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "Signature file, agreement, and branch",
description: "Signature file and agreement",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
required: ["sign", "agree"],
properties: {
sign: {
type: "string",
@@ -547,7 +547,6 @@ Returns status of each item (uploaded/captured or not).
type: "boolean",
description: "true to accept, false to reject",
},
branchId: { type: "string", description: "Insurer branch ID" },
},
},
})
@@ -577,7 +576,6 @@ Returns status of each item (uploaded/captured or not).
async submitOwnerSign(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() expert: any,
@UploadedFile() sign: Express.Multer.File,
) {
@@ -590,7 +588,6 @@ Returns status of each item (uploaded/captured or not).
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
expert.sub,
expert,

View File

@@ -19,6 +19,41 @@ describe("fanavaranClaimReferences", () => {
});
});
it("exposes the persisted Fanavaran reference codes to expert detail APIs", () => {
expect(
fanavaranClaimReferences({
status: ClaimCaseStatus.COMPLETED,
claimId: 100,
claimNo: 101,
dmgCaseId: 102,
expertiseId: 103,
fanavaranSync: {
baseClaim: { policyId: 104 },
damageCase: {
driverId: 105,
vehicleKindId: 106,
plaqueKindId: 107,
plaqueSampleId: 108,
accidentVehicleUsedId: 109,
insuranceCorpId: 110,
},
},
}),
).toEqual({
claimId: 100,
claimNo: 101,
dmgCaseId: 102,
expertiseId: 103,
policyId: 104,
driverId: 105,
vehicleKindId: 106,
plaqueKindId: 107,
plaqueSampleId: 108,
accidentVehicleUsedId: 109,
insuranceCorpId: 110,
});
});
it("omits missing ids", () => {
expect(
fanavaranClaimReferences({

View File

@@ -5,6 +5,13 @@ export type FanavaranClaimReferences = {
claimNo?: number;
dmgCaseId?: number;
expertiseId?: number;
policyId?: number;
driverId?: number;
vehicleKindId?: number;
plaqueKindId?: number;
plaqueSampleId?: number;
accidentVehicleUsedId?: number;
insuranceCorpId?: number;
};
/**
@@ -16,6 +23,10 @@ export function fanavaranClaimReferences(claim: {
claimNo?: number | null;
dmgCaseId?: number | null;
expertiseId?: number | null;
fanavaranSync?: {
baseClaim?: FanavaranReferenceStage | null;
damageCase?: FanavaranReferenceStage | null;
} | null;
}): FanavaranClaimReferences | undefined {
if (claim.status !== ClaimCaseStatus.COMPLETED) {
return undefined;
@@ -27,5 +38,43 @@ export function fanavaranClaimReferences(claim: {
if (claim.dmgCaseId != null) refs.dmgCaseId = claim.dmgCaseId;
if (claim.expertiseId != null) refs.expertiseId = claim.expertiseId;
const baseClaim = claim.fanavaranSync?.baseClaim;
const damageCase = claim.fanavaranSync?.damageCase;
if (baseClaim?.policyId != null) refs.policyId = baseClaim.policyId;
if ((damageCase?.driverId ?? baseClaim?.driverId) != null) {
refs.driverId = damageCase?.driverId ?? baseClaim?.driverId;
}
if ((damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId) != null) {
refs.vehicleKindId =
damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId;
}
if (damageCase?.plaqueKindId != null) {
refs.plaqueKindId = damageCase.plaqueKindId;
}
if (damageCase?.plaqueSampleId != null) {
refs.plaqueSampleId = damageCase.plaqueSampleId;
}
if (
(damageCase?.accidentVehicleUsedId ?? baseClaim?.accidentVehicleUsedId) !=
null
) {
refs.accidentVehicleUsedId =
damageCase?.accidentVehicleUsedId ?? baseClaim?.accidentVehicleUsedId;
}
if ((damageCase?.insuranceCorpId ?? baseClaim?.insuranceCorpId) != null) {
refs.insuranceCorpId =
damageCase?.insuranceCorpId ?? baseClaim?.insuranceCorpId;
}
return Object.keys(refs).length > 0 ? refs : undefined;
}
type FanavaranReferenceStage = {
policyId?: number | null;
driverId?: number | null;
vehicleKindId?: number | null;
plaqueKindId?: number | null;
plaqueSampleId?: number | null;
accidentVehicleUsedId?: number | null;
insuranceCorpId?: number | null;
};

View File

@@ -0,0 +1,71 @@
import { ExpertInitiatedClaimMirrorController } from "./expert-initiated-claim.mirror.controller";
import { FileReviewerBlameV4Controller } from "../request-management/file-reviewer-blame-v4.controller";
import { FileReviewerBlameV5Controller } from "../request-management/file-reviewer-blame-v5.controller";
describe("owner insurer approval mirror endpoints", () => {
const claimRequestId = "507f1f77bcf86cd799439011";
const actor = { sub: "507f1f77bcf86cd799439012" };
const sign = {
filename: "sign.png",
path: "/tmp/sign.png",
} as Express.Multer.File;
const createDependencies = () => {
const claimRequestManagementService = {
submitOwnerInsurerApprovalSignV2: jest
.fn()
.mockResolvedValue({ accepted: true }),
};
const mediaPolicyService = {
assertForClaim: jest.fn().mockResolvedValue(undefined),
};
return { claimRequestManagementService, mediaPolicyService };
};
it.each([
[
"expert-initiated",
(deps: ReturnType<typeof createDependencies>) =>
new ExpertInitiatedClaimMirrorController(
deps.claimRequestManagementService as never,
deps.mediaPolicyService as never,
),
],
[
"V4 file-reviewer",
(deps: ReturnType<typeof createDependencies>) =>
new FileReviewerBlameV4Controller(
{} as never,
deps.claimRequestManagementService as never,
deps.mediaPolicyService as never,
),
],
[
"V5 file-reviewer",
(deps: ReturnType<typeof createDependencies>) =>
new FileReviewerBlameV5Controller(
{} as never,
deps.claimRequestManagementService as never,
deps.mediaPolicyService as never,
),
],
])(
"forwards a signature without branchId through the %s endpoint",
async (_name, createController) => {
const dependencies = createDependencies();
const controller = createController(dependencies) as {
submitOwnerSign: (...args: any[]) => Promise<unknown>;
};
await controller.submitOwnerSign(claimRequestId, "true", actor, sign);
expect(
dependencies.mediaPolicyService.assertForClaim,
).toHaveBeenCalledWith(sign, claimRequestId, "image");
expect(
dependencies.claimRequestManagementService
.submitOwnerInsurerApprovalSignV2,
).toHaveBeenCalledWith(claimRequestId, true, sign, actor.sub, actor);
},
);
});

View File

@@ -0,0 +1,62 @@
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum";
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
import { ClaimRequestManagementService } from "./claim-request-management.service";
describe("owner insurer approval without branch selection", () => {
it("records a final rejection when no branchId is supplied", async () => {
const service = Object.create(
ClaimRequestManagementService.prototype,
) as ClaimRequestManagementService;
const findByIdAndUpdate = jest.fn().mockResolvedValue(undefined);
(service as any).claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
_id: "507f1f77bcf86cd799439011",
status: ClaimCaseStatus.INSURER_REVIEW_AWAITING_OWNER_SIGN,
claimStatus: ClaimStatus.APPROVED,
workflow: { currentStep: ClaimWorkflowStep.INSURER_REVIEW },
owner: { fullName: "مالک تست", clientId: "client-id" },
evaluation: {
damageExpertReply: { submittedAt: new Date(), parts: [] },
},
}),
findByIdAndUpdate,
};
(service as any).resolveClaimEffectiveUserId = jest
.fn()
.mockResolvedValue("507f1f77bcf86cd799439012");
(service as any).assertEffectiveUserIsDamagedPartyOnClaim = jest
.fn()
.mockResolvedValue(undefined);
(service as any).claimSignDbService = {
create: jest
.fn()
.mockResolvedValue({ _id: "507f1f77bcf86cd799439013" }),
};
await expect(
service.submitOwnerInsurerApprovalSignV2(
"507f1f77bcf86cd799439011",
false,
{ filename: "sign.png", path: "/tmp/sign.png" } as Express.Multer.File,
"507f1f77bcf86cd799439012",
),
).resolves.toMatchObject({
accepted: false,
phase: "FINAL_APPROVAL",
status: ClaimCaseStatus.REJECTED,
});
expect(findByIdAndUpdate).toHaveBeenCalledWith(
"507f1f77bcf86cd799439011",
expect.objectContaining({
$set: expect.objectContaining({
"evaluation.ownerInsurerApproval": expect.not.objectContaining({
branchId: expect.anything(),
}),
}),
}),
);
});
});

View File

@@ -0,0 +1,195 @@
import {
ApiHideProperty,
ApiProperty,
ApiPropertyOptional,
} from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsBoolean,
IsEnum,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
ValidateNested,
} from "class-validator";
export enum InquiryParticipantRole {
DRIVER = "DRIVER",
VEHICLE_OWNER = "VEHICLE_OWNER",
THIRD_PARTY_POLICYHOLDER = "THIRD_PARTY_POLICYHOLDER",
CAR_BODY_POLICYHOLDER = "CAR_BODY_POLICYHOLDER",
}
export enum VehicleRegistrationState {
CURRENT = "CURRENT",
RECENTLY_TRANSFERRED = "RECENTLY_TRANSFERRED",
}
export class InquiryPlateDto {
@ApiProperty({ example: "44" })
@IsNotEmpty()
leftDigits: string | number;
@ApiProperty({ example: "ب" })
@IsString()
@IsNotEmpty()
centerAlphabet: string;
@ApiProperty({ example: "111" })
@IsNotEmpty()
centerDigits: string | number;
@ApiProperty({ example: "22" })
@IsNotEmpty()
ir: string | number;
}
export class InquiryParticipantInputDto {
@ApiPropertyOptional({ enum: InquiryParticipantRole })
@IsOptional()
@IsEnum(InquiryParticipantRole)
sameAs?: InquiryParticipantRole;
@ApiPropertyOptional({
description:
"Only for the damaged party's third-party policyholder when the identity is genuinely unknown.",
})
@IsOptional()
@IsBoolean()
unknown?: boolean;
@ApiPropertyOptional({ example: "0012345678" })
@IsOptional()
@IsString()
nationalCode?: string;
@ApiPropertyOptional({ example: "1370/01/01" })
@IsOptional()
birthday?: string | number;
@ApiPropertyOptional()
@IsOptional()
@IsString()
fullName?: string;
@ApiPropertyOptional({
description: "Required for a driver who has a licence.",
})
@IsOptional()
@IsBoolean()
hasDrivingLicense?: boolean;
@ApiPropertyOptional()
@IsOptional()
@IsString()
licenseNumber?: string;
@ApiPropertyOptional()
@IsOptional()
@IsString()
licenseType?: string;
}
export class InquiryVehicleInputDto {
@ApiPropertyOptional({
enum: VehicleRegistrationState,
default: VehicleRegistrationState.CURRENT,
})
@IsOptional()
@IsEnum(VehicleRegistrationState)
registrationState?: VehicleRegistrationState;
@ApiProperty({ type: InquiryPlateDto })
@ValidateNested()
@Type(() => InquiryPlateDto)
currentPlate: InquiryPlateDto;
@ApiPropertyOptional({ type: InquiryPlateDto })
@IsOptional()
@ValidateNested()
@Type(() => InquiryPlateDto)
previousPlate?: InquiryPlateDto;
@ApiPropertyOptional({ maxLength: 17, example: "NAAM01E15HK123456" })
@IsOptional()
@IsString()
@MaxLength(17)
vin?: string;
@ApiPropertyOptional({
description: "Whether the vehicle is newly purchased/registered.",
})
@IsOptional()
@IsBoolean()
isNewCar?: boolean;
}
/** Structured role-complete contract mixed into every inquiry DTO. */
export class InquiryParticipantFieldsDto {
@ApiProperty({ type: InquiryParticipantInputDto })
@ValidateNested()
@Type(() => InquiryParticipantInputDto)
driver: InquiryParticipantInputDto;
@ApiProperty({ type: InquiryParticipantInputDto })
@ValidateNested()
@Type(() => InquiryParticipantInputDto)
vehicleOwner: InquiryParticipantInputDto;
@ApiProperty({ type: InquiryParticipantInputDto })
@ValidateNested()
@Type(() => InquiryParticipantInputDto)
thirdPartyPolicyholder: InquiryParticipantInputDto;
@ApiPropertyOptional({ type: InquiryParticipantInputDto })
@IsOptional()
@ValidateNested()
@Type(() => InquiryParticipantInputDto)
carBodyPolicyholder?: InquiryParticipantInputDto;
@ApiProperty({ type: InquiryVehicleInputDto })
@ValidateNested()
@Type(() => InquiryVehicleInputDto)
vehicle: InquiryVehicleInputDto;
/** Internal normalized projections; rejected as request input by the resolver. */
@ApiHideProperty()
nationalCodeOfDriver?: string;
@ApiHideProperty()
driverBirthday?: any;
@ApiHideProperty()
driverLicense?: string;
@ApiHideProperty()
licenseType?: string;
@ApiHideProperty()
nationalCodeOfInsurer?: string;
@ApiHideProperty()
insurerBirthday?: any;
@ApiHideProperty()
insurerLicense?: string;
@ApiHideProperty()
driverIsInsurer?: boolean;
@ApiHideProperty()
userNoCertificate?: boolean;
@ApiHideProperty()
plate?: any;
@ApiHideProperty()
plateId?: string;
@ApiHideProperty()
vin?: string;
@ApiHideProperty()
isNewCar?: boolean;
}

View File

@@ -30,5 +30,8 @@ export class CaseInquiries {
@Prop({ type: InquiryStatusSchema })
drivingLicence?: InquiryStatus;
@Prop({ type: InquiryStatusSchema })
ownership?: InquiryStatus;
}
export const CaseInquiriesSchema = SchemaFactory.createForClass(CaseInquiries);

View File

@@ -178,6 +178,13 @@ export class ClaimDetailV2ResponseDto {
claimNo?: number;
dmgCaseId?: number;
expertiseId?: number;
policyId?: number;
driverId?: number;
vehicleKindId?: number;
plaqueKindId?: number;
plaqueSampleId?: number;
accidentVehicleUsedId?: number;
insuranceCorpId?: number;
};
@ApiPropertyOptional({
@@ -200,14 +207,12 @@ export class ClaimDetailV2ResponseDto {
damageExpertResend: unknown;
ownerInsurerApproval?: {
agree: boolean;
branchId?: string;
signDetailId?: string;
signLink?: string;
signedAt?: Date | string;
};
ownerPricedPartsApproval?: {
agree: boolean;
branchId?: string;
signDetailId?: string;
signLink?: string;
signedAt?: Date | string;

View File

@@ -51,9 +51,9 @@ describe("SubmitExpertReplyV2Dto", () => {
{
partId: 201,
typeOfDamage: TypeOfDamage.Repair,
price: "10000",
salary: "0",
totalPayment: "10000",
price: "100000",
salary: "100000",
totalPayment: "200000",
factorNeeded: false,
},
],
@@ -69,14 +69,14 @@ describe("SubmitExpertReplyV2Dto", () => {
{
partId: 11,
typeOfDamage: TypeOfDamage.Repair,
salary: "۵,۰۰۰",
totalPayment: "5000",
salary: "۱۰۰,۰۰۰",
totalPayment: "100000",
factorNeeded: false,
},
{
partId: 23,
typeOfDamage: TypeOfDamage.Change,
price: "۵۰,۰۰۰",
price: "۱۰۰,۰۰۰",
salary: "۱۰۰,۰۰۰",
totalPayment: "150000",
factorNeeded: false,

View File

@@ -27,7 +27,7 @@ export class DaghiDetailsV2Dto {
option: DaghiOption;
@ApiPropertyOptional({
description: `Required when option is '${DaghiOption.RECYCLED_PARTS_VALUE}' (Toman)`,
description: `Required when option is '${DaghiOption.RECYCLED_PARTS_VALUE}' (Toman; 100,000 to 10,000,000,000).`,
})
@ValidateIf(
(daghi: DaghiDetailsV2Dto) =>
@@ -38,12 +38,6 @@ export class DaghiDetailsV2Dto {
@IsMoneyAmountString()
price?: string;
@ApiPropertyOptional({
description: `Required when option is '${DaghiOption.DELIVER_DAMAGED_PART}' (Mongo ObjectId string)`,
})
@IsOptional()
@IsString()
branchId?: string;
}
export class PartPricingV2Dto {
@@ -63,7 +57,8 @@ export class PartPricingV2Dto {
@ApiPropertyOptional({
example: "5000000",
description: "Required for change lines; omitted for repair lines. Use 0 if unused.",
description:
"Required for change lines; omitted for repair lines. Every supplied amount must be between 100,000 and 10,000,000,000 Toman.",
})
@ValidateIf(
(part: PartPricingV2Dto) =>
@@ -78,7 +73,8 @@ export class PartPricingV2Dto {
@ApiProperty({
example: "2000000",
description: "Labor in Toman (integer string). Use 0 if the full amount is in price.",
description:
"Labor in Toman (integer string; 100,000 to 10,000,000,000).",
})
@IsString()
@IsNotEmpty()
@@ -87,7 +83,8 @@ export class PartPricingV2Dto {
@ApiProperty({
example: "7000000",
description: "Line total in Toman (integer string).",
description:
"Line total in Toman (integer string; 100,000 to 10,000,000,000).",
})
@IsString()
@IsNotEmpty()
@@ -116,10 +113,13 @@ export class PartPricingV2Dto {
}
export class SubmitExpertReplyV2Dto {
@ApiProperty({ example: 'Front door and hood have severe paint damage' })
@ApiPropertyOptional({
example: 'Front door and hood have severe paint damage',
description: "Optional expert note about the damage assessment.",
})
@IsOptional()
@IsString()
@IsNotEmpty()
description: string;
description?: string;
@ApiProperty({
type: [PartPricingV2Dto],

View File

@@ -25,12 +25,6 @@ export class DaghiDetailsDto {
})
price?: string;
@ApiProperty({
required: false,
type: String,
description: "Branch ID required when option is 'تحویل داغی'",
})
branchId?: string;
}
export class PartsList {

View File

@@ -52,6 +52,32 @@ describe("ExpertClaimService expert-reply pricing", () => {
]);
});
it("allows a deliver-damaged-part line without a branch", () => {
const service = createService() as any;
expect(
service.validateAndNormalizeDaghiForExpertReplyV2([
{
partId: 201,
typeOfDamage: TypeOfDamage.Change,
price: "100000",
salary: "100000",
totalPayment: "200000",
daghi: { option: DaghiOption.DELIVER_DAMAGED_PART },
},
]),
).toEqual([
{
partId: 201,
typeOfDamage: TypeOfDamage.Change,
price: "100000",
salary: "100000",
totalPayment: "200000",
daghi: { option: DaghiOption.DELIVER_DAMAGED_PART },
},
]);
});
it("rejects a blank pricing line on the legacy submit endpoint before changing status", async () => {
const service = createService() as any;
const findAndUpdate = jest.fn();
@@ -95,4 +121,45 @@ describe("ExpertClaimService expert-reply pricing", () => {
expect(findByIdAndUpdate).not.toHaveBeenCalled();
});
it("returns a Persian, field-specific error when a V2 price is below the minimum", async () => {
const service = createService() as any;
const findByIdAndUpdate = jest.fn();
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
status: ClaimCaseStatus.EXPERT_REVIEWING,
workflow: { locked: true, lockedBy: { actorId: "expert-1" } },
}),
findByIdAndUpdate,
};
service.assertExpertActorOnClaim = jest.fn().mockResolvedValue(undefined);
await expect(
service.submitExpertReplyV2(
"v2-claim",
{
description: "Damage assessment",
parts: [
{
partId: 201,
typeOfDamage: TypeOfDamage.Repair,
price: "99,999",
salary: "100000",
totalPayment: "100000",
factorNeeded: false,
},
],
},
{ sub: "expert-1", role: RoleEnum.FIELD_EXPERT },
),
).rejects.toMatchObject({
response: {
code: "EXPERT_REPLY_VALIDATION_ERROR",
field: "parts[0].price",
message: expect.stringContaining("حداقل"),
},
});
expect(findByIdAndUpdate).not.toHaveBeenCalled();
});
});

View File

@@ -913,6 +913,19 @@ export class ExpertClaimService {
);
}
private expertReplySubmissionError(
message: string,
code: string,
details: Record<string, unknown> = {},
) {
return {
message,
error: "EXPERT_REPLY_SUBMISSION_ERROR",
code,
...details,
};
}
/** Factor validation: expert must send a line amount (OCR is not used for factor photos). */
private expertFactorValidationDecisionHasLinePricing(decision: {
totalPayment?: string;
@@ -944,32 +957,32 @@ export class ExpertClaimService {
return pr + sa;
}
/** Same rules as V1 `submitReplyRequest`: daghi option + conditional price / branchId; `branchId` stored as ObjectId. */
/** Same rules as V1 `submitReplyRequest`: daghi option plus conditional price. */
private validateAndNormalizeDaghiForExpertReplyV2(
parts: import("./dto/expert-claim-v2.dto").PartPricingV2Dto[],
) {
for (const part of parts) {
for (const [partIndex, part] of parts.entries()) {
if (part.typeOfDamage === TypeOfDamage.Repair) continue;
if (!part.daghi || !part.daghi.option) {
throw new BadRequestException(
`Daghi option is required for part ${part.partId}`,
this.expertReplySubmissionError(
`گزینه داغی برای قطعه ${part.partId} الزامی است.`,
"DAGHI_OPTION_REQUIRED",
{ field: `parts[${partIndex}].daghi.option`, partId: part.partId },
),
);
}
if (part.daghi.option === DaghiOption.RECYCLED_PARTS_VALUE) {
if (!part.daghi.price) {
throw new BadRequestException(
`Price is required for part ${part.partId} when option is '${DaghiOption.RECYCLED_PARTS_VALUE}'`,
);
}
} else if (part.daghi.option === DaghiOption.DELIVER_DAMAGED_PART) {
if (!part.daghi.branchId) {
throw new BadRequestException(
`Branch ID is required for part ${part.partId} when option is '${DaghiOption.DELIVER_DAMAGED_PART}'`,
);
}
if (!Types.ObjectId.isValid(part.daghi.branchId)) {
throw new BadRequestException(
`Invalid branch ID format for part ${part.partId}`,
this.expertReplySubmissionError(
`قیمت داغی برای قطعه ${part.partId} الزامی است.`,
"DAGHI_PRICE_REQUIRED",
{
field: `parts[${partIndex}].daghi.price`,
partId: part.partId,
},
),
);
}
}
@@ -985,10 +998,6 @@ export class ExpertClaimService {
daghi: {
option: part.daghi!.option,
...(part.daghi!.price && { price: part.daghi!.price }),
...(part.daghi!.branchId &&
Types.ObjectId.isValid(part.daghi!.branchId) && {
branchId: new Types.ObjectId(part.daghi!.branchId),
}),
},
};
});
@@ -1735,18 +1744,6 @@ export class ExpertClaimService {
`Price is required for part ${part.partId} when option is '${DaghiOption.RECYCLED_PARTS_VALUE}'`,
);
}
} else if (part.daghi.option === DaghiOption.DELIVER_DAMAGED_PART) {
if (!part.daghi.branchId) {
throw new BadRequestException(
`Branch ID is required for part ${part.partId} when option is '${DaghiOption.DELIVER_DAMAGED_PART}'`,
);
}
// Validate branchId is a valid ObjectId
if (!Types.ObjectId.isValid(part.daghi.branchId)) {
throw new BadRequestException(
`Invalid branch ID format for part ${part.partId}`,
);
}
}
// For NO_VALUE and WITH_DAMAGED_PART_CALCULATION, no additional fields needed
}
@@ -1768,7 +1765,7 @@ export class ExpertClaimService {
? ClaimStepsEnum.WaitingForFactorUpload
: ClaimStepsEnum.WaitingForUserToReact;
// Process parts: convert branchId string to ObjectId if present
// Branch selection is no longer part of claim pricing.
const processedParts = reply.parts.map((part) => {
if (part.typeOfDamage === TypeOfDamage.Repair) {
const { daghi: _daghi, ...repairPart } = part;
@@ -1779,9 +1776,6 @@ export class ExpertClaimService {
daghi: {
option: part.daghi!.option,
...(part.daghi!.price && { price: part.daghi!.price }),
...(part.daghi!.branchId && {
branchId: new Types.ObjectId(part.daghi!.branchId),
}),
},
};
});
@@ -2300,7 +2294,12 @@ export class ExpertClaimService {
) {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
throw new NotFoundException(
this.expertReplySubmissionError(
"پرونده خسارت یافت نشد.",
"CLAIM_NOT_FOUND",
),
);
}
await this.assertExpertActorOnClaim(claim, actor);
@@ -3247,7 +3246,7 @@ export class ExpertClaimService {
* - Must be locked by this expert (workflow.lockedBy.actorId === actor.sub)
* - Must be in EXPERT_REVIEWING status
* - Total payment across all parts must not exceed 53,000,000 (same cap as factor validation totals)
* - Each part must include `daghi` (option + conditional price/branchId) like V1
* - Each part must include `daghi` (option + conditional price) like V1
*
* On success:
* - Stores reply; clears owner signature fields (`ownerInsurerApproval`, `ownerPricedPartsApproval`)
@@ -3265,29 +3264,47 @@ export class ExpertClaimService {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException("Claim request not found");
throw new NotFoundException(
this.expertReplySubmissionError(
"پرونده خسارت یافت نشد.",
"CLAIM_NOT_FOUND",
),
);
}
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
`Claim is not in a reviewable state. Current status: ${claim.status}`,
this.expertReplySubmissionError(
"پرونده در وضعیت قابل بررسی برای ثبت پاسخ کارشناسی نیست.",
"CLAIM_NOT_REVIEWABLE",
{ currentStatus: claim.status },
),
);
}
if (!claim.workflow?.locked) {
throw new ForbiddenException(
"You must lock the claim before submitting a reply",
this.expertReplySubmissionError(
"پیش از ثبت پاسخ کارشناسی باید پرونده را قفل کنید.",
"CLAIM_NOT_LOCKED",
),
);
}
if (claim.workflow.lockedBy?.actorId?.toString() !== actor.sub) {
throw new ForbiddenException("This claim is locked by another expert");
throw new ForbiddenException(
this.expertReplySubmissionError(
"این پرونده توسط کارشناس دیگری قفل شده است.",
"CLAIM_LOCKED_BY_ANOTHER_EXPERT",
),
);
}
const pricingValidationError = getExpertReplyPricingValidationError(
reply.parts,
{ locale: "fa", enforceAmountBounds: true },
);
if (pricingValidationError) {
throw new BadRequestException(pricingValidationError);
@@ -3305,8 +3322,9 @@ export class ExpertClaimService {
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `You have reached the maximum acceptable total price (Toman). The sum of priced parts and factor lines (${totalPrice.toLocaleString()}) exceeds the limit (${priceCap.toLocaleString()}).`,
message: `مجموع مبلغ قطعات (${totalPrice.toLocaleString("fa-IR")}) از سقف مجاز (${priceCap.toLocaleString("fa-IR")}) تومان بیشتر است.`,
error: "PRICE_CAP_ERROR",
code: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
@@ -3337,7 +3355,11 @@ export class ExpertClaimService {
);
if (!selected) {
throw new BadRequestException(
`Unknown partId "${p.partId}". Use numeric catalog id from claim detail damagedParts.`,
this.expertReplySubmissionError(
`قطعه با شناسه ${p.partId} در فهرست قطعات آسیب‌دیده پرونده وجود ندارد.`,
"PART_NOT_ON_CLAIM",
{ field: "partId", partId: p.partId },
),
);
}
@@ -3355,22 +3377,32 @@ export class ExpertClaimService {
);
} catch (err) {
throw new BadRequestException(
`Invalid part ${p.partId}: ${
err instanceof Error ? err.message : String(err)
}`,
this.expertReplySubmissionError(
`اطلاعات قطعه ${p.partId} معتبر نیست.`,
"PART_INVALID",
{ field: "partId", partId: p.partId },
),
);
}
const catalogId = catalogPartIdFromCarPartDamage(carPartDamage);
if (catalogId == null) {
throw new BadRequestException(
`Invalid part ${p.partId}: a numeric catalog id is required.`,
this.expertReplySubmissionError(
`شناسه قطعه ${p.partId} معتبر نیست.`,
"PART_ID_INVALID",
{ field: "partId", partId: p.partId },
),
);
}
if (seenCatalogIds.has(catalogId)) {
throw new BadRequestException(
`Duplicate part submitted in expert reply: ${catalogId}.`,
this.expertReplySubmissionError(
`قطعه ${catalogId} بیش از یک‌بار ارسال شده است.`,
"DUPLICATE_PART",
{ field: "partId", partId: catalogId },
),
);
}
seenCatalogIds.add(catalogId);
@@ -3399,7 +3431,10 @@ export class ExpertClaimService {
if (objectionSubmitted && hasFinalReply) {
throw new ConflictException(
"A final expert reply after objection already exists for this claim.",
this.expertReplySubmissionError(
"پاسخ نهایی کارشناسی پس از اعتراض، پیش‌تر برای این پرونده ثبت شده است.",
"FINAL_REPLY_ALREADY_SUBMITTED",
),
);
}

View File

@@ -10,6 +10,7 @@ import {
Post,
Put,
UseGuards,
UsePipes,
Query,
Res,
} from "@nestjs/common";
@@ -50,6 +51,7 @@ import {
import { FactorValidationV2Dto } from "./dto/factor-validation.dto";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { OuterPartCatalogItemDto } from "src/claim-request-management/dto/select-outer-parts-v2.dto";
import { submitExpertReplyValidationPipe } from "./pipes/submit-expert-reply-validation.pipe";
class InPersonVisitV2Dto {
@ApiPropertyOptional({ example: "Paint damage requires physical inspection" })
@@ -266,7 +268,7 @@ export class ExpertClaimV2Controller {
@ApiOperation({
summary: "Submit expert damage assessment reply",
description:
"**Preconditions:** claim locked by this expert (`EXPERT_REVIEWING`). **Unlocks** the claim. Each `parts[]` line needs `partId` (from GET claim detail `damagedParts[].partId`), plus pricing, `daghi`, and optional `factorNeeded`. **Cap:** sum of line `totalPayment` values ≤ 53,000,000 **Toman** (same limit as factor-validation totals across priced + factor lines). Clears any prior `evaluation.ownerInsurerApproval` / `ownerPricedPartsApproval`.\n\n" +
"**Preconditions:** claim locked by this expert (`EXPERT_REVIEWING`). **Unlocks** the claim. Each `parts[]` line needs `partId` (from GET claim detail `damagedParts[].partId`), plus pricing, `daghi`, and optional `factorNeeded`. Every supplied monetary field (`price`, `salary`, `totalPayment`, and `daghi.price`) must be 100,000–10,000,000,000 **Toman**. **Cap:** sum of line `totalPayment` values ≤ 53,000,000 **Toman** (same limit as factor-validation totals across priced + factor lines). Clears any prior `evaluation.ownerInsurerApproval` / `ownerPricedPartsApproval`.\n\n" +
"**Frontend routing by `ClaimCaseStatus` (`status`):**\n" +
"- **All parts `factorNeeded`:** `OWNER_REPAIR_FACTOR_UPLOAD_PENDING`, `claimStatus=NEEDS_REVISION`, `workflow.currentStep=OWNER_UPLOAD_FACTOR_DOCUMENTS`, `workflow.nextStep=EXPERT_COST_EVALUATION` → owner uploads all factors; then `status` becomes **`EXPERT_VALIDATING_REPAIR_FACTORS`**, `claimStatus=UNDER_REVIEW`, `currentStep=EXPERT_COST_EVALUATION` for expert **validate-factors**.\n" +
"- **Mixed (some priced, some factorNeeded):** `INSURER_REVIEW_MIXED_FACTORS_PENDING`, `claimStatus=NEEDS_REVISION`, `currentStep=INSURER_REVIEW`, `nextStep=OWNER_UPLOAD_FACTOR_DOCUMENTS` → owner must call **owner-insurer-approval/sign** first (priced-line acceptance); `currentStep` then moves to `OWNER_UPLOAD_FACTOR_DOCUMENTS` (same case `status` until factors are done).\n" +
@@ -276,6 +278,7 @@ export class ExpertClaimV2Controller {
})
@ApiParam({ name: "claimRequestId" })
@ApiBody({ type: SubmitExpertReplyV2Dto })
@UsePipes(submitExpertReplyValidationPipe)
async submitExpertReplyV2(
@Param("claimRequestId") claimRequestId: string,
@Body() body: SubmitExpertReplyV2Dto,

View File

@@ -0,0 +1,70 @@
import { SubmitExpertReplyV2Dto } from "../dto/expert-claim-v2.dto";
import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-damage.enum";
import { submitExpertReplyValidationPipe } from "./submit-expert-reply-validation.pipe";
describe("submitExpertReplyValidationPipe", () => {
it("converts DTO validation failures into Persian, field-addressable errors", async () => {
await expect(
submitExpertReplyValidationPipe.transform(
{ parts: [] },
{ type: "body", metatype: SubmitExpertReplyV2Dto },
),
).rejects.toMatchObject({
response: {
code: "EXPERT_REPLY_VALIDATION_ERROR",
message: "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
validationErrors: expect.arrayContaining([
expect.objectContaining({ field: "parts" }),
]),
},
});
});
it("accepts a reply without a description", async () => {
await expect(
submitExpertReplyValidationPipe.transform(
{
parts: [
{
partId: 201,
typeOfDamage: TypeOfDamage.Repair,
salary: "100000",
totalPayment: "100000",
factorNeeded: false,
},
],
},
{ type: "body", metatype: SubmitExpertReplyV2Dto },
),
).resolves.toBeInstanceOf(SubmitExpertReplyV2Dto);
});
it("identifies invalid nested price fields for the frontend", async () => {
await expect(
submitExpertReplyValidationPipe.transform(
{
description: "Damage assessment",
parts: [
{
partId: 201,
typeOfDamage: "repair",
salary: "not-a-number",
totalPayment: "100000",
factorNeeded: false,
},
],
},
{ type: "body", metatype: SubmitExpertReplyV2Dto },
),
).rejects.toMatchObject({
response: {
validationErrors: expect.arrayContaining([
{
field: "parts[0].salary",
message: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
},
]),
},
});
});
});

View File

@@ -0,0 +1,59 @@
import {
BadRequestException,
ValidationError,
ValidationPipe,
} from "@nestjs/common";
type FrontendValidationError = {
field: string;
message: string;
};
const constraintMessages: Record<string, string> = {
isString: "باید به‌صورت متن ارسال شود.",
isNotEmpty: "وارد کردن این فیلد الزامی است.",
isArray: "باید به‌صورت فهرست ارسال شود.",
arrayMinSize: "حداقل یک قطعه آسیب‌دیده باید ارسال شود.",
isBoolean: "باید درست یا نادرست باشد.",
isInt: "باید یک عدد صحیح باشد.",
isEnum: "مقدار واردشده معتبر نیست.",
nestedValidation: "اطلاعات این بخش معتبر نیست.",
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
};
function flattenValidationErrors(
errors: ValidationError[],
parentPath = "",
): FrontendValidationError[] {
return errors.flatMap((error) => {
const field = parentPath
? /^\d+$/.test(error.property)
? `${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)];
});
}
/**
* Endpoint-scoped because this application deliberately has no global
* ValidationPipe. It preserves DTO validation while returning a stable,
* Persian payload that the frontend can render by field.
*/
export const submitExpertReplyValidationPipe = new ValidationPipe({
transform: true,
whitelist: true,
exceptionFactory: (errors: ValidationError[]) => {
const validationErrors = flattenValidationErrors(errors);
return new BadRequestException({
message: "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
error: "EXPERT_REPLY_VALIDATION_ERROR",
code: "EXPERT_REPLY_VALIDATION_ERROR",
validationErrors,
});
},
});

View File

@@ -0,0 +1,52 @@
import { ExpertInsurerService } from "./expert-insurer.service";
describe("insurer expert file summaries", () => {
const service = Object.create(
ExpertInsurerService.prototype,
) as ExpertInsurerService;
it("calculates blame review duration in minutes on the backend", () => {
const summary = (service as any).mapBlameFileSummaryForInsurerExpert({
_id: "6aa50ce70545fc1906433c85",
publicId: "RPT832-00049",
requestNo: "BL-RPT832-000049",
type: "THIRD_PARTY",
status: "WAITING_FOR_SIGNATURES",
blameStatus: "AGREED",
createdAt: new Date("2026-06-21T12:42:28.000Z"),
updatedAt: new Date("2026-06-21T15:32:28.000Z"),
});
expect(summary.reviewDurationMinutes).toBe(170);
});
it("calculates claim review duration with the same contract", () => {
const summary = (service as any).mapClaimFileSummaryForInsurerExpert({
_id: "6aa50ce70545fc1906433c86",
publicId: "RPT832-00049",
createdAt: "2026-06-21T12:42:28.000Z",
updatedAt: "2026-06-21T12:43:58.000Z",
});
expect(summary.reviewDurationMinutes).toBe(1.5);
});
it("returns null instead of NaN when a duration timestamp is unavailable", () => {
const summary = (service as any).mapBlameFileSummaryForInsurerExpert({
_id: "6aa50ce70545fc1906433c85",
createdAt: "invalid",
});
expect(summary.reviewDurationMinutes).toBeNull();
});
it("clamps malformed negative durations to zero", () => {
const summary = (service as any).mapClaimFileSummaryForInsurerExpert({
_id: "6aa50ce70545fc1906433c86",
createdAt: "2026-06-21T15:32:28.000Z",
updatedAt: "2026-06-21T12:42:28.000Z",
});
expect(summary.reviewDurationMinutes).toBe(0);
});
});

View File

@@ -78,7 +78,11 @@ import {
extractExpertNamesFromBlame,
extractExpertNamesFromClaim,
} from "./helper/insurer.helper";
import { getEventFaLabel } from "./helper/timeline-fa-labels";
import {
getEventFaDescription,
getEventFaLabel,
localizeTimelineMetadata,
} from "./helper/timeline-fa-labels";
import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher";
@Injectable()
@@ -260,6 +264,18 @@ export class ExpertInsurerService {
return String(aid);
}
private calculateReviewDurationMinutes(
createdAt: Date | string | undefined,
updatedAt: Date | string | undefined,
): number | null {
const startedAtMs = new Date(createdAt as any).getTime();
const reviewedAtMs = new Date(updatedAt as any).getTime();
if (Number.isNaN(startedAtMs) || Number.isNaN(reviewedAtMs)) return null;
const durationMinutes = Math.max(reviewedAtMs - startedAtMs, 0) / 60_000;
return Math.round(durationMinutes * 100) / 100;
}
private mapBlameFileSummaryForInsurerExpert(b: any) {
return {
kind: "blame" as const,
@@ -271,6 +287,10 @@ export class ExpertInsurerService {
blameStatus: b.blameStatus,
createdAt: b.createdAt,
updatedAt: b.updatedAt,
reviewDurationMinutes: this.calculateReviewDurationMinutes(
b.createdAt,
b.updatedAt,
),
};
}
@@ -284,6 +304,10 @@ export class ExpertInsurerService {
claimStatus: c.claimStatus,
createdAt: c.createdAt,
updatedAt: c.updatedAt,
reviewDurationMinutes: this.calculateReviewDurationMinutes(
c.createdAt,
c.updatedAt,
),
};
}
@@ -2819,6 +2843,7 @@ export class ExpertInsurerService {
source: "blame",
type: ev.type,
faLabel: getEventFaLabel(ev),
description: getEventFaDescription(ev),
timestamp: ev.timestamp,
actor: this.buildTimelineActor(ev.actor, actorName, performedBy),
actorName,
@@ -2827,7 +2852,7 @@ export class ExpertInsurerService {
ExpertInsurerService.resolveTimelinePerformedByCategory(performedBy),
performedByFaLabel:
ExpertInsurerService.resolveTimelinePerformedByFaLabel(performedBy),
metadata: ev.metadata ?? null,
metadata: localizeTimelineMetadata(ev),
});
}
}
@@ -2856,6 +2881,7 @@ export class ExpertInsurerService {
source: "claim",
type: ev.type,
faLabel: getEventFaLabel(ev),
description: getEventFaDescription(ev),
timestamp: ev.timestamp,
actor: this.buildTimelineActor(ev.actor, actorName, performedBy),
actorName,
@@ -2864,7 +2890,7 @@ export class ExpertInsurerService {
ExpertInsurerService.resolveTimelinePerformedByCategory(performedBy),
performedByFaLabel:
ExpertInsurerService.resolveTimelinePerformedByFaLabel(performedBy),
metadata: ev.metadata ?? null,
metadata: localizeTimelineMetadata(ev),
});
}
}

View File

@@ -0,0 +1,137 @@
import {
getEventFaDescription,
getEventFaLabel,
localizeTimelineMetadata,
} from "./timeline-fa-labels";
describe("insurer timeline Persian labels", () => {
it("localizes the user-submission detail shown to insurers", () => {
const event = {
type: "STEP_COMPLETED",
metadata: {
stepKey: "USER_SUBMISSION_COMPLETE",
description:
"User submission complete. Claim ready for damage expert review.",
},
};
expect(getEventFaLabel(event)).toBe("ارسال اطلاعات توسط کاربر");
expect(getEventFaDescription(event)).toBe(
"ثبت اطلاعات کاربر تکمیل شد و پرونده آماده بررسی کارشناس خسارت است.",
);
});
it("never returns an English event type as the description fallback", () => {
expect(getEventFaDescription({ type: "UNRECOGNIZED_EVENT" })).toBe(
"رویدادی در روند پرونده ثبت شد.",
);
});
it.each([
["FIRST_INITIAL_FORM_SUBMITTED", "فرم اولیه طرف اول ثبت شد"],
["FIRST_LOCATION_SUBMITTED", "موقعیت مکانی طرف اول ثبت شد"],
["FIRST_VOICE_UPLOADED", "صدای طرف اول بارگذاری شد"],
["FIRST_DESCRIPTION_SUBMITTED", "توضیحات طرف اول ثبت شد"],
["EXPERT_REPLY_SUBMITTED", "پاسخ کارشناس ثبت شد"],
])("localizes sample timeline event %s", (type, expectedLabel) => {
expect(getEventFaLabel({ type })).toBe(expectedLabel);
});
it("uses a Persian faLabel fallback for an unknown event type", () => {
expect(getEventFaLabel({ type: "UNRECOGNIZED_EVENT" })).toBe(
"رویداد پرونده",
);
});
it("preserves human-readable assignment metadata exactly", () => {
expect(
localizeTimelineMetadata({
type: "CLAIM_ASSIGNED",
metadata: { note: "Expert assigned via review assign endpoint" },
}),
).toEqual({
note: "Expert assigned via review assign endpoint",
});
});
it("preserves Fanavaran metadata keys and values exactly", () => {
expect(
localizeTimelineMetadata({
type: "FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED",
metadata: {
clientKey: "parsian",
error: "Fanavaran expertise payload is not ready.",
},
}),
).toEqual({
clientKey: "parsian",
error: "Fanavaran expertise payload is not ready.",
});
});
it("does not add fields to existing metadata", () => {
expect(
localizeTimelineMetadata({
type: "STEP_COMPLETED",
metadata: {
role: "FIRST",
stepKey: "USER_SUBMISSION_COMPLETE",
carType: "sedan",
captureType: "angle",
captureKey: "front",
},
}),
).toEqual({
role: "FIRST",
stepKey: "USER_SUBMISSION_COMPLETE",
carType: "sedan",
captureType: "angle",
captureKey: "front",
});
});
it("localizes the auto-resolved first-party confession reason", () => {
expect(
localizeTimelineMetadata({
type: "AUTO_CONFESSION_SKIPPED",
metadata: {
reason:
"IN_PERSON expert-initiated: first party is always guilty; confession auto-resolved",
stepKey: "FIRST_BLAME_CONFESSION",
advancedTo: "FIRST_VIDEO",
},
}),
).toEqual({
reason:
"در پرونده حضوری ایجادشده توسط کارشناس، طرف اول همیشه مقصر است؛ بنابراین مرحله اقرار به‌صورت خودکار تعیین تکلیف شد.",
stepKey: "FIRST_BLAME_CONFESSION",
advancedTo: "FIRST_VIDEO",
});
});
it("localizes the call-center auto-confession reason", () => {
expect(
localizeTimelineMetadata({
type: "AUTO_CONFESSION_SKIPPED",
metadata: {
reason:
"V6 call-center initiated: first party is always guilty; confession auto-resolved",
advancedTo: "FIRST_VIDEO",
},
}),
).toEqual({
reason:
"در پرونده ایجادشده توسط مرکز تماس، طرف اول همیشه مقصر است؛ بنابراین مرحله اقرار به‌صورت خودکار تعیین تکلیف شد.",
advancedTo: "FIRST_VIDEO",
});
});
it("preserves user-entered reasons that are not system messages", () => {
expect(
localizeTimelineMetadata({
type: "V5_FILE_MAKER_REJECTED",
metadata: { reason: "تصویر کارت خودرو خوانا نیست" },
}),
).toEqual({ reason: "تصویر کارت خودرو خوانا نیست" });
});
});

View File

@@ -9,7 +9,7 @@
* Usage:
* const label = EVENT_TYPE_FA_LABELS[event.type]
* ?? resolveStepCompletedFaLabel(event)
* ?? event.type;
* ?? "رویداد پرونده";
*/
// ---------------------------------------------------------------------------
@@ -40,6 +40,16 @@ export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
// First video
FIRST_VIDEO_UPLOADED: "ویدیوی اول بارگذاری شد",
// Legacy first/second-party self-service flow
FIRST_INITIAL_FORM_SUBMITTED: "فرم اولیه طرف اول ثبت شد",
SECOND_INITIAL_FORM_SUBMITTED: "فرم اولیه طرف دوم ثبت شد",
FIRST_LOCATION_SUBMITTED: "موقعیت مکانی طرف اول ثبت شد",
SECOND_LOCATION_SUBMITTED: "موقعیت مکانی طرف دوم ثبت شد",
FIRST_VOICE_UPLOADED: "صدای طرف اول بارگذاری شد",
SECOND_VOICE_UPLOADED: "صدای طرف دوم بارگذاری شد",
FIRST_DESCRIPTION_SUBMITTED: "توضیحات طرف اول ثبت شد",
SECOND_DESCRIPTION_SUBMITTED: "توضیحات طرف دوم ثبت شد",
// Second party invitation
SECOND_PARTY_INVITED: "طرف دوم دعوت شد",
@@ -101,6 +111,12 @@ export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
EXPERT_RESEND_FULFILLED: "مدارک درخواستی ارسال شد",
IN_PERSON_VISIT_REQUESTED: "کارشناس بازدید حضوری درخواست کرد",
EXPERT_DAMAGED_PARTS_UPDATED: "کارشناس قطعات آسیب‌دیده را به‌روزرسانی کرد",
EXPERT_REPLY_SUBMITTED: "پاسخ کارشناس ثبت شد",
EXPERT_FINAL_REPLY_SUBMITTED: "پاسخ نهایی کارشناس ثبت شد",
FACTORS_REJECTED_REPRICED_AUTO_COMPLETED:
"بررسی فاکتورها با قیمت‌گذاری مجدد تکمیل شد",
FACTORS_VALIDATED_ALL_APPROVED_AUTO_COMPLETED:
"همه فاکتورها تأیید و پرونده تکمیل شد",
// Workflow steps (generic)
STEP_COMPLETED: "مرحله تکمیل شد",
@@ -120,7 +136,8 @@ export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
// Owner insurer approval
OWNER_SIGNED_INSURER_APPROVAL: "صاحب خودرو قرارداد بیمه را امضا کرد",
OWNER_REJECTED_INSURER_APPROVAL_PRICING: "صاحب خودرو قیمت‌گذاری بیمه را رد کرد",
OWNER_REJECTED_INSURER_APPROVAL_PRICING:
"صاحب خودرو قیمت‌گذاری بیمه را رد کرد",
OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD:
"صاحب خودرو قطعات قیمت‌گذاری‌شده را امضا کرد و در انتظار بارگذاری فاکتور",
OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS:
@@ -129,8 +146,10 @@ export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
// Fanavaran sync
FANAVARAN_AUTO_SUBMIT_SUCCEEDED: "ارسال خودکار به فناوران موفق بود",
FANAVARAN_AUTO_SUBMIT_FAILED: "ارسال خودکار به فناوران ناموفق بود",
FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED: "ارسال زودهنگام خودکار به فناوران موفق بود",
FANAVARAN_EARLY_AUTO_SUBMIT_FAILED: "ارسال زودهنگام خودکار به فناوران ناموفق بود",
FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED:
"ارسال زودهنگام خودکار به فناوران موفق بود",
FANAVARAN_EARLY_AUTO_SUBMIT_FAILED:
"ارسال زودهنگام خودکار به فناوران ناموفق بود",
FANAVARAN_EXPERTISE_AUTO_SUBMIT_SUCCEEDED:
"ارسال خودکار کارشناسی به فناوران موفق بود",
FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED:
@@ -168,6 +187,38 @@ export const STEP_KEY_FA_LABELS: Record<string, string> = {
CLAIM_COMPLETED: "پرونده خسارت تکمیل شد",
};
const GENERIC_EVENT_FA_LABEL = "رویداد پرونده";
const GENERIC_EVENT_FA_DESCRIPTION = "رویدادی در روند پرونده ثبت شد.";
const SYSTEM_REASON_FA_TRANSLATIONS: Record<string, string> = {
"IN_PERSON expert-initiated: first party is always guilty; confession auto-resolved":
"در پرونده حضوری ایجادشده توسط کارشناس، طرف اول همیشه مقصر است؛ بنابراین مرحله اقرار به‌صورت خودکار تعیین تکلیف شد.",
"V6 call-center initiated: first party is always guilty; confession auto-resolved":
"در پرونده ایجادشده توسط مرکز تماس، طرف اول همیشه مقصر است؛ بنابراین مرحله اقرار به‌صورت خودکار تعیین تکلیف شد.",
};
/**
* Persian descriptions for workflow-step events. These are deliberately
* complete sentences because the insurer timeline exposes them as the event
* detail, while `STEP_KEY_FA_LABELS` is intended for short UI labels.
*/
const STEP_KEY_FA_DESCRIPTIONS: Record<string, string> = {
CLAIM_CREATED: "پرونده خسارت ایجاد شد.",
SELECT_OUTER_PARTS: "قطعات بیرونی آسیب‌دیده انتخاب و ثبت شدند.",
SELECT_OTHER_PARTS: "سایر قطعات آسیب‌دیده و اطلاعات بانکی ثبت شدند.",
CAPTURE_PART_DAMAGES: "تصاویر آسیب قطعات و تصاویر مورد نیاز خودرو ثبت شدند.",
UPLOAD_REQUIRED_DOCUMENTS: "مدارک مورد نیاز برای بررسی خسارت بارگذاری شدند.",
USER_SUBMISSION_COMPLETE:
"ثبت اطلاعات کاربر تکمیل شد و پرونده آماده بررسی کارشناس خسارت است.",
USER_EXPERT_RESEND: "مدارک درخواستی توسط کاربر دوباره ارسال شدند.",
EXPERT_DAMAGE_ASSESSMENT: "ارزیابی خسارت توسط کارشناس انجام شد.",
EXPERT_FINAL_REPLY: "پاسخ نهایی کارشناس ثبت شد.",
EXPERT_COST_EVALUATION: "هزینه خسارت توسط کارشناس ارزیابی شد.",
OWNER_UPLOAD_FACTOR_DOCUMENTS: "فاکتورهای تعمیر توسط مالک بارگذاری شدند.",
INSURER_REVIEW: "پرونده توسط بیمه‌گر بررسی شد.",
CLAIM_COMPLETED: "رسیدگی به پرونده خسارت تکمیل شد.",
};
/**
* For `STEP_COMPLETED` and `V3_STEP_COMPLETED` events whose final label
* depends on the `metadata.stepKey` value, this function returns the
@@ -177,10 +228,7 @@ export function resolveStepCompletedFaLabel(event: {
type: string;
metadata?: any;
}): string | undefined {
if (
event.type !== "STEP_COMPLETED" &&
event.type !== "V3_STEP_COMPLETED"
) {
if (event.type !== "STEP_COMPLETED" && event.type !== "V3_STEP_COMPLETED") {
return undefined;
}
const stepKey: string | undefined = event.metadata?.stepKey;
@@ -200,6 +248,50 @@ export function getEventFaLabel(event: {
return (
resolveStepCompletedFaLabel(event) ??
EVENT_TYPE_FA_LABELS[event.type] ??
event.type
GENERIC_EVENT_FA_LABEL
);
}
/**
* Returns a Persian sentence suitable for the timeline event `description`.
*
* History is persisted over time, so its older metadata can contain English
* system messages. The insurer endpoint uses this derived value instead of
* exposing persisted text, which localizes both old and new timeline records.
*/
export function getEventFaDescription(event: {
type: string;
metadata?: any;
}): string {
const stepKey: string | undefined = event.metadata?.stepKey;
if (stepKey && STEP_KEY_FA_DESCRIPTIONS[stepKey]) {
return STEP_KEY_FA_DESCRIPTIONS[stepKey];
}
const label =
resolveStepCompletedFaLabel(event) ?? EVENT_TYPE_FA_LABELS[event.type];
return label ? `${label}.` : GENERIC_EVENT_FA_DESCRIPTION;
}
/**
* Keeps the established metadata contract intact. Only a pre-existing
* description field is localized; no keys are added, removed, or renamed.
*/
export function localizeTimelineMetadata(event: {
type: string;
metadata?: Record<string, unknown> | null;
}): Record<string, unknown> | null {
if (!event.metadata) return null;
const reason = event.metadata.reason;
const localizedReason =
typeof reason === "string" ? SYSTEM_REASON_FA_TRANSLATIONS[reason] : null;
return {
...event.metadata,
...(Object.prototype.hasOwnProperty.call(event.metadata, "description")
? { description: getEventFaDescription(event) }
: {}),
...(localizedReason ? { reason: localizedReason } : {}),
};
}

View File

@@ -0,0 +1,17 @@
import { toJalaliDateAndTime } from "./date-jalali";
describe("toJalaliDateAndTime", () => {
it("always formats timestamps in Asia/Tehran regardless of server timezone", () => {
expect(toJalaliDateAndTime("2026-08-10T12:30:45.000Z")).toEqual([
"1405/05/19",
"16:00",
]);
});
it("uses the Tehran calendar day when UTC and Tehran dates differ", () => {
expect(toJalaliDateAndTime("2026-08-10T21:30:00.000Z")).toEqual([
"1405/05/20",
"01:00",
]);
});
});

View File

@@ -1,3 +1,5 @@
import { IRAN_TIMEZONE } from "./iran-datetime";
/**
* Converts an ISO date string or Date to Jalali (Persian) date and time.
* @param input - ISO date string (e.g. 2026-02-08T13:51:20.747+00:00) or Date
@@ -70,6 +72,7 @@ export function jalaliToGregorianDate(
*/
export function toJalaliDate(d: Date): string {
const persianDate = d.toLocaleDateString("fa-IR", {
timeZone: IRAN_TIMEZONE,
year: "numeric",
month: "2-digit",
day: "2-digit",
@@ -81,9 +84,12 @@ export function toJalaliDate(d: Date): string {
* Converts a Date to 24h time string (e.g. 13:37).
*/
export function toJalaliTime(d: Date): string {
const hours = d.getHours().toString().padStart(2, "0");
const minutes = d.getMinutes().toString().padStart(2, "0");
return `${hours}:${minutes}`;
return new Intl.DateTimeFormat("en-GB", {
timeZone: IRAN_TIMEZONE,
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
}).format(d);
}
/**

View File

@@ -1,4 +1,8 @@
import { getExpertReplyPricingValidationError } from "./expert-reply-pricing";
import {
EXPERT_REPLY_MAX_AMOUNT_TOMAN,
EXPERT_REPLY_MIN_AMOUNT_TOMAN,
getExpertReplyPricingValidationError,
} from "./expert-reply-pricing";
import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-damage.enum";
import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum";
@@ -121,4 +125,41 @@ describe("getExpertReplyPricingValidationError", () => {
]),
).toBeNull();
});
it.each([
["price", "99,999", "parts[0].price"],
["salary", "10,000,000,001", "parts[0].salary"],
["totalPayment", "99,999", "parts[0].totalPayment"],
["daghi.price", "10,000,000,001", "parts[0].daghi.price"],
])(
"enforces the amount range for %s",
(field, invalidValue, expectedField) => {
const part = {
partId: 201,
typeOfDamage: TypeOfDamage.Change,
price: "100000",
salary: "100000",
totalPayment: "100000",
daghi: {
option: DaghiOption.RECYCLED_PARTS_VALUE,
price: "100000",
},
};
if (field === "daghi.price") part.daghi.price = invalidValue;
else part[field] = invalidValue;
expect(
getExpertReplyPricingValidationError([part], {
locale: "fa",
enforceAmountBounds: true,
}),
).toMatchObject({
code: "EXPERT_REPLY_VALIDATION_ERROR",
field: expectedField,
rule: "amount_out_of_range",
minAmount: EXPERT_REPLY_MIN_AMOUNT_TOMAN,
maxAmount: EXPERT_REPLY_MAX_AMOUNT_TOMAN,
});
},
);
});

View File

@@ -11,6 +11,34 @@ type ExpertReplyPricingPart = {
daghi?: { option?: unknown; price?: unknown };
};
export const EXPERT_REPLY_MIN_AMOUNT_TOMAN = 100_000;
export const EXPERT_REPLY_MAX_AMOUNT_TOMAN = 10_000_000_000;
export type ExpertReplyPricingValidationError = {
message: string;
error: "EXPERT_REPLY_VALIDATION_ERROR";
code: "EXPERT_REPLY_VALIDATION_ERROR";
field: string;
partId?: string | number;
rule:
| "required"
| "invalid_value"
| "invalid_amount"
| "amount_out_of_range";
minAmount?: number;
maxAmount?: number;
};
type ValidationOptions = {
/** Preserve legacy English strings unless the V2 endpoint explicitly asks for a localized response. */
locale?: "fa";
enforceAmountBounds?: boolean;
};
function toPersianAmount(amount: number): string {
return amount.toLocaleString("fa-IR");
}
/**
* Validates the pricing that an expert must provide for every submitted
* damaged-part line. This is deliberately independent of DTO validation:
@@ -19,9 +47,33 @@ type ExpertReplyPricingPart = {
*/
export function getExpertReplyPricingValidationError(
parts: unknown,
): string | null {
options: ValidationOptions = {},
): string | ExpertReplyPricingValidationError | null {
const localizedError = (
message: string,
field: string,
rule: ExpertReplyPricingValidationError["rule"],
partId?: string | number,
range?: { minAmount: number; maxAmount: number },
): string | ExpertReplyPricingValidationError => {
if (options.locale !== "fa") return message;
return {
message,
error: "EXPERT_REPLY_VALIDATION_ERROR",
code: "EXPERT_REPLY_VALIDATION_ERROR",
field,
...(partId != null && { partId }),
rule,
...(range ?? {}),
};
};
if (!Array.isArray(parts) || parts.length === 0) {
return "At least one damaged part with pricing is required to submit an expert reply.";
return localizedError(
"برای ثبت پاسخ کارشناسی، حداقل یک قطعه آسیب‌دیده همراه با مبلغ لازم است.",
"parts",
"required",
);
}
for (const [index, rawPart] of parts.entries()) {
@@ -32,13 +84,22 @@ export function getExpertReplyPricingValidationError(
: `Damaged part ${index + 1}`;
if (!part || typeof part !== "object" || part.partId == null) {
return `${label} must include a damaged-part partId.`;
return localizedError(
`شناسه قطعه در ردیف ${index + 1} الزامی است.`,
`parts[${index}].partId`,
"required",
);
}
if (
!Object.values(TypeOfDamage).includes(part.typeOfDamage as TypeOfDamage)
) {
return `${label} requires typeOfDamage to be either '${TypeOfDamage.Repair}' or '${TypeOfDamage.Change}'.`;
return localizedError(
`نوع خسارت قطعه ${String(part.partId)} معتبر نیست.`,
`parts[${index}].typeOfDamage`,
"invalid_value",
String(part.partId),
);
}
const daghi = part.daghi;
@@ -47,7 +108,12 @@ export function getExpertReplyPricingValidationError(
(!daghi ||
!Object.values(DaghiOption).includes(daghi.option as DaghiOption))
) {
return `${label} requires a valid daghi option.`;
return localizedError(
`گزینه داغی برای قطعه ${String(part.partId)} الزامی و باید معتبر باشد.`,
`parts[${index}].daghi.option`,
"required",
String(part.partId),
);
}
const price = parseMoneyAmountToman(part.price);
@@ -60,21 +126,96 @@ export function getExpertReplyPricingValidationError(
const amountIsValid = (amount: number | null) => amount !== null;
const priceIsRequired = part.typeOfDamage === TypeOfDamage.Change;
const priceIsValid = !hasPrice || amountIsValid(price);
if (
!amountIsValid(salary) ||
!amountIsValid(totalPayment) ||
(priceIsRequired && !amountIsValid(price)) ||
!priceIsValid
) {
const requiredAmountFields: Array<[
"price" | "salary" | "totalPayment",
number | null,
boolean,
]> = [
["price", price, priceIsRequired || hasPrice],
["salary", salary, true],
["totalPayment", totalPayment, true],
];
const invalidAmount = requiredAmountFields.find(
([, amount, required]) => required && !amountIsValid(amount),
);
if (invalidAmount) {
const field = invalidAmount[0] as "price" | "salary" | "totalPayment";
if (options.locale === "fa") {
const fieldName =
field === "price"
? "قیمت قطعه"
: field === "salary"
? "دستمزد"
: "مبلغ کل";
return localizedError(
`${fieldName} قطعه ${String(part.partId)} باید به‌صورت مبلغ صحیح و غیرمنفی (تومان) وارد شود.`,
`parts[${index}].${field}`,
"invalid_amount",
String(part.partId),
);
}
return `${label} requires valid salary and totalPayment; price is also required for '${TypeOfDamage.Change}' damage. Price, salary, and totalPayment may be 0.`;
}
if (options.enforceAmountBounds) {
const monetaryFields: Array<[
"price" | "salary" | "totalPayment" | "daghi.price",
number | null,
boolean,
]> = [
["price", price, priceIsRequired || hasPrice],
["salary", salary, true],
["totalPayment", totalPayment, true],
[
"daghi.price",
daghiPrice,
daghi?.option === DaghiOption.RECYCLED_PARTS_VALUE,
],
];
const outOfRange = monetaryFields.find(
([, amount, required]) =>
required &&
amount !== null &&
(amount < EXPERT_REPLY_MIN_AMOUNT_TOMAN ||
amount > EXPERT_REPLY_MAX_AMOUNT_TOMAN),
);
if (outOfRange) {
const [field] = outOfRange;
const fieldName =
field === "price"
? "قیمت قطعه"
: field === "salary"
? "دستمزد"
: field === "totalPayment"
? "مبلغ کل"
: "قیمت داغی";
return localizedError(
`${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),
{
minAmount: EXPERT_REPLY_MIN_AMOUNT_TOMAN,
maxAmount: EXPERT_REPLY_MAX_AMOUNT_TOMAN,
},
);
}
}
if (
daghi?.option === DaghiOption.RECYCLED_PARTS_VALUE &&
daghiPrice === null
) {
if (options.locale === "fa") {
return localizedError(
`قیمت داغی قطعه ${String(part.partId)} باید به‌صورت مبلغ صحیح و غیرمنفی (تومان) وارد شود.`,
`parts[${index}].daghi.price`,
"invalid_amount",
String(part.partId),
);
}
return `${label} requires a valid daghi price when option is '${DaghiOption.RECYCLED_PARTS_VALUE}'.`;
}
}

View File

@@ -1,44 +1,9 @@
import { ApiProperty } from "@nestjs/swagger";
import { PlatesDto } from "src/plates/dto/plate.dto";
import { Plates } from "src/Types&Enums/plate.interface";
import { InquiryParticipantFieldsDto } from "src/common/dto/inquiry-participants.dto";
export class AddPlateDto {
plateId: string;
@ApiProperty({ type: String, required: true })
nationalCodeOfInsurer: string;
@ApiProperty({ type: String, required: true })
nationalCodeOfDriver: string;
@ApiProperty({ type: String, required: true })
insurerLicense: string;
@ApiProperty({ type: String, required: true })
driverLicense: string;
@ApiProperty({ type: PlatesDto, required: true })
plate: Plates;
@ApiProperty({ type: Boolean, required: true })
driverIsInsurer: boolean;
@ApiProperty({ type: Boolean, required: true, default: false })
isNewCar: boolean;
@ApiProperty({ type: Boolean, required: true })
userNoCertificate: boolean;
@ApiProperty({
type: Number,
required: true,
})
insurerBirthday: number;
@ApiProperty({
type: String,
required: false,
})
driverBirthday: string | null;
}
export class AddPlateDto extends InquiryParticipantFieldsDto {}
export class AddPlateProfileDto {
plateId: string;

View File

@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsNotEmpty, IsOptional, IsString, MaxLength } from "class-validator";
import { IsNotEmpty, IsOptional, IsString } from "class-validator";
import { Types } from "mongoose";
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
import { StepsEnum } from "src/Types&Enums/blame-request-management/steps.enum";
@@ -10,6 +10,7 @@ import {
} from "src/Types&Enums/blame-request-management/accident-conditions.enum";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { IsEnum } from "class-validator";
import { InquiryParticipantFieldsDto } from "src/common/dto/inquiry-participants.dto";
export class InitialFormDto {
@ApiProperty({ required: false, default: false })
@@ -222,51 +223,8 @@ export class BlameConfessionDtoV2 {
imGuilty?: boolean;
}
/**
* V2 initial-form step submitted with a VIN/chassis number instead of a plate.
* All identity and license fields from {@link AddPlateDto} are preserved; only
* `plate` is replaced by `vin` (the 17-character chassis / VIN string).
*/
export class InitialFormVinDto {
@ApiProperty({
type: String,
required: true,
description: "17-character VIN / chassis number (شماره شاسی)",
example: "NAAM01E15HK123456",
maxLength: 17,
})
@IsString()
@IsNotEmpty()
@MaxLength(17)
vin: string;
@ApiProperty({ type: String, required: true })
nationalCodeOfInsurer: string;
@ApiProperty({ type: String, required: true })
nationalCodeOfDriver: string;
@ApiProperty({ type: String, required: true })
insurerLicense: string;
@ApiProperty({ type: String, required: true })
driverLicense: string;
@ApiProperty({ type: Boolean, required: true })
driverIsInsurer: boolean;
@ApiProperty({ type: Boolean, required: true, default: false })
isNewCar: boolean;
@ApiProperty({ type: Boolean, required: true })
userNoCertificate: boolean;
@ApiProperty({ type: Number, required: true })
insurerBirthday: number;
@ApiPropertyOptional({ type: String, required: false })
driverBirthday: string | null;
}
/** V2 initial-form step submitted with the shared structured vehicle contract. */
export class InitialFormVinDto extends InquiryParticipantFieldsDto {}
// export class DocsOfThisFile {
// @ApiProperty()

View File

@@ -1,143 +1,14 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsBoolean,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
ValidateNested,
} from "class-validator";
import { Type } from "class-transformer";
class PlateV6Dto {
@ApiProperty({ example: "44", description: "Left two digits" })
@IsString()
@IsNotEmpty()
leftDigits: string;
@ApiProperty({ example: "ب", description: "Center alphabet letter" })
@IsString()
@IsNotEmpty()
centerAlphabet: string;
@ApiProperty({ example: "111", description: "Center three digits" })
@IsString()
@IsNotEmpty()
centerDigits: string;
@ApiProperty({ example: "22", description: "Right two digits (Iran region code)" })
@IsString()
@IsNotEmpty()
ir: string;
}
import { InquiryParticipantFieldsDto } from "src/common/dto/inquiry-participants.dto";
/**
* Inquiry body for the V6 call-center flow.
* Same as V3 but without `sheba` — the user adds their own IBAN later via the link.
*/
export class RunCallCenterInquiryV6Dto {
@ApiProperty({
type: PlateV6Dto,
description: "Plate segments — Tejarat block / third-party inquiry.",
})
@ValidateNested()
@Type(() => PlateV6Dto)
plate: PlateV6Dto;
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
@IsString()
@IsNotEmpty()
nationalCodeOfInsurer: string;
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
@IsString()
@IsNotEmpty()
nationalCodeOfDriver: string;
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
@IsBoolean()
driverIsInsurer: boolean;
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
insurerBirthday: number | string;
@ApiPropertyOptional({
example: 13780624,
description: "Driver birth date (Jalali). Required when driverIsInsurer is false.",
})
@IsOptional()
driverBirthday?: number | string | null;
@ApiPropertyOptional({
example: "123456789",
description: "Driver license (required when driverIsInsurer is false).",
})
@IsOptional()
@IsString()
driverLicense?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Insurer license (required when driverIsInsurer is true).",
})
@IsOptional()
@IsString()
insurerLicense?: string;
}
export class RunCallCenterInquiryV6Dto extends InquiryParticipantFieldsDto {}
/**
* VIN / chassis variant of the V6 call-center inquiry.
* Identical to `RunCallCenterInquiryV6Dto` but replaces `plate` with `vin`.
* Sheba (IBAN) is intentionally absent — the user provides it themselves via the link.
*/
export class RunCallCenterInquiryVinV6Dto {
@ApiProperty({
example: "NAAM01E15HK123456",
description: "17-character VIN / chassis number (شماره شاسی)",
maxLength: 17,
})
@IsString()
@IsNotEmpty()
@MaxLength(17)
vin: string;
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
@IsString()
@IsNotEmpty()
nationalCodeOfInsurer: string;
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
@IsString()
@IsNotEmpty()
nationalCodeOfDriver: string;
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
@IsBoolean()
driverIsInsurer: boolean;
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
insurerBirthday: number | string;
@ApiPropertyOptional({
example: 13780624,
description: "Driver birth date (Jalali). Required when driverIsInsurer is false.",
})
@IsOptional()
driverBirthday?: number | string | null;
@ApiPropertyOptional({
example: "123456789",
description: "Driver license (required when driverIsInsurer is false).",
})
@IsOptional()
@IsString()
driverLicense?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Insurer license (required when driverIsInsurer is true).",
})
@IsOptional()
@IsString()
insurerLicense?: string;
}
export class RunCallCenterInquiryVinV6Dto extends InquiryParticipantFieldsDto {}

View File

@@ -1,70 +1,12 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsBoolean,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
ValidateNested,
} from "class-validator";
import { Type } from "class-transformer";
class PlateV3Dto {
@ApiProperty({ example: "44", description: "Left two digits" })
@IsString()
@IsNotEmpty()
leftDigits: string;
@ApiProperty({ example: "ب", description: "Center alphabet letter" })
@IsString()
@IsNotEmpty()
centerAlphabet: string;
@ApiProperty({ example: "111", description: "Center three digits" })
@IsString()
@IsNotEmpty()
centerDigits: string;
@ApiProperty({ example: "22", description: "Right two digits (Iran region code)" })
@IsString()
@IsNotEmpty()
ir: string;
}
import { ApiPropertyOptional } from "@nestjs/swagger";
import { IsOptional, IsString } from "class-validator";
import { InquiryParticipantFieldsDto } from "src/common/dto/inquiry-participants.dto";
/**
* Body for `POST run-inquiries/:requestId`.
* First call = guilty party (+ auto claim). Second call = damaged party (THIRD_PARTY only).
*/
export class RunInquiriesV3Dto {
@ApiProperty({
type: PlateV3Dto,
description: "Plate segments — Tejarat block / third-party inquiry.",
})
@ValidateNested()
@Type(() => PlateV3Dto)
plate: PlateV3Dto;
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
@IsString()
@IsNotEmpty()
nationalCodeOfInsurer: string;
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
@IsString()
@IsNotEmpty()
nationalCodeOfDriver: string;
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
@IsBoolean()
driverIsInsurer: boolean;
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
insurerBirthday: number | string;
@ApiPropertyOptional({ example: 13780624, description: "Driver birth date (Jalali). Required when driverIsInsurer is false." })
@IsOptional()
driverBirthday?: number | string | null;
export class RunInquiriesV3Dto extends InquiryParticipantFieldsDto {
@ApiPropertyOptional({
example: "IR123456789012345678901234",
description:
@@ -73,32 +15,6 @@ export class RunInquiriesV3Dto {
@IsOptional()
@IsString()
sheba?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Driver license (required when driverIsInsurer is false).",
})
@IsOptional()
@IsString()
driverLicense?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Insurer license (required when driverIsInsurer is true).",
})
@IsOptional()
@IsString()
insurerLicense?: string;
@ApiPropertyOptional({
example: "1",
description:
"Driving licence type code from GET /lookups/driving-licence-types. " +
"Optional — used in V4 FileMaker flow.",
})
@IsOptional()
@IsString()
licenseType?: string;
}
/**
@@ -106,38 +22,7 @@ export class RunInquiriesV3Dto {
* Identical to RunInquiriesV3Dto but uses `vin` (17-char chassis number) instead of `plate`.
* First call = guilty party (+ auto claim). Second call = damaged party (THIRD_PARTY only).
*/
export class RunInquiriesVinV3Dto {
@ApiProperty({
example: "NAAM01E15HK123456",
description: "17-character VIN / chassis number (شماره شاسی)",
maxLength: 17,
})
@IsString()
@IsNotEmpty()
@MaxLength(17)
vin: string;
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
@IsString()
@IsNotEmpty()
nationalCodeOfInsurer: string;
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
@IsString()
@IsNotEmpty()
nationalCodeOfDriver: string;
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
@IsBoolean()
driverIsInsurer: boolean;
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
insurerBirthday: number | string;
@ApiPropertyOptional({ example: 13780624, description: "Driver birth date (Jalali). Required when driverIsInsurer is false." })
@IsOptional()
driverBirthday?: number | string | null;
export class RunInquiriesVinV3Dto extends InquiryParticipantFieldsDto {
@ApiPropertyOptional({
example: "IR123456789012345678901234",
description:
@@ -146,30 +31,4 @@ export class RunInquiriesVinV3Dto {
@IsOptional()
@IsString()
sheba?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Driver license (required when driverIsInsurer is false).",
})
@IsOptional()
@IsString()
driverLicense?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Insurer license (required when driverIsInsurer is true).",
})
@IsOptional()
@IsString()
insurerLicense?: string;
@ApiPropertyOptional({
example: "1",
description:
"Driving licence type code from GET /lookups/driving-licence-types. " +
"Optional — used in V4 FileMaker flow.",
})
@IsOptional()
@IsString()
licenseType?: string;
}

View File

@@ -38,8 +38,8 @@ export class Person {
@Prop({ type: Boolean })
userNoCertificate?: boolean;
@Prop({ type: Number })
insurerBirthday?: number;
@Prop({ type: String })
insurerBirthday?: string;
@Prop({ type: String })
driverBirthday?: string | null;
@@ -50,6 +50,38 @@ export class Person {
}
export const PersonSchema = SchemaFactory.createForClass(Person);
@Schema({ _id: false })
export class InquiryParticipant {
@Prop({ required: true })
participantId: string;
@Prop()
nationalCode: string;
@Prop()
birthday: string;
@Prop() fullName?: string;
@Prop() phoneNumber?: string;
@Prop({ type: Boolean }) hasDrivingLicense?: boolean;
@Prop() licenseNumber?: string;
@Prop() licenseType?: string;
@Prop({ type: Boolean }) unknown?: boolean;
}
export const InquiryParticipantSchema =
SchemaFactory.createForClass(InquiryParticipant);
@Schema({ _id: false })
export class InquiryParticipantRoles {
@Prop() driver?: string;
@Prop() vehicleOwner?: string;
@Prop() thirdPartyPolicyholder?: string;
@Prop() carBodyPolicyholder?: string;
}
export const InquiryParticipantRolesSchema = SchemaFactory.createForClass(
InquiryParticipantRoles,
);
@Schema({ _id: false })
export class Vehicle {
@Prop() plateId?: string;
@@ -58,7 +90,10 @@ export class Vehicle {
@Prop() name?: string;
@Prop() model?: string;
@Prop() type?: string;
@Prop() isNew?: boolean;
@Prop({ type: Boolean }) isNewCar?: boolean;
@Prop({ enum: ["CURRENT", "RECENTLY_TRANSFERRED"] })
registrationState?: "CURRENT" | "RECENTLY_TRANSFERRED";
@Prop() previousPlateId?: string;
/**
* Full external inquiry payload (Tejarat/SandHub) stored as-is
@@ -123,7 +158,6 @@ export const InsuranceSchema = SchemaFactory.createForClass(Insurance);
@Schema({ _id: false })
export class PartyStatement {
@Prop({ default: false })
acceptsExpertOpinion?: boolean;
@@ -143,11 +177,11 @@ export class PartyStatement {
@Prop() roadCondition?: string;
@Prop() lightCondition?: string;
}
export const PartyStatementSchema = SchemaFactory.createForClass(PartyStatement);
export const PartyStatementSchema =
SchemaFactory.createForClass(PartyStatement);
@Schema({ _id: false })
export class EvidenceBundle {
@Prop({ type: [String] })
images?: string[];
@@ -156,7 +190,8 @@ export class EvidenceBundle {
@Prop() videoId?: string;
}
export const EvidenceBundleSchema = SchemaFactory.createForClass(EvidenceBundle);
export const EvidenceBundleSchema =
SchemaFactory.createForClass(EvidenceBundle);
@Schema({ _id: false })
export class Signature {
@@ -178,13 +213,19 @@ export const PartyConfirmationSchema =
@Schema({ _id: false })
export class Party {
@Prop({ enum: PartyRole })
role: PartyRole;
@Prop({ type: PersonSchema })
person: Person;
/** Distinct people involved with this vehicle; roles below reference participantId. */
@Prop({ type: [InquiryParticipantSchema], default: undefined })
participants?: InquiryParticipant[];
@Prop({ type: InquiryParticipantRolesSchema })
participantRoles?: InquiryParticipantRoles;
/**
* CAR_BODY only: first form – accident with car vs object.
* Second form (guilty/damaged) may be added later as carBodySecondForm.

View File

@@ -146,6 +146,22 @@ export class FirstPartyDetail {
@Prop({ type: Boolean })
firstPartyCertificate: boolean | null;
@Prop({ type: [MongooseSchema.Types.Mixed] })
participants?: Record<string, unknown>[];
@Prop({ type: MongooseSchema.Types.Mixed })
participantRoles?: Record<string, string>;
@Prop({ type: MongooseSchema.Types.Mixed })
participantInquiries?: Record<string, unknown>;
@Prop({ type: MongooseSchema.Types.Mixed })
policyInquiry?: Record<string, unknown>;
@Prop() registrationState?: string;
@Prop() previousPlateId?: string;
@Prop() vehicleVin?: string;
}
export class SecondPartyDetail {
@@ -178,6 +194,22 @@ export class SecondPartyDetail {
@Prop({ type: SecondPartyFile })
secondPartyFiles?: SecondPartyFile;
@Prop({ type: [MongooseSchema.Types.Mixed] })
participants?: Record<string, unknown>[];
@Prop({ type: MongooseSchema.Types.Mixed })
participantRoles?: Record<string, string>;
@Prop({ type: MongooseSchema.Types.Mixed })
participantInquiries?: Record<string, unknown>;
@Prop({ type: MongooseSchema.Types.Mixed })
policyInquiry?: Record<string, unknown>;
@Prop() registrationState?: string;
@Prop() previousPlateId?: string;
@Prop() vehicleVin?: string;
}
export class LocationDto {

View File

@@ -0,0 +1,219 @@
import { Types } from "mongoose";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { CreationMethod } from "./entities/schema/request-management.schema";
import { PartyRole } from "./entities/schema/partyRole.enum";
import { RequestManagementService } from "./request-management.service";
describe("RequestManagementService V4 FileMaker workflow", () => {
it("persists FIRST_INITIAL_FORM after the first party OTP is verified", async () => {
const fileMakerId = new Types.ObjectId();
const userId = new Types.ObjectId();
const request = {
_id: new Types.ObjectId(),
publicId: "BL-V4-001",
type: BlameRequestType.THIRD_PARTY,
expertInitiated: true,
isMadeByFileMaker: true,
requiresFileMakerApproval: false,
initiatedByFieldExpertId: fileMakerId,
creationMethod: CreationMethod.IN_PERSON,
parties: [{ role: PartyRole.FIRST, person: {} }],
workflow: {
currentStep: WorkflowStep.CREATED,
nextStep: WorkflowStep.FIRST_BLAME_CONFESSION,
completedSteps: [WorkflowStep.CREATED],
},
history: [],
save: jest.fn().mockResolvedValue(undefined),
};
const service =
new (RequestManagementService as any)() as RequestManagementService;
(service as any).blameRequestDbService = {
findById: jest.fn().mockResolvedValue(request),
};
(service as any).userDbService = {
findOne: jest.fn().mockResolvedValue({
_id: userId,
otp: "hashed-otp",
otpExpire: Date.now() + 60_000,
}),
};
(service as any).hashService = {
compare: jest.fn().mockResolvedValue(true),
};
(service as any).claimCaseDbService = {
findOne: jest.fn().mockResolvedValue(null),
};
(service as any).workflowStepDbService = {
findByStepNumber: jest.fn().mockImplementation((stepNumber: number) => {
if (stepNumber === 2) {
return {
stepNumber: 2,
stepKey: WorkflowStep.FIRST_BLAME_CONFESSION,
nextPossibleSteps: [WorkflowStep.FIRST_VIDEO],
};
}
if (stepNumber === 3) {
return {
stepNumber: 3,
stepKey: WorkflowStep.FIRST_VIDEO,
nextPossibleSteps: [WorkflowStep.FIRST_INITIAL_FORM],
};
}
return null;
}),
findByStepKey: jest.fn().mockResolvedValue(null),
};
await service.verifyPartyOtpV2(
{
sub: String(fileMakerId),
role: RoleEnum.FILE_MAKER,
firstName: "File",
lastName: "Maker",
},
String(request._id),
{
phoneNumber: "09121234567",
otp: "12345",
partyRole: "FIRST",
},
);
expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM);
expect(request.workflow.currentStep).not.toBe(WorkflowStep.FIRST_VIDEO);
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE);
expect(request.workflow.completedSteps).not.toContain(
WorkflowStep.FIRST_VIDEO,
);
expect(request.save).toHaveBeenCalled();
const reopened = await service.getMyFileMakerFileDetail(
{ sub: String(fileMakerId), role: RoleEnum.FILE_MAKER },
String(request._id),
);
expect(reopened.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM);
expect(reopened.workflow.currentStep).not.toBe(WorkflowStep.FIRST_VIDEO);
});
it("keeps FIRST_VIDEO out of the FileMaker car-body workflow", async () => {
const fileMakerId = new Types.ObjectId();
const request = {
_id: new Types.ObjectId(),
publicId: "BL-V4-002",
type: BlameRequestType.CAR_BODY,
expertInitiated: true,
isMadeByFileMaker: true,
requiresFileMakerApproval: false,
initiatedByFieldExpertId: fileMakerId,
creationMethod: CreationMethod.IN_PERSON,
parties: [{ role: PartyRole.FIRST, person: {} }],
workflow: {
currentStep: WorkflowStep.CREATED,
nextStep: WorkflowStep.CAR_BODY_ACCIDENT_TYPE,
completedSteps: [WorkflowStep.CREATED],
},
history: [],
save: jest.fn().mockResolvedValue(undefined),
};
const service =
new (RequestManagementService as any)() as RequestManagementService;
(service as any).blameRequestDbService = {
findById: jest.fn().mockResolvedValue(request),
};
(service as any).userDbService = {
findOne: jest.fn().mockResolvedValue({
_id: new Types.ObjectId(),
otp: "hashed-otp",
otpExpire: Date.now() + 60_000,
}),
};
(service as any).hashService = {
compare: jest.fn().mockResolvedValue(true),
};
(service as any).workflowStepDbService = {
findByStepNumber: jest.fn().mockResolvedValue(null),
findByStepKey: jest.fn().mockResolvedValue({
stepNumber: 2,
stepKey: WorkflowStep.CAR_BODY_ACCIDENT_TYPE,
nextPossibleSteps: [WorkflowStep.FIRST_VIDEO],
}),
};
const actor = {
sub: String(fileMakerId),
role: RoleEnum.FILE_MAKER,
firstName: "File",
lastName: "Maker",
};
await service.verifyPartyOtpV2(actor, String(request._id), {
phoneNumber: "09121234567",
otp: "12345",
partyRole: "FIRST",
});
expect(request.workflow.currentStep).toBe(
WorkflowStep.CAR_BODY_ACCIDENT_TYPE,
);
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_INITIAL_FORM);
await service.carBodyAccidentTypeFormV3(
String(request._id),
{ car: true, object: false },
actor,
);
expect(request.workflow.currentStep).toBe(WorkflowStep.FIRST_INITIAL_FORM);
expect(request.workflow.nextStep).toBe(WorkflowStep.FIRST_VOICE);
expect(request.workflow.completedSteps).not.toContain(
WorkflowStep.FIRST_VIDEO,
);
});
it("repairs legacy stuck workflow values when a V4 file is reopened", async () => {
const fileMakerId = new Types.ObjectId();
const request = {
_id: new Types.ObjectId(),
publicId: "BL-V4-LEGACY",
type: BlameRequestType.THIRD_PARTY,
isMadeByFileMaker: true,
initiatedByFieldExpertId: fileMakerId,
workflow: {
currentStep: WorkflowStep.FIRST_VIDEO,
nextStep: WorkflowStep.FIRST_INITIAL_FORM,
completedSteps: [
WorkflowStep.CREATED,
WorkflowStep.FIRST_BLAME_CONFESSION,
],
},
parties: [
{ role: PartyRole.FIRST, person: { userId: new Types.ObjectId() } },
],
};
const service =
new (RequestManagementService as any)() as RequestManagementService;
(service as any).blameRequestDbService = {
findById: jest.fn().mockResolvedValue(request),
};
(service as any).claimCaseDbService = {
findOne: jest.fn().mockResolvedValue(null),
};
const reopened = await service.getMyFileMakerFileDetail(
{ sub: String(fileMakerId), role: RoleEnum.FILE_MAKER },
String(request._id),
);
expect(reopened.workflow).toEqual(
expect.objectContaining({
currentStep: WorkflowStep.FIRST_INITIAL_FORM,
nextStep: WorkflowStep.FIRST_VOICE,
}),
);
expect(reopened.workflow.completedSteps).not.toContain(
WorkflowStep.FIRST_VIDEO,
);
});
});

View File

@@ -350,14 +350,13 @@ export class FileReviewerBlameV4Controller {
@ApiParam({ name: "claimRequestId" })
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "Signature file, agreement, and branch",
description: "Signature file and agreement",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
required: ["sign", "agree"],
properties: {
sign: { type: "string", format: "binary", description: "Signature image" },
agree: { type: "boolean", description: "true to accept, false to reject" },
branchId: { type: "string", description: "Insurer branch ID" },
},
},
})
@@ -386,7 +385,6 @@ export class FileReviewerBlameV4Controller {
async submitOwnerSign(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() fileReviewer: any,
@UploadedFile() sign: Express.Multer.File,
) {
@@ -399,7 +397,6 @@ export class FileReviewerBlameV4Controller {
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
fileReviewer.sub,
fileReviewer,

View File

@@ -348,14 +348,13 @@ export class FileReviewerBlameV5Controller {
@ApiParam({ name: "claimRequestId" })
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "Signature file, agreement, and branch",
description: "Signature file and agreement",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
required: ["sign", "agree"],
properties: {
sign: { type: "string", format: "binary", description: "Signature image" },
agree: { type: "boolean", description: "true to accept, false to reject" },
branchId: { type: "string", description: "Insurer branch ID" },
},
},
})
@@ -384,7 +383,6 @@ export class FileReviewerBlameV5Controller {
async submitOwnerSign(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() fileReviewer: any,
@UploadedFile() sign: Express.Multer.File,
) {
@@ -397,7 +395,6 @@ export class FileReviewerBlameV5Controller {
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
fileReviewer.sub,
fileReviewer,

View File

@@ -0,0 +1,118 @@
import { model, Types } from "mongoose";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import {
BlameRequest,
BlameRequestSchema,
} from "./entities/schema/blame-cases.schema";
import { PartyRole } from "./entities/schema/partyRole.enum";
import { normalizeInquirySubmission } from "./inquiry-participant-resolver";
describe("inquiry participant persistence", () => {
it("accepts slash-formatted Jalali birthdays from the structured payload", () => {
const submission = normalizeInquirySubmission(
BlameRequestType.THIRD_PARTY,
{
driver: {
nationalCode: "0022324224",
birthday: "1378/04/26",
hasDrivingLicense: true,
licenseNumber: "1001011111",
licenseType: "10",
},
vehicleOwner: {
nationalCode: "5560568341",
birthday: "1378/06/27",
},
thirdPartyPolicyholder: { sameAs: "VEHICLE_OWNER" },
vehicle: {
registrationState: "CURRENT",
currentPlate: {
leftDigits: "59",
centerAlphabet: "ی",
centerDigits: "419",
ir: "78",
},
isNewCar: false,
},
},
);
const BlameRequestModel = model<BlameRequest>(
"InquiryParticipantBirthdayPersistenceTest",
BlameRequestSchema,
);
const request = new BlameRequestModel({
requestNo: "BL-PARTICIPANT-BIRTHDAY",
publicId: "PARTICIPANT-BIRTHDAY",
type: BlameRequestType.THIRD_PARTY,
parties: [
{
role: PartyRole.FIRST,
person: {
insurerBirthday: submission.dto.insurerBirthday,
driverBirthday: submission.dto.driverBirthday,
},
participants: submission.participants.participants,
participantRoles: submission.participants.roles,
},
],
});
expect(request.validateSync()).toBeUndefined();
expect(request.parties[0].person.insurerBirthday).toBe("1378/06/27");
expect(request.parties[0].person.driverBirthday).toBe("1378/04/26");
});
it("recasts populated party subdocuments during an inquiry-audit update", () => {
const BlameRequestModel = model<BlameRequest>(
"InquiryParticipantAuditPersistenceTest",
BlameRequestSchema,
);
const request = new BlameRequestModel({
requestNo: "BL-PARTICIPANT-AUDIT",
publicId: "PARTICIPANT-AUDIT",
type: BlameRequestType.THIRD_PARTY,
parties: [
{
role: PartyRole.FIRST,
person: {
userId: new Types.ObjectId(),
phoneNumber: "09120723528",
},
statement: {
acceptsExpertOpinion: false,
claimsDamage: false,
admitsGuilt: true,
},
participants: [
{
participantId: "DRIVER",
nationalCode: "0022324224",
birthday: "1378/04/26",
hasDrivingLicense: true,
licenseNumber: "1001011111",
licenseType: "10",
},
],
participantRoles: {
driver: "DRIVER",
vehicleOwner: "DRIVER",
thirdPartyPolicyholder: "DRIVER",
},
vehicle: {
registrationState: "CURRENT",
plateId: "78-59-ی-419",
},
},
],
inquiries: {},
});
const query = BlameRequestModel.findByIdAndUpdate(request._id, {
$set: {
inquiries: request.inquiries,
parties: request.parties,
},
});
expect(() => (query as any)._castUpdate(query.getUpdate())).not.toThrow();
});
});

View File

@@ -0,0 +1,566 @@
import { BadRequestException } from "@nestjs/common";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import {
InquiryParticipantRole,
VehicleRegistrationState,
} from "src/common/dto/inquiry-participants.dto";
import {
assertPreviousPlateInquiryMatchesVin,
isMappedPolicyCurrent,
normalizeInquirySubmission,
participantForRole,
participantForStoredPartyRole,
resolveInquiryParticipants,
resolveInquirySubjects,
resolveInquiryVehicle,
runPlateInquiryWithFallback,
vehiclePlateCandidates,
} from "./inquiry-participant-resolver";
describe("inquiry participant resolver", () => {
it("links several roles to one explicitly shared person", () => {
const resolved = resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, {
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: true,
licenseNumber: "123456789",
licenseType: "1",
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
sameAs: InquiryParticipantRole.VEHICLE_OWNER,
},
});
expect(resolved.participants).toHaveLength(1);
expect(resolved.roles).toEqual({
driver: "DRIVER",
vehicleOwner: "DRIVER",
thirdPartyPolicyholder: "DRIVER",
});
});
it("requires both previous plate and VIN for a recent transfer", () => {
expect(() =>
resolveInquiryVehicle({
registrationState: VehicleRegistrationState.RECENTLY_TRANSFERRED,
currentPlate: {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
},
}),
).toThrow(BadRequestException);
});
it("defaults an omitted registration state to CURRENT", () => {
expect(
resolveInquiryVehicle({
currentPlate: {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
},
}).registrationState,
).toBe(VehicleRegistrationState.CURRENT);
});
it("rejects the removed flat inquiry contract", () => {
expect(() =>
resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, {
nationalCodeOfDriver: "0012345678",
driverBirthday: "1370/01/01",
driverLicense: "123456789",
nationalCodeOfInsurer: "0098765432",
insurerBirthday: "1360/02/02",
driverIsInsurer: false,
} as any),
).toThrow(BadRequestException);
});
it("rejects phone numbers in participant inquiry identity", () => {
expect(() =>
resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, {
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: false,
phoneNumber: "09120000000",
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
sameAs: InquiryParticipantRole.DRIVER,
},
} as any),
).toThrow(BadRequestException);
});
it("keeps third-party and car-body policyholders distinct", () => {
const resolved = resolveInquiryParticipants(BlameRequestType.CAR_BODY, {
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: false,
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
nationalCode: "0023456789",
birthday: "1360/02/02",
},
carBodyPolicyholder: {
nationalCode: "0034567890",
birthday: "1350/03/03",
},
});
expect(
participantForRole(
resolved,
InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER,
)?.nationalCode,
).toBe("0023456789");
expect(
participantForRole(resolved, InquiryParticipantRole.CAR_BODY_POLICYHOLDER)
?.nationalCode,
).toBe("0034567890");
});
it("projects role-complete input onto the existing inquiry fields", () => {
const normalized = normalizeInquirySubmission(BlameRequestType.CAR_BODY, {
vehicle: {
currentPlate: {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
},
},
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: true,
licenseNumber: "D-1",
licenseType: "1",
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
nationalCode: "0023456789",
birthday: "1360/02/02",
},
carBodyPolicyholder: {
nationalCode: "0034567890",
birthday: "1350/03/03",
},
});
expect(normalized.dto.nationalCodeOfInsurer).toBe("0023456789");
expect(normalized.dto.nationalCodeOfDriver).toBe("0012345678");
expect(normalized.carBodyPolicyholder?.nationalCode).toBe("0034567890");
expect(normalized.vehicleOwner?.nationalCode).toBe("0012345678");
});
it("routes each inquiry to its domain participant", () => {
const normalized = normalizeInquirySubmission(BlameRequestType.CAR_BODY, {
vehicle: {
currentPlate: {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
},
},
driver: {
nationalCode: "0011111111",
birthday: "1370/01/01",
hasDrivingLicense: false,
},
vehicleOwner: {
nationalCode: "0022222222",
birthday: "1365/02/02",
},
thirdPartyPolicyholder: {
nationalCode: "0033333333",
birthday: "1360/03/03",
},
carBodyPolicyholder: {
nationalCode: "0044444444",
birthday: "1355/04/04",
},
});
expect(resolveInquirySubjects(normalized)).toEqual({
thirdPartyPolicyNationalCode: "0033333333",
carBodyPolicyNationalCode: "0044444444",
shebaNationalCode: "0022222222",
driverNationalCode: "0011111111",
});
});
it("resolves a persisted vehicle owner for later Sheba validation", () => {
const party = {
participants: [
{ participantId: "DRIVER", nationalCode: "0011111111" },
{ participantId: "VEHICLE_OWNER", nationalCode: "0022222222" },
],
participantRoles: {
driver: "DRIVER",
vehicleOwner: "VEHICLE_OWNER",
thirdPartyPolicyholder: "DRIVER",
},
};
expect(
participantForStoredPartyRole(party, InquiryParticipantRole.VEHICLE_OWNER)
?.nationalCode,
).toBe("0022222222");
});
it("orders the current plate before the previous-plate fallback", () => {
const currentPlate = {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
};
const previousPlate = {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
};
expect(
vehiclePlateCandidates({
registrationState: VehicleRegistrationState.RECENTLY_TRANSFERRED,
currentPlate,
previousPlate,
vin: "NAAM01E15HK123456",
}),
).toEqual([
{ kind: "CURRENT", plate: currentPlate },
{ kind: "PREVIOUS", plate: previousPlate },
]);
});
it("rejects a previous-plate result for another chassis", () => {
expect(() =>
assertPreviousPlateInquiryMatchesVin("NAAM01E15HK123456", {
VinNumberField: "DIFFERENTVIN00001",
}),
).toThrow(BadRequestException);
});
it("requires the driver's licence status in the new contract", () => {
expect(() =>
resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, {
driver: { nationalCode: "0012345678", birthday: "1370/01/01" },
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
sameAs: InquiryParticipantRole.VEHICLE_OWNER,
},
}),
).toThrow(BadRequestException);
});
it("falls back to the previous plate and accepts only a matching VIN", async () => {
const currentPlate = {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
};
const previousPlate = {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
};
const query = jest
.fn()
.mockRejectedValueOnce(new Error("not found"))
.mockResolvedValueOnce({
mapped: { VinNumberField: "NAAM01E15HK123456", CompanyName: "پارسیان" },
});
const result = await runPlateInquiryWithFallback<{
mapped: { VinNumberField?: string; CompanyName?: string };
}>({
vehicle: {
registrationState: VehicleRegistrationState.RECENTLY_TRANSFERRED,
currentPlate,
previousPlate,
vin: "NAAM01E15HK123456",
},
fallbackCurrentPlate: currentPlate,
query,
isUsable: (value) => !!value.mapped.CompanyName,
mappedValue: (value) => value.mapped,
});
expect(query).toHaveBeenCalledTimes(2);
expect(result.plateKind).toBe("PREVIOUS");
expect(result.attempts).toMatchObject([
{ plateKind: "CURRENT", succeeded: false, error: "not found" },
{ plateKind: "PREVIOUS", succeeded: true, usable: true },
]);
expect(result.attempts[0]).toMatchObject({
plate: currentPlate,
vin: "NAAM01E15HK123456",
});
expect(result.attempts[1]).toMatchObject({
plate: previousPlate,
vin: "NAAM01E15HK123456",
});
});
it("rejects a car-body policyholder on a third-party case", () => {
expect(() =>
resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, {
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: false,
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
sameAs: InquiryParticipantRole.VEHICLE_OWNER,
},
carBodyPolicyholder: {
nationalCode: "0034567890",
birthday: "1350/03/03",
},
}),
).toThrow(BadRequestException);
});
it("does not accept a previous plate unless recent transfer is declared", () => {
expect(() =>
resolveInquiryVehicle({
registrationState: VehicleRegistrationState.CURRENT,
currentPlate: {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
},
previousPlate: {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
},
}),
).toThrow(BadRequestException);
});
it("rejects sameAs together with any person-specific fields", () => {
expect(() =>
resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, {
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: false,
},
vehicleOwner: {
sameAs: InquiryParticipantRole.DRIVER,
fullName: "Duplicate details must not be silently discarded",
},
thirdPartyPolicyholder: {
sameAs: InquiryParticipantRole.DRIVER,
},
}),
).toThrow(BadRequestException);
});
it("rejects conflicting legacy and structured current plates", () => {
expect(() =>
normalizeInquirySubmission(BlameRequestType.THIRD_PARTY, {
plate: {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
},
vehicle: {
registrationState: VehicleRegistrationState.CURRENT,
currentPlate: {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
},
},
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: false,
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: {
sameAs: InquiryParticipantRole.DRIVER,
},
}),
).toThrow(BadRequestException);
});
it("treats an expired policy result as stale", () => {
expect(isMappedPolicyCurrent({ EndDate: "1404/01/01" }, "2026-09-13")).toBe(
false,
);
expect(isMappedPolicyCurrent({ EndDate: "1406/01/01" }, "2026-09-13")).toBe(
true,
);
});
it("falls back from a stale current policy to a current previous-plate policy", async () => {
const currentPlate = {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
};
const previousPlate = {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
};
const query = jest
.fn()
.mockResolvedValueOnce({
mapped: { CompanyName: "پارسیان", EndDate: "1404/01/01" },
})
.mockResolvedValueOnce({
mapped: {
CompanyName: "پارسیان",
EndDate: "1406/01/01",
VinNumberField: "NAAM01E15HK123456",
},
});
const result = await runPlateInquiryWithFallback<{
mapped: Record<string, any>;
}>({
vehicle: resolveInquiryVehicle({
registrationState: VehicleRegistrationState.RECENTLY_TRANSFERRED,
currentPlate,
previousPlate,
vin: "NAAM01E15HK123456",
}),
fallbackCurrentPlate: currentPlate,
query,
isUsable: (value) =>
!!value.mapped.CompanyName &&
isMappedPolicyCurrent(value.mapped, "2026-09-13"),
mappedValue: (value) => value.mapped,
});
expect(result.plateKind).toBe("PREVIOUS");
expect(result.attempts[0]).toMatchObject({
plateKind: "CURRENT",
succeeded: true,
usable: false,
});
});
it("rejects the result and retains audit attempts when every plate is unusable", async () => {
const currentPlate = {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
};
const previousPlate = {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
};
await expect(
runPlateInquiryWithFallback({
vehicle: resolveInquiryVehicle({
registrationState: VehicleRegistrationState.RECENTLY_TRANSFERRED,
currentPlate,
previousPlate,
vin: "NAAM01E15HK123456",
}),
fallbackCurrentPlate: currentPlate,
query: async () => ({ mapped: { CompanyName: "پارسیان" } }),
isUsable: () => false,
mappedValue: (value) => value.mapped,
}),
).rejects.toMatchObject({
attempts: [
{ plateKind: "CURRENT", succeeded: true, usable: false },
{ plateKind: "PREVIOUS", succeeded: true, usable: false },
],
});
});
it("does not use the previous plate after a transport or provider outage", async () => {
const currentPlate = {
leftDigits: "44",
centerAlphabet: "ب",
centerDigits: "111",
ir: "22",
};
const query = jest.fn().mockRejectedValue(
Object.assign(new Error("upstream timeout"), {
code: "ETIMEDOUT",
}),
);
await expect(
runPlateInquiryWithFallback({
vehicle: resolveInquiryVehicle({
registrationState: VehicleRegistrationState.RECENTLY_TRANSFERRED,
currentPlate,
previousPlate: {
leftDigits: "55",
centerAlphabet: "ج",
centerDigits: "222",
ir: "33",
},
vin: "NAAM01E15HK123456",
}),
fallbackCurrentPlate: currentPlate,
query,
isUsable: () => false,
mappedValue: () => ({}),
}),
).rejects.toThrow("upstream timeout");
expect(query).toHaveBeenCalledTimes(1);
});
it("allows an explicitly unknown policyholder only for a damaged-party submission", () => {
const input = {
driver: {
nationalCode: "0012345678",
birthday: "1370/01/01",
hasDrivingLicense: false,
},
vehicleOwner: { sameAs: InquiryParticipantRole.DRIVER },
thirdPartyPolicyholder: { unknown: true },
};
expect(() =>
resolveInquiryParticipants(BlameRequestType.THIRD_PARTY, input),
).toThrow(BadRequestException);
const resolved = resolveInquiryParticipants(
BlameRequestType.THIRD_PARTY,
input,
{ allowUnknownThirdPartyPolicyholder: true },
);
expect(
participantForRole(
resolved,
InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER,
),
).toMatchObject({ unknown: true });
});
});

View File

@@ -0,0 +1,627 @@
import { BadRequestException } from "@nestjs/common";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { jalaliToGregorianDate } from "src/helpers/date-jalali";
import { gregorianDateInIran } from "src/helpers/iran-datetime";
import {
InquiryParticipantFieldsDto,
InquiryParticipantInputDto,
InquiryParticipantRole,
InquiryVehicleInputDto,
VehicleRegistrationState,
} from "src/common/dto/inquiry-participants.dto";
export interface ResolvedInquiryParticipant {
participantId: string;
nationalCode: string;
birthday: string;
fullName?: string;
hasDrivingLicense?: boolean;
licenseNumber?: string;
licenseType?: string;
unknown?: boolean;
}
export interface InquiryParticipantResolutionOptions {
allowUnknownThirdPartyPolicyholder?: boolean;
}
export interface InquiryParticipantRoleAssignments {
driver: string;
vehicleOwner?: string;
thirdPartyPolicyholder: string;
carBodyPolicyholder?: string;
}
export interface ResolvedInquiryParticipants {
participants: ResolvedInquiryParticipant[];
roles: InquiryParticipantRoleAssignments;
legacy: boolean;
}
export interface NormalizedInquirySubmission<T extends Record<string, any>> {
dto: T & {
nationalCodeOfDriver: string;
driverBirthday: string;
driverLicense?: string;
licenseType?: string;
userNoCertificate?: boolean;
nationalCodeOfInsurer: string;
insurerBirthday: string;
driverIsInsurer: boolean;
insurerLicense?: string;
};
participants: ResolvedInquiryParticipants;
driver: ResolvedInquiryParticipant;
vehicleOwner?: ResolvedInquiryParticipant;
thirdPartyPolicyholder: ResolvedInquiryParticipant;
carBodyPolicyholder?: ResolvedInquiryParticipant;
vehicle?: ResolvedInquiryVehicle;
}
export interface InquirySubjects {
thirdPartyPolicyNationalCode: string;
carBodyPolicyNationalCode?: string;
shebaNationalCode: string;
driverNationalCode: string;
}
/**
* The single routing seam for external inquiries. Policy checks belong to
* their policyholder, Sheba belongs to the vehicle owner, and licence data
* belongs to the driver even when those roles resolve to different people.
*/
export function resolveInquirySubjects(
submission: NormalizedInquirySubmission<Record<string, any>>,
): InquirySubjects {
if (!submission.vehicleOwner) {
throw new BadRequestException(
"Vehicle owner identity is required for Sheba validation.",
);
}
return {
thirdPartyPolicyNationalCode:
submission.thirdPartyPolicyholder.nationalCode,
...(submission.carBodyPolicyholder
? {
carBodyPolicyNationalCode:
submission.carBodyPolicyholder.nationalCode,
}
: {}),
shebaNationalCode: submission.vehicleOwner.nationalCode,
driverNationalCode: submission.driver.nationalCode,
};
}
export type ResolvedInquiryVehicle = InquiryVehicleInputDto & {
registrationState: VehicleRegistrationState;
};
export function participantForRole(
resolved: ResolvedInquiryParticipants,
role: InquiryParticipantRole,
): ResolvedInquiryParticipant | undefined {
const roleField = ROLE_FIELDS[
role
] as keyof InquiryParticipantRoleAssignments;
const participantId = resolved.roles[roleField];
return resolved.participants.find(
(participant) => participant.participantId === participantId,
);
}
/** Resolve a participant from the role links persisted on a blame party. */
export function participantForStoredPartyRole(
party: {
participants?: Array<Record<string, any>>;
participantRoles?: Partial<InquiryParticipantRoleAssignments>;
},
role: InquiryParticipantRole,
): Record<string, any> | undefined {
const roleField = ROLE_FIELDS[
role
] as keyof InquiryParticipantRoleAssignments;
const participantId = party.participantRoles?.[roleField];
if (!participantId || !Array.isArray(party.participants)) return undefined;
return party.participants.find(
(participant) => participant?.participantId === participantId,
);
}
const ROLE_FIELDS: Record<
InquiryParticipantRole,
keyof InquiryParticipantFieldsDto
> = {
[InquiryParticipantRole.DRIVER]: "driver",
[InquiryParticipantRole.VEHICLE_OWNER]: "vehicleOwner",
[InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER]: "thirdPartyPolicyholder",
[InquiryParticipantRole.CAR_BODY_POLICYHOLDER]: "carBodyPolicyholder",
};
function requiredIdentity(
role: InquiryParticipantRole,
input: InquiryParticipantInputDto,
): ResolvedInquiryParticipant {
if (Object.prototype.hasOwnProperty.call(input, "phoneNumber")) {
throw new BadRequestException(
`${role} does not accept phoneNumber; phone numbers are collected separately from inquiry identity.`,
);
}
const nationalCode = String(input.nationalCode ?? "").trim();
const birthday = String(input.birthday ?? "").trim();
if (!nationalCode || !birthday) {
throw new BadRequestException(
`${role} requires nationalCode and birthday.`,
);
}
if (
role === InquiryParticipantRole.DRIVER &&
typeof input.hasDrivingLicense !== "boolean"
) {
throw new BadRequestException("DRIVER requires hasDrivingLicense.");
}
if (
role === InquiryParticipantRole.DRIVER &&
input.hasDrivingLicense === true &&
(!String(input.licenseNumber ?? "").trim() ||
!String(input.licenseType ?? "").trim())
) {
throw new BadRequestException(
"DRIVER requires licenseNumber and licenseType when hasDrivingLicense is true.",
);
}
return {
participantId: role,
nationalCode,
birthday,
...(input.fullName ? { fullName: input.fullName } : {}),
...(input.hasDrivingLicense != null
? { hasDrivingLicense: input.hasDrivingLicense }
: {}),
...(input.licenseNumber ? { licenseNumber: input.licenseNumber } : {}),
...(input.licenseType ? { licenseType: input.licenseType } : {}),
};
}
export function resolveInquiryParticipants(
caseType: BlameRequestType,
input: Partial<InquiryParticipantFieldsDto> & Record<string, any>,
options: InquiryParticipantResolutionOptions = {},
): ResolvedInquiryParticipants {
assertStructuredInquiryInput(input);
const hasRoleCompleteInput = Object.values(ROLE_FIELDS).some(
(field) => input[field] != null,
);
if (!hasRoleCompleteInput) {
throw new BadRequestException(
"driver, vehicleOwner, and thirdPartyPolicyholder are required in the structured inquiry format.",
);
}
if (
caseType === BlameRequestType.THIRD_PARTY &&
input.carBodyPolicyholder != null
) {
throw new BadRequestException(
"CAR_BODY_POLICYHOLDER is not allowed for a THIRD_PARTY case.",
);
}
const requiredRoles = [
InquiryParticipantRole.DRIVER,
InquiryParticipantRole.VEHICLE_OWNER,
InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER,
...(caseType === BlameRequestType.CAR_BODY
? [InquiryParticipantRole.CAR_BODY_POLICYHOLDER]
: []),
];
const participants = new Map<string, ResolvedInquiryParticipant>();
const resolvedRoleIds = new Map<InquiryParticipantRole, string>();
const resolving = new Set<InquiryParticipantRole>();
const resolveRole = (role: InquiryParticipantRole): string => {
const existing = resolvedRoleIds.get(role);
if (existing) return existing;
if (resolving.has(role)) {
throw new BadRequestException(
"Participant sameAs references cannot be circular.",
);
}
const value = input[ROLE_FIELDS[role]] as
| InquiryParticipantInputDto
| undefined;
if (!value) throw new BadRequestException(`${role} is required.`);
resolving.add(role);
let participantId: string;
if (
role === InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER &&
value.unknown === true
) {
if (!options.allowUnknownThirdPartyPolicyholder) {
throw new BadRequestException(
"An unknown third-party policyholder is allowed only for the damaged party.",
);
}
const hasIdentityFields = Object.entries(value).some(
([field, fieldValue]) => field !== "unknown" && fieldValue != null,
);
if (hasIdentityFields) {
throw new BadRequestException(
`${role} must contain either unknown=true or person fields, not both.`,
);
}
const participant: ResolvedInquiryParticipant = {
participantId: role,
nationalCode: "",
birthday: "",
unknown: true,
};
participants.set(participant.participantId, participant);
participantId = participant.participantId;
} else if (value.unknown != null) {
throw new BadRequestException(
`${role} does not support the unknown option.`,
);
} else if (value.sameAs) {
const hasPersonSpecificFields = Object.entries(value).some(
([field, fieldValue]) => field !== "sameAs" && fieldValue != null,
);
if (hasPersonSpecificFields) {
throw new BadRequestException(
`${role} must contain either sameAs or identity fields, not both.`,
);
}
participantId = resolveRole(value.sameAs);
} else {
const participant = requiredIdentity(role, value);
const duplicate = [...participants.values()].find(
(item) => item.nationalCode === participant.nationalCode,
);
if (duplicate) {
throw new BadRequestException(
`${role} duplicates an existing nationalCode; use sameAs instead.`,
);
}
participants.set(participant.participantId, participant);
participantId = participant.participantId;
}
resolving.delete(role);
resolvedRoleIds.set(role, participantId);
return participantId;
};
for (const role of requiredRoles) resolveRole(role);
return {
participants: [...participants.values()],
roles: {
driver: resolvedRoleIds.get(InquiryParticipantRole.DRIVER)!,
vehicleOwner: resolvedRoleIds.get(InquiryParticipantRole.VEHICLE_OWNER)!,
thirdPartyPolicyholder: resolvedRoleIds.get(
InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER,
)!,
...(caseType === BlameRequestType.CAR_BODY
? {
carBodyPolicyholder: resolvedRoleIds.get(
InquiryParticipantRole.CAR_BODY_POLICYHOLDER,
)!,
}
: {}),
},
legacy: false,
};
}
export function resolveInquiryVehicle(
input: InquiryVehicleInputDto,
): ResolvedInquiryVehicle {
const registrationState =
input.registrationState ?? VehicleRegistrationState.CURRENT;
if (!input.currentPlate) {
throw new BadRequestException("vehicle.currentPlate is required.");
}
if (
registrationState === VehicleRegistrationState.RECENTLY_TRANSFERRED &&
(!input.previousPlate || !String(input.vin ?? "").trim())
) {
throw new BadRequestException(
"RECENTLY_TRANSFERRED requires previousPlate and vin.",
);
}
if (
registrationState !== VehicleRegistrationState.RECENTLY_TRANSFERRED &&
input.previousPlate
) {
throw new BadRequestException(
"previousPlate is only allowed for RECENTLY_TRANSFERRED vehicles.",
);
}
return { ...input, registrationState };
}
export function vehiclePlateCandidates(input?: ResolvedInquiryVehicle): Array<{
kind: "CURRENT" | "PREVIOUS";
plate: InquiryVehicleInputDto["currentPlate"];
}> {
if (!input) return [];
return [
{ kind: "CURRENT" as const, plate: input.currentPlate },
...(input.registrationState ===
VehicleRegistrationState.RECENTLY_TRANSFERRED && input.previousPlate
? [{ kind: "PREVIOUS" as const, plate: input.previousPlate }]
: []),
];
}
function normalizeVehicleSerial(value: unknown): string {
return String(value ?? "")
.toUpperCase()
.replace(/[^A-Z0-9]/g, "");
}
/** A dated result is usable only while the returned policy has not expired. */
export function isMappedPolicyCurrent(
mapped: Record<string, any>,
todayGregorian: string = gregorianDateInIran(new Date()),
): boolean {
const rawEndDate =
mapped?.EndDate ??
mapped?.HEndDte ??
mapped?.persianEndDate ??
mapped?.PolicyEndDate ??
mapped?.endDate;
if (rawEndDate == null || String(rawEndDate).trim() === "") return true;
const endDate = jalaliToGregorianDate(rawEndDate);
return endDate != null && endDate >= todayGregorian;
}
function normalizePlateForComparison(
plate: InquiryVehicleInputDto["currentPlate"],
): string {
return [
plate?.ir,
plate?.leftDigits,
plate?.centerAlphabet,
plate?.centerDigits,
]
.map((part) => String(part ?? "").trim())
.join("|");
}
const LEGACY_INQUIRY_FIELDS = [
"nationalCodeOfDriver",
"driverBirthday",
"driverLicense",
"licenseType",
"nationalCodeOfInsurer",
"insurerBirthday",
"insurerLicense",
"driverIsInsurer",
"userNoCertificate",
"plate",
"plateId",
"vin",
"isNewCar",
] as const;
function assertStructuredInquiryInput(input: Record<string, any>): void {
const legacyFields = LEGACY_INQUIRY_FIELDS.filter((field) =>
Object.prototype.hasOwnProperty.call(input, field),
);
if (legacyFields.length > 0) {
throw new BadRequestException(
`Legacy inquiry fields are not accepted: ${legacyFields.join(", ")}. Use driver, vehicleOwner, thirdPartyPolicyholder, carBodyPolicyholder, and vehicle.`,
);
}
}
export function assertPreviousPlateInquiryMatchesVin(
expectedVin: string,
mapped: Record<string, any>,
): void {
const expected = normalizeVehicleSerial(expectedVin);
const candidates = [
mapped?.VinNumberField,
mapped?.vin,
mapped?.VIN,
mapped?.ChassisNumberField,
mapped?.chassisNumber,
mapped?.ChassisNo,
mapped?.vehicle?.VIN,
mapped?.vehicle?.ChassisNo,
]
.map(normalizeVehicleSerial)
.filter(Boolean);
if (!expected || !candidates.includes(expected)) {
throw new BadRequestException(
"Previous-plate inquiry does not match the submitted VIN/chassis; manual review is required.",
);
}
}
export function isPolicyNotFoundError(error: unknown): boolean {
const candidate = error as Record<string, any> | null;
const status = candidate?.status ?? candidate?.response?.status;
if (Number(status) === 404) return true;
const code = String(
candidate?.code ?? candidate?.response?.data?.code ?? "",
).toUpperCase();
if (["NOT_FOUND", "POLICY_NOT_FOUND", "NO_POLICY"].includes(code)) {
return true;
}
const message = String(
candidate?.message ?? candidate?.response?.data?.message ?? error ?? "",
);
return /\bnot[ -]?found\b|\bno (?:relevant )?policy\b|یافت نشد|فاقد بیمه(?:نامه)?/i.test(
message,
);
}
export async function runPlateInquiryWithFallback<T>(options: {
vehicle?: ResolvedInquiryVehicle;
fallbackCurrentPlate: InquiryVehicleInputDto["currentPlate"];
query: (plate: InquiryVehicleInputDto["currentPlate"]) => Promise<T>;
isUsable: (value: T) => boolean;
mappedValue: (value: T) => Record<string, any>;
shouldFallbackOnError?: (error: unknown) => boolean;
}): Promise<{
value: T;
plateKind: "CURRENT" | "PREVIOUS";
attempts: Array<{
plateKind: "CURRENT" | "PREVIOUS";
plate: InquiryVehicleInputDto["currentPlate"];
vin?: string;
succeeded: boolean;
usable?: boolean;
error?: string;
}>;
}> {
const candidates = options.vehicle
? vehiclePlateCandidates(options.vehicle)
: [{ kind: "CURRENT" as const, plate: options.fallbackCurrentPlate }];
let lastError: unknown;
const attempts: Array<{
plateKind: "CURRENT" | "PREVIOUS";
plate: InquiryVehicleInputDto["currentPlate"];
vin?: string;
succeeded: boolean;
usable?: boolean;
error?: string;
}> = [];
for (let index = 0; index < candidates.length; index += 1) {
const candidate = candidates[index];
const isLast = index === candidates.length - 1;
try {
const value = await options.query(candidate.plate);
const usable = options.isUsable(value);
if (!usable) {
attempts.push({
plateKind: candidate.kind,
plate: candidate.plate,
...(options.vehicle?.vin ? { vin: options.vehicle.vin } : {}),
succeeded: true,
usable: false,
});
if (!isLast) continue;
const error = new BadRequestException(
"No current usable policy was found for the submitted vehicle identifiers.",
) as BadRequestException & { attempts?: typeof attempts };
error.attempts = attempts;
throw error;
}
if (candidate.kind === "PREVIOUS" && usable) {
assertPreviousPlateInquiryMatchesVin(
options.vehicle!.vin!,
options.mappedValue(value),
);
}
attempts.push({
plateKind: candidate.kind,
plate: candidate.plate,
...(options.vehicle?.vin ? { vin: options.vehicle.vin } : {}),
succeeded: true,
usable: true,
});
return { value, plateKind: candidate.kind, attempts };
} catch (error) {
lastError = error;
const alreadyRecorded =
typeof error === "object" &&
error != null &&
Array.isArray((error as { attempts?: unknown }).attempts);
if (!alreadyRecorded) {
attempts.push({
plateKind: candidate.kind,
plate: candidate.plate,
...(options.vehicle?.vin ? { vin: options.vehicle.vin } : {}),
succeeded: false,
error: error instanceof Error ? error.message : String(error),
});
}
if (
!isLast &&
!(options.shouldFallbackOnError ?? isPolicyNotFoundError)(error)
) {
if (typeof error === "object" && error != null) {
(error as { attempts?: typeof attempts }).attempts = attempts;
}
throw error;
}
if (isLast) {
if (typeof error === "object" && error != null) {
(error as { attempts?: typeof attempts }).attempts = attempts;
}
throw error;
}
}
}
throw lastError ?? new BadRequestException("Inquiry failed for all plates.");
}
export function normalizeInquirySubmission<T extends Record<string, any>>(
caseType: BlameRequestType,
input: T,
options: InquiryParticipantResolutionOptions = {},
): NormalizedInquirySubmission<T> {
const participants = resolveInquiryParticipants(
caseType,
input as any,
options,
);
const driver = participantForRole(
participants,
InquiryParticipantRole.DRIVER,
);
const thirdPartyPolicyholder = participantForRole(
participants,
InquiryParticipantRole.THIRD_PARTY_POLICYHOLDER,
);
if (!driver || !thirdPartyPolicyholder) {
throw new BadRequestException(
"Driver and third-party policyholder identities are required.",
);
}
const vehicleOwner = participantForRole(
participants,
InquiryParticipantRole.VEHICLE_OWNER,
);
const carBodyPolicyholder = participantForRole(
participants,
InquiryParticipantRole.CAR_BODY_POLICYHOLDER,
);
const vehicle = resolveInquiryVehicle(
input.vehicle as InquiryVehicleInputDto,
);
const sameDriverAndPolicyholder =
participants.roles.driver === participants.roles.thirdPartyPolicyholder;
return {
dto: {
...input,
plate: vehicle.currentPlate,
vin: vehicle.vin,
nationalCodeOfDriver: driver.nationalCode,
driverBirthday: driver.birthday,
driverLicense: driver.licenseNumber,
licenseType: driver.licenseType,
userNoCertificate:
driver.hasDrivingLicense == null
? undefined
: !driver.hasDrivingLicense,
nationalCodeOfInsurer: thirdPartyPolicyholder.nationalCode,
insurerBirthday: thirdPartyPolicyholder.birthday,
driverIsInsurer: sameDriverAndPolicyholder,
insurerLicense: sameDriverAndPolicyholder
? driver.licenseNumber
: undefined,
isNewCar: vehicle.isNewCar,
} as NormalizedInquirySubmission<T>["dto"],
participants,
driver,
vehicleOwner,
thirdPartyPolicyholder,
carBodyPolicyholder,
vehicle,
};
}

View File

@@ -104,6 +104,69 @@ describe("RequestManagementService FileReviewer inbox", () => {
).rejects.toThrow("does not belong to your organization");
});
it("returns party identity, VIN plate and claim payment/reference data to the V4 reviewer", async () => {
const { service } = createService([]);
const request = {
...sealedFile,
parties: [
{
role: "FIRST",
person: {
clientId,
fullName: "راننده و بیمه‌گذار نمونه",
nationalCodeOfInsurer: "1111111111",
nationalCodeOfDriver: "2222222222",
driverIsInsurer: false,
licenseType: "پایه یک",
driverLicense: "L-123",
},
vehicle: { plateId: "11-22-ب-333", vin: "VIN-123" },
},
],
};
(service as any).blameRequestDbService.findById = jest
.fn()
.mockResolvedValue(request);
(service as any).claimCaseDbService = {
findOne: jest.fn().mockResolvedValue({
_id: new Types.ObjectId(),
status: "COMPLETED",
workflow: {},
money: { sheba: "IR123" },
claimId: 101,
fanavaranSync: { baseClaim: { policyId: 202 } },
}),
};
const result = await service.getMyFileReviewerFileDetail(
{
sub: String(reviewerId),
role: RoleEnum.FILE_REVIEWER,
clientKey: String(clientId),
},
String(sealedFile._id),
);
expect(result.parties[0]).toEqual(
expect.objectContaining({
person: expect.objectContaining({
fullName: "راننده و بیمه‌گذار نمونه",
nationalCodeOfInsurer: "1111111111",
nationalCodeOfDriver: "2222222222",
licenseType: "پایه یک",
}),
vehicle: expect.objectContaining({
plateId: "11-22-ب-333",
vin: "VIN-123",
}),
}),
);
expect(result.money).toEqual({ sheba: "IR123" });
expect(result.fanavaran).toEqual(
expect.objectContaining({ claimId: 101, policyId: 202 }),
);
});
it("does not let a reviewer claim another tenant's file through its linked claim ID", async () => {
const blameRequestDbService = {
findById: jest.fn().mockResolvedValue({

File diff suppressed because it is too large Load Diff

View File

@@ -176,14 +176,46 @@ describe("SandHubService inquiry mocks", () => {
});
await expect(
service.getPolicyByChassisInquiry("NAAR03HFFRDE07024", {
enforceDeploymentClientMatch: true,
}),
service.getPolicyByChassisInquiry(
{
nationalCode: "1234567890",
chassis: "NAAR03HFFRDE07024",
},
{ enforceDeploymentClientMatch: true },
),
).rejects.toBeInstanceOf(ForbiddenException);
});
it("sends the policyholder national code with the VIN inquiry", async () => {
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
const esg = jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({
success: true,
data: { CmpCod: "8", CmpNam: "بیمه پارسیان" },
});
await service.getPolicyByChassisInquiry({
nationalCode: "0012345678",
chassis: "NAAR03HFFRDE07024",
});
expect(esg).toHaveBeenCalledWith(
expect.stringContaining("/inquiry/policyByChassis"),
{
nationalCode: "0012345678",
chassis: "NAAR03HFFRDE07024",
},
"vinChassis",
undefined,
);
});
it("does not accept a policy when CLIENT_ID is not configured", async () => {
delete process.env.CLIENT_ID;
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({
raw: { data: { companyId: "15" } },
mapped: { companyId: "15", CompanyCode: "15" },
});
await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf(
ServiceUnavailableException,
@@ -207,6 +239,7 @@ describe("SandHubService inquiry mocks", () => {
it("rejects a CAR_BODY policy from another insurer on the Tejarat lookup route", async () => {
process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({
raw: { data: { companyId: "8" } },
mapped: { companyId: "8", CompanyCode: "8" },
@@ -217,6 +250,24 @@ describe("SandHubService inquiry mocks", () => {
);
});
it("accepts a mocked Parsian CAR_BODY inquiry for the deployment client", async () => {
process.env.CLIENT_ID = "15";
process.env.FANAVARAN_CLIENT = "parsian";
externalInquirySettings.isInquiryLive.mockResolvedValue(false);
externalInquirySettings.getMockCompanyContext.mockResolvedValue({
companyId: "15",
companyName: "بیمه سامان",
});
await expect(service.getCarBodyInquiry(userDetail)).resolves.toEqual(
expect.objectContaining({
source: "ESG_CAR_BODY_INQUIRY",
mapped: expect.objectContaining({ companyId: 15 }),
}),
);
expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled();
});
it("uses the processed CAR_BODY lookup when the active Fanavaran client is Parsian", async () => {
process.env.FANAVARAN_CLIENT = "parsian";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
@@ -271,6 +322,47 @@ describe("SandHubService inquiry mocks", () => {
expect(result.source).toBe("ESG_CAR_BODY_VIN_INQUIRY");
});
it("uses the tenant Fanavaran VIN lookup for non-Parsian car-body inquiries", async () => {
process.env.CLIENT_ID = "15";
process.env.FANAVARAN_CLIENT = "tejaratno";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({
policy: { CINumber: "BODY-15" },
customer: {},
vehicle: { VIN: "NAAR03HFFRDE07024" },
});
const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry");
const result = await service.getCarBodyInquiry({
nationalCodeOfInsurer: "0012345678",
plate: "NAAR03HFFRDE07024",
});
expect(lookupsService.findLastProcessedCarPolicy).toHaveBeenCalledWith(
"car-body",
{ nationalCode: "0012345678", vin: "NAAR03HFFRDE07024" },
);
expect(tejarat).not.toHaveBeenCalled();
expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY");
});
it("returns a VIN-shaped car-body mock without invoking a plate adapter", async () => {
process.env.CLIENT_ID = "15";
process.env.FANAVARAN_CLIENT = "tejaratno";
const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry");
const result = await service.getCarBodyInquiry({
nationalCodeOfInsurer: "0012345678",
plate: "NAAR03HFFRDE07024",
});
expect(tejarat).not.toHaveBeenCalled();
expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled();
expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY");
expect(result.mapped.VinNumberField).toBe("NAAR03HFFRDE07024");
expect(result.mapped.insurerNationalCode).toBe("0012345678");
});
it("uses car-body mock shape in Tejarat helper when inquiry is off", async () => {
const raw = await (service as any).makeTejaratRequest(
"http://example/block-inquiry-tejarat/badane",

View File

@@ -250,11 +250,16 @@ export class SandHubService {
}
private buildMockCarBodyInquiryRaw(
userDetail: SandHubDetailDto,
userDetail: CarBodyInquiryDetail,
ctx: MockInquiryCompanyContext,
): Record<string, unknown> {
const companyId = Number(ctx.companyId);
const plate = userDetail?.plate;
const plate =
typeof userDetail?.plate === "string" ? undefined : userDetail?.plate;
const vin =
typeof userDetail?.plate === "string"
? userDetail.plate
: "LFP8C7PC3R1K12157";
const platePartOne = Number(plate?.leftDigits ?? 16);
const platePartThree = Number(plate?.centerDigits ?? 498);
const plateSerialNumber = Number(plate?.ir ?? 60);
@@ -272,8 +277,8 @@ export class SandHubService {
issueDate: "1405/01/16",
hasEndorsement: null,
motorNumber: "TZ196XYAP223A210074",
chassisNumber: "LFP8C7PC3R1K12157",
vin: "LFP8C7PC3R1K12157",
chassisNumber: vin,
vin,
plateTypeId: 9,
plateTypeTitle: "پلاک قدیمی",
platePartOne,
@@ -931,46 +936,63 @@ export class SandHubService {
raw: any;
mapped: Record<string, unknown>;
}> {
if (!this.shouldUseParsianCarBodyLookup()) {
const useParsianCarBodyLookup = this.shouldUseParsianCarBodyLookup();
const live = await this.isInquiryLive("carBodyPlate", options);
const plateOrVin = userDetail.plate;
const isVinInquiry = typeof plateOrVin === "string";
if (!live) {
// Mock results are generated for the active deployment. They must not be
// treated as evidence of a real insurer and therefore do not go through
// the live-policy insurer gate.
const ctx = await this.mockCompanyContext(options);
const raw = this.buildMockCarBodyInquiryRaw(userDetail, ctx);
const result = { raw, mapped: this.mapCarBodyInquiryResponse(raw) };
return {
source: isVinInquiry
? useParsianCarBodyLookup
? "ESG_CAR_BODY_VIN_INQUIRY"
: "TEJARAT_CAR_BODY_VIN_INQUIRY"
: useParsianCarBodyLookup
? "ESG_CAR_BODY_INQUIRY"
: "TEJARAT_CAR_BODY_INQUIRY",
...result,
};
}
if (isVinInquiry) {
const raw = await this.lookupsService.findLastProcessedCarPolicy(
"car-body",
{
nationalCode: String(userDetail.nationalCodeOfInsurer),
vin: plateOrVin,
},
);
if (useParsianCarBodyLookup) {
this.assertParsianCarBodyLookupMatchesDeployment();
}
return {
source: useParsianCarBodyLookup
? "ESG_CAR_BODY_VIN_INQUIRY"
: "TEJARAT_CAR_BODY_VIN_INQUIRY",
raw,
mapped: mapEsgCarBodyPolicyToInquiry(raw),
};
}
if (!useParsianCarBodyLookup) {
const result = await this.getTejaratCarBodyInquiry(
userDetail as SandHubDetailDto,
options,
);
this.assertInsuranceMatchesDeployment(result.mapped, "CAR_BODY");
return {
source:
typeof userDetail.plate === "string"
? "TEJARAT_CAR_BODY_VIN_INQUIRY"
: "TEJARAT_CAR_BODY_INQUIRY",
source: "TEJARAT_CAR_BODY_INQUIRY",
...result,
};
}
const live = await this.isInquiryLive("carBodyPlate", options);
if (!live) {
// Reuse the established local mock contract without sending an HTTP request.
const result = await this.getTejaratCarBodyInquiry(
userDetail as SandHubDetailDto,
options,
);
this.assertParsianCarBodyLookupMatchesDeployment();
return {
source:
typeof userDetail.plate === "string"
? "ESG_CAR_BODY_VIN_INQUIRY"
: "ESG_CAR_BODY_INQUIRY",
...result,
};
}
const plateOrVin = userDetail.plate;
const query =
typeof plateOrVin === "string"
? {
nationalCode: String(userDetail.nationalCodeOfInsurer),
vin: plateOrVin,
}
: {
const query = {
nationalCode: String(userDetail.nationalCodeOfInsurer),
plaqueLeft: String(plateOrVin.leftDigits),
plaqueLetter: String(plateOrVin.centerAlphabet),
@@ -984,10 +1006,7 @@ export class SandHubService {
this.assertParsianCarBodyLookupMatchesDeployment();
return {
source:
typeof plateOrVin === "string"
? "ESG_CAR_BODY_VIN_INQUIRY"
: "ESG_CAR_BODY_INQUIRY",
source: "ESG_CAR_BODY_INQUIRY",
raw,
mapped: mapEsgCarBodyPolicyToInquiry(raw),
};
@@ -1102,16 +1121,19 @@ export class SandHubService {
* `buildMockPlateInquiryRaw` so the downstream mapper (`mapEsgPolicyByPlateToOldFormat`)
* can normalise it into the same `{ raw, mapped }` contract used by the plate path.
*
* @param chassisNo - 17-character VIN / chassis number
* @param identity - policyholder national code and 17-character VIN/chassis
* @param options - optional per-tenant client scope
*/
async getPolicyByChassisInquiry(
chassisNo: string,
identity: { nationalCode: string; chassis: string },
options?: SandHubInquiryOptions,
): Promise<{ raw: any; mapped: any }> {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestUrl = `${baseUrl}/inquiry/policyByChassis`;
const requestPayload = { chassisNo };
const requestPayload = {
nationalCode: String(identity.nationalCode),
chassis: String(identity.chassis),
};
const live = await this.isInquiryLive("vinChassis", options);
@@ -1119,7 +1141,7 @@ export class SandHubService {
const ctx = await this.mockCompanyContext(options);
const raw = this.buildMockPlateInquiryRaw(ctx);
this.logger.debug(
`[MOCK] getPolicyByChassisInquiry chassisNo=${chassisNo}`,
`[MOCK] getPolicyByChassisInquiry nationalCode=${identity.nationalCode} chassis=${identity.chassis}`,
);
const mapped = this.mapEsgPolicyByPlateToOldFormat(raw);
this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options);