Compare commits

24 Commits
Author SHA1 Message Date
s.hajizadeh 3f920c0be5 fix(fanavaran): resolve hull expertise policy from stored inquiry
Reuse the insured vehicle hull inquiry policy when saved base-claim policy metadata is absent. This lets expertise resolve policy accessories and factory coverage before stage 1 has been persisted. Add a regression test for the missing-cache case.
2026-11-24 12:59:05 +03:30
SepehrYahyaee f29461fa67 feat(claims): enforce insurer working hours 2026-11-24 12:18:39 +03:30
SepehrYahyaee 475780f17e feat(claims): require optional expert signatures and enrich PDF reports 2026-11-24 11:23:08 +03:30
SepehrYahyaee 297664a9a6 fix(reports): localize Persian reports and resolve person display names 2026-11-23 17:08:51 +03:30
SepehrYahyaee 187a0ea3a9 fix(claims): validate invoice decisions before saving and explain resend limits 2026-11-23 15:05:46 +03:30
SepehrYahyaee 036d218ebd fix(claim-pricing): keep invoice and repair states consistent 2026-11-23 12:03:02 +03:30
SepehrYahyaee c74b29337e feat(depreciation): apply Fanavaran tables and age eligibility
Use the supplied part, severity and age codes for depreciation. Exclude vehicles older than ten from calculated and manual amounts, preserve historical assessments, and send zero depreciation to Fanavaran for ineligible vehicles.
2026-11-23 11:10:55 +03:30
s.yahyaee 3bf6fcc8b0 Merge pull request 'fix(SMS): change the brand name of the sms' (#413) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#413
2026-11-22 16:04:52 +03:30
SepehrYahyaee e31e2c7be6 fix(SMS): change the brand name of the sms 2026-11-22 16:04:24 +03:30
s.yahyaee 70e7edcd19 Merge pull request 'fix(validation): normalize Persian accident condition labels' (#412) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#412
2026-11-22 15:25:36 +03:30
SepehrYahyaee 99aba7e0fd fix(validation): normalize Persian accident condition labels 2026-11-22 15:24:51 +03:30
s.hajizadeh fb192fd780 Merge pull request 'fix(fanavaran): require vehicle review and recover submitted base claims' (#411) from s.hajizadeh/yara724api:main into main
Reviewed-on: Yara724/api#411
2026-11-22 15:24:03 +03:30
s.hajizadeh 41a3372225 fix(fanavaran): require vehicle review and recover submitted base claims
Require approved vehicle classification before new base submissions. Allow a first review for existing base claims without damage or expertise, preserve remote IDs, and resume deferred damage submission. Keep approved submitted classifications locked and compare stage IDs and review snapshots when saving.
2026-11-22 15:23:11 +03:30
s.alikhani d2676d65d1 fix(ci): allow buildx writes and publish latest
Mount only the registry login file so Buildx can write temporary state. Build and deploy the latest image tag.
2026-11-22 15:02:19 +03:30
s.alikhani 6e56d0fa2e ci(deployment): build the maintenance api on parspack
Compile NestJS on Parspack and deploy the commit-tagged image from the existing API directory.
2026-11-22 14:43:23 +03:30
s.yahyaee 7b23262fd2 Merge pull request 'fix(workflows): resolve QA blockers and protect case evidence' (#410) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#410
2026-11-22 12:51:27 +03:30
SepehrYahyaee 6b968c0952 fix(workflows): resolve QA blockers and protect case evidence
Fix registrar signing, reviewer re-entry, replacement evidence freshness, owner decision and rating races, multipart objections, vehicle serialization and product reporting.

Validate uploaded media with FFmpeg, serve evidence through expiring signed links, and add targeted regressions plus a dry-run repair for prematurely completed visit cases.
2026-11-22 12:50:22 +03:30
s.yahyaee abc40df199 Merge pull request 'fix(claims): reuse saved Sheba across claim workflow steps' (#409) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#409
2026-11-21 16:48:57 +03:30
SepehrYahyaee 90f290154c fix(claims): reuse saved Sheba across claim workflow steps 2026-11-21 16:36:34 +03:30
s.yahyaee be364d94fe Merge pull request 'fix(inquiries): route all tenants through ESG and Fanavaran' (#408) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#408
2026-11-21 15:27:53 +03:30
SepehrYahyaee 1a38b98829 fix(inquiries): route all tenants through ESG and Fanavaran 2026-11-21 15:27:06 +03:30
s.hajizadeh 61ef4faaf4 fix(fanavaran): preserve assessed part ids in hull expertise
Use each saved expert-reply partId as AccessoryKindId and preserve its label. Resolve policy coverage separately so factory-bundle and caption matches cannot overwrite the selected part identity. Add coverage for the six-part expert reply and document the mapping.
2026-11-21 14:45:31 +03:30
s.hajizadeh 7bff702514 fix(flow-ui): enable explicit person role registration
Expose person registration for hull claims, require selection of the supported role 166 and check that role even when a driver ID is cached. Keep claim notifier validation out of person registration and populate the verified hull driver reference after success.
2026-11-21 13:33:41 +03:30
s.hajizadeh 99e6fa0850 fix(fanavaran): honor supplied submission payload fields
Apply every supplied JSON field over generated defaults, preserving IDs, nested values and explicit nulls across base, damage and expertise submits. Validate manual hull payloads without rewriting their values or premium, and derive an empty replacement flag for old hull licences.
2026-11-21 13:33:41 +03:30
156 changed files with 7779 additions and 1806 deletions
+20 -4
View File
@@ -46,7 +46,16 @@ JWT_EXPIRY =
CAPTCHA_ENABLED = true
# ---------------------------------------------
# 🧩 SanHub Microservice
# 🧩 ESG — third-party plate/VIN, personal identity and Sheba (all tenants)
# Include the gateway prefix in ESG_URL when one is required; no fallback URL.
# ---------------------------------------------
ESG_URL =
ESG_USERNAME =
ESG_PASSWORD =
# ---------------------------------------------
# Optional driving-licence and legal vehicle-ownership inquiries only
# ESG does not currently expose equivalent endpoints for these two checks.
# ---------------------------------------------
SANHUB_BASE_URL =
SANHUB_URL_LOGIN =
@@ -71,7 +80,14 @@ AI_DAMAGE_PRICE_MIN_SEVERITY=severe
# kavenegar | parsian | moalem (legacy SMS takes precedence when nonempty)
SMS_PROVIDER =
SMS_API_KEY =
# Display name used in SMS text for this deployment (blank/unset = یارا۷۲۴).
# Example for Moalem: SMS_BRAND_NAME="سامانه خسارت اپکس"
# Custom Kavenegar branding uses sms/send; the account must allow plain-text SMS.
SMS_BRAND_NAME="یارا۷۲۴"
AUTH_SMS_TEMPLATE =
# Optional OTP pattern; {token} is the code and {brandName} is SMS_BRAND_NAME.
# The deployment name is appended automatically when absent from a pattern.
AUTH_SMS_MESSAGE="کاربر محترم رمز یکبار مصرف شما در {brandName}: {token}"
EXP_OTP_TIME =
# Development-only fixed OTP. Production rejects true at startup.
FAKE_OTP = false
@@ -101,9 +117,6 @@ AUTO_CLIENT_KEY_ENABLED =
# ---------------------------------------------
# 🔗 Other Internal Services
# ---------------------------------------------
TEJARAT_INQUIRY_EMAIL =
TEJARAT_INQUIRY_PASSWORD =
PARSIAN_API_KEY =
PARSIAN_BASIC_TOKEN =
PARSIAN_SMS_URL =
@@ -117,3 +130,6 @@ MIC_SMS_TOKEN_TTL=86399
# Total normal send attempts; a single 401 refresh/resend is additional.
MIC_SMS_ATTEMPTS=2
MIC_SMS_TIMEOUT_MS=15000
# Require the submitting expert to sign before final Fanavaran submission.
FANAVARAN_REQUIRE_EXPERT_SIGNATURE=false
+32
View File
@@ -0,0 +1,32 @@
when:
- event: push
branch: main
- event: manual
branch: main
labels:
hostname: build-parspack
steps:
build:
image: docker.arvancloud.ir/docker:24-cli
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /home/opsadmin/.docker/config.json:/root/.docker/config.json:ro
commands:
- export YARA_IMAGE="registry.ittalie.com/yara724-maintenance-api:latest"
- docker build -t "$YARA_IMAGE" .
- docker push "$YARA_IMAGE"
notify-failure:
image: docker.arvancloud.ir/alpine:3.20
environment:
ROCKETCHAT_WEBHOOK:
from_secret: rocketchat_webhook
when:
- status: failure
commands:
- apk add --no-cache curl jq > /dev/null
- |
jq -n --arg text "Yara724 api build failed. $CI_PIPELINE_URL" '{text: $text}' |
curl -fsS -H 'Content-Type: application/json' --data-binary @- "$ROCKETCHAT_WEBHOOK"
+12 -6
View File
@@ -1,11 +1,11 @@
# yara724/api — development deployment (Deploy-Develop)
# Manual tasks: see ci-cd/TASK.md
# Requires: repo marked Trusted in Woodpecker (host volume mounts)
when:
- event: push
branch: main
- event: manual
branch: main
depends_on:
- build
labels:
hostname: build-node-01
@@ -40,7 +40,10 @@ steps:
- git config --global --add safe.directory /workspace
- mkdir -p /tmp && ssh-keyscan -H git.ittalie.com >> /tmp/known_hosts
- cd /workspace
- git pull origin main
- git fetch origin main
- test "$(git rev-parse FETCH_HEAD)" = "$CI_COMMIT_SHA"
- git merge --ff-only FETCH_HEAD
- test "$(git rev-parse HEAD)" = "$CI_COMMIT_SHA"
- date +%s > /workspace/.wp-deploy-start
deploy:
@@ -49,10 +52,13 @@ steps:
<<: *pipeline_env
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /home/talieh/.docker:/root/.docker:ro
- *workspace_volume
commands:
- cd /workspace
- docker compose -f docker-compose.yml up -d --build
- export YARA_IMAGE="registry.ittalie.com/yara724-maintenance-api:latest"
- docker compose -f docker-compose.yml pull
- docker compose -f docker-compose.yml up -d --no-build
notify-success:
image: docker.arvancloud.ir/alpine:3.20
+5 -1
View File
@@ -1,6 +1,8 @@
# Use the official Node.js image as the base image
FROM docker.arvancloud.ir/node:20-alpine
RUN apk add --no-cache ffmpeg
WORKDIR /app
COPY package*.json ./
@@ -15,8 +17,10 @@ RUN npm i --force --verbose --no-scripts
COPY . .
RUN npm run build && test -f dist/src/main.js
# Expose the port on which your NestJS application will run
EXPOSE 3002
# Start the NestJS application
CMD ["npm", "start"]
CMD ["node", "dist/src/main.js"]
+6
View File
@@ -0,0 +1,6 @@
.git
node_modules
dist
.env
.env.*
*.env
+8
View File
@@ -3,10 +3,18 @@
## Documentation
- [Fanavaran integration](docs/fanavaran/README.md)
- [Inquiry providers — ESG for all tenants and Fanavaran car-body policies](docs/inquiry-provider-routing.md)
- [AI damage detection and advisory prices — setup and testing](docs/ai-damage-companion.md)
- [Deployment-specific SMS display names](docs/sms-deployment-branding.md)
Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md).
### Moalem SMS
For MIC SMS environment settings, shared token-cache indexes and a test-send command, see [Moalem SMS adapter](docs/MIC/moalem-sms.md).
### Expert signature before final Fanavaran submission
Set `FANAVARAN_REQUIRE_EXPERT_SIGNATURE=true` in the API service environment and restart the API for the deployment that requires it. The expert app reads the setting from the API. The default is `false`.
With the setting enabled, the submitting expert signs the saved assessment in the Fanavaran tab, then clicks final submission. Changes to the signed assessment require a fresh signature. Automatic final expertise submission waits for this action, and manual final submissions use the saved fields without JSON overrides. Initial Fanavaran stages can still run at their usual points. The insurer PDF includes available party and expert signatures.
+1 -1
View File
@@ -6,7 +6,7 @@ services:
context: .
dockerfile: Dockerfile
container_name: yara724-main-api-dev
image: yara724-main-api:dev
image: ${YARA_IMAGE:-yara724-main-api:dev}
restart: unless-stopped
volumes:
- yara724-main-api-dev-files:/app/files/:rw
+2
View File
@@ -6,6 +6,7 @@ The deployment selects `moalem` as its SMS provider. This is independent of the
```dotenv
SMS_PROVIDER=moalem
SMS_BRAND_NAME="سامانه خسارت اپکس"
MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token
MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send
MIC_SMS_CLIENT_ID=<provided privately by MIC>
@@ -18,6 +19,7 @@ FAKE_OTP=false
- If the legacy `SMS` setting is nonempty, it overrides `SMS_PROVIDER`. Set it to `moalem` as well, or remove it. `moallem` is accepted as an alias; logs use `moalem`.
- Keep the existing `AUTH_SMS_TEMPLATE` and `AUTH_SMS_MESSAGE` settings for OTP text. Existing URL and `USER_BASE_PATH` settings continue controlling message links.
- `SMS_BRAND_NAME` controls the name in every SMS; unset or blank defaults to `یارا۷۲۴`. Custom OTP/database patterns can use `{brandName}`. See [SMS deployment branding](../sms-deployment-branding.md).
- Supply credentials privately through the server environment or secret store. The repository example contains no credentials. Restart API instances after changing configuration.
- Active Moalem deployments fail startup when required MIC credentials, HTTPS URLs or numeric settings are invalid. MIC settings do not block other SMS providers.
- Allow outbound HTTPS to `auth.mic.co.ir` and `api.mic.co.ir`. Redirects are disabled. The existing HTTP proxy configuration is reused.
+27
View File
@@ -0,0 +1,27 @@
# Claim resend and invoice workflow regressions — 2026-11-23
## Reported failures and causes
- **Resend PUT returned a generic 422.** The exact reported body (part ID 15, no documents and a non-empty description) is accepted for a first resend cycle. The service explicitly returns `DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED` after an earlier resend was fulfilled. The expert proxy discarded that code, and the English explanation fell through to a generic Persian form-validation message. The one-completed-resend policy remains unchanged. The API now gives a specific Persian explanation; the expert proxy retains the code; the sidebar explains and disables a completed resend when its case detail is available, and displays server errors inline.
- **Invoice approval shared the assessment submission UI.** Its decisions lived under user opinions and depended on globally initialized factor drafts. It could reach assessment selection/pricing validation and demand damaged parts. Review now belongs to each saved assessment part, beside its invoice viewer. The independent action calls `PATCH /v2/expert-claim/validate-factors/:id` with one decision; it does not update selected damaged parts or resubmit the assessment.
- **Mixed replies required a refresh after signing.** The owner page delayed dispatching the pre-signature step by three seconds, the upload callback captured old case state, and the part list also read a stale Redux step. The mutation response now immediately updates the case query, the current API step drives upload permissions, and signature/upload operations invalidate the case query. Pending invoice work also stays visible in in-person flows rather than being hidden by a completion summary.
- **Invoice validation could persist changes before rejecting a total.** The service now validates the proposed decisions and the completed-batch V1 total before persistence. The update checks the original case phase and update timestamp (or the parts snapshot for legacy fixtures) to reject a stale write. Invalid/duplicate/unrelated decisions cause no writes. A rejected invoice needs a reason and an expert amount.
## UI behavior
- Review actions appear only on `/requests/check`, for claim, field and file-reviewer experts, in the invoice review phase and after all required invoices are uploaded. Insurers and file makers retain viewing access.
- Each pending invoice can be approved or repriced/rejected in its own dialog. Enter the **whole line total including labor, in rials**. This is not an additional amount to add to the existing line.
- Local validation and server failures keep the dialog/draft available for correction and retry. Cancelling does not save a decision. Saved decisions disappear from the pending controls; case queries refresh. Completing the batch uses `caseStatus` to return to the list, including V5 FileMaker approval.
- Signing a mixed reply enables invoice upload on the current page. Every upload refreshes the case. Once all invoices arrive, upload controls and the signature action are replaced by the expert-review waiting state.
- The live claim query and in-person query take precedence over the original detail snapshot so refreshed decisions are visible.
- The previous invoice controls under user opinions and their unused validation component were removed.
## Verification
`test/claim-invoice-resend.e2e-spec.ts` exercises the real Nest controllers, JWT/role guards, DTO validation and workflow services with in-memory persistence. It covers v1–v6 × THIRD_PARTY/CAR_BODY × mixed/all-factor/priced assessments, mixed signing before upload, sequential uploads, duplicate upload rejection, per-invoice partial batches, completion/V5 handoff, malformed/duplicate/unknown decisions, Persian amounts, rejected invoice reasons, cap failure with no writes followed by a corrected retry, stale writes, and the exact resend payload followed by the documented 422 rule.
The full HTTP suite passes 72 tests with four pre-existing skips. The general API suite retains the ten previously documented failures in `fanavaran-submit-overrides.spec.ts`; they fail at its vehicle-review prerequisite and are unrelated to these changes.
Both UI suites include invoice regressions. Browser checks at 1440×1100 and 390×844 exercise the rendered expert invoice viewer/review action, required amount validation, an HTTP error with retry, and the actual user result page with canvas signing and two successive invoice uploads without a reload. Browser API replies are intercepted synthetic fixtures; no production case, SMS, Fanavaran or object storage is used. Test artifacts live under `/tmp/invoice-review-*`, and temporary preview routes are removed.
These are targeted workflow tests, not a claim that every production integration or every application route was manually exercised. Deploy **API, expert UI and user UI together**; there is no environment or database migration requirement.
@@ -19,7 +19,7 @@ Content-Type: application/json
## بدنه درخواست
تمام مبلغ‌ها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته می‌شوند؛ برای نمونه هر دو مقدار `"100000"` و `"۱۰۰,۰۰۰"` معتبرند.
تمام مبلغ‌ها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته می‌شوند؛ برای نمونه هر دو مقدار `"1000000"` و `"۱۰۰,۰۰۰"` معتبرند.
```json
{
@@ -29,12 +29,12 @@ Content-Type: application/json
"partId": 201,
"typeOfDamage": "تعویض",
"price": "2500000",
"salary": "400000",
"totalPayment": "2900000",
"salary": "1000000",
"totalPayment": "3500000",
"factorNeeded": false,
"daghi": {
"option": "ارزش لوازم بازیافتی",
"price": "300000"
"price": "1000000"
}
}
]
@@ -54,21 +54,29 @@ Content-Type: application/json
| --- | --- | --- |
| `partId` | بله | عدد صحیح؛ باید متعلق به قطعات آسیب‌دیده همان پرونده باشد. |
| `typeOfDamage` | بله | دقیقاً یکی از `"تعمیر"` یا `"تعویض"`. |
| `price` | برای `"تعویض"` بله؛ برای `"تعمیر"` اختیاری | در صورت ارسال، مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `salary` | بله | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `price` | فقط تعویض با قیمت قطعی | برای ردیف `factorNeeded=true` قیمت قطعه ارسال نشود؛ متن `factor` یا `فاکتور` مبلغ نیست. در صورت ارسال مبلغ، بازه 1,000,000 تا 100,000,000,000 ریال معتبر است. |
| `salary` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
| `totalPayment` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. فقط در جریان V1، مجموع این فیلدها در کل پرونده نباید از 530,000,000 ریال بیشتر شود. |
| `factorNeeded` | بله | مقدار Boolean واقعی (`true` یا `false`)؛ رشته ارسال نکنید. |
| `factorNeeded` | بله | مقدار Boolean واقعی؛ فقط ردیف تعویض می‌تواند `true` باشد. در تعمیر باید `false` باشد. |
| `daghi` | برای `"تعویض"` بله | برای `"تعمیر"` لازم نیست و در ثبت نهایی حذف می‌شود. |
| `daghi.option` | در صورت وجود `daghi` بله | یکی از `"ارزش لوازم بازیافتی"`، `"تحویل داغی"`، `"فاقد ارزش"` یا `"با احتساب داغی"`. |
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
| `daghi.branchId` | فقط وقتی `option` برابر `"تحویل داغی"` است | Mongo ObjectId معتبرِ شعبه. |
نکته‌ها:
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 100,000 تومان است.
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 1,000,000 ریال است.
- محدودیت هر فیلد مبلغ مستقل است؛ سقف 530 میلیون ریال فقط برای **مجموع `totalPayment` تمام ردیف‌های پرونده V1** اعمال می‌شود. جریان‌های V2 تا V6 سقف مجموع ندارند.
- فیلدهای ناشناخته در body حذف می‌شوند. فرانت‌اند نباید برای انتقال داده به آن‌ها تکیه کند.
### تغییر روش قیمت‌گذاری و خطاها
- انتخاب فاکتور، قیمت قطعی قطعه را پاک می‌کند؛ `salary` و `totalPayment` همچنان مبلغ عددی معتبر لازم دارند.
- تبدیل تعویض به تعمیر، روش فاکتور، قیمت قطعه و اطلاعات داغی را یکجا پاک می‌کند و مجموع شناخته‌شده را از اجرت محاسبه می‌کند.
- تبدیل فاکتور به قیمت، `factorNeeded` را خاموش و انتخاب قیمت جدید را الزامی می‌کند؛ قیمت قدیمی به‌طور پنهان استفاده نمی‌شود.
- خطای اعتبارسنجی، پرچم فاکتور یا وضعیت ذخیره‌شده پرونده را تغییر نمی‌دهد. UI پیش از ذخیره تغییرات انتخاب قطعات، پیش‌اعتبارسنجی می‌کند و ارسال تکراری هم‌زمان را مسدود می‌کند.
- پیام‌های خطای این مسیر با واحد ریال نمایش داده می‌شوند.
## پاسخ موفق
پاسخ `200` شامل مسیر بعدی workflow است. نمونه:
@@ -106,7 +114,7 @@ Content-Type: application/json
"validationErrors": [
{
"field": "parts[0].salary",
"message": "باید مبلغ صحیح و غیرمنفی به تومان باشد."
"message": "باید مبلغ صحیح و غیرمنفی به ریال باشد."
},
{
"field": "parts[0].factorNeeded",
@@ -125,14 +133,14 @@ Content-Type: application/json
```json
{
"statusCode": 400,
"message": "قیمت قطعه 201 باید حداقل ۱۰۰٬۰۰۰ و حداکثر ۱۰٬۰۰۰٬۰۰۰٬۰۰۰ تومان باشد.",
"message": "قیمت قطعه 201 باید حداقل ۱٬۰۰۰٬۰۰۰ و حداکثر ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
"error": "EXPERT_REPLY_VALIDATION_ERROR",
"code": "EXPERT_REPLY_VALIDATION_ERROR",
"field": "parts[0].price",
"partId": "201",
"rule": "amount_out_of_range",
"minAmount": 100000,
"maxAmount": 10000000000
"minAmount": 1000000,
"maxAmount": 100000000000
}
```
@@ -142,7 +150,7 @@ Content-Type: application/json
| --- | --- |
| `required` | فیلد لازم ارسال نشده است. |
| `invalid_value` | مقدار enum یا شناسه معتبر نیست. |
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به تومان نیست. |
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به ریال نیست. |
| `amount_out_of_range` | مبلغ خارج از بازه `minAmount` و `maxAmount` است. |
در صورت `amount_out_of_range`، برای نمایش محدوده از اعداد `minAmount` و `maxAmount` استفاده کنید، نه از parse کردن متن `message`.
+18 -120
View File
@@ -319,81 +319,21 @@ curl -X POST "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims" \
--data @fanavaran-claim-submit.json
```
## Tejarat Inquiry Provider
Default base URL:
```sh
TEJARAT_INQUIRY_BASE_URL="${TEJARAT_INQUIRY_BASE_URL:-http://82.99.202.245:3027}"
TEJARAT_INQUIRY_EMAIL='xxx@example.com'
TEJARAT_INQUIRY_PASSWORD='123321'
```
Used by `src/sand-hub/sand-hub.service.ts` for third-party plate and car-body plate inquiries when ESG is not selected.
### Sequence
1. Login to `/user/login`.
2. Use returned `accessToken` as `Authorization: Bearer ...`.
3. Call inquiry endpoint.
### Login
```sh
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/user/login" \
-H "Accept: */*" \
-H "Content-Type: application/json" \
--data '{
"email": "'"$TEJARAT_INQUIRY_EMAIL"'",
"password": "'"$TEJARAT_INQUIRY_PASSWORD"'"
}'
```
```sh
TEJARAT_ACCESS_TOKEN="<response accessToken>"
```
### Third-Party Plate / Policy Block Inquiry
```sh
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat" \
-H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"leftTwoDigits": "12",
"serialLetter": "ب",
"threeDigits": "345",
"rightTwoDigits": "67",
"nationalCode": "0012345678"
}'
```
### Car-Body Plate Inquiry
```sh
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat/badane" \
-H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"part1": 12,
"part2": "ب",
"part3": 345,
"part4": 67,
"nationalCode": "0012345678"
}'
```
## ESG Inquiry Provider
Default/fallback base URL in some call sites:
Used by `src/sand-hub/sand-hub.service.ts` for third-party plate/VIN, identity
and Sheba inquiries in **every tenant**, including Moalem (`CLIENT_ID=7`).
```sh
ESG_URL="${ESG_URL:-http://192.168.20.22:8085}"
ESG_URL="https://<gateway-host>/<optional-prefix>"
ESG_USERNAME="<gateway-username>"
ESG_PASSWORD="<gateway-password>"
```
Used by `src/sand-hub/sand-hub.service.ts` for selected tenants, for example when `CLIENT_ID=8`.
There is no fallback URL or fallback to the deprecated Tejarat provider.
Car-body plate and VIN inquiries use the tenant’s Fanavaran profile through
`LookupsService.findLastProcessedCarPolicy("car-body", query)`, not ESG.
See [inquiry provider routing](inquiry-provider-routing.md) for deployment notes.
### Sequence
@@ -417,7 +357,7 @@ curl -X POST "$ESG_URL/auth/login" \
ESG_ACCESS_TOKEN="<response accessToken>"
```
### Car By Plate (canonical Parsian third-party plate inquiry)
### Car By Plate (third-party inquiry for all tenants)
```sh
curl -X POST "$ESG_URL/inquiry/carByPlate" \
@@ -483,15 +423,18 @@ curl -X POST "$ESG_URL/inquiry/sheba" \
## SandHub Provider
Used by `src/sand-hub/sand-hub.service.ts` for legacy inquiry flows.
Used only for the optional driving-licence and legal vehicle-ownership checks.
The current ESG API has no equivalent contract for these checks. Plate/VIN,
personal identity and Sheba inquiries do not use this adapter. Configure these
settings only when the optional checks are enabled.
Environment:
```sh
SANHUB_BASE_URL='http://82.99.202.245:3027'
SANHUB_URL_LOGIN='http://82.99.202.245:3027/user/login'
SANHUB_USERNAME='default@admin.com'
SANHUB_PASSWORD='123321'
SANHUB_BASE_URL='https://<optional-check-provider>'
SANHUB_URL_LOGIN='https://<optional-check-provider>/<login-path>'
SANHUB_USERNAME='<optional-check-username>'
SANHUB_PASSWORD='<optional-check-password>'
```
### Sequence
@@ -515,37 +458,6 @@ curl -X POST "$SANHUB_URL_LOGIN" \
SANHUB_ACCESS_TOKEN="<response accessToken>"
```
### Third-Party Plate / Policy Block Inquiry
```sh
curl -X POST "$SANHUB_BASE_URL/block-inquiry-tejarat" \
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"leftTwoDigits": "12",
"serialLetter": "ب",
"threeDigits": "345",
"rightTwoDigits": "67",
"nationalCode": "0012345678"
}'
```
### Personal Inquiry
The app converts Jalali birth dates to Gregorian before sending to SandHub.
```sh
curl -X POST "$SANHUB_BASE_URL/personal-inquiry/tejarat-no" \
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"nationalCode": "0012345678",
"birthdate": "1999-02-13"
}'
```
### Driving License Check
```sh
@@ -575,20 +487,6 @@ curl -X POST "$SANHUB_BASE_URL/ownership" \
}'
```
### Sheba Validation
```sh
curl -X POST "$SANHUB_BASE_URL/sheba/sheba-tejaratno" \
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"AccountOwnerType": "1",
"NationalId": "0012345678",
"ShebaId": "IR000000000000000000000000"
}'
```
## Map.ir Reverse Geocoding
Used by `src/claim-request-management/claim-request-management.service.ts`.
+9
View File
@@ -43,3 +43,12 @@ The same tab also supports [expert editing of accident and assessment fields](fa
Base claim, damage case, attachments, and expertise writes enforce the persisted approval. Automatic stages are deferred with a skip reason; manual stages return `409` with code `FANAVARAN_VEHICLE_REVIEW_REQUIRED`. Read-only previews remain available for diagnosis.
Once Fanavaran has created the base claim, the review is immutable in the panel because changing it would make the local snapshot disagree with data already written remotely.
## Recovery for previously submitted base claims
New base submissions (automatic and manual) require vehicle approval. Existing base claims are reused without another POST.
A case whose base was already submitted without vehicle approval may receive its first approval while `dmgCaseId` and `expertiseId` are absent. This uses the normal authorized review endpoint and active lookup/relationship validation. Approval preserves the existing base IDs and resumes damage submission when selected parts exist. The update compares the current review and stage IDs atomically so a competing approval or submission requires refresh.
An approved classification stays locked after base submission. Recovery does not rewrite the remote base payload. Base and damage use-type derivation can refer to different parties, so recovery does not impose equality between their use-type fields.
+2
View File
@@ -21,6 +21,8 @@ source: fanavaran-module-docs
## Document index
Depreciation coefficients, age codes and expert entry: [Fanavaran price drop](price-drop.md).
| # | Document | Covers |
|---|----------|--------|
| 1 | [01-write-apis.md](./01-write-apis.md) | Auth + GEN.03 / GEN.12 / GEN.44 / GEN.07 / GEN.08 write APIs |
+17 -7
View File
@@ -20,6 +20,15 @@ A PUT to `/vehicle-hull-claims/{Id}` may run before files/expertise; Parsian oft
**Send rule:** send the **hull whitelist only**. Do not send ثالث-only keys (`DamagedCount`, `HasOtherCulprit`, `CompensationReferenceId`, `DocReceivedDate`, `IsLicenseReplacement`, plaque block on base, …).
**Manual submit body:** every supplied top-level field overrides its generated
value, including IDs, arrays, nested objects, `false`, `0` and JSON `null`.
Omitted fields retain generated defaults. Arrays and nested objects replace the
corresponding value; they are not merged element by element. Lookup validation
checks a copy of manual payloads and does not refresh their supplied premium or
rewrite their values. Automatic submission without overrides keeps its existing
inquiry, normalization and validation behavior. This also applies to third-party
base/damage submits and both products' expertise submits.
**Source tags:** same as `third-party-stage-fields.md` (`system` / `lookup` / `inquiry` / `user` / `staff` / `derived`).
---
@@ -32,10 +41,11 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
`CustomerFaultPercent`, `AuthorityCulpritId`, `AccidentTypeId`, `CostSeparationToDmgSections`, `IsOwnerChanged`, `PolicyId`, `ClaimExpertId`, dates/time, `CulpritTypeId`.
**IsLicenseReplaced:** derived on the server from `CulpritLicenceIssuDate` and
`AccidentDate`: `0` through the third anniversary, `null` after three years
through the tenth anniversary, and `1` after ten years. Intake accepts valid past
issue dates older than ten years; no expiry-date or replacement-checkbox input
is required. The existing missing-date fallback is `1400/01/01`.
`AccidentDate`: default `0` through the third anniversary and `null` afterward.
Do not infer replacement from licence age exceeding ten years: Parsian rejects
that `1` with «باید خالی باشد». The hull base-claim submit body may explicitly
override `IsLicenseReplaced` with `0`, `1`, or JSON `null`; omitted fields keep
the derived default. Intake accepts valid past issue dates older than ten years. The existing missing-date fallback is `1400/01/01`.
| Field | Persian | Type | Null? | Current value / source |
|-------|---------|------|-------|------------------------|
@@ -55,7 +65,7 @@ is required. The existing missing-date fallback is `1400/01/01`.
| CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` |
| CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` |
| IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` |
| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | often null | **derived** `1` if issue date &gt;10y before accident, else `null` (hull name; ثالث uses `IsLicenseReplacement`) |
| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | often null | **derived** `0` through three years, otherwise `null`; explicit hull submit answer is preserved (ثالث uses `IsLicenseReplacement`) |
| ActualPremium | حق بیمه واقعی | number | preferred | **inquiry** hull policy `TotalPremium` via `GET /lookups/body-policy/{PolicyId}` |
| EstimateAmount | برآورد | number | **no** | **user** expert prices / provisional |
| CulpritLicenceNo | شماره گواهینامه | string | **no** | dummy / **user** |
@@ -142,9 +152,9 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
| AccidentPercent | درصد حادثه | number | yes | null |
| TheftCases | موارد سرقت | array | empty `[]` | system |
| DmgSections[].Count | تعداد | number | **no** | **system** `1` |
| DmgSections[].Desc | شرح قطعه | string | **no** | **user** part label |
| DmgSections[].Desc | شرح قطعه | string | **no** | Saved expert-reply part label (`carPartDamage.label_fa`) |
| DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** |
| DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` |
| DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | Saved `evaluation.damageExpertReply.parts[].partId`, passed through directly; policy matching and factory bundles must never replace it |
| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | Current `vehicle-hull-dmg-kind` API row caption تخریب; no numeric fallback |
| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | preferred | Current policy `dmg-accessories`: exact `AccessoryKindId` or caption match; else the «کليه قطعات فابريک» factory-bundle row `Id`. Keep selected car-components `AccessoryKindId` + part `Desc` |
| DmgSections[].DmgSectionCosts[].Caption | عنوان هزینه | string | **no** | **user** label |
+107
View File
@@ -0,0 +1,107 @@
# Fanavaran depreciation tables
The calculation now uses [ضرایب افت قیمت.xlsx](<../ضرایب افت قیمت.xlsx>) and [افت قیمت سن.png](<../افت قیمت سن.png>). Their reference data lives in `src/static/fanavaran-price-drop.ts`; the previous fixed production-year table and part coefficients are retired.
## Part and severity codes
These codes identify depreciation categories, **not** tenant car-component IDs. The original component ID remains `partId`. The expert can explicitly choose a category when a tenant's component caption is ambiguous. Clear names receive a suggestion; numeric IDs are never assumed to mean the same thing across insurers.
The depreciation path preserves saved tenant captions even when their component IDs collide with the legacy global fallback snapshot. It does not replace a tenant's saved roof caption with another tenant's trunk-floor-tray caption merely because both use ID 52.
| Category code | Caption | Minor / Moderate / Severe codes | Coefficients |
| --- | --- | --- | --- |
| 1 | سقف | 1 / 2 / 3 | 3 / 5 / 7 |
| 2 | کلاف | 4 / 5 / 6 | 2 / 3 / 4 |
| 3 | ستون | 7 / 8 / 9 | 2 / 3 / 4 |
| 4 | درب موتور | 10 / 11 / 12 | 2 / 3 / 4 |
| 5 | سینی جلو | 13 / 14 / 15 | 1 / 2 / 3 |
| 6 | شاسی جلو | 16 / 17 / 18 | 3 / 5 / 7 |
| 7 | گلگیر جلو | 19 / 20 / 21 | 1 / 2 / 3 |
| 8 | درب جلو | 22 / 23 / 24 | 1 / 2 / 3 |
| 9 | درب عقب | 25 / 26 / 27 | 1 / 2 / 3 |
| 10 | رکاب | 28 / 29 / 30 | 1 / 2 / 3 |
| 11 | گلگیر عقب | 31 / 32 / 33 | 2 / 3 / 5 |
| 12 | درب صندوق | 34 / 35 / 36 | 1 / 3 / 5 |
| 13 | سینی عقب | 37 / 38 / 39 | 1 / 2 / 3 |
| 14 | سینی کف صندوق | 40 / 41 / 42 | 2 / 4 / 5 |
| 15 | شاسی عقب | 43 / 44 / 45 | 2 / 4 / 6 |
| 16 | کف اتاق | 46 / 47 / 48 | 4 / 6 / 8 |
| 17 | بلوک سیلندر | Severe only: 49 | Severe only: 3 |
Front/rear bumpers are absent from the supplied table and no longer receive an automatic coefficient. Rear tray and trunk-floor tray are separate. Glass, pillar trim and roof accessories are not mapped to a door/pillar/roof just because that word occurs in their caption. A submitted part must exist among the case's selected damaged parts, and each part may occur only once per calculation. Non-catalog internal rows without a component ID remain available through the existing manual-total option.
## Age codes
| Age at accident | Code | Coefficient |
| --- | --- | --- |
| 0 | 1 | 3 |
| 1 | 2 | 2.9 |
| 2 | 3 | 2.8 |
| 3 | 4 | 2.7 |
| 4 | 5 | 2.6 |
| 5 | 6 | 2.5 |
| 6 | 7 | 2.4 |
| 7 | 8 | 2.3 |
| 8 | 9 | 2.2 |
| 9 | 10 | 2.1 |
| 10 | 11 | 2.05 |
Suggested age is the Jalali accident year minus the **damaged vehicle's** Jalali model year. It does not use the current year or the guilty party's vehicle, even when an expert or the guilty party owns the claim record. Experts can confirm/correct age directly. A Gregorian model year without month/day is not converted speculatively; use explicit age instead.
The screenshot marks these age rows effective from `1404/05/28`. Cases with a known earlier accident date cannot use automatic calculation from this table. Cars **older than ten at the accident are not eligible for depreciation**. Their calculated and manual depreciation must be zero, with no invented age/coefficient code. Exactly ten remains eligible. Positive manual totals require a known or explicitly entered eligible age. The UI offers an over-ten option, explains the exclusion and only lets the expert save zero. For pre-table accident dates, the manual-total path remains subject to the same age rule.
## Formula and currency
The supplied documents define reference rows, not a replacement formula. The existing formula is retained with the new coefficients:
```text
Depreciation = vehicle market price × age coefficient × sum(part severity coefficients) / 400
```
All amounts are **Rials**. Integer arithmetic in hundredths of the coefficient prevents floating-point rounding drift; the result is rounded to whole Rials. Example: a 400,000,000 Rial car aged 3 with moderate trunk-floor-tray damage produces `400000000 × 2.7 × 4 / 400 = 10800000` Rials.
## Existing API routes
```text
GET /v2/expert-claim/request/:claimRequestId/price-drop
PUT /v2/expert-claim/request/:claimRequestId/price-drop
```
The context includes `priceDropCatalog` with `fanavaranPartId`, `severities` and `severityCodes`; `ageCatalog`; `suggestedVehicleAge`; `accidentYear`; `calculationVersion`; `ageTableEffectiveFrom`; and `calculationUnavailableReason` when the accident predates the table.
Example calculation, where `9876` is an illustrative component ID actually selected on that case:
```json
{
"carPrice": 400000000,
"vehicleAge": 3,
"partSeverities": [
{ "partId": 9876, "fanavaranPartId": 14, "severity": "Moderate" }
]
}
```
`fanavaranPartId` is optional when a safe name mapping exists. The older `carModelYear` input remains supported when an accident date is available. Clients never choose coefficients directly: the API derives them from the static source.
`evaluation.priceDrop` stores version `fanavaran-v1`, age, `fanavaranAgeId` and the coefficient. Each saved part line includes the actual component `partId`, category `fanavaranPartId` and `fanavaranSeverityId`. The response and strict Mongoose schema retain these fields.
For eligible ages, the manual path remains (zero is also allowed without an age):
```json
{ "manualPriceDrop": 0 }
```
Calculated requests must omit `manualPriceDrop`; its presence explicitly chooses the manual path. The expert UI separates these writes so a previously saved total cannot silently override recalculation. Manual entry also has an optional `carPrice` field for Fanavaran's market-value data. Manual writes preserve an existing market price when omitted and clear obsolete calculated rows. `manualOverride` now survives schema casting.
## Fanavaran writes and rollout
The existing documented write contracts still receive the final total in third-party `DropAmountAdditionsDeductions` or car-body `DropAmount`. Category/severity/age codes are calculation/audit metadata; they are not inserted into undocumented outgoing fields. GEN.13 is read-only in the currently supplied API contract.
Saved historical assessments are never automatically recalculated. When a known over-ten vehicle has an old positive total, a new Fanavaran submission uses zero; the stored historical assessment is preserved until explicitly corrected. The UI identifies results without the new calculation version and lets the expert explicitly recalculate them. Deploy the API first, then the expert UI. No new environment variables or database migration are required.
## Verification
- All 17 category codes/captions and all 49 severity codes/coefficients were compared directly with the supplied workbook.
- API regression tests cover age boundaries, date validity, separate severity codes, tenant-ID collisions, explicit mappings, real schema persistence, manual zero, duplicate/unselected parts, vehicle-party isolation and failed writes preserving previous results.
- Expert UI regression tests cover request construction and rendered controls. Browser checks at 1440×1100 and 390×844 cover labels, keyboard, overflow, age zero, severe-only cylinder block, HTTP-error retry and separate calculated/manual requests. Browser API calls used synthetic intercepted responses.
- The full API suite additionally reports ten failures in the unchanged `fanavaran-submit-overrides.spec.ts` fixture, reproduced on an archive of the unmodified commit. These fail at the existing vehicle-review prerequisite before reaching their intended assertions; they are unrelated to depreciation.
+84
View File
@@ -0,0 +1,84 @@
# Inquiry provider routing
The running NestJS API routes inquiries through `src/sand-hub/sand-hub.service.ts`.
The class name remains for existing dependency injection; it does not select the
provider by tenant anymore.
| Inquiry | Provider | Entry point |
| --- | --- | --- |
| Third-party policy by plate | ESG `/inquiry/carByPlate` | `getCarByPlateInquiry` |
| Third-party policy by national code + VIN | ESG `/inquiry/carByChassis` | `getCarByChassisInquiry` |
| Person identity | ESG `/inquiry/person` | `getPersonalInquiry` |
| Sheba ownership | ESG `/inquiry/sheba` | `getShebaValidation` |
| Car-body policy by plate or VIN | Tenant-specific Fanavaran processed policy lookup | `getCarBodyInquiry` |
| Optional driving-licence / legal vehicle ownership | Existing configured `SANHUB_*` adapter | `getDrivingLicenseInfo` / `getCarOwnershipInfo` |
The ESG endpoints above apply to every tenant. Existing per-client live/mock
settings still apply. Disabled inquiries retain their mock behavior; offline
third-party plate records are consulted only in disabled mode. No mock or
deprecated provider is used as a fallback when a live ESG inquiry fails.
## Why Moalem reached the retired login
Previously only `CLIENT_ID=8` selected ESG. `CLIENT_ID=7` therefore selected the
old Tejarat transport for third-party plate inquiries, and the old configurable
hub for identity and Sheba. Car-body plate inquiries also used the Tejarat
transport unless the Fanavaran profile was Parsian. Car-body VIN inquiries
already used Fanavaran.
The retired `getTejaratAccessToken`, `/user/login` transport and
`TEJARAT_INQUIRY_*` configuration have been removed from the running API.
Both car-body input formats now use the existing Fanavaran lookup. The mapper
uses the selected source insurer rather than assuming every car-body result
belongs to Parsian. Explicit conflicting insurer codes are rejected.
## Deployment settings
Supply these through the API environment, then restart the API:
```dotenv
CLIENT_ID=7
FANAVARAN_CLIENT=moallem
ESG_URL=https://<gateway-host>/<optional-prefix>
ESG_USERNAME=<gateway-username>
ESG_PASSWORD=<gateway-password>
```
`moallem` is the existing Fanavaran profile spelling. The explicit
`FANAVARAN_CLIENT` setting takes precedence; when absent, `CLIENT_ID=7` now
resolves to `moallem`, and `CLIENT_ID=8` still resolves to `parsian`. Other
deployments must select their own Fanavaran profile as before. The selected
profile must have its existing Fanavaran credentials/contracts configured.
`ESG_URL` is the base **before** `/auth/login` and `/inquiry/...`; include any
gateway prefix in that value. Trailing slashes are normalized. No internal-IP
default is used. The ESG user needs access to all four inquiry types. Birth
dates are sent in Jalali `YYYY-MM-DD`, with `dateHasPostfix: 0`. The cached ESG
token is reused, and an inquiry HTTP 401 clears it before the existing retry.
`TEJARAT_INQUIRY_BASE_URL`, `TEJARAT_INQUIRY_EMAIL` and
`TEJARAT_INQUIRY_PASSWORD` are no longer read by the running API and can be
removed from deployment configuration. Do not repoint `SANHUB_*` to ESG: their
optional licence/ownership payloads differ, and the ESG repository currently
has no matching endpoints. Those two checks keep their existing settings
until an explicit replacement contract is provided.
## Compatibility and verification
The mapped inquiry fields consumed by the UI remain unchanged. The old
`getSandHubResponse` entry point delegates to ESG and returns the mapped result.
New car-body audit records identify their source as
`FANAVARAN_CAR_BODY_INQUIRY` or `FANAVARAN_CAR_BODY_VIN_INQUIRY`. Historical raw
inquiries, audit records and database documents are not rewritten.
`scripts/refresh-blame-inquiries.js` and `scripts/fanavaran-flow-ui-server.js`
are separate manually run diagnostic tools with their own legacy provider
settings. They are not invoked by the running application and have not been
migrated by this change; do not use their inquiry shortcuts as evidence of the
application's current routing.
Regression tests in `sand-hub.esg-routing.spec.ts` cover tenant IDs 7, 8 and 15,
ESG token reuse/401 refresh, missing configuration, disabled inquiries,
Fanavaran plate/VIN routing, source-company checks and optional-check
compatibility. Provider HTTP calls in these tests are mocked; deployment still
requires valid gateway credentials and connectivity.
+9
View File
@@ -20,6 +20,7 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw
| --- | --- | --- |
| List/create insurers | `GET/POST /super-admin/management/clients` | Unavailable |
| Edit insurer metadata | `PATCH /super-admin/management/clients/:id` | Unavailable |
| Read or update case working hours | `GET/PATCH /super-admin/management/working-hours?clientId=...` | `GET/PATCH /expert-insurer/management/working-hours` |
| List/create insurer login accounts | `GET/POST /super-admin/management/clients/:clientId/accounts` | Unavailable |
| Edit insurer login account | `PATCH /super-admin/management/clients/:clientId/accounts/:id` | Unavailable |
| List/create staff | `GET/POST /super-admin/management/staff?clientId=...` | `GET/POST /expert-insurer/management/staff` |
@@ -30,6 +31,14 @@ All endpoints require bearer authentication and strictly validate their DTOs. Sw
Staff list queries accept `search`, `role`, `page` and `limit` (default 20, capped at 100). Responses contain `list`, `total`, `page` and `limit`. Branch responses contain `list`; clients contain `clients`. Account lists share the staff pagination contract.
## Case working hours
Insurers edit their own hours in **تنظیمات شرکت بیمه** (`/settings`). Super-admins use **ساعات کاری** on the relevant company in `/insurers`. Existing companies default to 24/7. Saving a change applies it immediately to new case submissions, including submissions for existing cases.
Schedules use Tehran time and allow one opening window per weekday. Omitted days are closed. For an overnight shift, enter an end time earlier than the start. The API numbers weekdays from Sunday (`0`) through Saturday (`6`) and accepts `24:00` as the end of a day. For example, `{"alwaysOpen":false,"windows":[{"weekday":6,"opensAt":"08:00","closesAt":"16:00"}]}` opens Saturday from 08:00 inclusive to 16:00 exclusive. Enable `alwaysOpen` to allow access around the clock.
Case creation and updates use the liable insurer's hours once it is identified. At intake, staff use their own insurer's hours. For public intake before the case insurer is known, set the API's existing `CLIENT_ID` to the deployment insurer's numeric client code. If an intake has no known insurer and the deployment has no configured insurer, the schedule applies once the insurer is identified. Case reads, login and schedule settings are available outside those hours. Blocked case updates return HTTP 403 with `OUTSIDE_WORKING_HOURS` and the next opening.
## Fields
`role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism.
+28
View File
@@ -0,0 +1,28 @@
# Persian panel and report presentation
The expert/user panels and insurer file report use Persian interface labels and system values. The report builder translates persisted lifecycle statuses and known inquiry fields. Unmapped provider field names are omitted instead of being printed as raw English keys. Cached report fields receive the same protection in the PDF renderer.
Actual identifiers and user-entered facts are preserved: VINs, policy numbers, phone numbers, email addresses and saved vehicle names are not translated or rewritten. National codes remain available in explicitly labelled identity fields; they are never used as a person's display name. No stored case, inquiry or Fanavaran payload is changed by report formatting.
## Person labels
The presentation helper prefers a saved full name or first/last name, then an explicitly recorded phone number. Numeric placeholders, database IDs, national codes, email addresses and generic English placeholder names are rejected as names. If neither name nor phone exists, the interface uses a Persian unavailable label. Insurer detail/report views resolve current user profiles by the case's user ID, with a per-request lookup cache. Timeline names resolve the actual event actor rather than the other party or the claim owner by default.
Driver and owner names are resolved separately. A licence number is never substituted for its issue date. Monetary amounts already stored in rials are labelled ریال without changing their numeric value.
## Shared damaged-parts catalogue
The user application no longer asks for a vehicle body type or side before selecting parts, including the objection/additional-parts picker. It searches the shared catalogue by name or code and submits the selected numeric IDs. It does not invent a vehicle type. Existing vehicle identity data used by inquiries and pricing is retained.
Selections persisted under the old side buckets are merged into the shared selection, deduplicated by ID and preserved. Search does not clear selections. The picker displays loading/failure/retry states, and its catalogue cache is scoped to the current account. Existing document, bank-information and photo steps remain in their flow-specific order.
## Verification
- API report/presentation tests: 52 passing tests, plus 21 insurer summary/timeline regression tests.
- Both frontend `npm run test:ui` suites, including new Persian presentation and flat-catalogue scenarios covering all six flows.
- Type checking and production builds for both frontends; API build.
- Real local browser pages at desktop (1440 × 1100, v1) and mobile (390 × 844, v6), using synthetic cases and intercepted API responses: catalogue failure/retry, thin catalogue rows, search by code, selections across searches, no vehicle-type/side prompt, correct IDs-only submission and document-step navigation.
- A report was rendered using the actual report builder and PDF component. Persian layout and extracted text were checked; Latin content in the fixture was limited to actual identifiers. Local existing fonts were used for this offline rendering check; production font configuration was unchanged.
- The full API suite still has ten previously identified failures in `fanavaran-submit-overrides.spec.ts`, whose fixtures lack reviewed vehicle data. Those unrelated fixtures were not changed.
No production database or external provider was used for the browser/PDF checks. These checks do not claim every production record or every page was manually exercised.
@@ -0,0 +1,85 @@
{
"date": "2026-11-22",
"environment": "isolated local MongoDB, synthetic accounts and generated media; external providers mocked",
"httpFlowMatrix": {
"v1-CAR_BODY": {
"status": "COMPLETED"
},
"v1-THIRD_PARTY": {
"status": "COMPLETED"
},
"v2-CAR_BODY": {
"status": "COMPLETED"
},
"v2-THIRD_PARTY": {
"status": "COMPLETED"
},
"v3-CAR_BODY": {
"status": "COMPLETED"
},
"v3-THIRD_PARTY": {
"status": "COMPLETED"
},
"v4-CAR_BODY": {
"status": "COMPLETED"
},
"v4-THIRD_PARTY": {
"status": "COMPLETED"
},
"v5-CAR_BODY": {
"status": "COMPLETED"
},
"v5-THIRD_PARTY": {
"status": "COMPLETED"
},
"v6-CAR_BODY": {
"status": "COMPLETED"
},
"v6-THIRD_PARTY": {
"status": "COMPLETED"
}
},
"negativeControls": {
"malformedId": 400,
"createRace": {
"success": 1,
"conflict": 5
},
"invalidMedia": 400,
"invalidEnums": 400,
"foreignFieldMutation": 403
},
"signedMedia": {
"expertCapture": 200,
"ownerDocument": true,
"blameEvidence": true,
"bareFile": 401,
"duplicateSignature": 401
},
"browserChecks": [
"v6 login retains blame context",
"five formerly denied versioned routes render",
"repair-only objection form renders",
"Persian-locale expert assessment renders",
"written blame resend submits without an image",
"instruction-only claim resend acknowledgment reaches expert queue"
],
"historicalRepair": {
"dryRunMatched": 2,
"applied": 2,
"signedControlUnchanged": true,
"pricedControlUnchanged": true
},
"automatedChecks": {
"apiSuites": 111,
"apiTestsPassed": 1070,
"httpE2ePassed": 26,
"httpE2eSkipped": 4,
"userUiSuite": "passed",
"expertUiSuite": "passed",
"apiBuild": "passed",
"userUiBuild": "passed",
"expertUiBuild": "passed",
"uiHardeningDetectorFindings": 0
}
}
+107
View File
@@ -0,0 +1,107 @@
# QA remediation — 22 November 2026
Scope: the 28 distinct findings in `QA_REPORT_2026-11-22.txt`,
`QA_REPORT_2026-11-22_CONTINUED.txt`, `QA_REPORT_2026-11-22_EXTENDED.txt`, and
`qa-reports/`. The extended report repeats several continued findings; its
reconciliation supplies IDs 25–28. Changes cover `api`, `ui-user`, and
`ui-expert`. No production database changes or external provider writes were
performed. `rewrite` and `esg` are outside this change.
## Findings and changes
| ID | Resolution | Verification |
| --- | --- | --- |
| 1 | All V3 claim evidence/selection entry points authorize the actor against the case before changing it. | Authorization regression; real foreign-field-expert 403 and positive V3 HTTP filing/capture. |
| 2 | Reviewer assignment distinguishes initial capture from subsequent assessment after maker rejection. An assigned reviewer can acquire an assessment lock again. | HTTP V5: two reject/review cycles, rejection limit, final maker approval. |
| 3 | Both UIs spell rial amounts using locale-independent integer grouping instead of the library recursion triggered by Persian grouping. | Both UI suites; real Persian-locale expert assessment browser. |
| 4 | Added the ordinary-user V6 login page; the incoming blame token survives login redirection. | Real mobile browser link and URL assertion. |
| 5 | Labor-only lines tolerate absent prices; objection payloads omit absent optional monetary values and submission failures remain visible. | Real mobile browser protest form; UI regression suite. |
| 6 | Expired V6 ordinary-user sessions return to `/v6/login`; call-center sessions retain their expert login route. | Role-aware redirect regression. |
| 7 | Multipart nested objection rows become DTO instances and are validated explicitly at the service boundary, including deployments without a global validation pipe. | DTO tests and a real multipart objection through HTTP/MongoDB. |
| 8 | Vehicle subdocuments are serialized before merging resolved identity fields, exposing saved vehicle prices without Mongoose internals or parent documents. | HTTP detail assertions for price and absence of `_doc`/`$__parent`. |
| 9 | Unique-index conflicts during concurrent claim creation become HTTP 409 rather than 500. The database uniqueness constraint remains intact. | Real six-way creation race: one success, five HTTP 409 responses. |
| 10 | Owner claim-detail rejects malformed ObjectIds before querying MongoDB. | Real malformed-ID HTTP 400 control and explicit ID guard. |
| 11 | Upload policy verifies readable media streams and decodes content; text disguised as MP4, wrong media kinds and unreadable content cannot satisfy evidence steps. | Generated image/video/audio controls and corrupt/wrong-kind regression tests. |
| 12 | Shared description handlers enforce the declared weather, road and light enums, including expert form variants. | HTTP invalid-enum rejection without advancement, then valid filing; full API suite. |
| 13 | Expert cards recognize rejected cases and treat rejected/cancelled/stopped cases as view-only. | Expert UI status regressions. |
| 14 | Sheba masking preserves the existing prefix rather than prepending another `IR`. | Response mapping review and full API suite. |
| 15 | Car-body video instructions describe the vehicle and accident scene without requiring two vehicles. | User production build and UI source check. |
| 16 | Evidence is served through a signed, expiring read route, replacing anonymous static serving. Authorized case responses supply links usable by image/video/PDF elements. Arbitrary description text does not mint links. | Bare link 401; signed link 200; altered/expired/cross-path capability tests. See proxy requirements below. |
| 17 | Owner acceptance/rejection uses one conditional atomic update; only its winner records the decision and invokes integrations. Concurrent losing signature records are removed. Signature upload names use UUIDs. | Six-way unit and real MongoDB/HTTP race. |
| 18 | Registrar signatures accept registrar-created cases and follow the same signatures-before-accident-fields order as the shared V2 contract. | HTTP registrar CAR_BODY and THIRD_PARTY through signatures and accident fields. |
| 19 | Instruction-only claim resends display the instruction and offer acknowledgment through the existing endpoint. | Actual mobile browser acknowledgment and persisted queue transition. |
| 20 | Part resends send a stable catalog key/ID, independent of an optional English label. | Client key mapping and HTTP catalog-ID capture. |
| 21 | In-person visits have a pending status, owner instructions and a resumable expert review lock. They no longer imply completion/acceptance. Historical repair is provided separately. | HTTP visit → owner guidance → reassignment → assessment; V4/V5 visit controls; repair dry-run/apply controls. |
| 22 | Expert portfolio queries retain linked blame product type for product filters. | HTTP product counts: both products nonzero and their sum equals the total. |
| 23 | Insurer expert reports use linked blame product types. Missing types for roster-owned claims are resolved in one batch after claim scoping. | Reporting regression, including a linked blame outside the party-insurer list. |
| 24 | Satisfaction rating is written only if no rating exists, in one conditional atomic update. | Six-way concurrent rating regression and real HTTP/MongoDB race: one successful rating. |
| 25 | Versioned user route allowlists use real end anchors instead of requiring a literal `$`. | Browser assertions on five formerly denied routes. |
| 26 | Written blame resends use the text field; voice and document requests render their respective controls. The old duplicate page reuses the shared implementation. | Real browser text-only resend and successful navigation after submission. |
| 27 | Every requested replacement must have a timestamp at or after the current resend request. A partial upload cannot reuse old evidence to finish the request. | Real three-item replacement replay plus timestamp regression; original evidence stays intact. |
| 28 | Legacy top-rated-file normalization preserves root `userRating`, with a fallback for old nested records. | Reporting regression. |
## Verification
Sanitized results: [verification JSON](qa-remediation-2026-11-22-verification.json).
- API: **111 suites, 1,070 tests passed** (`npm test -- --runInBand`).
- API HTTP E2E suite: **26 passed, 4 skipped** (`npm run test:e2e -- --runInBand`).
The four opt-in browser scenarios were not enabled in that runner; independent
browser replays were run separately as described above.
- Both UI regression suites passed (`npm run test:ui`).
- All three production builds passed (`npm run build` in each repository).
- Browser checks used Chromium/Brave, Persian locale, a 390×844 user viewport
and a desktop expert viewport. The UI hardening detector reported no findings
on the changed user-facing views.
- **All 12 flow/product combinations** (v1–v6 × CAR_BODY/THIRD_PARTY) reached
completed claims through filing, capture and assessment. V1/V6 included owner
acceptance; V5 included maker approval. V4/V5 also resumed after a visit.
- Additional HTTP replays used the actual updated Nest process and a disposable
local MongoDB database, synthetic users and generated media. External inquiry,
SMS, AI and Fanavaran requests were intercepted with offline provider fixtures.
These checks do not verify customer WAF/proxy configuration or real provider
acceptance.
## Deployment requirements
Deploy the API and both UIs together, because the pending-visit status and signed
evidence links span their contracts.
1. **Media tools:** the API Dockerfile now installs `ffmpeg`, which includes
`ffprobe`. For deployments outside that Dockerfile, install both binaries in
the API runtime and verify that its service account can execute them. Missing
binaries will correctly reject uploads as unreadable; do not bypass validation.
2. **Evidence proxy:** remove any public Nginx `alias`/`root`/static/CDN rule that
directly exposes the API's `files` directory. Proxy `/files/*` (including its
deployed `/car-damage/api/` prefix, if applicable) to Nest, preserving the
query string and Range headers. A reverse-proxy static bypass would leave the
original anonymous-access issue unresolved. Purge previously cached public
evidence responses. Keep the existing API prefix/rewrite conventions; do not
copy a new `proxy_pass` prefix blindly.
3. **Signing secret:** all API instances serving the same files must share the
existing `JWT_SECRET`. File URLs expire after one hour; reopening/refetching
the authorized case returns fresh URLs. No additional signing secret or
public access switch is introduced. Old cached bare links require a refresh.
4. **Historical visits:** back up the database and preview the narrow repair
from the `api` directory with the intended deployment's environment:
```bash
node scripts/repair-premature-visit-completions.js
# After checking the matched count:
node scripts/repair-premature-visit-completions.js --apply
```
Dry-run is the default. The script only changes `COMPLETED` +
`NEEDS_REVISION` records with an in-person-visit history event and no
submitted assessment, priced parts or recorded owner approvals. It unlocks
review and writes a repair history event. It does not invent an address or
change evidence, payment amounts, signatures or other completed cases.
Dry-run and apply were exercised on synthetic records, with signed/priced
controls left closed. More ambiguous old records need individual review.
5. **Historical races:** overwritten satisfaction ratings or contradictory
owner decisions already recorded before this change cannot be reliably
reconstructed automatically. Review their history and provider submission
records; the code prevents new overlapping writes but does not guess which
old decision was intended.
No commits or pushes are included in this remediation task.
+51
View File
@@ -0,0 +1,51 @@
# Sheba is entered once per claim
| UI flow | Bank information is collected at |
| --- | --- |
| v1, user-created, third-party or car-body | Claim other-parts/bank-information step |
| v2, field expert | Claim other-parts/bank-information step |
| v3, field expert | Damaged party's inquiry: first party for car-body, second party for third-party |
| v4/v5, file maker and reviewer | File maker's damaged-party inquiry; reviewer reuses the claim's bank information |
| v6, call centre and user | User's claim other-parts/bank-information step; call centre never collects Sheba |
The v1/v6 initial-form endpoints do not persist a Sheba. The shared inquiry UI
previously requested it for v1, and then requested it again during the claim.
It now asks only on inquiry endpoints that actually validate and save it.
At the claim step, the UI fetches the current claim before showing bank inputs.
It requests only missing fields, reuses an already uploaded green card, and
shows a Persian confirmation when Sheba is already available. A failed or
pending fetch does not display empty bank fields. Values are not copied between
cases or kept in browser storage. User-facing bank values remain masked.
The claim snapshot adds `bankInformation.shebaProvided` and
`bankInformation.ownerNationalCodeProvided`. These booleans let the UI reuse
saved data without receiving unmasked account numbers. The owner national code
can come from the linked blame's vehicle-owner participant.
`selectOtherPartsV2` accepts omitted bank fields when the claim already has
them. It normalizes IR-prefixed and digits-only Sheba consistently and validates
new or changed bank details. It retains beneficiary authorization and rejects
another owner's saved account. Unchanged saved bank details do not trigger a
second inquiry. Explicit replacement remains available during expert resend;
an ordinary parts submission cannot silently replace an existing account.
The expert panel renders one claim-entry form for the damaged vehicle rather
than independent forms for both vehicles. It passes saved bank details into
that form. The expert claim-completion service also recognizes an IR-prefixed
saved Sheba when advancing the workflow.
No database migration is required. A Sheba entered into an old initial form and
discarded by the old endpoint cannot be recovered; those cases still need it
once at the claim step.
## Regression checks
- API: `npm test -- --runInBand claim-bank-information.spec.ts claim-beneficiary-access.spec.ts`
- User UI: `node scripts/test-claim-bank-information.cjs` (also run by `npm run test:ui`)
- Expert UI: `node scripts/test-claim-bank-information.cjs` (also run by `npm run test:ui`)
Tests cover every flow/role/party/case-type collection combination, saved and
missing values, stale/loading/error states, legacy aliases and formats,
resends, vehicle-owner mismatches, masked responses and the single expert
claim-entry form. HTTP and database dependencies are mocked.
+47
View File
@@ -0,0 +1,47 @@
# Deployment-specific SMS names
Set the public display name in the API deployment environment and restart the API:
```env
SMS_BRAND_NAME="سامانه خسارت اپکس"
```
The default for an absent, empty or whitespace-only value is `یارا۷۲۴`.
This name is independent of the Fanavaran tenant and SMS provider settings.
No database migration or frontend deployment is required.
Every locally rendered SMS carries this name: OTPs, invitations, field-expert
links, signature notices, document requests, case-review updates, Fanavaran
registration confirmations and plain messages loaded from `sms-texts`.
Messages without an embedded name receive the name on a final line. Existing
Persian/English Yara724 name spellings in message patterns are replaced when
rendered; stored patterns are not changed. URLs and inserted token values are
preserved.
Custom OTP and database message patterns can place the name explicitly:
```env
AUTH_SMS_MESSAGE="رمز ورود شما در {brandName}: {token}"
```
`{brandName}` is resolved from `SMS_BRAND_NAME`. The existing `{token}`,
`{token2}`, `{token3}` and `{token10}` placeholders retain their purposes.
Locally rendered deliveries and skipped test OTPs record the same rendered text
in the SMS audit. Kavenegar hosted lookups record a locally reconstructed text;
their actual body is controlled by the provider's approved template. Previously
stored SMS logs are historical records and are not modified.
## Provider behavior
- **Parsian and Moalem:** all templates are rendered locally; no provider-side
template changes are needed.
- **Kavenegar:** with the default name, existing hosted lookup templates continue
to work. With a custom name, application templates and OTPs are rendered locally
and sent through `sms/send.json` using the existing sender. The Kavenegar
account/sender must support plain-text delivery, including the intended
recipients. Hosted templates cannot have their fixed text changed by this
environment variable. Unknown external template identifiers continue to use
hosted lookup; all current application notifications have local templates.
Changing the display name does not change provider credentials, sender numbers,
template identifiers, user-panel links or the SMS destination numbers.
Binary file not shown.
+25 -5
View File
@@ -831,15 +831,23 @@
<select id="DRIVER_IS_OWNER"><option value="1" selected>1</option><option value="0">0</option></select>
</label>
</div>
<p class="hint">اگر این شخص در فناوران نیست، موبایل و بقیه مشخصات ثبت را در تب «ثبت شخص» وارد کنید. همان مقادیر در GEN.44 فرستاده می‌شود.</p>
<p class="hint">اگر این شخص در فناوران نیست یا برای بدنه نقش «سایر» ندارد، مشخصات او را در تب «ثبت شخص» وارد کنید.</p>
</div>
</section>
</div>
<div class="tab-panel" data-form-panel="person" hidden>
<section class="card">
<h2><span class="n">+</span> ثبت شخص — GEN.44</h2>
<p class="hint">وقتی استعلام نقش ۱۶۱ یا ۱۶۶ خالی است، این فیلدها در POST سایر اشخاص می‌روند. خالی یا کلمه null یعنی JSON null. موبایل برای این تنانت اجباری است.</p>
<p class="hint">برای بدنه، شخص باید نقش «سایر» (۱۶۶) داشته باشد؛ نقش بیمه‌گذار (۱۶۱) به‌تنهایی کافی نیست. مشخصات همین فرم برای ثبت شخص استفاده می‌شود. خالی یا کلمه null یعنی JSON null. موبایل برای این تنانت اجباری است.</p>
<div class="grid 3">
<label class="s3"><b>نقش مورد نظر برای ثبت</b>
<select id="PERSON_ROLE_ID" required>
<option value="">— نقش را انتخاب کنید —</option>
<option value="166">سایر — 166 (برای ثبت راننده)</option>
<option value="161" disabled>بیمه‌گذار — 161 (در این سرویس قابل ثبت نیست)</option>
</select>
<span class="hint">این فرم نقش «سایر» را با سرویس ثبت سایر اشخاص اضافه می‌کند. نقش‌های قبلی شخص حفظ می‌شوند.</span>
</label>
<label><b>کد ملی</b><input id="personNc" value="0017819199" maxlength="10" /></label>
<label><b>تاریخ تولد</b><input id="personBd" value="13731228" placeholder="YYYYMMDD" /></label>
<label><b>موبایل</b><input id="DRIVER_MOBILE" placeholder="0912…" dir="ltr" /></label>
@@ -1684,6 +1692,7 @@ node scripts/fanavaran-flow-ui-server.js</pre>
DRIVER_BIRTH_DAY:bd.d,
DRIVER_IS_INSURER:q("DRIVER_IS_INSURER"),
DRIVER_IS_OWNER:q("DRIVER_IS_OWNER"),
PERSON_ROLE_ID:q("PERSON_ROLE_ID"),
DRIVER_MOBILE:q("DRIVER_MOBILE"),
DRIVER_TEL:q("DRIVER_TEL"),
DRIVER_ADDRESS:q("DRIVER_ADDRESS"),
@@ -1819,12 +1828,11 @@ node scripts/fanavaran-flow-ui-server.js</pre>
$("EXPERTISE_CLAIM_EXPERT_ID").closest("label").querySelector("b").textContent = hull ? "GEN.06 ClaimExpertId" : "GEN.08 ExpertiseClaimExpertId";
$("stageNotification").hidden = hull || q("FANAVARAN_API_VERSION") !== "v15";
$("formTabNotify").hidden = hull || (q("FANAVARAN_API_VERSION") !== "v15" && q("FANAVARAN_CLIENT") !== "moallem");
document.querySelector('[data-form-panel="person"]').hidden = hull;
document.querySelector('[data-form-tab="person"]').hidden = hull;
if (hull && document.querySelector('[data-form-tab="person"]')?.classList.contains("active")) showFormTab("cars");
document.querySelector('[data-form-tab="person"]').hidden = false;
}
function missingRequiredNotifier(stage) {
if (stage === "auth" || stage === "person") return "";
if (q("FANAVARAN_PRODUCT") === "CAR_BODY") return "";
const v15 = q("FANAVARAN_API_VERSION") === "v15";
const moallemV14 = q("FANAVARAN_CLIENT") === "moallem" && !v15;
@@ -2025,6 +2033,7 @@ node scripts/fanavaran-flow-ui-server.js</pre>
}
set("DRIVER_IS_INSURER","DRIVER_IS_INSURER");
set("DRIVER_IS_OWNER","DRIVER_IS_OWNER");
set("PERSON_ROLE_ID","PERSON_ROLE_ID");
set("DRIVER_MOBILE","DRIVER_MOBILE");
set("DRIVER_TEL","DRIVER_TEL");
set("DRIVER_ADDRESS","DRIVER_ADDRESS");
@@ -2323,6 +2332,12 @@ node scripts/fanavaran-flow-ui-server.js</pre>
setStatus("سرور UI روشن نیست.", "err");
return;
}
if (stage === "person" && q("PERSON_ROLE_ID") !== "166") {
setStatus("نقش مورد نظر را انتخاب کنید. این فرم ثبت نقش سایر (166) را پشتیبانی می‌کند.", "err");
showFormTab("person");
$("PERSON_ROLE_ID").focus();
return;
}
if (q("FANAVARAN_PRODUCT") !== "CAR_BODY" && q("CULPRIT_TYPE_ID")==="338" && !q("ACCIDENT_CULPRIT_ID") && (stage==="base"||stage==="all")) {
setStatus("ACCIDENT_CULPRIT_ID برای CulpritTypeId=338 لازم است.", "err");
return;
@@ -2408,6 +2423,11 @@ node scripts/fanavaran-flow-ui-server.js</pre>
body: JSON.stringify({ stage, env, ui: collectUi() }),
});
if (result.ids) Object.assign(stateIds, result.ids);
if (result.ok && stage === "person" && q("FANAVARAN_PRODUCT") === "CAR_BODY" && result.ids?.ACCIDENT_CULPRIT_ID) {
setComboValue("ACCIDENT_CULPRIT_ID", result.ids.ACCIDENT_CULPRIT_ID, {
id: result.ids.ACCIDENT_CULPRIT_ID, caption: "راننده ثبت‌شده با نقش سایر",
});
}
renderIds();
const snap = snapshot();
persistLocal(snap);
+24 -12
View File
@@ -812,7 +812,8 @@ inquire_hull_policy_vehicle() {
}
inquire_driver_id() {
if [[ -n "${DRIVER_ID:-}" ]]; then
local required_role="${1:-}"
if [[ -n "${DRIVER_ID:-}" && "$required_role" != "166" ]] && ! is_car_body; then
ok "Using DRIVER_ID=$DRIVER_ID from env (skip inquiry)"
return 0
fi
@@ -830,14 +831,14 @@ inquire_driver_id() {
fv_curl_json GET "$url" "$out"
local target_role=166
if [[ "$DRIVER_IS_INSURER" == "1" || "${DRIVER_IS_INSURER,,}" == "true" ]]; then
if [[ "$required_role" != "166" ]] && ! is_car_body && [[ "$DRIVER_IS_INSURER" == "1" || "${DRIVER_IS_INSURER,,}" == "true" ]]; then
target_role=161
fi
DRIVER_ID="$(node -e '
const fs = require("fs");
const target = Number(process.argv[2]);
const ACCEPTED = new Set([161, 166]);
const ACCEPTED = new Set(process.argv[3] === "CAR_BODY" || process.argv[4] === "166" ? [166] : [161, 166]);
const data = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
const rows = Array.isArray(data) ? data : (data?.value || data?.data || []);
if (!Array.isArray(rows) || !rows.length) { console.log(""); process.exit(0); }
@@ -846,20 +847,21 @@ if (match && Number(match.Id) > 0) { console.log(String(match.Id)); process.exit
const accepted = rows.find(r => ACCEPTED.has(Number(r.RoleId)) && Number(r.Id) > 0);
if (accepted) console.log(String(accepted.Id));
else console.log("");
' "$out" "$target_role")"
' "$out" "$target_role" "$FANAVARAN_PRODUCT" "$required_role")"
if [[ -n "$DRIVER_ID" ]]; then
ok "DriverId=$DRIVER_ID (inquiry RoleId=$target_role or accepted 161/166)"
ok "DriverId=$DRIVER_ID (verified acceptable role; target RoleId=$target_role)"
persist_env DRIVER_ID
save_ids
return 0
fi
warn "Driver inquiry has no RoleId 161/166 for $DRIVER_NATIONAL_CODE — GEN.44 other-people create"
create_other_person
warn "Driver inquiry has no acceptable role for $DRIVER_NATIONAL_CODE — GEN.44 other-people create"
create_other_person "$required_role"
}
create_other_person() {
local required_role="${1:-}"
require_var DRIVER_NATIONAL_CODE
require_var DRIVER_BIRTH_YEAR
require_var DRIVER_BIRTH_MONTH
@@ -956,7 +958,7 @@ NODE
DRIVER_ID="$(node -e '
const fs = require("fs");
const ACCEPTED = new Set([161, 166]);
const ACCEPTED = new Set(process.argv[2] === "CAR_BODY" || process.argv[3] === "166" ? [166] : [161, 166]);
const data = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
const rows = Array.isArray(data) ? data : (data?.value || data?.data || []);
const accepted = Array.isArray(rows)
@@ -964,9 +966,9 @@ const accepted = Array.isArray(rows)
: null;
if (accepted) console.log(String(accepted.Id));
else console.log("");
' "$retry")"
' "$retry" "$FANAVARAN_PRODUCT" "$required_role")"
if [[ -z "$DRIVER_ID" && -n "${OTHER_PERSON_ID:-}" ]]; then
if [[ -z "$DRIVER_ID" && -n "${OTHER_PERSON_ID:-}" && "$required_role" != "166" ]] && ! is_car_body; then
DRIVER_ID="$OTHER_PERSON_ID"
warn "Re-inquiry still empty — using GEN.44 Id as DriverId=$DRIVER_ID"
fi
@@ -1644,10 +1646,20 @@ info "Fanavaran-only flow | client=$FANAVARAN_CLIENT | api=$API_VERSION_LABEL |
info "Env file (section B will be updated in-place): $ENV_FILE"
info "Output: $OUT_DIR"
if stage_wanted person; then
[[ "${PERSON_ROLE_ID:-}" == "166" ]] || die "Select PERSON_ROLE_ID=166 (سایر). GEN.44 does not register arbitrary roles."
fi
fanavaran_login
if stage_wanted person && ! is_car_body; then
inquire_driver_id
if stage_wanted person; then
info "Person registration requested: RoleId=$PERSON_ROLE_ID (سایر); checking live inquiry"
inquire_driver_id "$PERSON_ROLE_ID"
if is_car_body && [[ -n "${DRIVER_ID:-}" && "$PREVIEW_ONLY" -eq 0 ]]; then
ACCIDENT_CULPRIT_ID="$DRIVER_ID"
persist_env ACCIDENT_CULPRIT_ID
save_ids
fi
fi
# Soft-ensure order like the app: later stages create earlier ones if ids missing
+1
View File
@@ -786,6 +786,7 @@ function envObjectToText(obj) {
"DRIVER_BIRTH_DAY",
"DRIVER_IS_INSURER",
"DRIVER_IS_OWNER",
"PERSON_ROLE_ID",
"DRIVER_MOBILE",
"DRIVER_TEL",
"DRIVER_ADDRESS",
@@ -0,0 +1,139 @@
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const { test } = require("node:test");
const { spawnSync } = require("node:child_process");
const html = fs.readFileSync(path.join(__dirname, "data/fanavaran-flow-ui.html"), "utf8");
const shell = fs.readFileSync(path.join(__dirname, "fanavaran-flow-test.sh"), "utf8");
test("hull selection keeps the registration tab visible and preserves an open registration panel", () => {
const tab = { hidden: true, classList: { contains: () => true } };
const panel = { hidden: false };
const element = { closest: () => ({ querySelector: () => ({}) }) };
const context = vm.createContext({
q: (id) => id === "FANAVARAN_PRODUCT" ? "CAR_BODY" : "v14",
$: () => element,
showFormTab: () => assert.fail("switching product must not eject the person tab"),
document: {
body: { dataset: {} },
querySelector: (selector) => selector.includes('panel="person"') ? panel : tab,
},
});
const start = html.indexOf(" function syncProduct()");
const end = html.indexOf(" function missingRequiredNotifier", start);
vm.runInContext(html.slice(start, end) + "\nsyncProduct();", context);
assert.equal(tab.hidden, false);
assert.equal(panel.hidden, false);
});
function selectDriver(product, rows, afterCreate = false, requiredRole = "") {
const start = shell.indexOf(' DRIVER_ID="$(node -e \'', shell.indexOf(afterCreate ? "create_other_person() {" : "inquire_driver_id() {"));
const bodyStart = shell.indexOf("\n", start) + 1;
const end = shell.indexOf("\n' ", bodyStart);
let selected = "";
const exited = {};
const context = vm.createContext({
require: () => ({ readFileSync: () => JSON.stringify(rows) }),
process: { argv: afterCreate ? ["node", "fixture", product, requiredRole] : ["node", "fixture", "166", product, requiredRole], exit: () => { throw exited; } },
console: { log: (value) => { selected = String(value); } },
});
try { vm.runInContext(shell.slice(bodyStart, end), context); }
catch (error) { if (error !== exited) throw error; }
return selected;
}
for (const afterCreate of [false, true]) {
test(`hull ${afterCreate ? "post-registration verification" : "inquiry"} requires role 166`, () => {
assert.equal(selectDriver("CAR_BODY", [{ Id: 41, RoleId: 161 }], afterCreate), "");
assert.equal(selectDriver("CAR_BODY", [{ Id: 41, RoleId: 161 }, { Id: 42, RoleId: 166 }], afterCreate), "42");
});
test(`third-party ${afterCreate ? "verification" : "inquiry"} retains role-161 acceptance`, () => {
assert.equal(selectDriver("THIRD_PARTY", [{ Id: 41, RoleId: 161 }], afterCreate), "41");
});
}
test("the inline UI script parses", () => {
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
new vm.Script(script);
});
for (const [client, version] of [["moallem", "v14"], ["tejaratno", "v15"]]) {
test(`${client} ${version}: registering a person does not require claim notifier fields`, () => {
const context = vm.createContext({
q: (id) => ({ FANAVARAN_PRODUCT: "THIRD_PARTY", FANAVARAN_CLIENT: client,
FANAVARAN_API_VERSION: version, CLAIM_NOTIFICATION_DATE: "1405/08/30",
NOTIFIER_PARTY_ID: "41" })[id] || "",
lookupValue: () => "",
stateIds: { CLAIM_ID: "" },
});
const start = html.indexOf(" function missingRequiredNotifier(stage)");
const end = html.indexOf(" function envToText", start);
vm.runInContext(html.slice(start, end), context);
assert.equal(vm.runInContext('missingRequiredNotifier("person")', context), "");
assert.match(vm.runInContext('missingRequiredNotifier("base")', context), /NotifierTypeId/);
assert.match(vm.runInContext('missingRequiredNotifier("base")', context), /NotifierRelationId/);
});
}
for (const afterCreate of [false, true]) {
test(`manual person ${afterCreate ? "verification" : "inquiry"} enforces the selected role even in third-party mode`, () => {
assert.equal(selectDriver("THIRD_PARTY", [{ Id: 41, RoleId: 161 }], afterCreate, "166"), "");
assert.equal(selectDriver("THIRD_PARTY", [{ Id: 41, RoleId: 161 }, { Id: 42, RoleId: 166 }], afterCreate, "166"), "42");
});
}
test("manual role-166 registration checks live inquiry despite a cached driver ID", () => {
const start = shell.indexOf("inquire_driver_id() {");
const end = shell.indexOf("create_other_person() {", start);
const script = `set -euo pipefail
${shell.slice(start, end)}
is_car_body() { return 1; }
ask_var() { :; }
info() { :; }
ok() { :; }
warn() { :; }
persist_env() { :; }
save_ids() { :; }
fv_curl_json() { echo LIVE_INQUIRY; }
node() { printf 42; }
create_other_person() { echo UNEXPECTED_CREATE; }
DRIVER_ID=41
DRIVER_IS_INSURER=1
DRIVER_NATIONAL_CODE=0012345678
DRIVER_BIRTH_YEAR=1360
DRIVER_BIRTH_MONTH=1
DRIVER_BIRTH_DAY=2
FANAVARAN_PRODUCT=THIRD_PARTY
FANAVARAN_BIME_URL=https://example.invalid
OUT_DIR=/tmp
inquire_driver_id 166
printf 'RESULT=%s' "$DRIVER_ID"
`;
const result = spawnSync("/bin/bash", ["-c", script], { encoding: "utf8", timeout: 5000 });
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /LIVE_INQUIRY/);
assert.match(result.stdout, /RESULT=42/);
assert.doesNotMatch(result.stdout, /UNEXPECTED_CREATE/);
});
test("the registration button requires an explicit supported role before sending a request", async () => {
const notices = [];
let focused = false;
const context = vm.createContext({
busy: false,
ping: async () => true,
q: () => "",
setStatus: (message) => notices.push(message),
showFormTab: (name) => assert.equal(name, "person"),
$: (id) => { assert.equal(id, "PERSON_ROLE_ID"); return { focus: () => { focused = true; } }; },
api: () => assert.fail("registration cannot run before role selection"),
});
const start = html.indexOf(" async function runStage(stage)");
const end = html.indexOf(' $("LOCATION").addEventListener', start);
vm.runInContext(html.slice(start, end), context);
await vm.runInContext('runStage("person")', context);
assert.equal(focused, true);
assert.match(notices[0], /166/);
});
@@ -0,0 +1,68 @@
#!/usr/bin/env node
// Dry-run by default. Repairs only the precise historical visit-only state;
// never reopens a signed, priced or paid claim.
require("dotenv").config();
const mongoose = require("mongoose");
(async () => {
if (!process.env.MONGO_URI) throw new Error("MONGO_URI is required");
await mongoose.connect(process.env.MONGO_URI, {
tls: process.env.MONGO_TLS === "true",
tlsAllowInvalidCertificates:
process.env.MONGO_TLS_ALLOW_INVALID_CERTS === "true",
});
try {
const collection = mongoose.connection.collection("claimCases");
const filter = {
status: "COMPLETED",
claimStatus: "NEEDS_REVISION",
"history.type": "IN_PERSON_VISIT_REQUESTED",
"evaluation.damageExpertReply.submittedAt": null,
"evaluation.damageExpertReplyFinal.submittedAt": null,
"evaluation.ownerInsurerApproval": null,
"evaluation.ownerPricedPartsApproval": null,
"evaluation.damageExpertReply.parts.0": { $exists: false },
"evaluation.damageExpertReplyFinal.parts.0": { $exists: false },
};
const matched = await collection.countDocuments(filter);
if (!process.argv.includes("--apply")) {
console.log(JSON.stringify({ dryRun: true, matched }));
return;
}
const result = await collection.updateMany(filter, {
$set: {
status: "IN_PERSON_VISIT_PENDING",
"workflow.locked": false,
"workflow.currentStep": "EXPERT_DAMAGE_ASSESSMENT",
"workflow.nextStep": "EXPERT_DAMAGE_ASSESSMENT",
updatedAt: new Date(),
},
$unset: {
"workflow.lockedBy": "",
"workflow.lockedAt": "",
"workflow.expiredAt": "",
"workflow.preLockQueueSnapshot": "",
},
$push: {
history: {
type: "VISIT_ONLY_COMPLETION_REPAIRED",
timestamp: new Date(),
metadata: { previousStatus: "COMPLETED" },
},
},
});
console.log(
JSON.stringify({
dryRun: false,
matched,
modified: result.modifiedCount,
}),
);
} finally {
await mongoose.disconnect();
}
})().catch(() => {
console.error(
"Visit-state repair failed. Check database connectivity and configuration.",
);
process.exitCode = 1;
});
@@ -16,6 +16,7 @@ export enum ClaimCaseStatus {
// Expert flow
WAITING_FOR_DAMAGE_EXPERT = "WAITING_FOR_DAMAGE_EXPERT",
IN_PERSON_VISIT_PENDING = "IN_PERSON_VISIT_PENDING",
EXPERT_REVIEWING = "EXPERT_REVIEWING",
/**
* @deprecated Prefer specific post-expert statuses below. Kept for existing DB rows and reads.
+4 -9
View File
@@ -1,3 +1,5 @@
import { CaseWorkingHoursInterceptor } from "./client/working-hours/case-working-hours.interceptor";
import { EvidenceAccessModule } from "./evidence-access/evidence-access.module";
import { PersianErrorFilter } from "./common/errors/persian-error.filter";
import { PersianErrorInterceptor } from "./common/errors/persian-error.interceptor";
import { ManagementModule } from "./management/management.module";
@@ -8,7 +10,6 @@ import { ConfigModule, ConfigService } from "@nestjs/config";
import { HttpModule } from "@nestjs/axios";
import { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor";
import { MongooseModule } from "@nestjs/mongoose";
import { ServeStaticModule } from "@nestjs/serve-static";
import { AiModule } from "./ai/ai.module";
import { AuthModule } from "./auth/auth.module";
import { ClaimRequestManagementModule } from "./claim-request-management/claim-request-management.module";
@@ -44,14 +45,7 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
AppConfigModule,
DatabaseModule,
CronModule,
ServeStaticModule.forRoot({
// process.cwd() is always the project/container root (/app in Docker),
// so the volume-mounted /app/files is resolved correctly regardless of
// where the compiled dist files live (__dirname would resolve to
// /app/dist/src because TypeScript preserves the src/ prefix in outDir).
rootPath: join(process.cwd(), "files"),
serveRoot: "/files",
}),
EvidenceAccessModule,
UsersModule,
AuthModule,
ClientModule,
@@ -75,6 +69,7 @@ import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
providers: [
{ provide: APP_FILTER, useClass: PersianErrorFilter },
{ provide: APP_INTERCEPTOR, useClass: PersianErrorInterceptor },
{ provide: APP_INTERCEPTOR, useClass: CaseWorkingHoursInterceptor },
{
provide: APP_INTERCEPTOR,
useClass: UnicodeDigitsNormalizeInterceptor,
@@ -297,10 +297,10 @@ describe("buildInsurerFileReport", () => {
"سپر جلو",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
"۲٬۵۰۰٬۰۰۰ تومان",
"۲٬۵۰۰٬۰۰۰ ریال",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / مبلغ کل")).toBe(
"۳٬۰۰۰٬۰۰۰ تومان",
"۳٬۰۰۰٬۰۰۰ ریال",
);
});
@@ -352,7 +352,7 @@ describe("buildInsurerFileReport", () => {
"چراغ جلو",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
"۴٬۰۰۰٬۰۰۰ تومان",
"۴٬۰۰۰٬۰۰۰ ریال",
);
});
@@ -392,7 +392,7 @@ describe("buildInsurerFileReport", () => {
vehicle: {
isNew: true,
hasEndorsement: false,
source: "ESG_CAR_BODY_INQUIRY",
source: "FANAVARAN_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
},
},
@@ -419,7 +419,7 @@ describe("buildInsurerFileReport", () => {
role: "FIRST",
person: { userId: "damaged", fullName: "بیمه‌گذار" },
vehicle: {
source: "ESG_CAR_BODY_INQUIRY",
source: "FANAVARAN_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
},
},
@@ -570,20 +570,8 @@ describe("buildInsurerFileReport", () => {
);
expect(driver).toContain("گواهینامه دارد: بله");
expect(driver).toContain("نوع گواهینامه: پایه دو");
expect(
getFieldValue(
report,
PR.damagedVehicleSection,
"خودرو / سوابق تلاش استعلام / تلاش ۱ / نوع پلاک استعلام‌شده",
),
).toBe("پلاک فعلی");
expect(
getFieldValue(
report,
PR.damagedVehicleSection,
"خودرو / سوابق تلاش استعلام / تلاش ۱ / خطا",
),
).toBe("موردی یافت نشد");
expect(report.sections.flatMap(section => section.fields)
.some(field => field.label.includes("سوابق تلاش استعلام"))).toBe(false);
const renderedText = report.sections
.flatMap((section) => [
@@ -1,3 +1,4 @@
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
import {
resolveClaimOwnerParty,
resolveDamagedPartyRow,
@@ -24,6 +25,7 @@ const SKIP_FLATTEN_KEYS = new Set([
"history",
"workflow",
"evidence",
"attempts",
"confirmation",
"inquiries",
"raw",
@@ -96,11 +98,11 @@ function normalizeNumber(value: unknown): number | undefined {
return Number.isFinite(parsed) ? parsed : undefined;
}
function formatToman(value: unknown): string | undefined {
function formatRial(value: unknown): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
const amount = normalizeNumber(value);
if (amount === undefined) return asString(value);
return `${PERSIAN_NUMBER_FORMATTER.format(amount)} تومان`;
if (amount === undefined) return /factor|invoice/i.test(String(value)) ? "طبق فاکتور" : /[a-z]/i.test(String(value)) ? undefined : asString(value);
return `${PERSIAN_NUMBER_FORMATTER.format(amount)} ریال`;
}
function firstDefined(...values: unknown[]): string | undefined {
@@ -188,7 +190,7 @@ function dedupeFields(
for (const field of fields) {
const value = asString(field.value);
if (!value) continue;
if (!value || !field.label) continue;
const key = `${field.label}::${value}`;
if (seen.has(key)) continue;
seen.add(key);
@@ -227,9 +229,7 @@ function expertNameFromSnapshot(snapshot?: {
lastName?: string;
}): string | undefined {
if (!snapshot) return undefined;
const name = [snapshot.firstName, snapshot.lastName]
.filter(Boolean)
.join(" ");
const name = personDisplayName(snapshot);
return name || undefined;
}
@@ -254,7 +254,7 @@ function collectExpertNames(
if (!reply) continue;
const actor = (reply.actorDetail as { actorName?: string } | undefined)
?.actorName;
if (actor) names.add(actor);
if (meaningfulPersonName(actor)) names.add(meaningfulPersonName(actor));
const snap = expertNameFromSnapshot(
reply.expertProfileSnapshot as
| { firstName?: string; lastName?: string }
@@ -263,7 +263,7 @@ function collectExpertNames(
if (snap) names.add(snap);
}
return names.size ? [...names].join(", ") : undefined;
return names.size ? [...names].join("، ") : undefined;
}
function inquiryRoleData(
@@ -598,8 +598,8 @@ function buildPartyOwnerSection(
{
label: PR.name,
value: options?.useClaimOwnerFallback
? firstDefined(person?.fullName, claimOwner?.fullName)
: firstDefined(person?.fullName),
? personDisplayName(person, claimOwner)
: personDisplayName(person),
},
{ label: PR.phone, value: asString(person?.phoneNumber) },
{
@@ -644,7 +644,7 @@ function buildParticipantRolesSection(
(candidate) => String(candidate.participantId) === String(participantId),
);
const value = [
asString(participant?.fullName),
personDisplayName(participant),
participant?.nationalCode
? `${PR.nationalCode}: ${asString(participant.nationalCode)}`
: undefined,
@@ -696,8 +696,6 @@ function licenseFieldsFromInquiry(inquiry?: Record<string, unknown>): {
inquiry.issueDate,
inquiry.LicenseIssueDate,
inquiry.licenseIssueDate,
inquiry.ExpireDate,
inquiry.expireDate,
),
};
}
@@ -716,9 +714,11 @@ function buildDriverSection(
String(role),
);
const { licenseType, licenseDate } = licenseFieldsFromInquiry(licenseInquiry);
const driverId = damagedParty?.participantRoles?.driver;
const driver = (sanitizeStoredInquiryParticipants(damagedParty?.participants) ?? []).find(participant => participant.participantId === driverId);
return buildSection(PR.driverSection, [
{ label: PR.name, value: asString(person.fullName) },
{ label: PR.name, value: personDisplayName(driver,{fullName:person.driverFullName,phoneNumber:person.driverPhoneNumber}) },
{
label: PR.licenseType,
value:
@@ -733,11 +733,9 @@ function buildDriverSection(
{
label: PR.licenseDate,
value:
asString(person.driverLicenseDate) ||
licenseDate ||
asString(person.driverLicense),
asString(person.driverLicenseDate) || licenseDate,
},
{ label: PR.phone, value: asString(person.phoneNumber) },
{ label: PR.phone, value: asString(person.driverPhoneNumber) },
{ label: PR.nationalCode, value: asString(person.nationalCodeOfDriver) },
{ label: PR.birthDate, value: formatBirthDate(person.driverBirthday) },
{ label: PR.licenseNumber, value: asString(person.driverLicense) },
@@ -774,7 +772,7 @@ function buildPartyStatementSection(
},
{
label: PR.name,
value: firstDefined(party.person?.fullName),
value: personDisplayName(party.person),
},
{
label: PR.admitsGuilt,
@@ -824,6 +822,7 @@ function buildFanavaranCodesSection(
claim?: Record<string, unknown> | null,
): InsurerFileReportSection | undefined {
if (!claim) return undefined;
const refs = (claim.fanavaran ?? {}) as Record<string, unknown>;
const sync =
(claim.fanavaranSync as Record<string, unknown> | undefined) ?? {};
const baseClaim =
@@ -836,31 +835,31 @@ function buildFanavaranCodesSection(
return buildSection(PR.fanavaranSection, [
{
label: PR.fanavaranClaimNo,
value: firstDefined(claim.claimNo, baseClaim.claimNo),
value: firstDefined(refs.claimNo, claim.claimNo, baseClaim.claimNo),
},
{
label: PR.fanavaranClaimId,
value: firstDefined(claim.claimId, baseClaim.claimId),
value: firstDefined(refs.claimId, claim.claimId, baseClaim.claimId),
},
{
label: PR.fanavaranDamageCaseId,
value: firstDefined(
claim.dmgCaseId,
refs.dmgCaseId, claim.dmgCaseId,
damageCase.dmgCaseId,
expertise.dmgCaseId,
),
},
{
label: PR.fanavaranExpertiseId,
value: firstDefined(claim.expertiseId, expertise.expertiseId),
value: firstDefined(refs.expertiseId, claim.expertiseId, expertise.expertiseId),
},
{
label: PR.fanavaranPolicyId,
value: firstDefined(baseClaim.policyId),
value: firstDefined(refs.policyId, baseClaim.policyId),
},
{
label: PR.fanavaranDriverId,
value: firstDefined(baseClaim.driverId),
value: firstDefined(refs.driverId, baseClaim.driverId),
},
{
label: PR.fanavaranVehicleKindId,
@@ -875,6 +874,7 @@ function buildFanavaranCodesSection(
function buildEvaluationSection(
claim?: Record<string, unknown> | null,
isCarBody = false,
): InsurerFileReportSection | undefined {
if (!claim) return undefined;
const reply = resolveEvaluationReply(claim);
@@ -892,12 +892,20 @@ function buildEvaluationSection(
},
{
label: PR.evaluationExpert,
value: actorDetail?.actorName ?? snapshotName,
value: snapshotName || meaningfulPersonName(actorDetail?.actorName),
},
{
label: PR.evaluationSubmittedAt,
value: formatDateTime(resolveEvaluationSubmittedAt(claim, reply)),
},
{
label: "ارزش روز خودرو",
value: formatRial((claim.vehicle as ReportRecord | undefined)?.carPrice ?? (claim.vehicle as ReportRecord | undefined)?.price),
},
{
label: "افت قیمت",
value: isCarBody ? undefined : formatRial((claim.evaluation as any)?.priceDrop?.total),
},
{
label: PR.evaluationResponse,
value: asString(reply?.description),
@@ -930,7 +938,7 @@ function evaluationDaghiValue(value: unknown): string | undefined {
}
const daghi = value as ReportRecord;
const option = asString(persianReportValue("daghi.option", daghi.option));
const price = formatToman(daghi.price);
const price = formatRial(daghi.price);
return [option, price].filter(Boolean).join(" - ") || undefined;
}
@@ -953,14 +961,14 @@ function buildEvaluationPartsSection(
persianReportValue("evaluation.part.typeOfDamage", part.typeOfDamage),
),
},
{ label: `${prefix} / ${PR.partPrice}`, value: formatToman(part.price) },
{ label: `${prefix} / ${PR.partPrice}`, value: formatRial(part.price) },
{
label: `${prefix} / ${PR.repairSalary}`,
value: formatToman(part.salary),
value: formatRial(part.salary),
},
{
label: `${prefix} / ${PR.totalPayment}`,
value: formatToman(part.totalPayment),
value: formatRial(part.totalPayment),
},
{
label: `${prefix} / ${PR.factorNeeded}`,
@@ -1109,7 +1117,7 @@ export function buildInsurerFileReport(file: {
? (resolveClaimOwnerParty(blameContext as any) as ReportParty | null)
: null;
const isCarBody =
String((blameContext?.type as string | undefined) ?? "") === "CAR_BODY";
(blameContext?.type ?? overview.type ?? claim?.blameRequestType) === "CAR_BODY";
const includeGuiltySections =
!!guiltyParty && !(isCarBody && sameParty(damagedParty, guiltyParty));
@@ -1173,7 +1181,7 @@ export function buildInsurerFileReport(file: {
)
: undefined,
buildFanavaranCodesSection(claim),
buildEvaluationSection(claim),
buildEvaluationSection(claim, isCarBody),
buildEvaluationPartsSection(claim),
buildAccidentReportSection(blameContext, claim, damagedParty),
]);
@@ -1,10 +1,16 @@
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
import { Module } from "@nestjs/common";
import { RequestManagementModule } from "src/request-management/request-management.module";
import { ExpertInsurerModule } from "src/expert-insurer/expert-insurer.module";
import { CaseExpertReportInsurerController } from "./case-expert-report.controller";
import { CaseExpertReportService } from "./case-expert-report.service";
@Module({
imports: [ExpertInsurerModule],
imports: [
ExpertInsurerModule,
RequestManagementModule,
ClaimRequestManagementModule,
],
controllers: [CaseExpertReportInsurerController],
providers: [CaseExpertReportService],
exports: [CaseExpertReportService],
@@ -1,5 +1,9 @@
import { Injectable, NotFoundException } from "@nestjs/common";
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.db.service";
import { Types } from "mongoose";
import { BlameDocumentDbService } from "src/request-management/entities/db-service/blame-document.db.service";
import { buildReportAttachments, buildReportSignatures } from "./report-media";
import { buildInsurerFileReport } from "./case-expert-report.builder";
import { InsurerFileReportViewModel } from "./case-expert-report.types";
@@ -7,6 +11,8 @@ import { InsurerFileReportViewModel } from "./case-expert-report.types";
export class CaseExpertReportService {
constructor(
private readonly expertInsurerService: ExpertInsurerService,
private readonly blameDocumentDbService: BlameDocumentDbService,
private readonly factorImageDbService: ClaimFactorsImageDbService,
) {}
async generateForInsurer(
@@ -21,7 +27,28 @@ export class CaseExpertReportService {
const file = await this.expertInsurerService.retrieveFileDetailsByPublicId(
clientKey,
publicId,
true,
);
return buildInsurerFileReport(file);
const blame = file.reportBlame ?? file.blame;
const blameId = String(blame?._id ?? "");
const claimId = String(file.claim?.claimRequestId ?? "");
const [blameDocuments, invoices] = await Promise.all([
Types.ObjectId.isValid(blameId)
? this.blameDocumentDbService.findByRequestId(blameId)
: [],
Types.ObjectId.isValid(claimId)
? this.factorImageDbService.findByClaimId(claimId)
: [],
]);
return {
...buildInsurerFileReport({ ...file, blame }),
attachments: buildReportAttachments(
file.claim,
blame,
blameDocuments,
invoices,
),
signatures: buildReportSignatures(blame, file.claim),
};
}
}
@@ -8,9 +8,13 @@ export type InsurerFileReportSection = {
fields: InsurerFileReportField[];
};
export type ReportAttachment = { label: string; url?: string; image?: string };
export type InsurerFileReportViewModel = {
title: string;
publicId: string;
requestNo?: string;
sections: InsurerFileReportSection[];
signatures?: ReportAttachment[];
attachments?: ReportAttachment[];
};
@@ -0,0 +1,101 @@
import {
PR,
persianFieldPath,
persianReportValue,
persianStatus,
} from "./persian-report-labels";
import { buildInsurerFileReport } from "./case-expert-report.builder";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
describe("Persian report presentation", () => {
it.each([...Object.values(ClaimCaseStatus), ...Object.values(CaseStatus)])(
"translates persisted status %s",
(status) => expect(persianStatus(status)).not.toMatch(/[a-z]/i),
);
it("uses meaningful Persian labels and suppresses unknown provider field keys", () => {
expect(persianFieldPath("party.vehicle.vin")).toBe(
"خودرو / شماره شناسایی خودرو",
);
expect(
persianFieldPath("party.vehicle.inquiry.unmappedProviderField"),
).toBe("");
expect(persianReportValue("vehicle.expedited", true)).toBe("فوری");
expect(persianReportValue("vehicle.carType", "sedan")).toBe("سواری");
expect(persianReportValue("vehicle.status", "NEW_UNKNOWN_STATUS")).toBe(
"وضعیت نامشخص",
);
});
it("keeps factual identifiers intact, uses phones for unnamed users and keeps driver/owner identities separate", () => {
const vin = "IR1ABC23456789012";
const report = buildInsurerFileReport({
overview: { publicId: "QA-1" },
blame: {
type: "CAR_BODY",
status: "COMPLETED",
parties: [
{
role: "FIRST",
person: {
userId: "650000000000000000000001",
fullName: "1234567890",
phoneNumber: "09120000000",
driverIsInsurer: false,
nationalCodeOfDriver: "1111111111",
driverLicense: "987654321",
},
participants: [
{
participantId: "driver",
fullName: "حسن احمدی",
nationalCode: "1111111111",
birthday: "1370/01/01",
},
],
participantRoles: { driver: "driver" },
vehicle: {
vin,
carType: "sedan",
unknownProviderField: "DO_NOT_SHOW",
},
},
],
},
claim: {
owner: { userId: "650000000000000000000001" },
evaluation: {
damageExpertReply: {
parts: [
{
carPartDamage: { label_fa: "گلگیر جلو" },
typeOfDamage: "تعویض",
price: "2000000",
totalPayment: "3000000",
factorNeeded: false,
},
],
},
},
},
});
const fields = report.sections.flatMap((section) => section.fields);
expect(fields.every((field) => !/[a-z]/i.test(field.label))).toBe(true);
expect(fields.some((field) => field.value === vin)).toBe(true);
expect(fields.some((field) => field.value === "DO_NOT_SHOW")).toBe(false);
expect(
report.sections
.find((section) => section.title === PR.ownerSection)
?.fields.find((field) => field.label === PR.name)?.value,
).toBe("09120000000");
const driver = report.sections.find(
(section) => section.title === PR.driverSection,
);
expect(driver?.fields.find((field) => field.label === PR.name)?.value).toBe(
"حسن احمدی",
);
expect(
driver?.fields.find((field) => field.label === PR.licenseDate),
).toBeUndefined();
expect(fields.some((field) => field.value === "۲٬۰۰۰٬۰۰۰ ریال")).toBe(true);
});
});
+57 -26
View File
@@ -1,5 +1,6 @@
import { UNIFIED_FILE_STATUS_CATALOG } from "src/helpers/unified-file-status";
export const PR = {
reportTitle: "گزارش پرونده بیمه گر",
reportTitle: "گزارش پرونده بیمه‌گر",
publicId: "شناسه عمومی",
requestNo: "شماره درخواست",
empty: "-",
@@ -21,17 +22,20 @@ export const PR = {
fanavaranSection: "کدهای فناوران",
evaluationSection: "نتیجه ارزیابی",
accidentSection: "گزارش حادثه",
name: "نام",
name: "نام و نام خانوادگی",
phone: "شماره تلفن",
nationalCode: "کد ملی",
birthDate: "تاریخ تولد",
sheba: "شماره شبا",
licenseType: "نوع گواهینامه",
licenseDate: "تاریخ گواهینامه",
licenseDate: "تاریخ صدور گواهینامه",
licenseNumber: "شماره گواهینامه",
hasDrivingLicense: "گواهینامه دارد",
driverLicense: "گواهینامه راننده",
insuranceCompany: "شرکت بیمه",
expedited: "رسیدگی فوری",
status: "وضعیت",
color: "رنگ",
policyNumber: "شماره بیمه‌نامه",
policyStartDate: "تاریخ شروع بیمه‌نامه",
policyEndDate: "تاریخ پایان بیمه‌نامه",
@@ -40,8 +44,8 @@ export const PR = {
fileRegisteredAt: "تاریخ و ساعت ثبت پرونده",
evaluationRegisteredAt: "تاریخ و ساعت ثبت نتیجه ارزیابی",
fanavaranClaimNo: "شماره پرونده فناوران",
fanavaranClaimId: "کد پرونده فناوران",
fanavaranDamageCaseId: "کد کیس خسارت فناوران",
fanavaranClaimId: "کد رایانه پرونده فناوران",
fanavaranDamageCaseId: "کد پرونده خسارت فناوران",
fanavaranExpertiseId: "کد کارشناسی فناوران",
fanavaranPolicyId: "کد بیمه‌نامه فناوران",
fanavaranDriverId: "کد راننده فناوران",
@@ -78,9 +82,9 @@ export const PR = {
weather: "وضعیت آب و هوا",
road: "وضعیت جاده",
light: "وضعیت نور",
blameStatus: "وضعیت مقصر",
blameStatus: "وضعیت پرونده تعیین مقصر",
claimStatus: "وضعیت خسارت",
expertDecision: "نظر کارشناس مقصر",
expertDecision: "نظر کارشناس تصادف",
accidentWay: "نحوه برخورد",
accidentReason: "علت حادثه",
accidentType: "نوع حادثه",
@@ -89,7 +93,11 @@ export const PR = {
partyDescription: "توضیحات طرف",
} as const;
const KEY_LABELS: Record<string, string> = {
export const KEY_LABELS: Record<string, string> = {
hasEndorsement: "دارای الحاقیه",
expedited: "رسیدگی فوری",
status: "وضعیت",
color: "رنگ",
policyNumber: "شماره بیمه‌نامه",
company: "شرکت بیمه",
insurerCompany: "شرکت بیمه‌گر",
@@ -140,8 +148,8 @@ const KEY_LABELS: Record<string, string> = {
MapTypNam: "نام نوع خودرو",
MtrNum: "شماره موتور",
ShsNum: "شماره شاسی",
vin: "VIN",
VinNumberField: "VIN",
vin: "شماره شناسایی خودرو",
VinNumberField: "شماره شناسایی خودرو",
DisFnYrPrcnt: "درصد تخفیف مالی",
DisLfYrPrcnt: "درصد تخفیف جانی",
DisPrsnYrPrcnt: "درصد تخفیف شخص ثالث",
@@ -209,7 +217,7 @@ const KEY_LABELS: Record<string, string> = {
previousPlate: "پلاک قبلی",
previousPlateId: "پلاک قبلی",
previousPolicyholderNationalCode: "کد ملی بیمه‌گذار پلاک قبلی",
vehicleVin: "شماره شاسی (VIN)",
vehicleVin: "شماره شناسایی خودرو",
driver: "راننده",
vehicleOwner: "مالک وسیله نقلیه",
thirdPartyPolicyholder: "بیمه‌گذار شخص ثالث",
@@ -222,7 +230,27 @@ const KEY_LABELS: Record<string, string> = {
error: "خطا",
};
const STATUS_LABELS: Record<string, string> = {
export const STATUS_LABELS: Record<string, string> = {
...Object.fromEntries(UNIFIED_FILE_STATUS_CATALOG.map(item => [item.key,item.labelFa])),
OPEN: "پرونده باز",
CREATED: "ثبت‌شده",
SELECTING_OUTER_PARTS: "در حال انتخاب قطعات آسیب‌دیده",
SELECTING_OTHER_PARTS: "در حال ثبت سایر قطعات",
UPLOADING_REQUIRED_DOCUMENTS: "در حال بارگذاری مدارک",
CAPTURING_PART_DAMAGES: "در حال ثبت تصاویر خسارت",
WAITING_FOR_EXPERT: "در انتظار کارشناس تصادف",
WAITING_FOR_USER_RESEND: "در انتظار تکمیل اطلاعات کاربر",
IN_PERSON_VISIT_PENDING: "در انتظار مراجعه حضوری",
WAITING_FOR_INSURER_APPROVAL: "در انتظار تأیید پرونده",
INSURER_REVIEW_AWAITING_OWNER_SIGN: "در انتظار امضای مالک",
INSURER_REVIEW_MIXED_FACTORS_PENDING: "در انتظار تأیید مبالغ و بارگذاری فاکتورها",
OWNER_REPAIR_FACTOR_UPLOAD_PENDING: "در انتظار بارگذاری فاکتورها",
EXPERT_VALIDATING_REPAIR_FACTORS: "در انتظار بررسی فاکتورها توسط کارشناس",
WAITING_FOR_FILE_REVIEWER: "در انتظار کارشناس ارزیاب",
WAITING_FOR_FILE_MAKER_APPROVAL: "در انتظار تأیید کارشناس مسئول پرونده",
FILE_MAKER_REJECTED: "نیازمند اصلاح توسط کارشناس ارزیاب",
AUTO_CLOSED: "بسته‌شده خودکار",
AGREED: "توافق",
DISAGREEMENT: "اختلاف نظر",
UNKNOWN: "نامشخص",
@@ -333,7 +361,9 @@ export function persianFieldPath(path: string): string {
if (!path) return PR.data;
const parts = path.split(".").filter(Boolean);
const last = parts[parts.length - 1] ?? path;
const translatedLast = KEY_LABELS[last] ?? last;
const translate = (key: string) => KEY_LABELS[key] ?? (/^\d+$/.test(key) ? Number(key).toLocaleString("fa-IR") : /[a-z]/i.test(key) ? "" : key);
const translatedLast = translate(last);
if (!translatedLast) return "";
const inquiryRoot = parts.find(
(p) => p === "thirdParty" || p === "carBody" || p === "mapped",
@@ -386,7 +416,7 @@ export function persianFieldPath(path: string): string {
if (parts.length === 1) return translatedLast;
const translated = parts.map((part) => KEY_LABELS[part] ?? part);
const translated = parts.map(translate).filter(Boolean);
return translated.join(" / ");
}
@@ -399,36 +429,37 @@ export function persianReportValue(
value: unknown,
): unknown {
if (value === undefined || value === null || value === "") return value;
if (typeof value === "boolean") return value ? "بله" : "خیر";
if (typeof value === "boolean") return path.endsWith("expedited") ? value ? "فوری" : "عادی" : value ? "بله" : "خیر";
if (typeof value !== "string" && typeof value !== "number") return value;
const raw = String(value).trim();
const key = raw.toUpperCase().replace(/[\s-]+/g, "_");
const field = path.split(".").filter(Boolean).pop() ?? "";
if (field === "expedited") return raw === "true" || raw === "1" ? "فوری" : "عادی";
if (field === "licenseType" || field === "LicenseType") {
return LICENSE_TYPE_LABELS[key] ?? raw;
return LICENSE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "عنوان گواهینامه ثبت نشده است" : raw);
}
if (field === "registrationState") {
return REGISTRATION_STATE_LABELS[key] ?? raw;
return REGISTRATION_STATE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
}
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? raw;
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
if (field === "role" || field.endsWith("Role")) {
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? raw;
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نقش ثبت‌نشده" : raw);
}
if (field === "blameRequestType" || field === "fileType") {
return CASE_TYPE_LABELS[key] ?? raw;
return CASE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع پرونده ثبت نشده است" : raw);
}
if (
(field === "carType" || field === "type") &&
path.toLowerCase().includes("vehicle")
) {
return VEHICLE_TYPE_LABELS[key] ?? raw;
return VEHICLE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع خودرو ثبت نشده است" : raw);
}
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? raw;
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? raw;
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? (/[a-z]/i.test(raw) ? "نوع خسارت ثبت نشده است" : raw);
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "استعلام ناموفق بود" : raw);
if (/status$/i.test(field)) {
return STATUS_LABELS[raw] ?? VALIDITY_LABELS[key] ?? raw;
return STATUS_LABELS[key] ?? VALIDITY_LABELS[key] ?? (/[a-z]/i.test(raw) ? "وضعیت نامشخص" : raw);
}
if (raw === "true" || raw === "false") return STATUS_LABELS[raw];
@@ -438,7 +469,7 @@ export function persianReportValue(
export function persianStatus(value: unknown): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
const key = String(value);
return STATUS_LABELS[key] ?? key;
return STATUS_LABELS[key] ?? STATUS_LABELS[key.toLowerCase()] ?? (/[a-z]/i.test(key) ? "وضعیت نامشخص" : key);
}
export function persianAccidentCondition(
@@ -454,5 +485,5 @@ export function persianAccidentCondition(
: kind === "road"
? ROAD_LABELS
: LIGHT_LABELS;
return labels[normalized] ?? raw;
return labels[normalized] ?? (/[a-z]/i.test(raw) ? "ثبت نشده است" : raw);
}
+132
View File
@@ -0,0 +1,132 @@
import { buildFileLink } from "src/helpers/urlCreator";
import { personDisplayName } from "src/helpers/person-display-name";
import type { ReportAttachment } from "./case-expert-report.types";
const documentLabels: Record<string, string> = {
accident_sketch: "کروکی",
car_green_card: "برگه سبز خودرو",
car_certificate: "سند خودرو",
national_card: "کارت ملی",
damaged_driving_license_front: "روی گواهینامه زیان‌دیده",
damaged_driving_license_back: "پشت گواهینامه زیان‌دیده",
damaged_chassis_number: "شماره شاسی",
damaged_engine_photo: "شماره موتور",
damaged_car_card_front: "روی کارت خودروی زیان‌دیده",
damaged_car_card_back: "پشت کارت خودروی زیان‌دیده",
damaged_metal_plate: "پلاک خودروی زیان‌دیده",
guilty_driving_license_front: "روی گواهینامه مقصر",
guilty_driving_license_back: "پشت گواهینامه مقصر",
guilty_car_card_front: "روی کارت خودروی مقصر",
guilty_car_card_back: "پشت کارت خودروی مقصر",
guilty_metal_plate: "پلاک خودروی مقصر",
guilty_damage_area: "آسیب خودروی مقصر",
drivingLicense: "گواهینامه",
nationalCertificate: "مدرک هویتی",
carCertificate: "سند خودرو",
carGreenCard: "برگه سبز خودرو",
};
const angleLabels: Record<string, string> = {
front: "نمای جلو",
back: "نمای عقب",
left: "نمای چپ",
right: "نمای راست",
};
export function buildReportAttachments(
claim: any,
blame: any,
blameDocuments: { path: string; documentType: string }[],
invoices: { path: string }[],
): ReportAttachment[] {
const attachments = new Map<string, ReportAttachment>();
function add(label: string, url: unknown) {
if (typeof url !== "string" || !/(?:^|\/)files\/[^?#]+/.test(url)) return;
const path =
url
.split(/[?#]/)[0]
.split(/(?:^|\/)files\//)
.at(-1) ?? "";
if (!attachments.has(path)) attachments.set(path, { label, url });
}
for (const [key, value] of Object.entries(claim?.carAngles ?? {})) {
const angle = value as { url?: string };
add(angleLabels[key] ?? "نمای خودرو", angle.url);
}
for (const part of claim?.damagedParts ?? []) {
const name =
typeof part.label_fa === "string" && /[\u0600-\u06ff]/.test(part.label_fa)
? part.label_fa
: "تصویر قطعه آسیب‌دیده";
add(name, part.url);
}
for (const [key, value] of Object.entries(claim?.requiredDocuments ?? {})) {
add(
documentLabels[key] ?? "مدرک خسارت",
(value as { fileUrl?: string }).fileUrl,
);
}
for (const party of blame?.parties ?? []) {
for (const image of party.evidence?.images ?? []) {
if (typeof image === "string" && /(?:^|\/)files\//.test(image)) {
add("تصویر حادثه", buildFileLink(image));
}
}
}
for (const document of blameDocuments) {
if (document.path)
add(
documentLabels[document.documentType] ?? "مدرک حادثه",
buildFileLink(document.path),
);
}
const evaluation = claim?.evaluation;
for (const invoice of invoices) {
if (invoice.path) add("فاکتور قطعه", buildFileLink(invoice.path));
}
for (const invoice of evaluation?.objection?.invoices ?? [])
add("فاکتور اعتراض", invoice.url);
return [...attachments.values()];
}
export function buildReportSignatures(
blame: any,
claim: any,
): ReportAttachment[] {
const parties: any[] = blame?.parties ?? claim?.snapshot?.parties ?? [];
const signatures: ReportAttachment[] = [];
for (const [index, party] of parties.entries()) {
const signature = party.confirmation?.signature;
const url =
signature?.link ||
(signature?.fileUrl ? buildFileLink(signature.fileUrl) : undefined);
if (!url) continue;
const isSecond = party.role ? party.role === "SECOND" : index === 1;
const role = isSecond ? "طرف دوم" : "طرف اول";
const name = personDisplayName(party.person);
signatures.push({
label: name ? `امضای ${role} · ${name}` : `امضای ${role}`,
url,
});
}
const ownerSign =
claim?.evaluation?.ownerInsurerApproval?.signLink ??
claim?.evaluation?.ownerPricedPartsApproval?.signLink;
if (ownerSign)
signatures.push({
label: "امضای زیان‌دیده برای تأیید خسارت",
url: ownerSign,
});
const expert = claim?.fanavaranExpertSignature;
if (expert?.image) {
signatures.push({
label:
expert.name && expert.name !== "کارشناس پرونده"
? `امضای کارشناس · ${expert.name}`
: "امضای کارشناس",
image: expert.image,
});
}
return signatures;
}
@@ -0,0 +1,247 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
} from "@nestjs/common";
import { validate } from "class-validator";
import { Types } from "mongoose";
import { ClaimRequestManagementService } from "./claim-request-management.service";
import { savedClaimBankInformation } from "./claim-bank-information";
import { SelectOtherPartsV2Dto } from "./dto/select-other-parts-v2.dto";
const claimId = "650000000000000000000001";
const userId = "650000000000000000000002";
const blameId = "650000000000000000000003";
const sheba = "IR" + "1".repeat(24);
const ownerCode = "0012345678";
function fixture(
money: any = undefined,
type = "CAR_BODY",
step = "SELECT_OTHER_PARTS",
) {
const claim: any = {
_id: new Types.ObjectId(claimId),
publicId: "TEST",
blameRequestId: blameId,
owner: { userId, fullName: "نمونه" },
money,
workflow: { currentStep: step },
};
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn().mockResolvedValue(claim),
};
service.blameRequestDbService = {
findById: jest.fn().mockResolvedValue({ type }),
};
service.resolveClaimEffectiveUserId = jest.fn().mockResolvedValue(userId);
service.assertEffectiveUserIsDamagedPartyOnClaim = jest
.fn()
.mockResolvedValue(undefined);
service.resolveVehicleOwnerNationalCodeForClaim = jest
.fn()
.mockReturnValue(ownerCode);
service.resolveOwnershipPlateForClaim = jest
.fn()
.mockReturnValue({ leftDigits: 12 });
service.sandHubService = {
getShebaValidation: jest.fn().mockResolvedValue({ ReturnValue: true }),
};
service.logger = { log: jest.fn(), error: jest.fn() };
return { service, claim };
}
describe("single-entry claim bank information", () => {
it.each(["CAR_BODY", "THIRD_PARTY"])(
"reuses saved bank information for %s, including resend",
async (type) => {
for (const step of ["SELECT_OTHER_PARTS", "USER_EXPERT_RESEND"]) {
for (const storedSheba of [sheba, sheba.slice(2)]) {
const { service } = fixture(
{ sheba: storedSheba, nationalCodeOfInsurer: ownerCode },
type,
step,
);
const result = await service.selectOtherPartsV2(
claimId,
{ otherParts: ["engine"] },
userId,
);
expect(result.currentStep).toBe("CAPTURE_PART_DAMAGES");
expect(
service.claimCaseDbService.findByIdAndUpdate,
).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"money.nationalCodeOfInsurer": ownerCode,
"damage.otherParts": ["engine"],
}),
);
expect(
service.sandHubService.getShebaValidation,
).not.toHaveBeenCalled();
}
}
},
);
it.each(["sheba", "shebaNumber"])(
"collects a new %s once and derives the vehicle owner identity",
async (field) => {
const { service } = fixture();
await service.selectOtherPartsV2(claimId, { [field]: sheba }, userId);
expect(service.sandHubService.getShebaValidation).toHaveBeenCalledWith(
ownerCode,
sheba,
);
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"money.nationalCodeOfInsurer": ownerCode,
}),
);
},
);
it("retains a saved Sheba when only the legacy owner identity was missing", async () => {
const { service } = fixture({ sheba });
await service.selectOtherPartsV2(claimId, {}, userId);
expect(service.sandHubService.getShebaValidation).toHaveBeenCalledWith(
ownerCode,
sheba,
);
});
it("accepts the same previously saved number with a different IR/whitespace representation", async () => {
const { service } = fixture({
sheba: sheba.slice(2),
nationalCodeOfInsurer: ownerCode,
});
await service.selectOtherPartsV2(
claimId,
{ sheba: " ir " + sheba.slice(2) },
userId,
);
expect(service.sandHubService.getShebaValidation).not.toHaveBeenCalled();
});
it("still requires and validates bank information when none was saved", async () => {
const { service } = fixture();
for (const value of [undefined, "IR", "invalid", "123"]) {
await expect(
service.selectOtherPartsV2(claimId, { sheba: value }, userId),
).rejects.toBeInstanceOf(BadRequestException);
}
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("does not silently replace saved bank information outside an explicit resend", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: ownerCode });
await expect(
service.selectOtherPartsV2(
claimId,
{ sheba: "IR" + "2".repeat(24) },
userId,
),
).rejects.toBeInstanceOf(ConflictException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("does not reuse another owner’s bank information", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: "0098765432" });
await expect(
service.selectOtherPartsV2(claimId, {}, userId),
).rejects.toBeInstanceOf(BadRequestException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
expect(
savedClaimBankInformation(
{ sheba, nationalCodeOfInsurer: "0098765432" },
ownerCode,
),
).toMatchObject({
shebaProvided: false,
ownerNationalCodeProvided: true,
});
});
it("rejects a submitted national code that differs from the vehicle owner", async () => {
const { service } = fixture();
await expect(
service.selectOtherPartsV2(
claimId,
{ sheba, nationalCodeOfInsurer: "0098765432" },
userId,
),
).rejects.toBeInstanceOf(BadRequestException);
});
it("keeps beneficiary authorization before reusing saved bank information", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: ownerCode });
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(
new ForbiddenException(),
);
await expect(
service.selectOtherPartsV2(claimId, {}, userId),
).rejects.toBeInstanceOf(ForbiddenException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it.each([sheba, sheba.slice(2)])(
"lets the expert continue with saved bank information (%s)",
async (storedSheba) => {
const { service } = fixture({
sheba: storedSheba,
nationalCodeOfInsurer: ownerCode,
});
service.assertFieldExpertInPersonBlameForClaimCase = jest
.fn()
.mockResolvedValue(undefined);
await service.expertCompleteClaimData(
claimId,
{ sub: userId },
{ otherParts: [] },
);
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"workflow.currentStep": "CAPTURE_PART_DAMAGES",
}),
);
},
);
it("allows omitted bank fields through DTO validation but rejects malformed field types", async () => {
expect(
await validate(
Object.assign(new SelectOtherPartsV2Dto(), { otherParts: [] }),
),
).toHaveLength(0);
expect(
await validate(
Object.assign(new SelectOtherPartsV2Dto(), { sheba: 123 }),
),
).not.toHaveLength(0);
});
it("recognizes incomplete and malformed saved details without exposing them", () => {
expect(savedClaimBankInformation()).toMatchObject({
shebaProvided: false,
ownerNationalCodeProvided: false,
});
expect(
savedClaimBankInformation({
sheba: "IR123",
nationalCodeOfInsurer: "123",
}),
).toMatchObject({ shebaProvided: false, ownerNationalCodeProvided: false });
expect(savedClaimBankInformation({ sheba })).toMatchObject({
shebaProvided: true,
ownerNationalCodeProvided: false,
});
});
});
@@ -0,0 +1,30 @@
export function normalizeClaimSheba(value: unknown): string | undefined {
const digits = String(value ?? "")
.replace(/\s/g, "")
.replace(/^IR/i, "");
return /^\d{24}$/.test(digits) ? `IR${digits}` : undefined;
}
export function normalizeClaimNationalCode(value: unknown): string | undefined {
const code = String(value ?? "").replace(/\s/g, "");
return /^\d{10}$/.test(code) ? code : undefined;
}
/** Saved bank details belong to this claim's vehicle owner, never another party. */
export function savedClaimBankInformation(
money?: { sheba?: string; nationalCodeOfInsurer?: string } | null,
vehicleOwnerNationalCode?: string,
) {
const savedOwner = normalizeClaimNationalCode(money?.nationalCodeOfInsurer);
const currentOwner = normalizeClaimNationalCode(vehicleOwnerNationalCode);
const ownerChanged =
!!savedOwner && !!currentOwner && savedOwner !== currentOwner;
const sheba = ownerChanged ? undefined : normalizeClaimSheba(money?.sheba);
const nationalCode = currentOwner ?? savedOwner;
return {
sheba,
nationalCode,
shebaProvided: !!sheba,
ownerNationalCodeProvided: !!nationalCode,
};
}
@@ -230,6 +230,7 @@ describe("claim beneficiary authorization across shared user flows", () => {
owner: { userId: firstId },
damagedPartyUserId: secondId,
status: "SELECTING_OUTER_PARTS",
money: { sheba: "IR" + "1".repeat(24), nationalCodeOfInsurer: "0012345678" },
};
service.claimCaseDbService.findById = jest.fn().mockResolvedValue(claim);
service.blameRequestDbService.find = jest
@@ -246,6 +247,9 @@ describe("claim beneficiary authorization across shared user flows", () => {
role: RoleEnum.USER,
});
expect(damaged.canAct).toBe(true);
expect(damaged.bankInformation).toEqual({ shebaProvided: true, ownerNationalCodeProvided: true });
expect(damaged.money.sheba).toContain("*");
expect(damaged.money.sheba).not.toBe(claim.money.sheba);
expect(damaged.ownerGuidance).toBeDefined();
});
@@ -118,6 +118,7 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz
VideoCaptureDbService,
ClaimRequiredDocumentDbService,
ClaimSignDbService,
ClaimFactorsImageDbService,
],
})
export class ClaimRequestManagementModule {}
File diff suppressed because it is too large Load Diff
@@ -1,3 +1,5 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { randomUUID } from "node:crypto";
import {
Controller,
HttpException,
@@ -63,6 +65,7 @@ import { UserObjectionV2Dto } from "./dto/user-objection-v2.dto";
import { UserRatingDto } from "./dto/user-rating.dto";
@ApiTags("claim-request-management (v2)")
@EnforceCaseWorkingHours()
@Controller("v2/claim-request-management")
@ApiBearerAuth()
@UseGuards(GlobalGuard, RolesGuard)
@@ -375,7 +378,7 @@ export class ClaimRequestManagementV2Controller {
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
@@ -621,8 +624,8 @@ Optional: upload car green card file in the same step.
- Claim must exist
- User must be the claim owner (damaged party from blame case)
- Current workflow step must be SELECT_OTHER_PARTS
- Bank information must not have been submitted previously
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits
- Previously saved bank information is reused when omitted
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits; required only if not saved
- National code must be exactly 10 digits
**Valid Other Parts (Optional):**
@@ -656,7 +659,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer` like THIRD_PARTY flow. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -671,7 +674,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -693,7 +695,7 @@ Optional: upload car green card file in the same step.
})
@ApiResponse({
status: 409,
description: "Bank information already submitted",
description: "Conflicting bank information",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@@ -182,6 +182,15 @@ export class ClaimDetailsV2ResponseDto {
nationalCodeOfOwner?: string;
};
@ApiPropertyOptional({
description: 'Whether bank fields can be reused from this claim or its vehicle-owner identity. Does not expose bank details.',
example: { shebaProvided: true, ownerNationalCodeProvided: true },
})
bankInformation?: {
shebaProvided: boolean;
ownerNationalCodeProvided: boolean;
};
@ApiPropertyOptional({
description: "Required documents status (link instead of id)",
})
@@ -254,6 +263,9 @@ export class ClaimDetailsV2ResponseDto {
})
expertResend?: ExpertResendDetailsV2Dto;
@ApiPropertyOptional()
visitLocation?: string;
@ApiPropertyOptional({
description:
"Fanavaran codes and image upload receipts. Claim codes appear on COMPLETED; fileIds and attachments upload status/errors are available earlier when recorded.",
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, IsEnum, IsNotEmpty, IsOptional, IsString, Matches, Length, ArrayMaxSize } from 'class-validator';
import { IsArray, IsEnum, IsOptional, IsString, Matches, Length, ArrayMaxSize } from 'class-validator';
/**
* Enum for valid other (non-body) car parts that can be damaged
@@ -40,13 +40,13 @@ export class SelectOtherPartsV2Dto {
})
otherParts?: OtherCarPart[];
@ApiProperty({
description: 'Sheba number (IBAN). Accepted: IR + 24 digits OR only 24 digits',
@ApiPropertyOptional({
description: 'Sheba number (IBAN). Required only if not already saved on this claim. Accepted: IR + 24 digits OR only 24 digits',
example: 'IR123456789012345678901234',
})
@IsNotEmpty({ message: 'sheba is required' })
@IsOptional()
@IsString({ message: 'sheba must be a string' })
sheba: string;
sheba?: string;
@ApiPropertyOptional({
description: 'Legacy alias of sheba for backward compatibility',
@@ -0,0 +1,26 @@
import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";
import { UserObjectionV2Dto } from "./user-objection-v2.dto";
describe("objection JSON and multipart parity", () => {
it.each([true, false])(
"validates nested entries for multipart=%s",
async (multipart) => {
const entries = [{ partId: 101, reason: "اعتراض به قیمت" }];
const dto = plainToInstance(UserObjectionV2Dto, {
objectionParts: multipart ? JSON.stringify(entries) : entries,
});
expect(await validate(dto)).toEqual([]);
},
);
it("still rejects invalid entries and malformed multipart JSON", async () => {
for (const raw of ["{", '[{"partId":"wrong"}]']) {
expect(
(
await validate(
plainToInstance(UserObjectionV2Dto, { objectionParts: raw }),
)
).length,
).toBeGreaterThan(0);
}
});
});
@@ -1,11 +1,6 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Type, Transform } from "class-transformer";
import {
IsArray,
IsOptional,
Validate,
ValidateNested,
} from "class-validator";
import { Type, Transform, plainToInstance } from "class-transformer";
import { IsArray, IsOptional, Validate, ValidateNested } from "class-validator";
import { HasObjectionEntriesConstraint } from "src/common/validators/has-objection-entries.validator";
import { NewPartDto, UserObjectionPartDto } from "./user-objection.dto";
@@ -28,7 +23,10 @@ export class UserObjectionV2Dto {
@Transform(({ value }) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? plainToInstance(UserObjectionPartDto, parsed)
: parsed;
} catch {
return value;
}
@@ -50,7 +48,10 @@ export class UserObjectionV2Dto {
@Transform(({ value }) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? plainToInstance(NewPartDto, parsed)
: parsed;
} catch {
return value;
}
@@ -20,6 +20,10 @@ export class ClaimCaseDbService {
return this.claimCaseModel.findById(id);
}
async findWithFanavaranSignature(id: string | Types.ObjectId) {
return this.claimCaseModel.findById(id).select("+fanavaranExpertSignature");
}
async findOne(
filter: FilterQuery<ClaimCase>,
): Promise<ClaimCaseDocument | null> {
@@ -14,6 +14,10 @@ export class ClaimSignDbService {
return await this.claimSignService.create(claimSign);
}
async deleteById(id: string): Promise<void> {
await this.claimSignService.findByIdAndDelete(id);
}
async findOne(filter: FilterQuery<ClaimSignModel>): Promise<ClaimSignModel> {
return await this.claimSignService.findOne(filter);
}
@@ -1,6 +1,6 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose";
import { Model, Types } from "mongoose";
import { ClaimFactorsImage } from "src/claim-request-management/entites/schema/factor-image.schema";
@Injectable()
@@ -13,6 +13,10 @@ export class ClaimFactorsImageDbService {
return await this.model.create(image);
}
async findByClaimId(id: string): Promise<ClaimFactorsImage[]> {
return this.model.find({ claimId: new Types.ObjectId(id) }).lean();
}
async findById(id: string): Promise<ClaimFactorsImage | null> {
return this.model.findById(id).lean();
}
@@ -218,6 +218,8 @@ export const ClaimUserObjectionPayloadSchema =
@Schema({ _id: false })
export class ClaimResendRequest {
@Prop({ type: Date })
requestedAt?: Date;
@Prop({ type: String })
resendDescription?: string;
@@ -274,6 +276,27 @@ export const ClaimFileRatingSchema =
@Schema({ _id: false })
export class ClaimPriceDrop {
@Prop({ type: Boolean })
eligible?: boolean;
@Prop({ type: String })
exclusionReason?: string;
@Prop({ type: Boolean })
manualOverride?: boolean;
@Prop({ type: String })
calculationVersion?: string;
@Prop({ type: Number })
vehicleAge?: number;
@Prop({ type: Number })
fanavaranAgeId?: number;
@Prop({ type: Number })
accidentYear?: number;
@Prop({ type: Number })
total?: number;
@@ -33,6 +33,7 @@ import {
ClaimWorkflowSchema,
} from "./claim-case.workflow.schema";
import { UserClaimRating } from "./claim-request-management.schema";
import type { FanavaranExpertSignature } from "src/fanavaran/fanavaran-expert-signature";
import type { FanavaranFieldReview } from "../../fanavaran-stage-fields";
import {
CaseInquiries,
@@ -350,6 +351,9 @@ export class ClaimCase {
@Prop({ type: FanavaranSyncStateSchema, default: () => ({}) })
fanavaranSync?: FanavaranSyncState;
@Prop({ type: MongooseSchema.Types.Mixed, select: false })
fanavaranExpertSignature?: FanavaranExpertSignature;
/** Expert-approved Fanavaran vehicle classification used by outbound stages. */
@Prop({ type: FanavaranVehicleReviewSchema })
fanavaranVehicleReview?: FanavaranVehicleReview;
@@ -1,3 +1,5 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { extname } from "node:path";
import {
@@ -67,6 +69,7 @@ import { Role } from "src/common/auth/enums";
* from their own account through the normal user endpoints.
*/
@ApiTags("expert-initiated claim (mirror v2)")
@EnforceCaseWorkingHours()
@Controller("v2/expert-initiated/claim-request-management")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@@ -241,8 +244,8 @@ Optional: upload car green card file in the same step.
**Validations:**
- Claim must exist
- Current workflow step must be SELECT_OTHER_PARTS
- Bank information must not have been submitted previously
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits
- Previously saved bank information is reused when omitted
- Sheba (sheba) accepted as IR + 24 digits or only 24 digits; required only if not saved
- National code must be exactly 10 digits
**Valid Other Parts (Optional):**
@@ -275,7 +278,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer`. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -290,7 +293,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -305,7 +307,7 @@ Optional: upload car green card file in the same step.
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({
status: 409,
description: "Bank information already submitted",
description: "Conflicting bank information",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@@ -565,7 +567,7 @@ Returns status of each item (uploaded/captured or not).
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const unique = randomUUID();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
@@ -223,4 +223,13 @@ describe("expertise submit completes earlier Fanavaran stages", () => {
"expertise",
]);
});
it("applies arbitrary expertise fields and replaces supplied damage sections", async () => {
const { service } = setup("car-body");
const body = { ClaimExpertId: 999, DmgSections: [{ AccessoryKindId: 42 }], CustomField: null };
await service.submitFanavaranExpertiseV2("claim-1", "parsian", body);
expect(service.executeFanavaranExpertiseSubmit).toHaveBeenCalledWith(
"claim-1", "parsian", expect.objectContaining(body), expect.anything(), true,
);
});
});
@@ -10,7 +10,7 @@ function setup(accessories: unknown) {
"vehicle-hull-dmg-cost-kinds": [
{ Id: 8002, Caption: "مجموع لوازم", IsActive: 1 },
],
"car-components": [{ Id: 9 }, { Id: 13 }, { Id: 112 }],
"car-components": [1, 9, 13, 112, 10, 48, 76, 29, 100, 37].map(Id => ({ Id })),
})[name] ?? [],
);
service.fanavaranLookupService = {
@@ -19,16 +19,20 @@ function setup(accessories: unknown) {
.fn()
.mockResolvedValue(accessories),
};
const build = (policyId = 123) =>
const build = (
policyId = 123,
parts: any[] = [
{ partId: 9, partName: "سپر جلو", price: 50000000, salary: 25000000 },
{ partId: 13, partName: "چراغ جلو چپ", price: 0, salary: 2000000 },
],
context: { claimCase?: any; blame?: any } = {},
) =>
service.buildCarBodyFanavaranExpertisePayload({
clientKey: "parsian",
claimCase: { fanavaranSync: { baseClaim: { policyId } } },
blame: { parties: [] },
claimCase: context.claimCase ?? { fanavaranSync: { baseClaim: { policyId } } },
blame: context.blame ?? { parties: [] },
profile: {},
parts: [
{ partId: 9, partName: "سپر جلو", price: 50000000, salary: 25000000 },
{ partId: 13, partName: "چراغ جلو چپ", price: 0, salary: 2000000 },
],
parts,
claimExpertId: 4044,
submittedAt: new Date("2026-11-11T09:09:00Z"),
priceDropTotal: 0,
@@ -40,6 +44,30 @@ function setup(accessories: unknown) {
}
describe("hull expertise policy accessory mapping", () => {
it("uses the hull inquiry policy when stage-1 policy metadata is absent", async () => {
const { service, build } = setup([
{ Id: 2598601, AccessoryKindId: 92, AccessoryDesc: "پايونير 1650" },
{ Id: 2598602, AccessoryKindId: 93, AccessoryDesc: "غير فابريک" },
{ Id: 3043330, AccessoryKindId: 112, AccessoryDesc: "کليه قطعات فابريک" },
]);
const { payload, warnings } = await build(null, [
{ partId: 1, partName: "جلو کامل", salary: 10000000 },
], {
claimCase: {},
blame: {
parties: [{ role: "FIRST", insurance: { carBodyInsurance: { policyId: 13764610 } } }],
},
});
expect(payload.DmgSections[0]).toMatchObject({
AccessoryKindId: 1,
VehicleHullAccessoryId: 3043330,
});
expect(warnings).toEqual([]);
expect(service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId)
.toHaveBeenCalledWith("parsian", 13764610, expect.any(Object));
});
it("uses the current policy accessory IDs for the bumper and headlamp", async () => {
const { service, build } = setup([
{ Id: 900001, AccessoryKindId: 9, AccessoryDesc: "سپر جلو" },
@@ -82,12 +110,14 @@ describe("hull expertise policy accessory mapping", () => {
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([3061139, 3061139]);
expect(payload.DmgSections.map((row: any) => row.AccessoryKindId)).toEqual([
112, 112,
9, 13,
]);
expect(warnings).toEqual([]);
expect(infoWarnings).toEqual(
expect.arrayContaining([
expect.stringContaining("mapped to factory bundle VehicleHullAccessoryId=3061139 AccessoryKindId=112"),
expect.stringContaining(
"mapped to factory bundle VehicleHullAccessoryId=3061139; preserving AccessoryKindId=9",
),
]),
);
});
@@ -157,7 +187,7 @@ describe("hull expertise policy accessory mapping", () => {
},
);
it("matches by part caption and keeps AccessoryKindId from that policy row", async () => {
it("resolves the policy reference by caption without replacing the evaluated partId", async () => {
const { build } = setup([
{
Id: 900010,
@@ -168,9 +198,71 @@ describe("hull expertise policy accessory mapping", () => {
const { payload, warnings } = await build();
expect(payload.DmgSections[0]).toMatchObject({
VehicleHullAccessoryId: 900010,
AccessoryKindId: 44,
AccessoryKindId: 9,
});
expect(payload.DmgSections[1].VehicleHullAccessoryId).toBeNull();
expect(warnings.some((w) => w.includes("چراغ جلو چپ"))).toBe(true);
});
it("preserves the six saved expert-reply part IDs under shared factory coverage", async () => {
const savedReplyParts = [
{
partId: 10,
carPartDamage: { id: 10, label_fa: "سپر عقب" },
typeOfDamage: "تعویض",
price: "150000000",
salary: "30000000",
daghi: { option: "ارزش لوازم بازیافتی", price: "20000000" },
},
{
partId: 48,
carPartDamage: { id: 48, label_fa: "درب صندوق عقب" },
typeOfDamage: "تعمیر",
salary: "80000000",
},
{
partId: 76,
carPartDamage: { id: 76, label_fa: "سيني عقب" },
typeOfDamage: "تعمیر",
salary: "70000000",
},
{
partId: 29,
carPartDamage: { id: 29, label_fa: "راهنماي عقب راست" },
typeOfDamage: "تعویض",
price: "95000000",
salary: "5000000",
},
{
partId: 100,
carPartDamage: { id: 100, label_fa: "سنسور دنده عقب" },
typeOfDamage: "تعویض",
price: "25000000",
salary: "5000000",
},
{
partId: 37,
carPartDamage: { id: 37, label_fa: "گلگير عقب سمت سرنشين" },
typeOfDamage: "تعمیر",
salary: "40000000",
},
];
const { build } = setup([
{ Id: 3092174, AccessoryKindId: 112, AccessoryDesc: "کليه قطعات فابريک" },
]);
const { payload, warnings } = await build(123, savedReplyParts);
expect(warnings).toEqual([]);
expect(payload.DmgSections.map((row: any) => row.AccessoryKindId)).toEqual([
10, 48, 76, 29, 100, 37,
]);
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual(Array(6).fill(3092174));
expect(payload.DmgSections.map((row: any) => row.Desc)).toEqual(
savedReplyParts.map((part) => part.carPartDamage.label_fa),
);
expect(
payload.DmgSections.map((row: any) => row.DmgSectionCosts[0].Amount),
).toEqual([180000000, 80000000, 70000000, 100000000, 30000000, 40000000]);
expect(payload.DmgSections[0].WasteValue).toBe(20000000);
});
});
@@ -34,17 +34,17 @@ describe("fanavaran hull base claim", () => {
expect(fanavaranHullNestedClaimId({ ClaimNo: 2268 })).toBeNull();
});
it("sets IsLicenseReplaced to 1 when licence issue is more than 10 years before accident", () => {
it("leaves IsLicenseReplaced empty when licence issue is more than 10 years before accident", () => {
const hull = toFanavaranHullBaseClaimPayload({
PolicyId: 1,
AccidentDate: "1405/08/20",
CulpritLicenceIssuDate: "1394/10/13",
});
expect(hull.IsLicenseReplaced).toBe(1);
expect(hull.IsLicenseReplaced).toBeNull();
expect(hull).not.toHaveProperty("IsLicenseReplacement");
});
it("sets IsLicenseReplaced to null when licence issue is within 10 years", () => {
it("sets IsLicenseReplaced to null when licence issue is more than three years before accident", () => {
const hull = toFanavaranHullBaseClaimPayload({
PolicyId: 1,
AccidentDate: "1405/08/20",
@@ -1,6 +1,7 @@
import type { FanavaranClientKey } from "src/core/config/fanavaran-client.config";
import { TEJARAT_NOTIFIER_FIELDS } from "src/fanavaran/tejarat-notifier";
import { resolveFanavaranIsLicenseReplaced } from "./fanavaran-party-roles";
import { isJalaliDateOlderThanYears } from "./fanavaran-party-roles";
import { parseJalaliDateParts } from "./fanavaran-driver-inquiry";
/** GEN.03 VHUD input fields. Do not send ثالث-only keys (DamagedCount, HasOtherCulprit, plaques, …). */
export const FANAVARAN_HULL_BASE_CLAIM_KEYS = [
@@ -118,6 +119,17 @@ export function customerIdFromHullPolicyRecord(
return Number.isFinite(n) && n > 0 ? n : null;
}
/** Hull requires an empty replacement flag for licences older than three years. */
export function resolveFanavaranHullIsLicenseReplaced(
licenceIssuDate: unknown,
accidentDate: unknown,
): 0 | null {
if (!parseJalaliDateParts(licenceIssuDate) || !parseJalaliDateParts(accidentDate)) {
return null;
}
return isJalaliDateOlderThanYears(licenceIssuDate, accidentDate, 3) ? null : 0;
}
export function toFanavaranHullBaseClaimPayload(
built: Record<string, unknown>,
clientKey?: FanavaranClientKey,
@@ -125,14 +137,14 @@ export function toFanavaranHullBaseClaimPayload(
const next: Record<string, unknown> = {};
for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) {
if (key === "IsLicenseReplaced") {
// Preserve the server's conditional 0 / null / 1 mapping for licence age.
// Preserve explicit answers; otherwise derive the hull-specific default.
if (
Object.prototype.hasOwnProperty.call(built, key) &&
(built[key] === 1 || built[key] === 0 || built[key] === null)
) {
next[key] = built[key];
} else {
next[key] = resolveFanavaranIsLicenseReplaced(
next[key] = resolveFanavaranHullIsLicenseReplaced(
built.CulpritLicenceIssuDate,
built.AccidentDate,
);
@@ -134,13 +134,14 @@ function normalizeAccessoryCaption(value: unknown): string {
export type ResolvedHullDmgAccessory = {
vehicleHullAccessoryId: number;
/** Must come from the same policy dmg-accessories row (Fanavaran filter rule). */
/** Policy-row metadata; does not replace the saved expert-reply partId. */
accessoryKindId: number;
};
/**
* GEN.06 accessory pair from `GET …/vehicle-hull-policies/{policyId}/dmg-accessories`.
* Only returns a coherent Id + AccessoryKindId from one policy row.
* Returns the policy coverage reference and that policy row's metadata.
* The caller preserves the evaluated partId as DmgSections[].AccessoryKindId.
* Exact/caption match only. Factory-bundle fallback for unmatched parts is applied
* by the expertise builder (VehicleHullAccessoryId from «کليه قطعات فابريک»).
*/
@@ -199,7 +199,7 @@ export function collectFanavaranExpertiseReadinessWarnings(
if (!thirdPartyLookups) {
// VehicleHullAccessoryId may be null: many hull policies only list the
// factory bundle (کليه قطعات فابريک), not every car-components part.
// Do not invent a factory Id with a mismatched AccessoryKindId.
// A shared coverage bundle must not replace the evaluated part kind.
if (row.AccessoryKindId == null || row.AccessoryKindId === "") {
warnings.push(
`DmgSections[${index}].AccessoryKindId is required from car-components (selected part).`,
@@ -187,4 +187,28 @@ describe("hull live lookup submission checks", () => {
ActualPremium: 123456,
});
});
it("validates a manual payload without normalizing values or refreshing the supplied premium", async () => {
const service = setup();
const ids = {
cities: 801, "accident-report-type": 802, "accident-causes": 803,
"vehicle-hull-accident-types": 804, "vehicle-hull-accident-culprit-type": 805,
"detection-accident-culprits": 806, "driving-licence-types": 807, "vehicle-use-types": 808,
};
service.fanavaranLookupService.fetchFromFanavaran.mockImplementation(async (_client, url) => [
{ Id: ids[url.split("/").at(-1)], IsActive: 1 },
]);
service.fanavaranLookupService.bodyPolicyById = jest.fn().mockResolvedValue({ TotalPremium: 123456 });
const payload = {
PolicyId: 1, ActualPremium: 12, AccidentCityId: "801", AccidentReportTypeId: 802,
AccidentCauseId: 803, AccidentTypeId: 804, CulpritTypeId: 805,
AuthorityCulpritId: 806, CulpritLicenceTypeId: 807, AccidentVehicleUsedId: 808,
IsLicenseReplaced: null,
};
const original = JSON.parse(JSON.stringify(payload));
await service.postFanavaranJson("https://example.test/car/vehicle-hull-claims", payload, "parsian", undefined, undefined, true);
expect(payload).toEqual(original);
expect(service.httpService.post).toHaveBeenCalledWith(expect.any(String), original, expect.any(Object));
expect(service.fanavaranLookupService.bodyPolicyById).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,66 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
describe("Fanavaran depreciation age eligibility", () => {
it.each(
["car-body", "third-party"].flatMap((product) =>
[10, 11].map((age) => ({ product, age })),
),
)(
"$product: age $age uses the eligible total only",
async ({ product, age }) => {
const service = Object.create(
ClaimRequestManagementService.prototype,
) as any;
const first = {
role: "FIRST",
person: { userId: "first" },
statement: { accidentDate: "2026-11-23" },
vehicle: { inquiry: { mapped: { ModelField: String(1405 - age) } } },
};
const second = {
role: "SECOND",
person: { userId: "second" },
vehicle: first.vehicle,
};
const blame =
product === "car-body"
? { type: "CAR_BODY", parties: [first] }
: {
type: "THIRD_PARTY",
parties: [first, second],
expert: { decision: { guiltyPartyId: "first" } },
};
service.blameRequestDbService = {
findById: jest.fn().mockResolvedValue(blame),
};
service.tryResolveFanavaranExpertiseClaimExpertId = jest
.fn()
.mockResolvedValue({ claimExpertId: 4044 });
service.resolveFanavaranClaimProduct = jest
.fn()
.mockResolvedValue(product);
service.getFanavaranLookupRows = jest.fn().mockResolvedValue([]);
service.buildCarBodyFanavaranExpertisePayload = jest.fn(
async (input) => ({ payload: { DropAmount: input.priceDropTotal ?? 0 } }),
);
const claimCase = {
_id: "claim",
blameRequestId: "blame",
owner: { userId: "first" },
evaluation: { priceDrop: { total: 999, carPrice: 400000000 } },
};
const result = await service.buildFanavaranExpertisePayload({
claimCase,
clientKey: "parsian",
});
expect(
result.payload[
product === "car-body"
? "DropAmount"
: "DropAmountAdditionsDeductions"
],
).toBe(product === "car-body" || age > 10 ? 0 : 999);
expect(claimCase.evaluation.priceDrop.total).toBe(999); // Historical data is preserved.
},
);
});
@@ -0,0 +1,176 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
import { toFanavaranHullBaseClaimPayload } from "./fanavaran-hull-base-claim";
function setup(product = "car-body") {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) };
service.fanavaranAuditService = { generateTrackingCode: () => "test" };
service.fanavaranAuthService = { assertNotInBackoff: jest.fn() };
service.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
PolicyId: 1,
AccidentVehicleUsedId: 1,
AccidentCauseId: 6,
CulpritLicenceNo: "1234567890",
IsLicenseReplaced: 1,
});
service.resolveFanavaranClaimProduct = jest.fn().mockResolvedValue(product);
service.getFanavaranAuthHeaders = jest.fn().mockResolvedValue({});
service.fanavaranClaimsUrlForClaim = jest
.fn()
.mockResolvedValue("https://example.test/car/vehicle-hull-claims");
const stop = new Error("Captured before HTTP POST");
service.assertFanavaranHullApiValues = jest.fn().mockRejectedValue(stop);
return { service, stop };
}
describe("hull licence replacement at submit", () => {
it("honours explicit null from the submit body before validating the outgoing hull payload", async () => {
const { service, stop } = setup();
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
IsLicenseReplaced: null,
PolicyId: 999,
AccidentVehicleUsedId: 999,
}),
).rejects.toBe(stop);
const outgoing = service.assertFanavaranHullApiValues.mock.calls[0][1];
expect(outgoing.IsLicenseReplaced).toBeNull();
expect(outgoing.PolicyId).toBe(999);
expect(outgoing.AccidentVehicleUsedId).toBe(999);
});
it("applies all supplied fields on third-party submissions too", async () => {
const { service, stop } = setup("third-party");
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
IsLicenseReplaced: null,
}),
).rejects.toBe(stop);
expect(
service.assertFanavaranHullApiValues.mock.calls[0][1].IsLicenseReplaced,
).toBeNull();
});
it("builds null for the old licence and accident dates from the rejected request", () => {
expect(
toFanavaranHullBaseClaimPayload({
CulpritLicenceIssuDate: "1381/03/26",
AccidentDate: "1405/08/30",
}).IsLicenseReplaced,
).toBeNull();
});
it.each([0, 1, null])(
"preserves the explicit hull answer %s",
async (answer) => {
const { service, stop } = setup();
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
IsLicenseReplaced: answer,
}),
).rejects.toBe(stop);
expect(
service.assertFanavaranHullApiValues.mock.calls[0][1].IsLicenseReplaced,
).toBe(answer);
},
);
it.each([
["1381/03/26", null],
["1404/08/30", 0],
])(
"derives an omitted hull answer from the final overridden licence date %s",
async (date, answer) => {
const { service, stop } = setup();
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
CulpritLicenceIssuDate: date,
AccidentDate: "1405/08/30",
}),
).rejects.toBe(stop);
expect(
service.assertFanavaranHullApiValues.mock.calls[0][1].IsLicenseReplaced,
).toBe(answer);
},
);
it("preserves null licence numbers, arbitrary fields and nested arrays in the final payload", async () => {
const { service, stop } = setup();
const body = {
CulpritLicenceNo: null,
ActualPremium: 12,
ClaimExpertId: 888,
CustomField: { nested: [1, null, { value: false }] },
DmgSections: [{ AccessoryKindId: 42 }],
};
await expect(
service.executeFanavaranV2Submit("claim", "parsian", body),
).rejects.toBe(stop);
expect(service.assertFanavaranHullApiValues.mock.calls[0][1]).toMatchObject(
body,
);
expect(service.assertFanavaranHullApiValues.mock.calls[0][4]).toBe(true);
});
it("merges against the generated payload rather than forwarding a preview warning envelope", async () => {
const { service, stop } = setup();
service.previewFanavaranSubmitV2.mockResolvedValue({
payload: { PolicyId: null, ActualPremium: null },
previewWarnings: [{ field: "PolicyId" }],
});
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
PolicyId: 999,
ActualPremium: 12,
}),
).rejects.toBe(stop);
const outgoing = service.assertFanavaranHullApiValues.mock.calls[0][1];
expect(outgoing.PolicyId).toBe(999);
expect(outgoing).not.toHaveProperty("payload");
expect(outgoing).not.toHaveProperty("previewWarnings");
expect(service.previewFanavaranSubmitV2).toHaveBeenCalledWith(
"claim",
"parsian",
expect.objectContaining({
policyIdOverride: 999,
requirePolicyId: false,
requireClaimExpertId: false,
}),
);
});
it("sends every supplied value to the HTTP client without replacing null licence numbers", async () => {
const { service, stop } = setup();
service.assertFanavaranHullApiValues.mockResolvedValue(undefined);
service.fanavaranAuthService.registerFailure = jest.fn();
service.fanavaranAuditService.recordStep = jest.fn();
service.fanavaranAuditService.captureAxiosExchange = jest
.fn()
.mockReturnValue({});
service.fanavaranAuditService.extractErrorMessage = jest
.fn()
.mockReturnValue(stop.message);
service.fanavaranAuditService.sanitizeErrorDetails = jest
.fn()
.mockReturnValue({});
service.httpService = {
post: jest.fn().mockImplementation(() => {
throw stop;
}),
};
const body = {
PolicyId: 999,
ActualPremium: 12,
AccidentVehicleUsedId: 42,
CulpritLicenceNo: null,
IsLicenseReplaced: null,
ArbitraryField: false,
};
await expect(
service.executeFanavaranV2Submit("claim", "parsian", body),
).rejects.toBe(stop);
expect(service.httpService.post).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining(body),
expect.any(Object),
);
});
});
@@ -8,7 +8,7 @@ describe("owner insurer approval without branch selection", () => {
const service = Object.create(
ClaimRequestManagementService.prototype,
) as ClaimRequestManagementService;
const findByIdAndUpdate = jest.fn().mockResolvedValue(undefined);
const findOneAndUpdate = jest.fn().mockResolvedValue({});
(service as any).claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
@@ -21,7 +21,7 @@ describe("owner insurer approval without branch selection", () => {
damageExpertReply: { submittedAt: new Date(), parts: [] },
},
}),
findByIdAndUpdate,
findOneAndUpdate,
};
(service as any).resolveClaimEffectiveUserId = jest
.fn()
@@ -48,8 +48,8 @@ describe("owner insurer approval without branch selection", () => {
status: ClaimCaseStatus.REJECTED,
});
expect(findByIdAndUpdate).toHaveBeenCalledWith(
"507f1f77bcf86cd799439011",
expect(findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({_id: "507f1f77bcf86cd799439011", "evaluation.ownerInsurerApproval.signedAt": null}),
expect.objectContaining({
$set: expect.objectContaining({
"evaluation.ownerInsurerApproval": expect.not.objectContaining({
@@ -0,0 +1,105 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
const id = "507f1f77bcf86cd799439011",
uid = "507f1f77bcf86cd799439012";
/** Simulated shared document: each conditional update is atomic, as Mongo is. */
function serviceFor(initial: any) {
const s: any = Object.create(ClaimRequestManagementService.prototype);
const doc = { _id: id, owner: { userId: uid }, ...initial };
s.claimCaseDbService = {
findById: jest.fn(async () => ({
...doc,
workflow: { ...doc.workflow },
evaluation: { ...doc.evaluation },
})),
findOneAndUpdate: jest.fn(async (filter, update) => {
if (filter.status !== doc.status) return null;
if (filter["userRating.createdAt"] === null && doc.userRating)
return null;
if (
filter["evaluation.ownerInsurerApproval.signedAt"] === null &&
doc.evaluation.ownerInsurerApproval
)
return null;
for (const [k, v] of Object.entries(update.$set || {})) {
const parts = k.split(".");
let target = doc;
for (const key of parts.slice(0, -1)) target = target[key] ??= {};
target[parts.at(-1)!] = v;
}
return doc;
}),
};
s.resolveClaimEffectiveUserId = jest.fn(async () => uid);
s.assertEffectiveUserIsDamagedPartyOnClaim = jest.fn(async () => {});
s.claimSignDbService = {
create: jest.fn(async () => ({ _id: "507f1f77bcf86cd799439013" })),
deleteById: jest.fn(async () => {}),
};
s.autoSubmitFanavaranExpertiseOnExpertReply = jest.fn(async () => ({
submitted: false,
}));
s.autoSubmitToFanavaranV2OnClaimCompleted = jest.fn(async () => ({
submitted: false,
}));
return { s, doc };
}
describe("one winning owner action", () => {
it("never records contradictory final decisions or duplicate integration calls", async () => {
const { s, doc } = serviceFor({
status: "INSURER_REVIEW_AWAITING_OWNER_SIGN",
claimStatus: "APPROVED",
workflow: { currentStep: "INSURER_REVIEW" },
evaluation: { damageExpertReply: { submittedAt: new Date(), parts: [] } },
});
const results = await Promise.allSettled(
[true, false, true, false, true, false].map((agree) =>
s.submitOwnerInsurerApprovalSignV2(
id,
agree,
{ filename: "a.jpg", path: "files/a.jpg" },
uid,
),
),
);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(s.claimSignDbService.deleteById).toHaveBeenCalledTimes(5);
expect(s.autoSubmitToFanavaranV2OnClaimCompleted).toHaveBeenCalledTimes(1);
expect(doc.status).toBe("COMPLETED");
expect(doc.evaluation.ownerInsurerApproval.agree).toBe(true);
});
it("allows exactly one satisfaction rating under concurrent submissions", async () => {
const { s } = serviceFor({
status: "COMPLETED",
workflow: {},
evaluation: {},
});
const results = await Promise.allSettled(
[0, 1, 2, 3, 4, 5].map((n) =>
s.addUserRatingV2(
id,
{ progressSpeed: n, registrationEase: n, overallEvaluation: n },
uid,
),
),
);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(results.filter((r) => r.status === "rejected")).toHaveLength(5);
});
it("authorizes V3 selection before changing workflow or parts", async () => {
const { s } = serviceFor({
status: "SELECTING_OTHER_PARTS",
workflow: {},
evaluation: {},
});
s.assertActorCanViewClaimV2 = jest.fn(async () => {
throw Error("forbidden");
});
await expect(
s.selectOtherPartsV3(id, { otherParts: ["engine"] }, uid, {
sub: uid,
role: "field_expert",
}),
).rejects.toThrow("forbidden");
expect(s.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled();
});
});
@@ -1,3 +1,4 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { readFile } from "node:fs/promises";
import { extname } from "node:path";
import {
@@ -63,6 +64,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-
* The registrar's job ends here — no reviewing panel is needed.
*/
@ApiTags("registrar claim (mirror v2)")
@EnforceCaseWorkingHours()
@Controller("v2/registrar/claim-request-management")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@@ -241,7 +243,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer`. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -256,7 +258,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -266,7 +267,7 @@ Optional: upload car green card file in the same step.
})
@ApiResponse({ status: 400, description: "Invalid workflow step or validation failed" })
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({ status: 409, description: "Bank information already submitted" })
@ApiResponse({ status: 409, description: "Conflicting bank information" })
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@Body() body: SelectOtherPartsV2Dto,
+3
View File
@@ -1,3 +1,4 @@
import { ClientWorkingHoursService } from "./working-hours/client-working-hours.service";
import { UserClaimBranchService } from "./user-claim-branch.service";
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
@@ -34,6 +35,7 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema";
ClientDbService,
BranchDbService,
ExternalInquirySettingsService,
ClientWorkingHoursService,
],
exports: [
UserClaimBranchService,
@@ -41,6 +43,7 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema";
ClientDbService,
BranchDbService,
ExternalInquirySettingsService,
ClientWorkingHoursService,
],
})
export class ClientModule {}
@@ -56,6 +56,14 @@ export class ClientDbService implements OnModuleInit {
return this.clientModel.findOne(client);
}
async findWorkingHours(filter: FilterQuery<ClientModel>) {
return this.clientModel
.findOne(filter)
.select("settings.workingHours")
.lean()
.exec();
}
async findAll(): Promise<ClientModel[]> {
return await this.clientModel.find();
}
@@ -1,4 +1,5 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import type { WorkingHours } from "src/client/working-hours/working-hours";
import type { ExternalInquiryFlags } from "src/common/types/external-inquiry.types";
export type ClientDocument = ClientModel & Document;
@@ -68,6 +69,9 @@ export class ClientExternalInquirySettings implements Partial<ExternalInquiryFla
* working when a field is missing.
*/
export class ClientSettings {
@Prop({ type: Object, required: false })
workingHours?: WorkingHours;
/**
* Max number of days between the accident and the moment a CAR_BODY blame
* file is allowed to be submitted. When unset, consumers fall back to the
@@ -0,0 +1,120 @@
import {
CallHandler,
ExecutionContext,
Injectable,
NestInterceptor,
SetMetadata,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { AsyncLocalStorage } from "node:async_hooks";
import { Types } from "mongoose";
import { Observable } from "rxjs";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service";
import {
actorWorkingHoursClientId,
ClientWorkingHoursService,
responsibleBlameInsurer,
workingHoursClientId,
} from "./client-working-hours.service";
const CASE_WRITES = Symbol("case-working-hours");
type CaseWriteOptions = { genericId?: "blame" };
export const EnforceCaseWorkingHours = (options: CaseWriteOptions = {}) =>
SetMetadata(CASE_WRITES, options);
const WRITE_METHODS = new Set(["POST", "PUT", "PATCH", "DELETE"]);
const caseScheduleScope = new AsyncLocalStorage<
(clientId: string) => Promise<void>
>();
// An intake inquiry can identify a different insurer before the case is saved.
export async function checkDiscoveredCaseInsurer(value: unknown) {
const clientId = workingHoursClientId(value);
if (clientId) await caseScheduleScope.getStore()?.(clientId);
}
export function checkDiscoveredBlameInsurer(
blame: Parameters<typeof responsibleBlameInsurer>[0],
) {
return checkDiscoveredCaseInsurer(responsibleBlameInsurer(blame));
}
@Injectable()
export class CaseWorkingHoursInterceptor implements NestInterceptor {
constructor(
private readonly reflector: Reflector,
private readonly hours: ClientWorkingHoursService,
private readonly claims: ClaimCaseDbService,
private readonly blames: BlameRequestDbService,
) {}
async intercept(context: ExecutionContext, next: CallHandler) {
const rule = this.reflector.getAllAndOverride<CaseWriteOptions>(
CASE_WRITES,
[context.getHandler(), context.getClass()],
);
const req = context.switchToHttp().getRequest();
if (!rule || !req.user?.sub || !WRITE_METHODS.has(req.method))
return next.handle();
const now = new Date();
const scope = await this.resolveScope(req.params ?? {}, rule);
if (!scope) return next.handle(); // Keep existing invalid/missing case responses.
const checked = new Set<string | undefined>();
const check = async (clientId?: string) => {
if (checked.has(clientId)) return;
await this.hours.assertOpen(clientId, now);
checked.add(clientId);
};
await check(scope.clientId ?? actorWorkingHoursClientId(req.user));
// Subscribe inside the scope so asynchronous handlers and multipart processing inherit it.
return new Observable((subscriber) =>
caseScheduleScope.run(check, () => next.handle().subscribe(subscriber)),
);
}
private async resolveScope(
params: Record<string, string>,
rule: CaseWriteOptions,
) {
const claimId = params.claimRequestId ?? params.claimCaseId;
let blameId =
params.blameRequestId ??
params.requestId ??
(rule.genericId === "blame" ? params.id : undefined);
if (claimId) {
if (!workingHoursClientId(claimId)) return null;
const [claim] = (await this.claims.find(
{ _id: new Types.ObjectId(claimId) },
{
lean: true,
select: "owner.clientId owner.userClientKey blameRequestId",
},
)) as Record<string, any>[];
if (!claim) return null;
const tenant =
workingHoursClientId(claim.owner?.clientId) ??
workingHoursClientId(claim.owner?.userClientKey);
if (tenant) return { clientId: tenant };
blameId = claim.blameRequestId ? String(claim.blameRequestId) : undefined;
}
if (!blameId) return {};
if (!workingHoursClientId(blameId)) return null;
const [blame] = await this.blames.find(
{ _id: new Types.ObjectId(blameId) },
{
lean: true,
select:
"type blameStatus parties.role parties.person.clientId parties.person.userId parties.statement expert.decision.guiltyPartyId callCenterInitiated workingHoursIntakeClientId",
},
);
if (!blame) return claimId ? {} : null;
return {
clientId:
responsibleBlameInsurer(blame) ??
workingHoursClientId(blame.workingHoursIntakeClientId),
};
}
}
@@ -0,0 +1,112 @@
import {
BadRequestException,
ForbiddenException,
Injectable,
NotFoundException,
} from "@nestjs/common";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { resolveGuiltyPartyClientId } from "src/helpers/tenant-scope";
import { ClientDbService } from "../entities/db-service/client.db.service";
import {
defaultWorkingHours,
getNextOpening,
parseWorkingHours,
workingHoursMessage,
} from "./working-hours";
export function workingHoursClientId(value: unknown): string | undefined {
const id = String(value ?? "");
return /^[a-f\d]{24}$/i.test(id) ? id.toLowerCase() : undefined;
}
export function actorWorkingHoursClientId(actor: {
role?: string;
clientKey?: unknown;
}) {
// The public user's JWT clientKey is not their insurer.
return actor?.role && actor.role !== RoleEnum.USER
? workingHoursClientId(actor.clientKey)
: undefined;
}
type CaseParties = {
type?: unknown;
blameStatus?: unknown;
expert?: { decision?: { guiltyPartyId?: unknown } };
callCenterInitiated?: unknown;
parties?: Array<{
role?: string;
person?: { clientId?: unknown; userId?: unknown };
statement?: { admitsGuilt?: boolean; claimsDamage?: boolean };
}>;
};
export function responsibleBlameInsurer(blame: CaseParties | null | undefined) {
if (!blame) return undefined;
const first = blame.parties?.find((party) => party.role === "FIRST");
if (blame.type === "CAR_BODY")
return workingHoursClientId(first?.person?.clientId);
if (
blame.expert?.decision?.guiltyPartyId ||
blame.parties?.some((party) => party.statement?.admitsGuilt)
) {
return workingHoursClientId(resolveGuiltyPartyClientId(blame));
}
// AGREED can mean that the first party reported being the injured party.
if (blame.blameStatus === "AGREED" && first?.statement?.claimsDamage) {
const second = blame.parties?.find((party) => party.role === "SECOND");
return workingHoursClientId(second?.person?.clientId);
}
return blame.blameStatus === "AGREED" || blame.callCenterInitiated
? workingHoursClientId(first?.person?.clientId)
: undefined;
}
@Injectable()
export class ClientWorkingHoursService {
constructor(private readonly clients: ClientDbService) {}
async read(clientId: string) {
const id = this.requireClientId(clientId);
const client = await this.clients.findWorkingHours({ _id: id });
if (!client) throw new NotFoundException("شرکت بیمه یافت نشد.");
return client.settings?.workingHours ?? defaultWorkingHours();
}
async update(clientId: string, body: unknown) {
const id = this.requireClientId(clientId);
const schedule = parseWorkingHours(body);
const updated = await this.clients.findByIdAndUpdate(id, {
$set: { "settings.workingHours": schedule },
});
if (!updated) throw new NotFoundException("شرکت بیمه یافت نشد.");
return schedule;
}
async assertOpen(clientId: string | undefined, now: Date) {
const deploymentCode = process.env.CLIENT_ID?.trim();
const filter = clientId
? { _id: clientId }
: deploymentCode && /^\d+$/.test(deploymentCode)
? { clientCode: Number(deploymentCode) }
: null;
if (!filter) return;
const client = await this.clients.findWorkingHours(filter);
const policy = client?.settings?.workingHours;
if (!policy) return;
const nextOpening = getNextOpening(policy, now);
if (nextOpening === null) return;
throw new ForbiddenException({
code: "OUTSIDE_WORKING_HOURS",
message: workingHoursMessage(nextOpening),
...(nextOpening ? { nextOpening } : {}),
});
}
private requireClientId(value: unknown) {
const id = workingHoursClientId(value);
if (!id) throw new BadRequestException("شرکت بیمه معتبر نیست.");
return id;
}
}
@@ -0,0 +1,263 @@
import { ForbiddenException } from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { ExecutionContextHost } from "@nestjs/core/helpers/execution-context-host";
import { lastValueFrom, defer, of } from "rxjs";
import { RoleEnum } from "src/Types&Enums/role.enum";
import {
CaseWorkingHoursInterceptor,
checkDiscoveredBlameInsurer,
EnforceCaseWorkingHours,
} from "./case-working-hours.interceptor";
import {
ClientWorkingHoursService,
responsibleBlameInsurer,
} from "./client-working-hours.service";
import { getNextOpening, parseWorkingHours } from "./working-hours";
const open = { alwaysOpen: true, windows: [] };
const saturday = { weekday: 6, opensAt: "08:00", closesAt: "16:00" };
const schedule = { alwaysOpen: false, windows: [saturday] };
const afterClosing = new Date("2026-11-21T12:30:00Z");
describe("Tehran working hours", () => {
it("includes the opening minute, excludes closing, and reports the next open day", () => {
expect(getNextOpening(open, afterClosing)).toBeNull();
expect(getNextOpening(schedule, new Date("2026-11-21T04:29:59Z"))).toEqual({
weekday: 6,
time: "08:00",
});
expect(
getNextOpening(schedule, new Date("2026-11-21T04:30:00Z")),
).toBeNull();
expect(
getNextOpening(schedule, new Date("2026-11-21T12:29:59Z")),
).toBeNull();
expect(getNextOpening(schedule, afterClosing)).toEqual({
weekday: 6,
time: "08:00",
});
});
it("handles the overnight week boundary and a day ending at midnight", () => {
const overnight = {
alwaysOpen: false,
windows: [{ weekday: 6, opensAt: "23:00", closesAt: "02:00" }],
};
expect(getNextOpening(overnight, new Date("2026-11-21T19:29:59Z"))).toEqual(
{ weekday: 6, time: "23:00" },
);
expect(
getNextOpening(overnight, new Date("2026-11-21T21:30:00Z")),
).toBeNull();
expect(getNextOpening(overnight, new Date("2026-11-21T22:30:00Z"))).toEqual(
{ weekday: 6, time: "23:00" },
);
const allSaturday = parseWorkingHours({
alwaysOpen: false,
windows: [{ weekday: 6, opensAt: "00:00", closesAt: "24:00" }],
});
expect(
getNextOpening(allSaturday, new Date("2026-11-21T20:29:59Z")),
).toBeNull();
expect(
getNextOpening(allSaturday, new Date("2026-11-21T20:30:00Z")),
).toEqual({ weekday: 6, time: "00:00" });
});
it("rejects duplicate, invalid, and empty restricted schedules", () => {
for (const value of [
{ alwaysOpen: false, windows: [] },
{ ...schedule, windows: [saturday, saturday] },
{ ...schedule, windows: [{ ...saturday, weekday: 7 }] },
{ ...schedule, windows: [{ ...saturday, opensAt: "24:00" }] },
{ ...schedule, windows: [{ ...saturday, closesAt: "08:00" }] },
{ ...schedule, windows: [{ ...saturday, closesAt: "25:00" }] },
{ ...schedule, clientId: "another insurer" },
]) {
expect(() => parseWorkingHours(value)).toThrow();
}
});
});
@EnforceCaseWorkingHours()
class CaseController {
write() {}
}
const first = "aaaaaaaaaaaaaaaaaaaaaaaa";
const second = "bbbbbbbbbbbbbbbbbbbbbbbb";
const caseId = "cccccccccccccccccccccccc";
function context(
params: Record<string, string> = {},
role = RoleEnum.USER,
method = "POST",
) {
const req = { method, params, user: { sub: "user", role, clientKey: first } };
return new ExecutionContextHost(
[req],
CaseController,
CaseController.prototype.write,
);
}
describe("case working-hours enforcement", () => {
const findWorkingHours = jest.fn();
const findByIdAndUpdate = jest.fn();
const hours = new ClientWorkingHoursService({
findWorkingHours,
findByIdAndUpdate,
} as any);
const assertOpen = jest.spyOn(hours, "assertOpen");
const claims = { find: jest.fn() };
const blames = { find: jest.fn() };
const interceptor = new CaseWorkingHoursInterceptor(
new Reflector(),
hours,
claims as any,
blames as any,
);
let deployment: string | undefined;
beforeEach(() => {
jest.clearAllMocks();
deployment = process.env.CLIENT_ID;
jest.useFakeTimers({ now: afterClosing });
findWorkingHours.mockImplementation(async (filter) =>
filter._id === first
? { settings: {} }
: { settings: { workingHours: schedule } },
);
});
afterEach(() => {
if (deployment === undefined) delete process.env.CLIENT_ID;
else process.env.CLIENT_ID = deployment;
jest.useRealTimers();
});
it("uses the second party's insurer when the first party reports being injured", () => {
const injured = {
role: "FIRST",
person: { clientId: first },
statement: { claimsDamage: true },
};
const atFault = { role: "SECOND", person: { clientId: second } };
expect(
responsibleBlameInsurer({
type: "THIRD_PARTY",
blameStatus: "AGREED",
parties: [injured],
}),
).toBeUndefined();
expect(
responsibleBlameInsurer({
type: "THIRD_PARTY",
blameStatus: "AGREED",
parties: [injured, atFault],
}),
).toBe(second);
});
it("blocks public intake using the deployment insurer instead of the public JWT key", async () => {
process.env.CLIENT_ID = "8";
const handle = jest.fn(() => of(true));
await expect(
interceptor.intercept(context(), { handle }),
).rejects.toMatchObject({
status: 403,
response: {
code: "OUTSIDE_WORKING_HOURS",
nextOpening: { weekday: 6, time: "08:00" },
},
});
expect(findWorkingHours).toHaveBeenCalledWith({ clientCode: 8 });
expect(handle).not.toHaveBeenCalled();
});
it("uses a case's payer over the actor's insurer, including Fanavaran writes", async () => {
claims.find.mockResolvedValue([{ owner: { clientId: second } }]);
const handle = jest.fn(() => of(true));
await expect(
interceptor.intercept(
context({ claimCaseId: caseId }, RoleEnum.DAMAGE_EXPERT),
{ handle },
),
).rejects.toBeInstanceOf(ForbiddenException);
expect(findWorkingHours).toHaveBeenCalledWith({ _id: second });
expect(handle).not.toHaveBeenCalled();
});
it("uses the initiating insurer for a call-center case before policy details are known", async () => {
blames.find.mockResolvedValue([
{ type: "CAR_BODY", workingHoursIntakeClientId: second },
]);
await expect(
interceptor.intercept(context({ requestId: caseId }), {
handle: () => of(true),
}),
).rejects.toBeInstanceOf(ForbiddenException);
expect(findWorkingHours).toHaveBeenCalledWith({ _id: second });
});
it("checks a newly discovered payer inside the handler before it persists a transition", async () => {
const save = jest.fn();
const result = await interceptor.intercept(
context({}, RoleEnum.FIELD_EXPERT),
{
handle: () =>
defer(async () => {
await checkDiscoveredBlameInsurer({
type: "THIRD_PARTY",
parties: [
{ role: "FIRST", person: { clientId: first } },
{
role: "SECOND",
person: { clientId: second },
statement: { admitsGuilt: true },
},
],
});
save();
}),
},
);
await expect(lastValueFrom(result)).rejects.toBeInstanceOf(
ForbiddenException,
);
expect(assertOpen).toHaveBeenNthCalledWith(1, first, afterClosing);
expect(assertOpen).toHaveBeenNthCalledWith(2, second, afterClosing);
expect(save).not.toHaveBeenCalled();
});
it("defaults old insurers to always open and updates only the schedule", async () => {
expect(await hours.read(first)).toEqual(open);
findByIdAndUpdate.mockResolvedValueOnce({
settings: { workingHours: schedule },
});
expect(await hours.update(first, schedule)).toEqual(schedule);
expect(findByIdAndUpdate).toHaveBeenCalledWith(first, {
$set: { "settings.workingHours": schedule },
});
});
it("leaves reads and the existing missing-case error path alone", async () => {
blames.find.mockResolvedValue([]);
const read = await interceptor.intercept(
context({ requestId: caseId }, RoleEnum.USER, "GET"),
{
handle: () => of("read"),
},
);
expect(await lastValueFrom(read)).toBe("read");
expect(blames.find).not.toHaveBeenCalled();
const missing = await interceptor.intercept(
context({ requestId: caseId }),
{
handle: () => of("existing not found handling"),
},
);
expect(await lastValueFrom(missing)).toBe("existing not found handling");
expect(assertOpen).not.toHaveBeenCalled();
});
});
+151
View File
@@ -0,0 +1,151 @@
import { BadRequestException } from "@nestjs/common";
export const WORKING_HOURS_TIMEZONE = "Asia/Tehran";
const DAYS = [
"یکشنبه",
"دوشنبه",
"سه‌شنبه",
"چهارشنبه",
"پنجشنبه",
"جمعه",
"شنبه",
];
const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const DAY = 1440;
const WEEK = 7 * DAY;
const timeFormat = new Intl.DateTimeFormat("en-GB", {
timeZone: WORKING_HOURS_TIMEZONE,
weekday: "short",
hour: "2-digit",
minute: "2-digit",
hourCycle: "h23",
});
const timePattern = /^([01]\d|2[0-3]):[0-5]\d$/;
export type WorkingHoursWindow = {
weekday: number;
opensAt: string;
closesAt: string;
};
export type WorkingHours = {
alwaysOpen: boolean;
windows: WorkingHoursWindow[];
};
export const defaultWorkingHours = (): WorkingHours => ({
alwaysOpen: true,
windows: [],
});
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}
export function parseWorkingHours(value: unknown): WorkingHours {
if (
!isRecord(value) ||
Object.keys(value).some(
(key) => !["alwaysOpen", "windows"].includes(key),
) ||
typeof value.alwaysOpen !== "boolean" ||
!Array.isArray(value.windows) ||
value.windows.length > 7
) {
throw new BadRequestException("برنامه ساعات کاری معتبر نیست.");
}
const days = new Set<number>();
const windows = value.windows.map((window: unknown) => {
if (
!isRecord(window) ||
Object.keys(window).some(
(key) => !["weekday", "opensAt", "closesAt"].includes(key),
)
) {
throw new BadRequestException("برنامه روز کاری معتبر نیست.");
}
const { weekday, opensAt, closesAt } = window;
if (
typeof weekday !== "number" ||
!Number.isInteger(weekday) ||
weekday < 0 ||
weekday > 6 ||
days.has(weekday)
) {
throw new BadRequestException(
"برای هر روز هفته فقط یک بازه کاری تعریف کنید.",
);
}
if (
typeof opensAt !== "string" ||
!timePattern.test(opensAt) ||
typeof closesAt !== "string" ||
!(timePattern.test(closesAt) || closesAt === "24:00") ||
opensAt === closesAt
) {
throw new BadRequestException(
`ساعت شروع و پایان روز ${DAYS[weekday]} را به‌درستی وارد کنید.`,
);
}
days.add(weekday);
return { weekday, opensAt, closesAt };
});
if (!value.alwaysOpen && windows.length === 0) {
throw new BadRequestException(
"حداقل یک روز کاری انتخاب کنید یا دسترسی شبانه‌روزی را فعال کنید.",
);
}
return {
alwaysOpen: value.alwaysOpen,
windows: windows.sort((a, b) => a.weekday - b.weekday),
};
}
function minutes(time: string) {
const [hour, minute] = time.split(":").map(Number);
return hour * 60 + minute;
}
/** Null means open. The opening minute is included and the closing minute is excluded. */
export function getNextOpening(policy: WorkingHours, now: Date) {
if (policy.alwaysOpen) return null;
const parts = Object.fromEntries(
timeFormat.formatToParts(now).map(({ type, value }) => [type, value]),
);
const weekday = WEEKDAYS.indexOf(parts.weekday);
const current =
weekday * DAY + Number(parts.hour) * 60 + Number(parts.minute);
const spans = policy.windows.map((window) => {
const open = minutes(window.opensAt);
const close = minutes(window.closesAt);
return {
start: window.weekday * DAY + open,
duration: close > open ? close - open : DAY + close - open,
window,
};
});
if (
spans.some((span) => (current - span.start + WEEK) % WEEK < span.duration)
)
return null;
const next = spans.reduce<(typeof spans)[number] | undefined>(
(earliest, span) => {
const delay = (span.start - current + WEEK) % WEEK;
return !earliest || delay < (earliest.start - current + WEEK) % WEEK
? span
: earliest;
},
undefined,
);
return next
? { weekday: next.window.weekday, time: next.window.opensAt }
: undefined;
}
export function workingHoursMessage(next: ReturnType<typeof getNextOpening>) {
const message =
"ثبت و ادامه پرونده فقط در ساعات کاری شرکت بیمه امکان‌پذیر است.";
if (!next) return message;
const time = next.time.replace(/\d/g, (digit) => "۰۱۲۳۴۵۶۷۸۹"[Number(digit)]);
return `${message} شروع بعدی: ${DAYS[next.weekday]} ساعت ${time} به وقت تهران.`;
}
+8
View File
@@ -20,6 +20,10 @@ export enum Environment {
}
export class EnvironmentVariables {
@IsOptional()
@IsBooleanString()
FANAVARAN_REQUIRE_EXPERT_SIGNATURE?: string;
@IsEnum(Environment, {
message: "NODE_ENV should be development or production",
})
@@ -29,6 +33,10 @@ export class EnvironmentVariables {
@IsBooleanString({ message: "FAKE_OTP must be boolean" })
FAKE_OTP?: string;
@IsOptional()
@IsString()
SMS_BRAND_NAME?: string;
// --------------------------------------------------------- //
@IsNumber(
@@ -218,6 +218,9 @@ export function resolveFanavaranClientKey(): FanavaranClientKey {
}
// Optional deployment hint when FANAVARAN_CLIENT is not set.
if (String(process.env.CLIENT_ID ?? '').trim() === '7') {
return 'moallem';
}
if (String(process.env.CLIENT_ID ?? '') === '8') {
return 'parsian';
}
@@ -0,0 +1,75 @@
import {
CallHandler,
Controller,
ExecutionContext,
Get,
Injectable,
Module,
NestInterceptor,
Param,
Query,
Res,
ForbiddenException,
} from "@nestjs/common";
import { APP_INTERCEPTOR } from "@nestjs/core";
import {
EvidenceAccessService,
evidenceRequestScope,
} from "./evidence-access.service";
export { EvidenceAccessService } from "./evidence-access.service";
import { realpath } from "node:fs/promises";
import { resolve, sep } from "node:path";
import { Response } from "express";
import { map, Observable } from "rxjs";
@Injectable()
class EvidenceLinksInterceptor implements NestInterceptor {
constructor(private readonly access: EvidenceAccessService) {}
intercept(context: ExecutionContext, next: CallHandler) {
const req = context.switchToHttp().getRequest();
if (!req.user?.sub) return next.handle();
return new Observable((observer) =>
evidenceRequestScope.run(true, () =>
next
.handle()
.pipe(map((value) => this.access.project(value)))
.subscribe(observer),
),
);
}
}
@Controller("files")
class EvidenceController {
constructor(private readonly access: EvidenceAccessService) {}
@Get("*path")
async read(
@Param("path") raw: string | string[],
@Query("expires") expires: string,
@Query("signature") signature: string,
@Res() res: Response,
) {
const path = Array.isArray(raw) ? raw.join("/") : raw;
this.access.verify(path, expires, signature);
const root = await realpath(resolve("files"));
let target: string;
try {
target = await realpath(resolve(root, path));
} catch {
res.status(404).end();
return;
}
if (!target.startsWith(root + sep)) throw new ForbiddenException();
res.setHeader("Cache-Control", "private, no-store");
res.setHeader("X-Content-Type-Options", "nosniff");
// sendFile retains Range/HEAD support needed by video players.
res.sendFile(target);
}
}
@Module({
controllers: [EvidenceController],
providers: [
EvidenceAccessService,
{ provide: APP_INTERCEPTOR, useClass: EvidenceLinksInterceptor },
],
})
export class EvidenceAccessModule {}
@@ -0,0 +1,118 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { createHmac, timingSafeEqual } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
/** Short-lived read capabilities, minted only inside authenticated API responses.
* Browser image/video/PDF elements cannot attach an Authorization header. */
@Injectable()
export class EvidenceAccessService {
private digest(path: string, expires: string): string {
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error("JWT_SECRET is required for evidence access");
return createHmac("sha256", secret)
.update(`evidence\n${path}\n${expires}`)
.digest("hex");
}
sign(value: string): string {
const match = value.match(
/^(?:https?:\/\/[^/?#]+\/(?:[^?#]*\/)?|(?:\.?\/)?(?:[^\s/?#]+\/)*)files\/([^?#]+)(?:[?#].*)?$/,
);
if (!match || !/\.[a-z0-9]+$/i.test(match[1])) return value;
const path = match[1];
// Signing uses the same canonical URL path that Express decodes on read.
let decoded: string;
try {
decoded = decodeURIComponent(path);
} catch {
return value;
}
const expires = String(Math.floor(Date.now() / 1000) + 3600);
return `${value.split(/[?#]/)[0]}?expires=${expires}&signature=${this.digest(decoded, expires)}`;
}
verify(path: string, expires: string, signature: string): void {
if (
typeof path !== "string" ||
typeof expires !== "string" ||
typeof signature !== "string"
)
throw new UnauthorizedException("نشانی مدرک معتبر نیست.");
const exp = Number(expires);
if (
!Number.isSafeInteger(exp) ||
exp <= Date.now() / 1000 ||
exp > Date.now() / 1000 + 3660 ||
!/^[a-f0-9]{64}$/.test(signature || "")
)
throw new UnauthorizedException(
"نشانی مدرک معتبر نیست یا منقضی شده است. پرونده را دوباره باز کنید.",
);
if (
!timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(this.digest(path, expires), "hex"),
)
)
throw new UnauthorizedException("دسترسی به این مدرک مجاز نیست.");
}
/** Only mirror a capability already minted by the trusted file-link builder.
* Reflected form fields or arbitrary URL-shaped text cannot mint access. */
project(value: unknown): unknown {
const allowed = new Set<string>();
const walk = (
v: unknown,
convert: (text: string, field: string) => unknown,
field = "",
): unknown => {
if (v && typeof (v as any).toObject === "function")
return walk((v as any).toObject(), convert, field);
if (typeof v === "string") return convert(v, field);
if (Array.isArray(v)) return v.map((item) => walk(item, convert, field));
if (v instanceof Map)
return Object.fromEntries(
[...v].map(([k, item]) => [k, walk(item, convert, String(k))]),
);
if (
v &&
typeof v === "object" &&
Object.getPrototypeOf(v) === Object.prototype
)
return Object.fromEntries(
Object.entries(v).map(([k, item]) => [k, walk(item, convert, k)]),
);
return v;
};
walk(value, (text) => {
if (!text.includes("signature=")) return text;
try {
const url = new URL(text, "https://evidence.invalid");
const path = decodeURIComponent(url.pathname.split("/files/")[1] || "");
this.verify(
path,
url.searchParams.get("expires")!,
url.searchParams.get("signature")!,
);
allowed.add(path);
} catch {
/* Ordinary text and untrusted links never grant access. */
}
return text;
});
return walk(value, (text, field) => {
if (!/(?:url|urls|path|paths|link|links)$/i.test(field)) return text;
try {
const url = new URL(text, "https://evidence.invalid");
const path = decodeURIComponent(url.pathname.split("/files/")[1] || "");
return allowed.has(path) ? this.sign(text) : text;
} catch {
return text;
}
});
}
}
export const evidenceRequestScope = new AsyncLocalStorage<boolean>();
const links = new EvidenceAccessService();
/** Called only when constructing a link from server-owned file metadata. */
export function signAuthorizedEvidenceLink(value: string): string {
return evidenceRequestScope.getStore() ? links.sign(value) : value;
}
@@ -0,0 +1,65 @@
import { EvidenceAccessService } from "./evidence-access.module";
describe("evidence read capabilities", () => {
const secret = process.env.JWT_SECRET;
beforeEach(() => {
process.env.JWT_SECRET = "test-only-evidence-key";
});
afterEach(() => {
if (secret == null) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secret;
});
it("rejects bare, expired, altered and cross-path links but accepts its own signature", () => {
const service = new EvidenceAccessService();
const signed = new URL(
service.sign("https://example.test/car-damage/api/files/signs/a.jpg"),
);
const exp = signed.searchParams.get("expires")!;
const sig = signed.searchParams.get("signature")!;
expect(() => service.verify("signs/a.jpg", exp, sig)).not.toThrow();
expect(() => service.verify("signs/b.jpg", exp, sig)).toThrow();
expect(() => service.verify("signs/a.jpg", "1", sig)).toThrow();
expect(() => service.verify("signs/a.jpg", exp, "")).toThrow();
expect(() => service.verify("signs/a.jpg", exp, [sig] as any)).toThrow();
expect(() => service.verify("signs/a.jpg", exp, "0".repeat(64))).toThrow();
});
it("signs nested evidence without changing ordinary links, dates, or policy text", () => {
const service = new EvidenceAccessService();
const projected: any = service.project({
files: [
{ url: service.sign("files/car/a.jpg"), path: "files/car/a.jpg" },
],
reflected: { url: "files/car/private.jpg" },
site: "https://example.test/auth",
note: "files/car/private.jpg",
description: "https://example.test/files/signs/private.png",
});
expect(projected.files[0].url).toContain("?expires=");
expect(projected.files[0].path).toContain("?expires=");
expect(projected.reflected.url).toBe("files/car/private.jpg");
expect(projected.site).toBe("https://example.test/auth");
expect(projected.note).toBe("files/car/private.jpg");
expect(projected.description).toBe(
"https://example.test/files/signs/private.png",
);
expect(service.sign("See https://example.test/files/private.jpg")).toBe(
"See https://example.test/files/private.jpg",
);
});
});
it("mints links only while an authenticated request constructs them from stored media", () => {
const { evidenceRequestScope } = require("./evidence-access.service");
const { buildFileLink } = require("src/helpers/urlCreator");
const secret = process.env.JWT_SECRET;
process.env.JWT_SECRET = "qa-test-only";
try {
expect(buildFileLink("files/car/a.jpg")).not.toContain("signature=");
expect(
evidenceRequestScope.run(true, () => buildFileLink("files/car/a.jpg")),
).toContain("signature=");
expect(buildFileLink("files/car/a.jpg")).not.toContain("signature=");
} finally {
if (secret == null) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secret;
}
});
@@ -1,3 +1,4 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import {
Controller,
Get,
@@ -38,6 +39,7 @@ import { ExpertBlameService } from "./expert-blame.service";
@ApiExcludeController()
// @ApiTags("expert-blame-panel")
@EnforceCaseWorkingHours()
@Controller("expert-blame")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
+6
View File
@@ -1,3 +1,4 @@
import { checkDiscoveredBlameInsurer } from "src/client/working-hours/case-working-hours.interceptor";
import {
BadRequestException,
ConflictException,
@@ -2034,6 +2035,11 @@ export class ExpertBlameService {
},
};
await checkDiscoveredBlameInsurer({
type: request.type,
parties: request.parties,
expert: { decision: decisionPayload },
});
const updatePayload = {
$set: {
"workflow.locked": false,
@@ -1,3 +1,4 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import {
Body,
Controller,
@@ -35,6 +36,7 @@ import { SubmitReplyDto } from "./dto/reply.dto";
import { ResendRequestDto } from "./dto/resend.dto";
@ApiTags("expert-blame-panel (v2)")
@EnforceCaseWorkingHours({ genericId: "blame" })
@Controller("v2/expert-blame")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@@ -0,0 +1,357 @@
import { BadRequestException } from "@nestjs/common";
import { model, Schema, Types } from "mongoose";
import { ExpertClaimService } from "./expert-claim.service";
import { ClaimPriceDropSchema } from "src/claim-request-management/entites/schema/claim-case.evaluation.schema";
const Stored = model(
"FanavaranPriceDropTest",
new Schema({ priceDrop: ClaimPriceDropSchema }),
);
function setup() {
const claim: any = {
_id: new Types.ObjectId(),
blameRequestId: new Types.ObjectId(),
owner: { userId: "beneficiary" },
vehicle: { carType: "sedan" },
damage: {
selectedParts: [
{
id: 9876,
name: "9876",
label_fa: "قطعه اختصاصی شرکت",
side: "",
catalogKey: "9876",
},
],
},
evaluation: {},
};
const blame: any = {
type: "THIRD_PARTY",
expert: { decision: { guiltyPartyId: "other-party" } },
parties: [
{
role: "FIRST",
person: { userId: "beneficiary" },
vehicle: { inquiry: { mapped: { ModelField: "1402" } } },
statement: { accidentDate: "2026-11-23" },
},
{ role: "SECOND", person: { userId: "other-party" } },
],
};
const service = Object.create(ExpertClaimService.prototype) as any;
service.assertExpertCanEditClaimDuringReviewV2 = jest
.fn()
.mockResolvedValue(undefined);
service.blameRequestDbService = {
find: jest.fn().mockResolvedValue([blame]),
};
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn(async (_id, update) => {
// Exercise Mongoose's real strict schema casting: IDs and override flags
// must survive persistence, not merely exist in the response object.
claim.evaluation.priceDrop = new Stored({
priceDrop: update.$set["evaluation.priceDrop"],
}).toObject().priceDrop;
return claim;
}),
};
const body = {
carPrice: 400_000_000,
partSeverities: [
{ partId: 9876, fanavaranPartId: 14, severity: "Moderate" },
],
};
return { service, claim, blame, body, id: String(claim._id) };
}
describe("Fanavaran depreciation review and persistence", () => {
it("does not provide depreciation options or save depreciation for car-body claims", async () => {
const { service, blame, body, id } = setup();
blame.type = "CAR_BODY";
await expect(service.getPriceDropContextV2(id, {})).rejects.toThrow("افت قیمت برای پرونده بیمه بدنه");
await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow("افت قیمت برای پرونده بیمه بدنه");
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("returns the Fanavaran catalog and age at accident without changing the saved assessment", async () => {
const { service, claim, id } = setup();
claim.evaluation.priceDrop = { total: 123, partLines: [] };
const result = await service.getPriceDropContextV2(id, {});
expect(result).toMatchObject({
calculationVersion: "fanavaran-v1",
accidentYear: 1405,
suggestedCarModelYear: 1402,
suggestedVehicleAge: 3,
priceDrop: { total: 123 },
});
expect(result.priceDropCatalog).toHaveLength(17);
expect(result.ageCatalog).toHaveLength(11);
expect(result.damagedParts[0]).toMatchObject({
partId: 9876,
fanavaranPartId: null,
});
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("derives age and persists real Fanavaran category/severity/age codes", async () => {
const { service, claim, id, body } = setup();
const response = await service.upsertPriceDropV2(id, body, {});
const expected = {
total: 10_800_000,
carPrice: 400_000_000,
carModel: 1402,
accidentYear: 1405,
vehicleAge: 3,
fanavaranAgeId: 4,
coefficientYear: 2.7,
manualOverride: false,
calculationVersion: "fanavaran-v1",
};
expect(response.priceDrop).toMatchObject(expected);
expect(claim.evaluation.priceDrop).toMatchObject(expected);
expect(claim.evaluation.priceDrop.partLines[0]).toMatchObject({
partId: 9876,
fanavaranPartId: 14,
fanavaranSeverityId: 41,
coefficient: 4,
});
});
it("never uses a legacy tenant's caption just because component IDs collide", async () => {
const { service, claim, id } = setup();
// ID 52 means trunk-floor tray in the fallback snapshot, but this tenant
// saved its own live caption: roof. The saved tenant caption is authoritative.
claim.damage.selectedParts = [
{ id: 52, name: "52", catalogKey: "52", side: "", label_fa: "سقف" },
];
const context = await service.getPriceDropContextV2(id, {});
expect(context.damagedParts[0]).toMatchObject({
partId: 52,
label_fa: "سقف",
fanavaranPartId: 1,
});
await service.upsertPriceDropV2(
id,
{
carPrice: 400_000_000,
vehicleAge: 3,
partSeverities: [{ partId: 52, severity: "Severe" }],
},
{},
);
expect(claim.evaluation.priceDrop.partLines[0]).toMatchObject({
partId: 52,
fanavaranPartId: 1,
fanavaranSeverityId: 3,
coefficient: 7,
});
});
it("allows expert age when inquiry/date is unavailable and never sends a Gregorian year into the age table", async () => {
const { service, claim, blame, id, body } = setup();
blame.parties[0].vehicle.inquiry.mapped.ModelField = "2020";
delete blame.parties[0].statement.accidentDate;
await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow(
"سن خودرو",
);
await service.upsertPriceDropV2(id, { ...body, vehicleAge: 0 }, {});
expect(claim.evaluation.priceDrop).toMatchObject({
vehicleAge: 0,
fanavaranAgeId: 1,
total: 12_000_000,
});
});
it("preserves the manual zero path and market price, and clears stale calculated rows", async () => {
const { service, claim, id } = setup();
claim.evaluation.priceDrop = {
carPrice: 400_000_000,
partLines: [{ coefficient: 7 }],
total: 123,
};
await service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {});
expect(claim.evaluation.priceDrop).toMatchObject({
manualOverride: true,
carPrice: 400_000_000,
total: 0,
partLines: [],
});
expect(service.blameRequestDbService.find).toHaveBeenCalled();
});
it("explicit recalculation replaces an old manual value and stores its source", async () => {
const { service, claim, id, body } = setup();
claim.evaluation.priceDrop = { manualOverride: true, total: 42 };
await service.upsertPriceDropV2(id, body, {});
expect(claim.evaluation.priceDrop).toMatchObject({
manualOverride: false,
total: 10_800_000,
calculationVersion: "fanavaran-v1",
});
});
it.each([
{ vehicleAge: -1 },
{ vehicleAge: 1.5 },
{ carPrice: "invalid" },
{ carPrice: -1 },
{
partSeverities: [
{ partId: 9876, fanavaranPartId: 17, severity: "Minor" },
],
},
{
partSeverities: [
{ partId: 9876, fanavaranPartId: 999, severity: "Severe" },
],
},
{ partSeverities: [{ partId: 50, severity: "Severe" }] },
{ partSeverities: [null] },
{ partSeverities: "bad" },
])(
"invalid calculation does not overwrite a previously saved result: %j",
async (invalid) => {
const { service, claim, id, body } = setup();
claim.evaluation.priceDrop = { total: 777 };
await expect(
service.upsertPriceDropV2(id, { ...body, ...invalid }, {}),
).rejects.toBeInstanceOf(BadRequestException);
expect(claim.evaluation.priceDrop.total).toBe(777);
expect(
service.claimCaseDbService.findByIdAndUpdate,
).not.toHaveBeenCalled();
},
);
it("keeps the existing review authorization check before either write mode", async () => {
const { service, id, body } = setup();
service.assertExpertCanEditClaimDuringReviewV2.mockRejectedValue(
new Error("denied"),
);
await expect(service.upsertPriceDropV2(id, body, {})).rejects.toThrow(
"denied",
);
await expect(
service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {}),
).rejects.toThrow("denied");
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("respects the age table start date without blocking manual totals", async () => {
const { service, claim, blame, id, body } = setup();
blame.parties[0].statement.accidentDate = "1404/05/27";
const context = await service.getPriceDropContextV2(id, {});
expect(context.calculationUnavailableReason).toContain("۱۴۰۴/۰۵/۲۸");
await expect(
service.upsertPriceDropV2(id, { ...body, vehicleAge: 3 }, {}),
).rejects.toThrow("۱۴۰۴/۰۵/۲۸");
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
await service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {});
expect(claim.evaluation.priceDrop).toMatchObject({
total: 0,
manualOverride: true,
});
});
it("makes an inferred age above ten ineligible in context and saves zero without requiring parts/prices", async () => {
const { service, claim, blame, id } = setup();
blame.parties[0].vehicle.inquiry.mapped.ModelField = "1394";
const context = await service.getPriceDropContextV2(id, {});
expect(context).toMatchObject({
suggestedVehicleAge: 11,
depreciationEligible: false,
});
expect(context.ineligibilityReason).toContain("بیشتر از ۱۰ سال");
await service.upsertPriceDropV2(id, {}, {});
expect(claim.evaluation.priceDrop).toMatchObject({
vehicleAge: 11,
eligible: false,
total: 0,
partLines: [],
fanavaranAgeId: null,
});
});
it.each([undefined, 0, 10])(
"an entered age %s cannot bypass known old age for a positive manual override",
async (vehicleAge) => {
const { service, claim, blame, id } = setup();
blame.parties[0].vehicle.inquiry.mapped.ModelField = "1394";
await expect(
service.upsertPriceDropV2(id, { manualPriceDrop: 1, vehicleAge }, {}),
).rejects.toThrow("بیشتر از ۱۰ سال");
expect(
service.claimCaseDbService.findByIdAndUpdate,
).not.toHaveBeenCalled();
},
);
it("accepts manual zero for an old car and preserves its market value", async () => {
const { service, claim, id } = setup();
await service.upsertPriceDropV2(
id,
{ manualPriceDrop: 0, vehicleAge: 12, carPrice: 400_000_000 },
{},
);
expect(claim.evaluation.priceDrop).toMatchObject({
eligible: false,
total: 0,
vehicleAge: 12,
carPrice: 400_000_000,
});
});
it("keeps exactly age ten eligible for manual and calculated amounts", async () => {
const { service, claim, id, body } = setup();
await service.upsertPriceDropV2(id, { ...body, vehicleAge: 10 }, {});
expect(claim.evaluation.priceDrop).toMatchObject({
eligible: true,
total: 8_200_000,
vehicleAge: 10,
});
await service.upsertPriceDropV2(
id,
{ manualPriceDrop: 99, vehicleAge: 10 },
{},
);
expect(claim.evaluation.priceDrop).toMatchObject({
eligible: true,
total: 99,
vehicleAge: 10,
});
});
it("requires age for a positive manual amount when inquiry age is unknown, while allowing zero", async () => {
const { service, claim, blame, id } = setup();
delete blame.parties[0].vehicle.inquiry;
await expect(
service.upsertPriceDropV2(id, { manualPriceDrop: 99 }, {}),
).rejects.toThrow("سن خودرو");
await service.upsertPriceDropV2(id, { manualPriceDrop: 0 }, {});
expect(claim.evaluation.priceDrop.total).toBe(0);
});
it("allows correction of a mistyped expert-entered age when inquiry age is unknown", async () => {
const { service, claim, blame, id } = setup();
delete blame.parties[0].vehicle.inquiry;
await service.upsertPriceDropV2(
id,
{ vehicleAge: 12, manualPriceDrop: 0 },
{},
);
expect(claim.evaluation.priceDrop.eligible).toBe(false);
await service.upsertPriceDropV2(
id,
{ vehicleAge: 10, manualPriceDrop: 99 },
{},
);
expect(claim.evaluation.priceDrop).toMatchObject({
eligible: true,
vehicleAge: 10,
total: 99,
});
});
});
@@ -285,6 +285,13 @@ export class ClaimDetailV2ResponseDto {
signedAt?: Date | string;
};
priceDrop?: {
eligible?: boolean;
exclusionReason?: string;
manualOverride?: boolean;
calculationVersion?: string;
vehicleAge?: number;
fanavaranAgeId?: number;
accidentYear?: number;
total?: number;
carPrice?: number;
carModel?: number;
@@ -5,6 +5,8 @@ import {
IsInt,
IsNotEmpty,
IsNumber,
Min,
Max,
IsOptional,
IsString,
ValidateNested,
@@ -26,6 +28,17 @@ export class PriceDropPartSeverityV2Dto {
})
@IsIn(["Minor", "Moderate", "Severe"])
severity: PriceDropSeverity;
@ApiPropertyOptional({
description:
"Price-drop category code from priceDropCatalog (1–17), NOT a tenant car-component ID. Expert selection overrides a suggested mapping.",
example: 14,
})
@IsOptional()
@IsInt()
@Min(1)
@Max(17)
fanavaranPartId?: number;
}
export class UpsertClaimPriceDropV2Dto {
@@ -42,11 +55,12 @@ export class UpsertClaimPriceDropV2Dto {
@IsString()
carModel?: string;
@ApiProperty({
@ApiPropertyOptional({
example: 450000000,
description: "Market price of the car (Toman)",
description:
"Market price of the damaged car in Rials. Required for calculation; optional for manual override.",
})
carPrice: number | string;
carPrice?: number | string;
@ApiPropertyOptional({
example: 1394,
@@ -57,15 +71,27 @@ export class UpsertClaimPriceDropV2Dto {
@IsNumber()
carModelYear?: number;
@ApiProperty({
@ApiPropertyOptional({
description:
"Vehicle age at the accident. Ages above ten are ineligible for depreciation, including manual overrides, and save zero. Otherwise derived from Jalali accident year minus model year.",
minimum: 0,
example: 3,
})
@IsOptional()
@IsInt()
@Min(0)
vehicleAge?: number;
@ApiPropertyOptional({
type: [PriceDropPartSeverityV2Dto],
description:
"One row per damaged part on the claim; coefficients come from the price-drop table × severity.",
})
@IsOptional()
@IsArray()
@ValidateNested({ each: true })
@Type(() => PriceDropPartSeverityV2Dto)
partSeverities: PriceDropPartSeverityV2Dto[];
partSeverities?: PriceDropPartSeverityV2Dto[];
@ApiPropertyOptional({
description:
@@ -94,6 +120,42 @@ export class ClaimPriceDropContextV2Dto {
})
suggestedCarModelYear?: number | null;
@ApiPropertyOptional()
accidentYear?: number | null;
@ApiPropertyOptional()
suggestedVehicleAge?: number | null;
@ApiPropertyOptional()
inquiryVehicleAge?: number | null;
@ApiPropertyOptional({
description:
"False when the damaged vehicle is older than ten at the accident.",
})
depreciationEligible?: boolean | null;
@ApiPropertyOptional()
ineligibilityReason?: string | null;
@ApiProperty()
calculationVersion: string;
@ApiProperty()
ageTableEffectiveFrom: string;
@ApiPropertyOptional()
calculationUnavailableReason?: string | null;
@ApiProperty({
description: "Fanavaran age codes and coefficients for ages 0–10",
})
ageCatalog: Array<{
vehicleAge: number;
fanavaranAgeId: number;
coefficient: number;
}>;
@ApiPropertyOptional()
priceDrop?: Record<string, unknown>;
+4 -4
View File
@@ -50,7 +50,7 @@ export class PartPricingV2Dto {
@ApiProperty({
enum: TypeOfDamage,
description: "'change' requires price; 'repair' may omit it.",
description: "Replacement requires a part price unless factorNeeded=true. Repairs cannot request a part invoice.",
})
@IsEnum(TypeOfDamage)
typeOfDamage: TypeOfDamage;
@@ -58,11 +58,11 @@ export class PartPricingV2Dto {
@ApiPropertyOptional({
example: "5000000",
description:
"Required for change lines; omitted for repair lines. Every supplied amount must be between 1,000,000 and 100,000,000,000 Rial.",
"Required for priced replacement lines; omit for repair lines and replacement lines awaiting an invoice (factorNeeded=true). Every supplied amount must be between 1,000,000 and 100,000,000,000 Rial.",
})
@ValidateIf(
(part: PartPricingV2Dto) =>
part.typeOfDamage === TypeOfDamage.Change ||
(part.typeOfDamage === TypeOfDamage.Change && part.factorNeeded !== true) ||
(part.price != null &&
(typeof part.price !== 'string' || part.price.trim() !== '')),
)
@@ -106,7 +106,7 @@ export class PartPricingV2Dto {
@ApiProperty({
example: false,
description:
"If true, the owner must upload a repair factor image for this line; expert confirms cost later (validate-factors). Priced lines omit this or set false.",
"Replacement lines only: if true, the owner uploads the part invoice and the expert confirms its cost later (validate-factors). Omit price in this mode. Repair lines must set false.",
})
@IsBoolean()
factorNeeded: boolean;
+11 -8
View File
@@ -2,13 +2,15 @@ import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import {
IsArray,
ArrayMinSize,
ArrayUnique,
IsEnum,
IsInt,
IsOptional,
IsString,
ValidateNested,
} from "class-validator";
import { IsRepairLineAmountToman } from "src/common/validators/repair-line-amount-toman.validator";
import { IsMoneyAmountString } from "src/common/validators/money-amount-string.validator";
import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum";
class FactorDecisionDto {
@@ -51,35 +53,36 @@ class FactorDecisionV2Dto {
@ApiPropertyOptional({
description:
"Part price (Toman). With totalPayment or price+salary for APPROVED/REJECTED factor lines. Use 0 if unused.",
"Part price (Rial). With totalPayment or price+salary for APPROVED/REJECTED factor lines. Use 0 if unused.",
})
@IsOptional()
@IsString()
@IsRepairLineAmountToman({ allowZero: true })
@IsMoneyAmountString()
price?: string;
@ApiPropertyOptional({
description:
"Salary in Toman. Send with price when not using only totalPayment. Use 0 if unused.",
"Salary in Rial. Send with price when not using only totalPayment. Use 0 if unused.",
})
@IsOptional()
@IsString()
@IsRepairLineAmountToman({ allowZero: true })
@IsMoneyAmountString()
salary?: string;
@ApiPropertyOptional({
description:
"Line total in Toman; or send both price and salary.",
description: "Line total in Rial; or send both price and salary.",
})
@IsOptional()
@IsString()
@IsRepairLineAmountToman()
@IsMoneyAmountString()
totalPayment?: string;
}
export class FactorValidationV2Dto {
@ApiProperty({ type: [FactorDecisionV2Dto] })
@IsArray()
@ArrayMinSize(1)
@ArrayUnique((decision: FactorDecisionV2Dto) => decision.partId)
@ValidateNested({ each: true })
@Type(() => FactorDecisionV2Dto)
decisions: FactorDecisionV2Dto[];
@@ -84,6 +84,24 @@ const validV2Reply = {
};
describe("ExpertClaimService expert-reply pricing", () => {
it("saves a replacement invoice without a part price and enters the invoice upload workflow", async () => {
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(BlameRequestType.THIRD_PARTY);
const response = await service.submitExpertReplyV2("v2-claim", { parts: [{ partId: 1, typeOfDamage: TypeOfDamage.Change, salary: "1000000", totalPayment: "1000000", factorNeeded: true, daghi: { option: DaghiOption.NO_VALUE } }] }, { sub: V2_EXPERT_ID, role: RoleEnum.FIELD_EXPERT });
expect(response).toMatchObject({ factorNeeded: true, allPartsFactorNeeded: true, currentStep: "OWNER_UPLOAD_FACTOR_DOCUMENTS" });
const saved = findByIdAndUpdate.mock.calls[0][1]["evaluation.damageExpertReply"].parts[0];
expect(saved.factorNeeded).toBe(true);
expect(saved.price).toBeUndefined();
});
it("a failed invoice/repair submission cannot persist flags or poison a subsequent priced repair", async () => {
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(BlameRequestType.THIRD_PARTY);
const actor = { sub: V2_EXPERT_ID, role: RoleEnum.FIELD_EXPERT };
await expect(service.submitExpertReplyV2("v2-claim", { parts: [{ ...validV2Reply.parts[0], factorNeeded: true }] }, actor)).rejects.toMatchObject({ response: { field: "parts[0].factorNeeded" } });
expect(findByIdAndUpdate).not.toHaveBeenCalled();
const response = await service.submitExpertReplyV2("v2-claim", validV2Reply, actor);
expect(response.factorNeeded).toBe(false);
expect(findByIdAndUpdate.mock.calls[0][1]["evaluation.damageExpertReply"].parts[0].factorNeeded).toBe(false);
});
it("requires the current car price for a car-body expert reply", async () => {
const { service, findByIdAndUpdate } = setupSuccessfulV2Submit(
BlameRequestType.CAR_BODY,
+302 -145
View File
@@ -55,9 +55,18 @@ import {
buildDamagedPartsPriceDropLines,
buildPriceDropCatalogForApi,
calculateClaimPriceDrop,
calculatePriceDropForVehicleAge,
parsePriceDropNumber,
PRICE_DROP_SEVERITY_OPTIONS,
resolveVehicleModelYearFromBlame,
resolvePriceDropAccidentYear,
resolvePriceDropAccidentDate,
normalizePriceDropSelectedParts,
resolveClaimPriceDropAge,
buildAgeIneligiblePriceDrop,
PRICE_DROP_AGE_INELIGIBLE_MESSAGE,
} from "src/helpers/claim-price-drop";
import { FANAVARAN_PRICE_DROP_AGES, FANAVARAN_PRICE_DROP_VERSION, FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM } from "src/static/fanavaran-price-drop";
import {
claimCaseStatusAfterExpertReplyV2,
claimIsAwaitingExpertFactorValidationV2,
@@ -980,7 +989,7 @@ export class ExpertClaimService {
if (!claimIsAwaitingExpertFactorValidationV2(claim)) {
throw new BadRequestException(
"Claim is not awaiting expert factor validation (UNDER_REVIEW at EXPERT_COST_EVALUATION).",
"پرونده در مرحله بررسی فاکتور توسط کارشناس نیست. وضعیت پرونده را دوباره دریافت کنید.",
);
}
@@ -993,76 +1002,160 @@ export class ExpertClaimService {
: claim.evaluation?.damageExpertReply;
if (!finalReply?.parts?.length) {
throw new BadRequestException("No expert reply found in this claim.");
throw new BadRequestException("پاسخ کارشناسی برای بررسی فاکتور در این پرونده یافت نشد.");
}
const requiredFactors = finalReply.parts.filter((p) => p.factorNeeded);
if (requiredFactors.length === 0) {
throw new BadRequestException("No parts require factor validation.");
throw new BadRequestException("در این پاسخ کارشناسی قطعه‌ای نیازمند بررسی فاکتور نیست.");
}
if (!requiredFactors.every((p) => !!p.factorLink)) {
throw new BadRequestException(
"Not all required factors have been uploaded yet.",
"هنوز همه فاکتورهای موردنیاز بارگذاری نشده‌اند.",
);
}
if (!Array.isArray(body.decisions) || body.decisions.length === 0) {
throw new BadRequestException("حداقل یک فاکتور را بررسی کنید.");
}
const $set: Record<string, unknown> = {};
const seen = new Set<string>();
const proposedParts = finalReply.parts.map((part: any) => ({
...(typeof part.toObject === "function" ? part.toObject() : part),
}));
for (const decision of body.decisions) {
const partIndex = finalReply.parts.findIndex((p) =>
sameCatalogPartId(p.partId, decision.partId),
const partIndex = proposedParts.findIndex((part) =>
sameCatalogPartId(part.partId, decision.partId),
);
if (partIndex === -1) {
this.logger.warn(
`Part ${decision.partId} not found in claim ${claimRequestId}, skipping.`,
const id = String(decision.partId);
if (seen.has(id))
throw new BadRequestException(
"برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید.",
);
continue;
}
const part = finalReply.parts[partIndex];
if (!part.factorNeeded) {
this.logger.warn(
`Part ${decision.partId} is not factor-needed, skipping.`,
seen.add(id);
if (partIndex < 0 || !proposedParts[partIndex].factorNeeded) {
throw new BadRequestException(
"قطعه انتخاب‌شده در فهرست فاکتورهای موردنیاز پرونده وجود ندارد.",
);
continue;
}
const base = `evaluation.${replyField}.parts.${partIndex}`;
$set[`${base}.factorStatus`] = decision.status;
$set[`${base}.rejectionReason`] = decision.rejectionReason ?? null;
if (decision.price !== undefined) {
$set[`${base}.price`] = decision.price;
}
if (decision.salary !== undefined) {
$set[`${base}.salary`] = decision.salary;
}
if (decision.totalPayment !== undefined) {
$set[`${base}.totalPayment`] = decision.totalPayment;
}
if (
decision.status === FactorStatus.APPROVED ||
decision.status === FactorStatus.REJECTED
![FactorStatus.APPROVED, FactorStatus.REJECTED].includes(
decision.status,
)
) {
if (!this.expertFactorValidationDecisionHasLinePricing(decision)) {
throw new BadRequestException(
"نتیجه بررسی فاکتور باید تأیید یا عدم تأیید باشد.",
);
}
if (
decision.status === FactorStatus.REJECTED &&
!String(decision.rejectionReason ?? "").trim()
) {
throw new BadRequestException("دلیل عدم تأیید فاکتور را وارد کنید.");
}
const providedTotal =
decision.totalPayment != null &&
String(decision.totalPayment).trim() !== "";
const price = parseMoneyAmountToman(decision.price);
const salary = parseMoneyAmountToman(decision.salary);
const lineTotal = providedTotal
? parseMoneyAmountToman(decision.totalPayment)
: price != null && salary != null
? price + salary
: NaN;
if (
!this.expertFactorValidationDecisionHasLinePricing(decision) ||
!Number.isSafeInteger(lineTotal) ||
lineTotal < 1_000_000 ||
lineTotal > 100_000_000_000
) {
throw new BadRequestException(
"مبلغ نهایی قطعه با احتساب اجرت باید بین ۱٬۰۰۰٬۰۰۰ و ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
);
}
const base = `evaluation.${replyField}.parts.${partIndex}`;
const updates: Record<string, unknown> = {
factorStatus: decision.status,
rejectionReason:
decision.status === FactorStatus.REJECTED
? decision.rejectionReason.trim()
: null,
totalPayment: String(lineTotal),
};
for (const field of ["price", "salary"] as const) {
if (decision[field] === undefined) continue;
const amount = parseMoneyAmountToman(decision[field]);
if (
!Number.isSafeInteger(amount) ||
amount < 0 ||
amount > 100_000_000_000
) {
throw new BadRequestException(
`Part ${decision.partId}: ${decision.status === FactorStatus.APPROVED ? "approved" : "rejected"} factor lines require expert totalPayment (or both price and salary).`,
"قیمت قطعه و اجرت باید مبلغ صحیح و نامنفی به ریال باشند.",
);
}
updates[field] = String(amount);
}
Object.assign(proposedParts[partIndex], updates);
for (const [field, value] of Object.entries(updates))
$set[`${base}.${field}`] = value;
}
const reqParts = proposedParts.filter((part) => part.factorNeeded);
const anyRejected = reqParts.some(
(part) => part.factorStatus === FactorStatus.REJECTED,
);
const anyStillPending = reqParts.some(
(part) =>
!part.factorStatus || part.factorStatus === FactorStatus.PENDING,
);
if (!anyStillPending) {
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null &&
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
? configuredPriceCap
: null;
if (priceCap !== null) {
let totalPrice = 0;
for (const part of proposedParts || []) {
const line = this.claimReplyPartLineTotalForCap(part);
if (isNaN(line)) {
throw new BadRequestException({
message: `مبلغ قطعه ${String(part.partId ?? "")} معتبر نیست. مبلغ نهایی یا قیمت قطعه و اجرت را ثبت کنید.`,
error: "PRICE_CAP_ERROR",
});
}
totalPrice += line;
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `مجموع مبلغ قطعات و فاکتورها (${totalPrice.toLocaleString("fa-IR")} ریال) از سقف مجاز پرونده (${priceCap.toLocaleString("fa-IR")} ریال) بیشتر است.`,
error: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
}
}
}
if (Object.keys($set).length === 0) {
throw new BadRequestException("No valid factor decisions to apply.");
}
if (factorValidationSnapshot) {
if (factorValidationSnapshot)
$set["evaluation.factorValidationExpertProfileSnapshot"] =
factorValidationSnapshot;
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set,
});
const updatedClaim = await this.claimCaseDbService.findOneAndUpdate(
{
_id: claim._id,
status: claim.status,
claimStatus: claim.claimStatus,
"workflow.currentStep": claim.workflow.currentStep,
...((claim as any).updatedAt != null
? { updatedAt: (claim as any).updatedAt }
: { [`evaluation.${replyField}.parts`]: finalReply.parts }),
},
{ $set },
);
if (!updatedClaim)
throw new ConflictException(
"اطلاعات فاکتورها هنگام بررسی تغییر کرده است. پرونده را دوباره دریافت و تلاش کنید.",
);
await this.recordClaimExpertActivity({
expertId: String(actor.sub),
tenantId: this.claimActivityTenantId(claim, actor),
@@ -1070,59 +1163,15 @@ export class ExpertClaimService {
eventType: ExpertFileActivityType.CHECKED,
idempotencyKey: `claim:${claimRequestId}:checked:${actor.sub}`,
});
const updatedClaim = await this.claimCaseDbService.findById(claimRequestId);
const updatedReply =
replyField === "damageExpertReplyFinal"
? updatedClaim!.evaluation!.damageExpertReplyFinal!
: updatedClaim!.evaluation!.damageExpertReply!;
const reqParts = updatedReply.parts.filter((p) => p.factorNeeded);
const anyRejected = reqParts.some(
(p) => p.factorStatus === FactorStatus.REJECTED,
);
const anyStillPending = reqParts.some(
(p) => !p.factorStatus || p.factorStatus === FactorStatus.PENDING,
);
const baseMessage = "Factor validation updated.";
if (anyStillPending) {
if (anyStillPending)
return {
message: `${baseMessage} Some factors are still pending review.`,
message:
"نتیجه بررسی فاکتور ثبت شد. فاکتورهای باقی‌مانده را نیز بررسی کنید.",
claimRequestId,
claimStatus: updatedClaim!.claimStatus,
caseStatus: updatedClaim!.status,
claimStatus: updatedClaim.claimStatus,
caseStatus: updatedClaim.status,
pendingFactorValidation: true,
};
}
const configuredPriceCap = getClaimV2TotalPaymentCapToman();
const priceCap =
configuredPriceCap !== null &&
claimPriceCapAppliesToBlame(await this.loadBlameForClaim(claim))
? configuredPriceCap
: null;
if (priceCap !== null) {
let totalPrice = 0;
for (const part of updatedReply.parts || []) {
const line = this.claimReplyPartLineTotalForCap(part);
if (isNaN(line)) {
throw new BadRequestException({
message: `Part ${String(part.partId ?? "")}: invalid amount for price total — use totalPayment or price and salary.`,
error: "PRICE_CAP_ERROR",
});
}
totalPrice += line;
}
if (totalPrice > priceCap) {
throw new BadRequestException({
message: `You have reached the maximum acceptable total price (Rial). The sum of priced parts and factor lines (${totalPrice.toLocaleString()}) exceeds the limit (${priceCap.toLocaleString()}).`,
error: "PRICE_CAP_ERROR",
totalPrice,
priceCap,
});
}
}
const historyActor = {
actorId: new Types.ObjectId(actor.sub),
@@ -1374,7 +1423,15 @@ export class ExpertClaimService {
: null;
const blameStatus = (reviewerBlame as any).status as string;
if (blameStatus === "WAITING_FOR_FILE_REVIEWER") {
const isReviewerCapturePhase = [
ClaimCaseStatus.CREATED,
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
ClaimCaseStatus.SELECTING_OUTER_PARTS,
ClaimCaseStatus.SELECTING_OTHER_PARTS,
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
].includes(claim.status as ClaimCaseStatus);
if (blameStatus === "WAITING_FOR_FILE_REVIEWER" && isReviewerCapturePhase) {
if (assignedReviewerId && assignedReviewerId === actor.sub) {
// Phase 1 is intentionally idempotent. The linked claim can still be
// in a data-capture status here, so falling through to the damage
@@ -1417,7 +1474,8 @@ export class ExpertClaimService {
const isFactorValidationLock =
claimIsAwaitingExpertFactorValidationV2(claim);
const isDamageReviewLock =
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT ||
claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING;
const isExpertReviewingReentry =
claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
const isResendPending =
@@ -1612,7 +1670,7 @@ export class ExpertClaimService {
assignFilter.initiatedByFieldExpertId = expertOid;
assignFilter.status = claim.status;
} else {
assignFilter.status = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
assignFilter.status = claim.status;
}
const updated = await this.claimCaseDbService.findOneAndUpdate(
@@ -1798,7 +1856,7 @@ export class ExpertClaimService {
if (existingResend?.fulfilledAt) {
throw new BusinessRuleException(
BusinessErrorCode.DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED,
"The owner has already fulfilled a damage-expert resend for this claim. You cannot request another resend.",
"کاربر درخواست قبلی تکمیل اطلاعات را انجام داده است. برای این پرونده امکان درخواست مجدد وجود ندارد؛ پاسخ کارشناسی را ثبت کنید یا مراجعه حضوری درخواست دهید.",
);
}
@@ -1842,6 +1900,7 @@ export class ExpertClaimService {
"workflow.currentStep": ClaimWorkflowStep.USER_EXPERT_RESEND,
"workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
"evaluation.damageExpertResend": {
requestedAt: new Date(),
resendDescription: desc || undefined,
resendDocuments: uniqueDocs,
resendCarParts: normalizedParts,
@@ -2338,7 +2397,7 @@ export class ExpertClaimService {
* - Status must be EXPERT_REVIEWING
*
* On success:
* - Sets status = EXPERT_REVIEWING (remains), claimStatus = NEEDS_REVISION
* - Sets status = IN_PERSON_VISIT_PENDING, claimStatus = NEEDS_REVISION
* - Sets evaluation.visitLocation (optional note)
* - Records history event IN_PERSON_VISIT_REQUESTED
* - Unlocks the workflow so user can act
@@ -2355,7 +2414,7 @@ export class ExpertClaimService {
throw new NotFoundException("Claim request not found");
}
assertClaimCaseForTenant(claim, actor);
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
@@ -2377,7 +2436,7 @@ export class ExpertClaimService {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
claimStatus: ClaimStatus.NEEDS_REVISION,
status: ClaimCaseStatus.COMPLETED,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
"workflow.locked": false,
$unset: {
"workflow.lockedAt": "",
@@ -2385,7 +2444,7 @@ export class ExpertClaimService {
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
},
...(note ? { "evaluation.visitLocation": note } : {}),
"evaluation.visitLocation": note?.trim() || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
...(visitSnapshot && {
"evaluation.inPersonVisitExpertProfileSnapshot": visitSnapshot,
}),
@@ -2415,7 +2474,7 @@ export class ExpertClaimService {
return {
claimRequestId,
status: ClaimCaseStatus.COMPLETED,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
claimStatus: ClaimStatus.NEEDS_REVISION,
message: "In-person visit requested. User will be notified.",
};
@@ -2635,7 +2694,7 @@ export class ExpertClaimService {
{
_id: { $in: blameIds.map((id) => new Types.ObjectId(id)) },
},
{ lean: true, select: "status publicId" },
{ lean: true, select: "status publicId type" },
)) as any[])
: [];
const blameById = new Map<string, any>(
@@ -3856,7 +3915,8 @@ export class ExpertClaimService {
new Map(blameLean ? [[String(claim.blameRequestId), blameLean]] : []),
);
const vehiclePayload = {
...((claim.vehicle as any) ?? {}),
...(typeof (claim.vehicle as any)?.toObject === "function"
? (claim.vehicle as any).toObject() : (claim.vehicle ?? {})),
...resolvedVehicle,
};
@@ -3916,6 +3976,9 @@ export class ExpertClaimService {
let evaluationForApi: Record<string, unknown> | undefined;
if (enrichedEvaluation) {
if (blameFileContext.blameRequestType === BlameRequestType.CAR_BODY) {
delete enrichedEvaluation.priceDrop;
}
evaluationForApi = {};
// damageExpertReply / damageExpertReplyFinal: include whenever present.
// Previously these were gated on isFactorValidationPending, which hid the
@@ -4012,6 +4075,18 @@ export class ExpertClaimService {
};
}
async assertCanSignFanavaranClaim(id: string, actor: any) {
if (!Types.ObjectId.isValid(id)) throw new BadRequestException("شناسه پرونده معتبر نیست.");
const roles = [
RoleEnum.DAMAGE_EXPERT, RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER, RoleEnum.REGISTRAR,
];
if (!actor?.sub || !roles.includes(actor.role)) {
throw new ForbiddenException("فقط کارشناس مجاز پرونده می‌تواند آن را امضا کند.");
}
await this.getClaimDetailV2(id, actor);
}
private asFanavaranLookupRows(value: unknown): Array<Record<string, any>> {
if (Array.isArray(value)) return value as Array<Record<string, any>>;
if (value && typeof value === "object") {
@@ -4109,9 +4184,13 @@ export class ExpertClaimService {
await this.getClaimDetailV2(claimRequestId, actor);
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) throw new NotFoundException("Claim request not found");
if (claim.claimId != null || claim.claimNo != null) {
const baseSent = claim.claimId != null || claim.claimNo != null;
// Recover cases created before base submission required vehicle approval.
// Never change an approved snapshot or classification already sent downstream.
if (baseSent && ((claim as any).fanavaranVehicleReview?.approved === true ||
claim.dmgCaseId != null || claim.expertiseId != null)) {
throw new ConflictException(
"Vehicle classification cannot be changed after the claim was sent to Fanavaran.",
"مشخصات تأییدشده خودرو پس از ارسال به فناوران قابل تغییر نیست.",
);
}
const fields =
@@ -4198,8 +4277,11 @@ export class ExpertClaimService {
const updated = await this.claimCaseDbService.findOneAndUpdate(
{
_id: claimRequestId,
claimId: null,
claimNo: null,
claimId: claim.claimId ?? null,
claimNo: claim.claimNo ?? null,
dmgCaseId: claim.dmgCaseId ?? null,
expertiseId: claim.expertiseId ?? null,
fanavaranVehicleReview: (claim as any).fanavaranVehicleReview ?? null,
...(fields?.filter ?? {}),
},
{
@@ -4421,6 +4503,12 @@ export class ExpertClaimService {
return { version: fields.review.version };
}
private assertPriceDropProduct(type: unknown) {
if (type === BlameRequestType.CAR_BODY) {
throw new BadRequestException("افت قیمت برای پرونده بیمه بدنه قابل ثبت نیست.");
}
}
/** V2 price-drop: claim locked by this expert during damage assessment. */
private async assertExpertCanEditClaimDuringReviewV2(
claim: any,
@@ -4454,29 +4542,40 @@ export class ExpertClaimService {
await this.assertExpertCanEditClaimDuringReviewV2(claim, actor);
const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
const selectedNorm = normalizeDamageSelectedParts(
const selectedNorm = normalizePriceDropSelectedParts(
claim.damage?.selectedParts,
carType,
(claim.damage as any)?.selectedOuterParts,
);
let suggestedCarModelYear: number | null = null;
let accidentYear: number | null = null;
let calculationUnavailableReason: string | null = null;
if (claim.blameRequestId) {
const blameRows = await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{
lean: true,
select: "parties.role parties.person.userId parties.vehicle.inquiry",
select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate",
},
);
const blame = blameRows[0] as Record<string, unknown> | undefined;
this.assertPriceDropProduct(blame?.type);
suggestedCarModelYear = resolveVehicleModelYearFromBlame(
claim,
blame as Parameters<typeof resolveVehicleModelYearFromBlame>[1],
);
accidentYear = resolvePriceDropAccidentYear(blame);
const accidentDate = resolvePriceDropAccidentDate(blame);
if (accidentDate && accidentDate < FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM) {
calculationUnavailableReason = "جدول سن ارسالی فناوران از ۱۴۰۴/۰۵/۲۸ معتبر است. برای حادثه پیش از این تاریخ مبلغ افت قیمت را دستی ثبت کنید.";
}
}
const existing = (claim as any).evaluation?.priceDrop;
const knownAges = [existing?.vehicleAge, suggestedCarModelYear != null && accidentYear != null ? accidentYear - suggestedCarModelYear : null]
.filter(age => Number.isInteger(age) && age >= 0);
const vehicleAge = knownAges.some(age => age > 10) ? Math.max(...knownAges) : existing?.vehicleAge ?? knownAges[0] ?? null;
return {
claimRequestId: String(claim._id),
@@ -4486,6 +4585,17 @@ export class ExpertClaimService {
carType: claim.vehicle?.carType,
},
suggestedCarModelYear,
accidentYear,
suggestedVehicleAge: vehicleAge,
inquiryVehicleAge: suggestedCarModelYear != null && accidentYear != null ? accidentYear - suggestedCarModelYear : null,
depreciationEligible: vehicleAge == null ? null : vehicleAge <= 10,
ineligibilityReason: vehicleAge != null && vehicleAge > 10 ? PRICE_DROP_AGE_INELIGIBLE_MESSAGE : null,
calculationVersion: FANAVARAN_PRICE_DROP_VERSION,
ageTableEffectiveFrom: FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM,
calculationUnavailableReason,
ageCatalog: FANAVARAN_PRICE_DROP_AGES.map(row => ({
vehicleAge: row.age, fanavaranAgeId: row.id, coefficient: row.coefficient,
})),
priceDrop: existing ?? null,
severityOptions: PRICE_DROP_SEVERITY_OPTIONS,
priceDropCatalog: buildPriceDropCatalogForApi(),
@@ -4515,18 +4625,72 @@ export class ExpertClaimService {
vehicleSet["vehicle.carModel"] = String(body.carModel).trim();
}
let carModelYear = body.carModelYear;
if (carModelYear != null && (!Number.isInteger(carModelYear) || carModelYear < 1300 || carModelYear >= 1500)) {
throw new BadRequestException("سال ساخت باید یک سال شمسی معتبر باشد؛ برای سال میلادی، سن خودرو در زمان حادثه را وارد کنید.");
}
let accidentYear: number | null = null;
let blame: any = null;
let accidentDate: string | null = null;
if (claim.blameRequestId) {
const blameRows = await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{
lean: true,
select: "type expert.decision.guiltyPartyId parties.role parties.person.userId parties.vehicle parties.statement.accidentDate",
},
);
this.assertPriceDropProduct(blameRows[0]?.type);
carModelYear ??=
resolveVehicleModelYearFromBlame(
claim,
blameRows[0] as Parameters<
typeof resolveVehicleModelYearFromBlame
>[1],
) ?? undefined;
blame = blameRows[0];
accidentYear = resolvePriceDropAccidentYear(blame);
accidentDate = resolvePriceDropAccidentDate(blame);
}
if (body.vehicleAge != null && (!Number.isInteger(body.vehicleAge) || body.vehicleAge < 0)) {
throw new BadRequestException("سن خودرو در زمان حادثه باید عددی صحیح و نامنفی باشد.");
}
const enteredAge = body.vehicleAge ?? (carModelYear != null && accidentYear != null ? accidentYear - carModelYear : undefined);
const vehicleAge = resolveClaimPriceDropAge(claim, blame, enteredAge);
if (vehicleAge != null && vehicleAge > 10) {
if (body.manualPriceDrop != null && body.manualPriceDrop !== 0) {
throw new BadRequestException(PRICE_DROP_AGE_INELIGIBLE_MESSAGE);
}
const priceDrop = {
...buildAgeIneligiblePriceDrop(vehicleAge, body.carPrice ?? (claim as any).evaluation?.priceDrop?.carPrice),
manualOverride: false,
partLines: [],
...(accidentYear != null ? { accidentYear } : {}),
...(carModelYear != null ? { carModel: carModelYear } : {}),
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: { ...vehicleSet, "evaluation.priceDrop": priceDrop },
});
return { claimRequestId, vehicle: claim.vehicle, priceDrop, partLines: [] };
}
// Manual override path — expert knows the number, skip calculation entirely
if (body.manualPriceDrop != null) {
if (!Number.isFinite(body.manualPriceDrop) || body.manualPriceDrop < 0) {
if (!Number.isSafeInteger(body.manualPriceDrop) || body.manualPriceDrop < 0) {
throw new BadRequestException(
"manualPriceDrop must be a non-negative finite number.",
"مبلغ افت قیمت باید عددی صحیح و نامنفی به ریال باشد.",
);
}
// Manual path — change totalPriceDrop → total to match calculated path
if (body.manualPriceDrop > 0 && vehicleAge == null) {
throw new BadRequestException("برای ثبت افت قیمت، سن خودرو در زمان حادثه را مشخص کنید.");
}
const manualPayload = {
...(vehicleAge != null ? { vehicleAge, eligible: true } : {}),
manualOverride: true,
total: body.manualPriceDrop, // ← was totalPriceDrop
total: parsePriceDropNumber(body.manualPriceDrop),
carPrice: body.carPrice != null ? parsePriceDropNumber(body.carPrice)
: (claim as any).evaluation?.priceDrop?.carPrice,
partLines: [],
};
@@ -4550,8 +4714,11 @@ export class ExpertClaimService {
};
}
// Calculated path — existing logic unchanged
// At the top of the calculated path, after the manualPriceDrop early return:
if (accidentDate && accidentDate < FANAVARAN_PRICE_DROP_AGE_EFFECTIVE_FROM) {
throw new BadRequestException("جدول سن ارسالی فناوران از ۱۴۰۴/۰۵/۲۸ معتبر است. برای حادثه پیش از این تاریخ مبلغ افت قیمت را دستی ثبت کنید.");
}
// An explicit part list is required when replacing a manual correction.
const existingPriceDrop = (claim as any).evaluation?.priceDrop;
if (
existingPriceDrop?.manualOverride === true &&
@@ -4564,38 +4731,24 @@ export class ExpertClaimService {
}
const carType = claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
const selectedNorm = normalizeDamageSelectedParts(
const selectedNorm = normalizePriceDropSelectedParts(
claim.damage?.selectedParts,
carType,
(claim.damage as any)?.selectedOuterParts,
);
if (!body.partSeverities?.length) {
if (!Array.isArray(body.partSeverities) || !body.partSeverities.length) {
throw new BadRequestException(
"Provide at least one partSeverities line, or use manualPriceDrop for a direct override.",
"شدت آسیب حداقل یک قطعه را انتخاب کنید یا مبلغ نهایی افت قیمت را دستی ثبت کنید.",
);
}
if (body.partSeverities.some(p => !p || typeof p !== "object")) {
throw new BadRequestException("فهرست قطعات افت قیمت معتبر نیست. گروه قطعات و شدت آسیب را دوباره انتخاب کنید.");
}
let carModelYear = body.carModelYear;
if (carModelYear == null && claim.blameRequestId) {
const blameRows = await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{
lean: true,
select: "parties.role parties.person.userId parties.vehicle.inquiry",
},
);
carModelYear =
resolveVehicleModelYearFromBlame(
claim,
blameRows[0] as Parameters<
typeof resolveVehicleModelYearFromBlame
>[1],
) ?? undefined;
}
if (carModelYear == null || !Number.isFinite(carModelYear)) {
if (body.vehicleAge == null && (carModelYear == null || accidentYear == null)) {
throw new BadRequestException(
"carModelYear is required when it cannot be resolved from the linked blame plate inquiry.",
"سن خودرو در زمان حادثه را وارد کنید؛ سال ساخت یا تاریخ حادثه برای محاسبه سن در دسترس نیست.",
);
}
@@ -4604,6 +4757,7 @@ export class ExpertClaimService {
body.partSeverities.map((p) => ({
partId: p.partId,
severity: p.severity,
fanavaranPartId: p.fanavaranPartId,
})),
carType,
);
@@ -4616,14 +4770,17 @@ export class ExpertClaimService {
);
}
const calculated = calculateClaimPriceDrop(
body.carPrice,
carModelYear,
coefficients,
);
const calculated = body.vehicleAge != null
? {
...calculatePriceDropForVehicleAge(body.carPrice, body.vehicleAge, coefficients),
...(carModelYear != null ? { carModel: carModelYear } : {}),
...(accidentYear != null ? { accidentYear } : {}),
}
: calculateClaimPriceDrop(body.carPrice, carModelYear!, coefficients, accidentYear!);
const priceDropPayload = {
...calculated,
manualOverride: false,
partLines: lines,
};
@@ -1,3 +1,4 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import { AiPricingRequestDto } from "src/ai/ai-pricing-request.dto";
import { ValidationPipe } from "@nestjs/common";
import { AiService } from "src/ai/ai.service";
@@ -68,6 +69,7 @@ class InPersonVisitV2Dto {
}
@ApiTags("expert-claim-panel (v2)")
@EnforceCaseWorkingHours()
@Controller("v2/expert-claim")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@@ -277,7 +279,7 @@ export class ExpertClaimV2Controller {
@ApiOperation({
summary: "Price-drop context for manual expert entry (V2)",
description:
"While the claim is locked in EXPERT_REVIEWING: severity labels (جزیی / متوسط / شدید), coefficient catalog, damaged parts with price-drop mapping, suggested Jalali year from linked blame plate inquiry (`ModelField` / `ModelCii`), and saved `evaluation.priceDrop` if any.",
"While locked in EXPERT_REVIEWING: Fanavaran depreciation categories, severity/age codes and coefficients, suggested mappings for selected damaged parts, damaged vehicle model year, accident year, suggested vehicle age, and saved evaluation.priceDrop. Part/category codes are separate from tenant car-component IDs.",
})
@ApiParam({ name: "claimRequestId" })
@ApiResponse({ status: 200, type: ClaimPriceDropContextV2Dto })
@@ -295,7 +297,7 @@ export class ExpertClaimV2Controller {
@ApiOperation({
summary: "Calculate and save price drop (V2)",
description:
"Expert supplies car market price, optional `vehicle.carName` / `vehicle.carModel`, per-damaged-part severity (`partId` from claim detail), and optional `carModelYear` (defaults from blame inquiry). Persists `evaluation.priceDrop` using `(carPrice × yearCoefficient × sumOfCoefficients) / 400`.",
"Expert supplies car market price in Rials, vehicleAge at accident or Jalali carModelYear, and per-damaged-part severity with optional explicit Fanavaran category. Ages 0–10 use (carPrice × ageCoefficient × sumOfCoefficients) / 400; vehicles older than ten are ineligible and save zero. Positive manual overrides require an eligible age. Saves category/severity/age codes and preserves historical results until explicitly recalculated.",
})
@ApiParam({ name: "claimRequestId" })
@ApiBody({ type: UpsertClaimPriceDropV2Dto })
@@ -455,7 +457,7 @@ export class ExpertClaimV2Controller {
@ApiBody({ type: FactorValidationV2Dto })
async validateClaimFactorsV2(
@Param("claimRequestId") claimRequestId: string,
@Body() body: FactorValidationV2Dto,
@Body(submitExpertReplyValidationPipe) body: FactorValidationV2Dto,
@CurrentUser() actor,
) {
return await this.expertClaimService.validateClaimFactorsV2(
@@ -173,11 +173,12 @@ describe("Expert Fanavaran stage fields", () => {
management.fanavaranLookupService = {
bodyPolicyById: jest.fn().mockResolvedValue({ TotalPremium: 123456 }),
};
const payload = await management.previewFanavaranSubmitV2(id, clientKey, {
const preview = await management.previewFanavaranSubmitV2(id, clientKey, {
persistPayload: false,
forceRefreshPolicy: false,
requireClaimExpertId: false,
});
const payload = preview.payload ?? preview;
expect(payload.ClaimExpertId).toBe(154);
expect(payload).toMatchObject({
AccidentLocationAddress: "نشانی واقعی",
@@ -747,7 +748,11 @@ describe("Expert Fanavaran stage fields", () => {
it("soft-skips automatic TejaratNo submission until both choices are saved", async () => {
process.env.FANAVARAN_CLIENT = "tejaratno";
const { management, claim } = setup("third-party", {
fanavaranVehicleReview: { approved: true },
fanavaranVehicleReview: {
approved: true,
vehicleGroup: { id: 1 }, vehicleUseType: { id: 1 },
vehicleSystem: { id: 14 }, vehicleKind: { id: 7456 },
},
});
management.blameRequestDbService = {
findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }),
@@ -114,6 +114,56 @@ describe("Fanavaran vehicle review", () => {
expect(service.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled();
});
it("recovers an unreviewed base claim and resumes damage submission", async () => {
const service = makeService();
const claim = { _id: "507f1f77bcf86cd799439012", claimId: 12378660,
damage: { selectedParts: ["front-wing"] } };
service.claimCaseDbService.findById.mockResolvedValue(claim);
service.claimCaseDbService.findOneAndUpdate.mockImplementation((_filter, update) =>
Promise.resolve({ ...claim, fanavaranVehicleReview: update.$set.fanavaranVehicleReview }));
const result = await service.approveFanavaranVehicleReviewV2(claim._id, {
vehicleGroupId: 1, vehicleUseTypeId: 3, vehicleSystemId: 14,
vehicleKindId: 7456, confirmed: true,
}, actor);
expect(result.review.approved).toBe(true);
expect(service.claimCaseDbService.findOneAndUpdate.mock.calls[0][0]).toMatchObject({
claimId: 12378660, dmgCaseId: null, fanavaranVehicleReview: null,
});
expect(service.claimRequestManagementService.autoSubmitFanavaranDamageCaseOnOuterPartsSelected)
.toHaveBeenCalledWith(claim._id, ["front-wing"]);
});
it.each([
{ fanavaranVehicleReview: { approved: true } },
{ dmgCaseId: 42 },
{ expertiseId: 43 },
])("locks submitted classification: %j", async (state) => {
const service = makeService();
service.claimCaseDbService.findById.mockResolvedValue({ claimId: 12378660, ...state });
await expect(service.approveFanavaranVehicleReviewV2("case", {}, actor))
.rejects.toBeInstanceOf(ConflictException);
expect(service.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled();
});
it("blocks a new manual base submission before building or posting its payload", async () => {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) };
service.previewFanavaranSubmitV2 = jest.fn();
await expect(service.executeFanavaranV2Submit("case", "moallem", { PolicyId: 1 }))
.rejects.toMatchObject({ response: { code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED" } });
expect(service.previewFanavaranSubmitV2).not.toHaveBeenCalled();
await expect(service.getFanavaranAutoSubmitSkipReason({})).resolves.toContain("تأیید");
});
it("reuses the existing base without requiring review or creating another base", async () => {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({ claimId: 12378660 }) };
await expect(service.executeFanavaranV2Submit("case", "moallem"))
.resolves.toMatchObject({ Id: 12378660 });
});
it("blocks outbound stages until all four values are approved", () => {
const service = Object.create(
ClaimRequestManagementService.prototype,
@@ -3,6 +3,41 @@ import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-d
import { submitExpertReplyValidationPipe } from "./submit-expert-reply-validation.pipe";
describe("submitExpertReplyValidationPipe", () => {
const replacementInvoice = {
partId: 201,
typeOfDamage: TypeOfDamage.Change,
salary: "1000000",
totalPayment: "1000000",
factorNeeded: true,
daghi: { option: "فاقد ارزش" },
};
it("accepts replacement invoices without a numeric part quote", async () => {
const result = await submitExpertReplyValidationPipe.transform(
{ parts: [replacementInvoice] },
{ type: "body", metatype: SubmitExpertReplyV2Dto },
);
expect(result.parts[0].factorNeeded).toBe(true);
expect(result.parts[0].price).toBeUndefined();
});
it.each([{ factorNeeded: false }, { price: "factor" }, { price: "فاکتور" }])(
"continues rejecting absent priced quotes and nonnumeric price markers: %j",
async (invalid) => {
await expect(
submitExpertReplyValidationPipe.transform(
{ parts: [{ ...replacementInvoice, ...invalid }] },
{ type: "body", metatype: SubmitExpertReplyV2Dto },
),
).rejects.toMatchObject({
response: {
validationErrors: expect.arrayContaining([
expect.objectContaining({ field: "parts[0].price" }),
]),
},
});
},
);
it("converts DTO validation failures into Persian, field-addressable errors", async () => {
await expect(
submitExpertReplyValidationPipe.transform(
@@ -61,7 +96,7 @@ describe("submitExpertReplyValidationPipe", () => {
validationErrors: expect.arrayContaining([
{
field: "parts[0].salary",
message: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
message: "باید مبلغ صحیح و غیرمنفی به ریال باشد.",
},
]),
},
@@ -18,7 +18,7 @@ const constraintMessages: Record<string, string> = {
isInt: "باید یک عدد صحیح باشد.",
isEnum: "مقدار واردشده معتبر نیست.",
nestedValidation: "اطلاعات این بخش معتبر نیست.",
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به تومان باشد.",
isMoneyAmountString: "باید مبلغ صحیح و غیرمنفی به ریال باشد.",
};
function flattenValidationErrors(
@@ -31,11 +31,20 @@ function flattenValidationErrors(
? `${parentPath}[${error.property}]`
: `${parentPath}.${error.property}`
: error.property;
const ownErrors = Object.keys(error.constraints ?? {}).map((constraint) => ({
field,
message: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
}));
return [...ownErrors, ...flattenValidationErrors(error.children ?? [], field)];
const ownErrors = Object.keys(error.constraints ?? {}).map(
(constraint) => ({
field,
message: field === "decisions" && constraint === "arrayMinSize"
? "حداقل یک فاکتور را بررسی کنید."
: field === "decisions" && constraint === "arrayUnique"
? "برای هر فاکتور فقط یک نتیجه بررسی ارسال کنید."
: constraintMessages[constraint] ?? "مقدار واردشده معتبر نیست.",
}),
);
return [
...ownErrors,
...flattenValidationErrors(error.children ?? [], field),
];
});
}
@@ -49,10 +58,12 @@ export const submitExpertReplyValidationPipe = new ValidationPipe({
whitelist: true,
exceptionFactory: (errors: ValidationError[]) => {
const validationErrors = flattenValidationErrors(errors);
const invoiceReview = errors.some(error => error.property === "decisions");
const code = invoiceReview ? "FACTOR_VALIDATION_ERROR" : "EXPERT_REPLY_VALIDATION_ERROR";
return new BadRequestException({
message: "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
error: "EXPERT_REPLY_VALIDATION_ERROR",
code: "EXPERT_REPLY_VALIDATION_ERROR",
message: invoiceReview ? "اطلاعات بررسی فاکتور معتبر نیست. فیلدهای مشخص‌شده را بررسی کنید." : "اطلاعات ارسالی پاسخ کارشناسی معتبر نیست.",
error: code,
code,
validationErrors,
});
},
+64 -36
View File
@@ -1,3 +1,5 @@
import { fanavaranSignatureRevision } from "src/fanavaran/fanavaran-expert-signature";
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
import {
BadRequestException,
ConflictException,
@@ -166,7 +168,7 @@ export class ExpertInsurerService {
carPlate: claim.vehicle?.plate,
claimStatus: claim.status,
rating: claim.evaluation?.rating,
userRating: claim.evaluation?.userRating,
userRating: claim.userRating ?? claim.evaluation?.userRating,
damageExpertReply: claim.evaluation?.damageExpertReply,
damageExpertReplyFinal: claim.evaluation?.damageExpertReplyFinal,
damageExpertResend: claim.evaluation?.damageExpertResend,
@@ -269,7 +271,7 @@ export class ExpertInsurerService {
if (!Array.isArray(parties) || !parties.length) return undefined;
return parties.map((p: any) => ({
role: p?.role,
fullName: p?.person?.fullName,
fullName: personDisplayName(p?.person),
vehicle: {
carName: p?.vehicle?.carName ?? p?.vehicle?.name,
carModel: p?.vehicle?.carModel ?? p?.vehicle?.model,
@@ -524,11 +526,24 @@ export class ExpertInsurerService {
}
}
private async personForDisplay(person: any, cache: Map<string, Promise<any>>) {
if (!person) return person;
const id = String(person.userId ?? "");
let profile: any;
if (Types.ObjectId.isValid(id) && this.userDbService?.findOne) {
if (!cache.has(id)) cache.set(id, this.userDbService.findOne({_id:new Types.ObjectId(id)}));
profile = await cache.get(id);
}
return {...person,fullName:personDisplayName(profile,person),phoneNumber:person.phoneNumber || profile?.mobile || ""};
}
private async buildInsurerBlameDetail(
blameLean: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const doc: Record<string, unknown> = { ...blameLean };
const parties = (Array.isArray(doc.parties) ? doc.parties : []) as any[];
const displayCache = new Map<string, Promise<any>>();
await Promise.all(parties.map(async party => { party.person = await this.personForDisplay(party.person,displayCache); }));
await this.enrichBlamePartyEvidenceUrls(parties);
doc.parties = enrichBlamePartiesForAgreementView(doc);
@@ -571,6 +586,11 @@ export class ExpertInsurerService {
claim: Record<string, unknown>,
blameForContext: Record<string, unknown> | null,
): Promise<Record<string, unknown>> {
const displayCache = new Map<string, Promise<any>>();
claim = {...claim,owner:await this.personForDisplay(claim.owner,displayCache)};
if (Array.isArray(blameForContext?.parties)) {
blameForContext = {...blameForContext,parties:await Promise.all(blameForContext.parties.map(async (party:any) => ({...party,person:await this.personForDisplay(party.person,displayCache)})))};
}
// Add at the top of buildInsurerClaimDetail, before the return:
const carType = (claim as any).vehicle?.carType as
| ClaimVehicleTypeV2
@@ -679,6 +699,9 @@ export class ExpertInsurerService {
const evaluationEnriched =
await this.enrichClaimEvaluationForInsurer(evaluation);
if (blameForContext?.type === BlameRequestType.CAR_BODY && evaluationEnriched) {
delete evaluationEnriched.priceDrop;
}
const vehicleSanitized = claim.vehicle
? this.sanitizeVehicleInquiry(claim.vehicle as any)
: undefined;
@@ -1065,6 +1088,19 @@ export class ExpertInsurerService {
range.toDate,
);
const blameTypes = new Map(blameFiles.map((file) => [String(file._id), file.type]));
// Roster-owned claims can belong to another party insurer. Resolve only the
// missing linked types in one batch, after claims have already been scoped.
const missingBlameIds = [...new Set(claimFiles.map((file) => String(file.blameRequestId || "")))]
.filter((id) => Types.ObjectId.isValid(id) && !blameTypes.has(id));
if (missingBlameIds.length) {
const linked = await this.blameRequestDbService.find(
{_id: {$in: missingBlameIds.map((id) => new Types.ObjectId(id))}},
{lean: true, select: "type"},
);
for (const file of linked) blameTypes.set(String(file._id), file.type);
}
const blameFilesInRange = blameFiles.filter((file) =>
this.isInDateRange(file?.createdAt, range.fromDate, range.toDate),
);
@@ -1098,7 +1134,8 @@ export class ExpertInsurerService {
.filter((expertId): expertId is string => !!expertId)
.filter((expertId) => rosterById.has(expertId));
const fileType = String(
file?.snapshot?.accident?.type ??
blameTypes.get(String(file.blameRequestId)) ??
file?.snapshot?.accident?.type ??
file?.blameFile?.type ??
BlameRequestType.THIRD_PARTY,
);
@@ -1809,7 +1846,7 @@ export class ExpertInsurerService {
};
}
async retrieveFileDetailsByPublicId(insurerId: string, publicId: string) {
async retrieveFileDetailsByPublicId(insurerId: string, publicId: string, includeReportMedia = false) {
if (!publicId?.trim()) {
throw new BadRequestException("publicId is required");
}
@@ -1884,10 +1921,22 @@ export class ExpertInsurerService {
? await this.buildInsurerClaimDetail(claimFull, blameForClaimContext)
: undefined;
const reportBlame = includeReportMedia
? blameDetails ?? (blameForClaimContext ? await this.buildInsurerBlameDetail(blameForClaimContext) : undefined)
: undefined;
if (includeReportMedia && claimDetails && claimFull?._id) {
const signedClaim = await this.claimCaseDbService.findWithFanavaranSignature(String(claimFull._id));
const signature = signedClaim?.fanavaranExpertSignature;
if (signature && (signedClaim.expertiseId != null || signature.revision === fanavaranSignatureRevision(signedClaim))) {
claimDetails.fanavaranExpertSignature = { name: signature.name, image: signature.image };
}
}
return {
overview,
blame: blameDetails,
claim: claimDetails,
...(includeReportMedia ? { reportBlame } : {}),
};
}
@@ -2497,25 +2546,14 @@ export class ExpertInsurerService {
]);
private static getDisplayNameFromRecord(record: any): string | null {
if (!record) return null;
const fullName =
typeof record.fullName === "string" ? record.fullName.trim() : "";
if (fullName) return fullName;
const firstName =
typeof record.firstName === "string" ? record.firstName.trim() : "";
const lastName =
typeof record.lastName === "string" ? record.lastName.trim() : "";
const combined = [firstName, lastName].filter(Boolean).join(" ").trim();
return combined || null;
return personDisplayName(record) || null;
}
private static isMeaningfulTimelineActorName(
name: string | undefined,
): boolean {
const trimmed = typeof name === "string" ? name.trim() : "";
if (!trimmed) return false;
if (!meaningfulPersonName(trimmed)) return false;
return !ExpertInsurerService.TIMELINE_PLACEHOLDER_ACTOR_NAMES.has(
trimmed.toLowerCase(),
);
@@ -2538,11 +2576,11 @@ export class ExpertInsurerService {
)
: null;
const matchedName = matchedParty?.person?.fullName?.trim?.();
const matchedName = personDisplayName(matchedParty?.person);
if (matchedName) return matchedName;
if (parties.length === 1) {
return parties[0]?.person?.fullName?.trim?.() || null;
return personDisplayName(parties[0]?.person) || null;
}
return null;
@@ -2697,7 +2735,7 @@ export class ExpertInsurerService {
): Promise<string | null> {
const explicitName =
typeof actor?.actorName === "string" ? actor.actorName.trim() : "";
if (ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) {
if (actorType !== "user" && ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) {
return explicitName;
}
@@ -2707,16 +2745,6 @@ export class ExpertInsurerService {
return ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
}
if (actorType === "user") {
const ownerName = sourceDoc?.owner?.fullName?.trim?.();
if (ownerName) return ownerName;
const blamePartyName = ExpertInsurerService.resolveBlamePartyName(
sourceDoc,
event?.metadata?.partyRole,
);
if (blamePartyName) return blamePartyName;
}
const actorId = actor?.actorId ? String(actor.actorId).trim() : "";
if (actorId) {
@@ -2731,14 +2759,13 @@ export class ExpertInsurerService {
);
if (!resolvedName && actorType === "user") {
resolvedName =
sourceDoc?.owner?.fullName?.trim?.() ??
ExpertInsurerService.resolveBlamePartyName(
sourceDoc,
event?.metadata?.partyRole,
);
const parties = Array.isArray(sourceDoc?.parties) ? sourceDoc.parties : [];
const party = parties.find((row:any) => String(row?.person?.userId ?? "") === actorId);
resolvedName = personDisplayName(party?.person,
String(sourceDoc?.owner?.userId ?? "") === actorId ? sourceDoc.owner : undefined) || null;
}
if (!resolvedName && ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) resolvedName = explicitName;
if (!resolvedName) {
resolvedName =
ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
@@ -2748,6 +2775,7 @@ export class ExpertInsurerService {
return resolvedName ?? null;
}
if (actorType === "user") return personDisplayName(sourceDoc?.owner) || ExpertInsurerService.resolveBlamePartyName(sourceDoc,event?.metadata?.partyRole);
return ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
}
@@ -0,0 +1,61 @@
import { ExpertInsurerService } from "./expert-insurer.service";
import { Types } from "mongoose";
describe("QA reporting regressions", () => {
it("classifies a roster-owned claim by its linked blame even when that blame is outside the party-insurer list", async () => {
const s: any = Object.create(ExpertInsurerService.prototype);
const clientKey = String(new Types.ObjectId()),
expertId = new Types.ObjectId(),
blameId = new Types.ObjectId();
s.expertDbService = { findAll: jest.fn().mockResolvedValue([]) };
s.damageExpertDbService = {
findAll: jest
.fn()
.mockResolvedValue([
{ _id: expertId, firstName: "QA", lastName: "Expert" },
]),
};
s.fieldExpertDbService = { findAll: jest.fn().mockResolvedValue([]) };
s.getClientBlameFiles = jest.fn().mockResolvedValue([]);
s.getClientClaimFiles = jest
.fn()
.mockResolvedValue([
{
_id: new Types.ObjectId(),
blameRequestId: blameId,
createdAt: new Date(),
},
]);
s.expertFileActivityDbService = {
findByTenant: jest.fn().mockResolvedValue([]),
};
s.claimDamageExpertActorId = jest.fn().mockReturnValue(String(expertId));
s.blameRequestDbService = {
find: jest.fn().mockResolvedValue([{ _id: blameId, type: "CAR_BODY" }]),
};
const result = await s.buildExpertReportRows({ clientKey });
expect(result.experts[0]).toMatchObject({
totalFiles: 1,
carBodyFiles: 1,
thirdPartyFiles: 0,
});
expect(s.blameRequestDbService.find).toHaveBeenCalledWith(
{ _id: { $in: [blameId] } },
{ lean: true, select: "type" },
);
});
it("preserves current root user ratings and falls back to legacy nested ratings", () => {
const s: any = Object.create(ExpertInsurerService.prototype);
const current = { overallEvaluation: 5 },
legacy = { overallEvaluation: 1 };
expect(
s.normalizeClaimCase({
userRating: current,
evaluation: { userRating: legacy },
}).userRating,
).toBe(current);
expect(
s.normalizeClaimCase({ evaluation: { userRating: legacy } }).userRating,
).toBe(legacy);
});
});
@@ -0,0 +1,144 @@
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { fanavaranSignatureRevision } from "./fanavaran-expert-signature";
describe("Fanavaran expert signature gate", () => {
const actor = {
sub: "expert-1",
role: "damage_expert",
fullName: "کارشناس نمونه",
};
const image =
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j3ZkAAAAASUVORK5CYII=";
let service: any;
let claim: any;
let old: string | undefined;
beforeEach(() => {
old = process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE;
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = "true";
claim = {
_id: "claim-1",
vehicle: { carName: "پژو" },
updatedAt: new Date(),
evaluation: {},
};
service = Object.create(ClaimRequestManagementService.prototype);
service.claimCaseDbService = {
findById: jest.fn(async () => claim),
findWithFanavaranSignature: jest.fn(async () => claim),
findOneAndUpdate: jest.fn(async (_query, update) => {
Object.assign(claim, update.$set);
return claim;
}),
};
service.completeFanavaranExpertisePrerequisites = jest.fn();
service.resolveFanavaranClaimProduct = jest.fn(async () => "third-party");
service.buildFanavaranExpertisePayload = jest.fn(async () => ({
payload: {},
warnings: [],
infoWarnings: [],
}));
service.assertFanavaranExpertisePayloadReady = jest.fn();
service.executeFanavaranExpertiseSubmit = jest.fn(async () => ({
Id: 123,
}));
});
afterEach(() => {
if (old === undefined)
delete process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE;
else process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = old;
});
it("requires a signature before running prerequisites and leaves automatic final submission pending", async () => {
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
undefined,
actor,
),
).rejects.toMatchObject({
response: { code: "FANAVARAN_EXPERT_SIGNATURE_REQUIRED" },
});
await expect(
service.autoSubmitFanavaranExpertiseOnExpertReply("claim-1"),
).resolves.toMatchObject({ skipped: true });
expect(
service.completeFanavaranExpertisePrerequisites,
).not.toHaveBeenCalled();
});
it("stores the authenticated signer's signature, rejects stale or mismatched signatures and accepts retry", async () => {
const revision = fanavaranSignatureRevision(claim);
await expect(
service.saveFanavaranExpertSignature("claim-1", actor, {
revision,
image: "invalid",
}),
).rejects.toMatchObject({ status: 400 });
await expect(
service.saveFanavaranExpertSignature("claim-1", actor, {
revision: "stale",
image,
}),
).rejects.toMatchObject({ status: 409 });
await expect(
service.saveFanavaranExpertSignature("claim-1", actor, {
revision,
image,
}),
).resolves.toMatchObject({ signed: true });
expect(claim.fanavaranExpertSignature).toMatchObject({
actorId: actor.sub,
actorRole: actor.role,
revision,
image,
});
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian", undefined, {
...actor,
sub: "other",
}),
).rejects.toMatchObject({ status: 409 });
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
{ ClaimExpertId: 12 },
actor,
),
).rejects.toMatchObject({ status: 400 });
expect(
service.completeFanavaranExpertisePrerequisites,
).not.toHaveBeenCalled();
claim.fanavaranSync = { baseClaim: { status: "success" } };
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
undefined,
actor,
),
).resolves.toEqual({ Id: 123 });
claim.evaluation.priceDrop = { total: 123 };
await expect(
service.submitFanavaranExpertiseV2(
"claim-1",
"parsian",
undefined,
actor,
),
).rejects.toMatchObject({ status: 409 });
});
it("retains unsigned submission when the deployment disables the feature", async () => {
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE = "false";
await expect(
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
).resolves.toEqual({ Id: 123 });
expect(
service.claimCaseDbService.findWithFanavaranSignature,
).not.toHaveBeenCalled();
});
});
+106
View File
@@ -0,0 +1,106 @@
import { BadRequestException, ConflictException } from "@nestjs/common";
import { createHash } from "node:crypto";
export type FanavaranExpertSignature = {
actorId: string;
actorRole: string;
name: string;
signedAt: Date;
revision: string;
image: string;
};
export function requiresFanavaranExpertSignature(): boolean {
return ["true", "1"].includes(
process.env.FANAVARAN_REQUIRE_EXPERT_SIGNATURE?.trim().toLowerCase() ?? "",
);
}
export function fanavaranSignatureRevision(claim: any): string {
const row = claim.toObject?.({ flattenMaps: true }) ?? claim;
const {
status,
claimStatus,
evaluation,
vehicle,
damage,
owner,
money,
fanavaranVehicleReview,
fanavaranFieldReview,
snapshot,
requiredDocuments,
media,
} = row;
return createHash("sha256")
.update(
JSON.stringify({
status,
claimStatus,
evaluation,
vehicle,
damage,
owner,
money,
fanavaranVehicleReview,
fanavaranFieldReview,
snapshot,
requiredDocuments,
media,
}),
)
.digest("hex");
}
export function hasFanavaranExpertSignature(
claim: any,
actor?: { sub: string; role?: string },
): boolean {
const signature: FanavaranExpertSignature | undefined =
claim.fanavaranExpertSignature;
return (
!!actor &&
!!signature?.image &&
signature.actorId === String(actor.sub) &&
signature.actorRole === actor.role &&
signature.revision === fanavaranSignatureRevision(claim)
);
}
export function assertFanavaranExpertSignature(
claim: any,
actor?: { sub: string; role?: string },
): void {
if (!hasFanavaranExpertSignature(claim, actor)) {
throw new ConflictException({
code: "FANAVARAN_EXPERT_SIGNATURE_REQUIRED",
message: "ابتدا نسخه فعلی پرونده را امضا کنید و سپس به فناوران بفرستید.",
});
}
}
export function readFanavaranSignatureImage(value: unknown): string {
const invalid = () =>
new BadRequestException("تصویر امضا معتبر نیست. امضا را دوباره ثبت کنید.");
if (
typeof value !== "string" ||
value.length > 100_000 ||
!/^data:image\/png;base64,[A-Za-z0-9+/]+={0,2}$/.test(value)
)
throw invalid();
const png = Buffer.from(
value.slice("data:image/png;base64,".length),
"base64",
);
if (
png.length < 45 ||
png.subarray(0, 8).toString("hex") !== "89504e470d0a1a0a" ||
png.toString("ascii", 12, 16) !== "IHDR" ||
png.subarray(-12).toString("hex") !== "0000000049454e44ae426082"
)
throw invalid();
const width = png.readUInt32BE(16);
const height = png.readUInt32BE(20);
if (!width || !height || width > 900 || height > 400) throw invalid();
return value;
}
+41 -6
View File
@@ -1,8 +1,10 @@
import { EnforceCaseWorkingHours } from "src/client/working-hours/case-working-hours.interceptor";
import {
BadRequestException,
Body,
Controller,
Get,
Patch,
Param,
Post,
Query,
@@ -16,6 +18,9 @@ import {
ApiQuery,
ApiTags,
} from "@nestjs/swagger";
import { CurrentUser } from "src/decorators/user.decorator";
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
import { requiresFanavaranExpertSignature } from "./fanavaran-expert-signature";
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import {
@@ -28,12 +33,14 @@ import {
} from "src/core/config/fanavaran-client.config";
@ApiTags("fanavaran")
@EnforceCaseWorkingHours()
@Controller("v2/fanavaran")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard)
export class FanavaranController {
constructor(
private readonly claimRequestManagementService: ClaimRequestManagementService,
private readonly expertClaimService: ExpertClaimService,
) {}
@Get("clients")
@@ -111,7 +118,7 @@ export class FanavaranController {
@ApiOperation({
summary: "Submit Fanavaran base claim create request",
description:
"Swagger JSON body is optional. Always rebuilds GEN.03 from live inquiries, then POSTs that rebuilt payload. Pasting a previous preview JSON does not skip inquiry. Only user-entry keys are applied from the body (EstimateAmount, licence, dates, address, police report). PolicyId and AccidentVehicleUsedId in pasted JSON are ignored.",
"Optional JSON overrides the generated GEN.03 defaults. Every supplied field takes precedence, including lookup IDs, nested objects, arrays and explicit null. Omitted fields retain generated defaults. Validation checks the final payload without rewriting supplied values.",
})
@ApiParam({
name: "client",
@@ -125,7 +132,7 @@ export class FanavaranController {
@ApiBody({
required: false,
description:
"Optional. Paste previous preview JSON if you want to tweak user-entry fields. Lookup ids in that JSON are ignored.",
"Optional JSON payload overrides. All supplied fields are applied as-is; arrays and nested objects replace their generated counterparts. Explicit null is preserved.",
schema: { type: "object", additionalProperties: true, example: {} },
})
async submit(
@@ -171,7 +178,7 @@ export class FanavaranController {
@ApiOperation({
summary: "Submit Fanavaran damage-case request",
description:
"Swagger JSON body is optional. Always rebuilds GEN.12 from live VIN/vehicle/driver inquiries, then POSTs that rebuilt payload. Pasting a previous preview JSON does not skip inquiry. Only Desc, EstimateAmount, LicenceNo, LicenceIssuDate, DriverIsOwner are taken from the body. PlaqueKindId, PlaqueSampleId, VehicleKindId, DriverId, InsuranceCorpId in pasted JSON are ignored.",
"Optional JSON overrides the generated GEN.12 defaults. Every supplied field takes precedence, including DriverId, plaque/vehicle IDs, nested objects, arrays and null. Omitted fields retain generated defaults.",
})
@ApiParam({
name: "client",
@@ -185,7 +192,7 @@ export class FanavaranController {
@ApiBody({
required: false,
description:
"Optional. Paste previous preview JSON if you want to tweak Desc / licence / estimate. Lookup-filter ids in that JSON are ignored.",
"Optional JSON overrides. Every supplied field is applied as-is, including IDs and explicit null.",
schema: { type: "object", additionalProperties: true, example: {} },
})
async submitDamageCase(
@@ -279,11 +286,31 @@ export class FanavaranController {
);
}
@Get("claim-cases/:claimCaseId/expert-signature")
async expertSignatureStatus(@Param("claimCaseId") id: string, @CurrentUser() actor: any) {
if (!requiresFanavaranExpertSignature()) return { required: false, signed: false };
await this.expertClaimService.assertCanSignFanavaranClaim(id, actor);
return this.claimRequestManagementService.getFanavaranExpertSignatureStatus(id, actor);
}
@Patch("claim-cases/:claimCaseId/expert-signature")
async saveExpertSignature(
@Param("claimCaseId") id: string,
@CurrentUser() actor: any,
@Body() body: { revision?: string; image?: string },
) {
if (!requiresFanavaranExpertSignature()) {
throw new BadRequestException("ثبت امضای کارشناس در این سامانه فعال نیست.");
}
await this.expertClaimService.assertCanSignFanavaranClaim(id, actor);
return this.claimRequestManagementService.saveFanavaranExpertSignature(id, actor, body);
}
@Post(":client/claim-cases/:claimCaseId/expertise/submit")
@ApiOperation({
summary: "Submit Fanavaran expertise request",
description:
"Completes missing prerequisite stages in order before expertise: base claim, third-party damage case when applicable, then all pending attachments. Skipped images are retried; any image without a saved Fanavaran file ID blocks expertise with stage and pendingFiles details. Existing IDs/receipts are reused; existing expertise is not duplicated. Optional JSON overrides only allowed money/date fields; the GEN.08 third-party or GEN.06 hull payload is rebuilt from the expert reply and live lookups.",
"Completes missing prerequisite stages in order before expertise: base claim, third-party damage case when applicable, then all pending attachments. Skipped images are retried; any image without a saved Fanavaran file ID blocks expertise with stage and pendingFiles details. Existing IDs/receipts are reused; existing expertise is not duplicated. Optional JSON overrides every supplied GEN.08 third-party or GEN.06 hull field, including DmgCaseId, ClaimExpertId, DmgSections and explicit null. Omitted fields retain generated defaults.",
})
@ApiParam({
name: "client",
@@ -297,19 +324,27 @@ export class FanavaranController {
@ApiBody({
required: false,
description:
"Optional. Paste previous preview JSON if you want to tweak money/date fields. DmgCaseId / ClaimExpertId / DmgSections in that JSON are ignored.",
"Optional JSON overrides every supplied field. IDs, arrays, nested objects and explicit null take precedence over generated defaults.",
schema: { type: "object", additionalProperties: true, example: {} },
})
async submitExpertise(
@Param("client") client: string,
@Param("claimCaseId") claimCaseId: string,
@CurrentUser() actor: any,
@Body() body?: Record<string, unknown>,
) {
const clientKey = this.parseClientParam(client);
if (requiresFanavaranExpertSignature()) {
if (clientKey !== resolveFanavaranClientKey()) {
throw new BadRequestException("شرکت بیمه با تنظیمات این سامانه مطابقت ندارد.");
}
await this.expertClaimService.assertCanSignFanavaranClaim(claimCaseId, actor);
}
return await this.claimRequestManagementService.submitFanavaranExpertiseV2(
claimCaseId,
clientKey,
body && Object.keys(body).length > 0 ? body : undefined,
actor,
);
}
+2
View File
@@ -3,6 +3,7 @@ import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
import { ExpertClaimModule } from "src/expert-claim/expert-claim.module";
import { FanavaranAuditModule } from "./fanavaran-audit.module";
import { FanavaranController } from "./fanavaran.controller";
import { FanavaranLookupModule } from "./fanavaran-lookup.module";
@@ -12,6 +13,7 @@ import { FanavaranHullReadController } from "./fanavaran-hull-read.controller";
@Module({
imports: [
ClaimRequestManagementModule,
ExpertClaimModule,
FanavaranAuditModule,
FanavaranLookupModule,
HttpModule.registerAsync({
@@ -103,6 +103,12 @@ export function buildClaimDetailsV2OwnerGuidance(
const objectionAllowed = ownerMaySubmitObjectionForClaimDetails(claim);
const objectionHint = objectionHintWhen(objectionAllowed);
if (claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return {
phaseKey: "IN_PERSON_VISIT_PENDING", headline: "مراجعه حضوری درخواست شده است",
detail: claim.evaluation?.visitLocation || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
nextActions: [], objectionAllowed: false,
};
if (claim.status === ClaimCaseStatus.COMPLETED) {
return {
phaseKey: "COMPLETED",

Some files were not shown because too many files have changed in this diff Show More