forked from Yara724/api
Compare commits
43
Commits
f021793b00
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3f920c0be5 | ||
|
|
f29461fa67 | ||
|
|
475780f17e | ||
|
|
297664a9a6 | ||
|
|
187a0ea3a9 | ||
|
|
036d218ebd | ||
|
|
c74b29337e | ||
|
|
3bf6fcc8b0 | ||
|
|
e31e2c7be6 | ||
|
|
70e7edcd19 | ||
|
|
99aba7e0fd | ||
|
|
fb192fd780 | ||
|
|
41a3372225 | ||
|
|
d2676d65d1
|
||
|
|
6e56d0fa2e
|
||
|
|
7b23262fd2 | ||
|
|
6b968c0952 | ||
|
|
abc40df199 | ||
|
|
90f290154c | ||
|
|
be364d94fe | ||
|
|
1a38b98829 | ||
|
|
61ef4faaf4 | ||
|
|
7bff702514 | ||
|
|
99e6fa0850 | ||
|
|
83d7351310 | ||
|
|
ab3ae53ec0 | ||
|
|
bc78bface0 | ||
|
|
e33f5736a2 | ||
|
|
5c6e21dd14 | ||
|
|
8f15040080 | ||
|
|
5818f7f881 | ||
|
|
5242a22c6c | ||
|
|
9197bccceb | ||
|
|
cda424a536 | ||
|
|
68e26920e2 | ||
|
|
c6022a1646 | ||
|
|
b63525c863 | ||
|
|
83376df4ad | ||
|
|
2cdbc35d2e | ||
|
|
7631a94071 | ||
|
|
e5c4b740e7 | ||
|
|
775934c056 | ||
|
|
a15c54d017 |
+20
-4
@@ -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
|
||||
|
||||
@@ -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"
|
||||
@@ -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
@@ -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"]
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.git
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
.env.*
|
||||
*.env
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -1143,7 +1143,7 @@
|
||||
<p class="section-intro">
|
||||
Two actors handle the same V3 work split across two controllers.
|
||||
<strong>FileMaker</strong> (<code>v4/file-maker/blame-request-management/</code>)
|
||||
handles the party narrative (OTPs, inquiries, details, signatures) and
|
||||
handles the party narrative (OTPs, inquiries, written details, signatures) and
|
||||
uploads the initial claim documents. <strong>FileReviewer</strong>
|
||||
(<code>v4/file-reviewer/blame-request-management/</code>) handles the
|
||||
damage assessment pass. The final blame video (upload-video) is a no-op
|
||||
@@ -1204,11 +1204,11 @@
|
||||
<div class="step-num purple">5</div>
|
||||
<div class="step-body">
|
||||
<div class="step-label">
|
||||
Location · description · voice (guilty)
|
||||
Written description (guilty; voice optional)
|
||||
</div>
|
||||
<div class="step-route">
|
||||
POST /add-detail-location, /add-detail-description,
|
||||
/upload-voice
|
||||
POST /add-detail-description
|
||||
(location skipped; voice not required)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Driver licence issue dates
|
||||
|
||||
Updated: 2026-11-14.
|
||||
|
||||
The inquiry field is the **issue date**, `driver.driverLicenseDate`, labelled
|
||||
«تاریخ صدور گواهینامه». It is not an expiry date. Both UIs keep the existing
|
||||
structured inquiry contract and send the actual selected date. No replacement
|
||||
checkbox or client-generated Fanavaran status is added.
|
||||
|
||||
For a licensed driver, the date is still required and must be valid and not in
|
||||
the future. The ten-year lower bound has been removed from both UI schemas and
|
||||
the shared API inquiry validator; otherwise an older date would pass the form
|
||||
and still fail at submission. Drivers without a licence retain their existing
|
||||
payload behavior, which omits the licence date.
|
||||
|
||||
The API derives the Fanavaran flag against the **accident date**, preserving the
|
||||
mapping introduced by the pulled changes:
|
||||
|
||||
| Age at accident | Outbound value |
|
||||
|---|---|
|
||||
| Through the third issue-date anniversary | `0` |
|
||||
| After the third anniversary through the tenth anniversary | `null` |
|
||||
| After the tenth anniversary | `1` |
|
||||
|
||||
Hull uses `IsLicenseReplaced`; third-party uses `IsLicenseReplacement`. Recent
|
||||
licences still receive explicit `0` because the current Fanavaran rule requires
|
||||
an answer. Users do not enter this flag themselves. Anniversary comparison uses
|
||||
the actual Jalali year/month/day, so ten years plus one day no longer waits until
|
||||
eleven completed years to become `1`.
|
||||
|
||||
The UIs validate against Iran's current date and reject invalid month/day
|
||||
combinations rather than accepting a date-picker library's rollover. The
|
||||
existing missing-date fallback for legacy records remains unchanged.
|
||||
|
||||
Validation covers old/current/future dates, invalid Jalali dates, Persian input,
|
||||
both insurance products, licensed/unlicensed drivers, inquiry payloads, and
|
||||
three-/ten-year anniversary boundaries. Run `npm run test:ui` in each UI and
|
||||
`npm test -- --runInBand` in the API.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Expert access, multiple roles and optional voice
|
||||
|
||||
## Account activation
|
||||
|
||||
In the expert panel, a super-admin selects an insurer, opens **اعضا و کارشناسان → مدیریت**, and uses **غیرفعال کردن / فعال کردن** beside the relevant role account. Insurers can see the status but cannot change it.
|
||||
|
||||
The endpoint is:
|
||||
|
||||
```http
|
||||
PATCH /super-admin/management/staff/:role/:id/status?clientId=<insurer-id>
|
||||
Authorization: Bearer <super-admin-token>
|
||||
Content-Type: application/json
|
||||
|
||||
{"isActive": false}
|
||||
```
|
||||
|
||||
Only a boolean is accepted. The selected account must belong to the supplied insurer. The response excludes passwords and OTPs. The general staff-edit endpoints, including insurer endpoints, do not accept `isActive`.
|
||||
|
||||
Supported roles: `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, `call_center`. Disabling one role account does not disable another role account belonging to the same person. Login and protected expert requests check the saved flag; previously issued tokens cannot be used while that account is disabled. Existing documents without `isActive` are treated as active.
|
||||
|
||||
No existing account, password, case owner or assignment is migrated. Deploy the API before the updated expert UI. No database backfill or index deletion is needed.
|
||||
|
||||
## Same person in several flows
|
||||
|
||||
Create an account for each required role using the same national code, email and password. Continue using the existing login URLs and role selectors. For example, one person can log into `/v4/expert-login` as either a file maker or a file reviewer with the same credentials, provided both assignments have been created. The expert panel likewise uses its existing role selector.
|
||||
|
||||
The creation and edit checks now reject duplicate identifiers **within the selected role**, rather than across all roles. Role collections already have separate indexes, so cross-role reuse requires no production index changes. Within-role uniqueness remains important because login has no insurer selector. This change does not grant another role automatically or merge existing records.
|
||||
|
||||
Credentials remain attached to their existing role records. Administrators should enter the same password when adding another role; changing one role's password does not silently overwrite credentials on another production account. National codes on existing accounts should only be corrected after verifying the person's identity.
|
||||
|
||||
## Voice in v4/v5
|
||||
|
||||
FileMaker flows v4 and v5 no longer display or require the blame voice recorder. Following each party's inquiry, the workflow goes to written details, then signature. Written accident information, car-body description validation, signatures, required documents and reviewer handoff remain in place.
|
||||
|
||||
Older v4/v5 files waiting at `FIRST_VOICE` or `SECOND_VOICE` resume at the corresponding description step. The details page fetches the FileMaker's case through its own `my-files/:requestId` endpoint, with loading/retry states, so reopening does not depend on a previously cached party or case type. The voice-permission notice is also hidden in these flows. Existing recordings, completed-step history and events are retained. The optional upload endpoints are retained for older clients. Other flows keep their voice requirements. The separate claim walk-around video requirement is unchanged.
|
||||
|
||||
## Verification
|
||||
|
||||
- Management tests exercise real Mongoose schemas, cross-role creation/editing, same-role duplicate rejection, activation/reactivation, legacy defaults and tenant boundaries.
|
||||
- HTTP tests use the real management/auth controllers and JWT guards with isolated repositories to verify login, status permissions, rejection of an old token, and the other role remaining usable.
|
||||
- Auth tests cover all staff roles and JWT guard entry points.
|
||||
- Workflow tests cover v4/v5, car-body/third-party, both parties, signatures without voice and older resume states.
|
||||
- Frontend regression scripts cover the status proxy allowlist and v4/v5 submission without voice while retaining the other flows' requirements.
|
||||
|
||||
Run the API suite with `npm test -- --runInBand`, and each frontend suite with `npm run test:ui`. These checks do not use production data or send SMS messages.
|
||||
@@ -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
@@ -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`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -56,7 +56,10 @@ because they appear in the defaults below. Hull collision type, culprit type,
|
||||
authority, damage kind, and cost kind select matching captions from API responses
|
||||
without numeric fallbacks. Policy accessories are read for the current PolicyId;
|
||||
ActualPremium is refreshed from that policy's TotalPremium. Expert-entered amounts
|
||||
and durations remain expert data. `IsLicenseReplaced` is `1` when licence issue is >10 years before the accident, otherwise `null`.
|
||||
and durations remain expert data. Licence issue dates have no 10-year intake
|
||||
cutoff. The server derives `IsLicenseReplaced`: `0` through the third anniversary,
|
||||
`null` after three years through the tenth anniversary, and `1` after ten years,
|
||||
measured against the accident date. Third-party uses `IsLicenseReplacement`.
|
||||
|
||||
| Name | Shared seed | Parsian override | Tejaratno | Moallem | Varies? |
|
||||
|------|-------------|------------------|-----------|---------|---------|
|
||||
|
||||
@@ -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 |
|
||||
@@ -38,6 +40,7 @@ source: fanavaran-module-docs
|
||||
| — | [third-party-stage-fields.md](./third-party-stage-fields.md) | ثالث: each stage body, null vs required, lookup/inquiry vs user |
|
||||
| — | [car-body-stage-fields.md](./car-body-stage-fields.md) | بدنه: each stage body, null vs required, lookup/inquiry vs user |
|
||||
| — | [flow-design-user-vs-inquiry.md](./flow-design-user-vs-inquiry.md) | Proposed intake: user vs inquiry, Persian titles + types |
|
||||
| — | [hardcoded-payload-audit.md](./hardcoded-payload-audit.md) | Current hardcoded outbound values, removed fallbacks, standalone-tool differences, and remediation priorities (2026-11-11) |
|
||||
|
||||
## Related sources (code)
|
||||
|
||||
|
||||
@@ -156,7 +156,7 @@ Example hull-only GEN.03 body (proven Parsian case): [`stage1-hull-body.json`](.
|
||||
| Field | Source |
|
||||
|-------|--------|
|
||||
| `ActualPremium` | `GET /lookups/body-policy/{PolicyId}` → `TotalPremium` |
|
||||
| `AccidentCulpritId` | `GET /lookups/inquiry-by-unique-identifier?nationalCode=…&birthday=…` → `driverId` (fallback: policy `CustomerId`) |
|
||||
| `AccidentCulpritId` | `GET /lookups/inquiry-by-unique-identifier?nationalCode=…&birthday=…` → inspect `parties` for RoleId **166**. Hull submit registers GEN.44 when missing and re-inquires to verify; preview stays read-only. The wrapper `driverId` may fall back to role 161 and is insufficient for this check. |
|
||||
| `CustomerFaultPercent` | **100** (required; درصد تقصير بيمه گذار) |
|
||||
| `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` → بیمهگذار (required; مرجع تعيين مقصر) |
|
||||
|
||||
|
||||
@@ -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`).
|
||||
|
||||
---
|
||||
@@ -31,7 +40,12 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
|
||||
**Fanavaran has rejected as required (must not be null):**
|
||||
`CustomerFaultPercent`, `AuthorityCulpritId`, `AccidentTypeId`, `CostSeparationToDmgSections`, `IsOwnerChanged`, `PolicyId`, `ClaimExpertId`, dates/time, `CulpritTypeId`.
|
||||
|
||||
**IsLicenseReplaced:** `1` when `CulpritLicenceIssuDate` is more than 10 years before `AccidentDate`; otherwise `null` (never send `0`). Dummy issue date when missing: `1404/08/20`.
|
||||
**IsLicenseReplaced:** derived on the server from `CulpritLicenceIssuDate` and
|
||||
`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 |
|
||||
|-------|---------|------|-------|------------------------|
|
||||
@@ -47,11 +61,11 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
|
||||
| AccidentTypeId | نوع حادثه بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-types` row caption تصادف(حادثه); no numeric fallback |
|
||||
| CulpritTypeId | نوع مقصر بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-culprit-type` row caption بیمهگذار; never reuse third-party `337` |
|
||||
| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | Reviewed choice, else current `detection-accident-culprits` row caption بیمهگذار; no numeric fallback |
|
||||
| AccidentCulpritId | شناسه مقصر فناوران | number | preferred | **inquiry** parties `inquiry-by-unique-identifier`, fallback hull policy `CustomerId` |
|
||||
| AccidentCulpritId | شناسه مقصر فناوران | number | **no** | Actual driver from parties inquiry with RoleId **166**; submit registers GEN.44 if missing, then verifies the role. Preview warns without creating a person. |
|
||||
| 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 >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** |
|
||||
@@ -138,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 |
|
||||
@@ -157,3 +171,16 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
|
||||
|
||||
Same routes as ثالث (`/base-claim`, `/attachments`, `/expertise`).
|
||||
`/damage-case` preview/submit **skips** for `CAR_BODY`.
|
||||
|
||||
### Hull driver registration
|
||||
|
||||
A policyholder-only (`RoleId=161`) inquiry does not satisfy the hull driver role.
|
||||
Before base-claim submission or hull synchronization, YARA checks the actual driver
|
||||
for `RoleId=166` (سایر) and registers `common/other-people` when missing, using
|
||||
national code, birthday and person details. The policyholder role is preserved.
|
||||
The returned create ID is used only after a subsequent inquiry verifies role 166.
|
||||
A successful registration is cached with national code and birthday so retries
|
||||
wait for verification rather than creating the same role again. Missing identity,
|
||||
lookup failures or unverified registration block the external hull write with
|
||||
`FANAVARAN_HULL_DRIVER_ROLE_REQUIRED`; local claim creation remains best-effort.
|
||||
Third-party driver/owner resolution continues to accept roles 161 or 166.
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# Fanavaran hardcoded outbound values — current audit
|
||||
|
||||
Date: **2026-11-11**. Remote baseline: API `90bdc51` on `origin/main`, with the
|
||||
existing local branch-routing work restored. This is a source audit of possible
|
||||
outbound values, not a capture of production requests. Mongo configuration can
|
||||
override seed defaults, so the numbers below are code defaults, not a claim about
|
||||
what is configured on a particular production server.
|
||||
|
||||
**The requirement “never send guessed/default business codes” is not satisfied.**
|
||||
The staff-location fix is present, and recent hull changes removed several
|
||||
numeric fallbacks, but other defaults can still reach Fanavaran. Merely checking
|
||||
that a default ID exists in a lookup does not establish that it describes this
|
||||
accident, driver, vehicle, or assessment.
|
||||
|
||||
This document updates the outbound-default findings in
|
||||
[lookup-coding-audit.md](./lookup-coding-audit.md), which predates the latest hull
|
||||
and location changes. This audit changes documentation only.
|
||||
|
||||
## Audited paths
|
||||
|
||||
| Area | Sources and responsibility |
|
||||
|---|---|
|
||||
| Application write entry points | `src/fanavaran/fanavaran.controller.ts`: base claim, damage case, attachments, expertise preview/submit; automatic and soft-ensure stage calls in `ClaimRequestManagementService` use the same builders |
|
||||
| Payloads and HTTP writes | `src/claim-request-management/claim-request-management.service.ts`: GEN.03, GEN.12, GEN.44, GEN.07, third-party GEN.08, hull base PUT and GEN.06 |
|
||||
| Product-specific helpers | `src/claim-request-management/fanavaran-{hull-base-claim,hull-expertise,hull-expertise-lookups,hull-lookup-validation,party-roles,other-people,accident-vehicle-used,v15-third-party-base}.ts` |
|
||||
| Configuration and headers | `src/core/config/fanavaran-client.config.ts`, `src/fanavaran/fanavaran-{client-config,auth,location}.service.ts`, config schema, system settings |
|
||||
| Lookup/inquiry and local catalogues | `src/fanavaran/fanavaran-lookup.service.ts`, `fanavaran-lookup.config.ts`, `src/lookups/`, `src/static/outer-car-parts-catalog.ts`, part helpers, vehicle/stage review code |
|
||||
| Expert and user UI | Expert Fanavaran API route, vehicle review, stage-field defaults, damage reply fields; user inquiry/part-selection consumers. No matching numeric payload defaults were found in the current UI source search; the expert UI does accept backend-prefilled defaults. |
|
||||
| Standalone tools | `scripts/fanavaran-flow-ui-server.js`, `scripts/data/fanavaran-flow-ui.html`, `scripts/fanavaran-flow-test.sh`, `scripts/fanavaran-auth.sh`, `scripts/get-fanavaran-car-parts.sh`; report-seeding fixtures were distinguished from application writes |
|
||||
|
||||
The runtime tenant type supports `parsian`, `tejaratno`, and `moallem`.
|
||||
`esg/src` had no direct Fanavaran references in the search. `rewrite` was excluded.
|
||||
|
||||
## 1. Business IDs that can still be sent from defaults
|
||||
|
||||
Line references are against the restored worktree at audit time. `service` means
|
||||
`src/claim-request-management/claim-request-management.service.ts`.
|
||||
|
||||
| Field / stage | Hardcoded or seeded value | When it reaches the payload | Evidence / required source |
|
||||
|---|---|---|---|
|
||||
| `AccidentCauseId` — base, both products | **6** | Always initialized to 6. `accidentReason` is passed into the builder but its selected ID / `fanavaran` code is not applied. Hull checks membership, which can accept the wrong but active cause. | `service:405`, `1894`; use the actual selected cause mapped to this tenant. |
|
||||
| `AccidentCityId` — base, both products | **701** | Profile default unless an expert stage review changes it. The shared builder does not resolve the supplied coordinates into a city. | Config `:100`; `service:1893`, `5691`; use accident-city selection/inquiry. |
|
||||
| `AccidentReportTypeId` — base, both products | **155** | Profile default unless reviewed. | Config `:101`; `service:5692`; explicit report-type selection. |
|
||||
| `CompensationReferenceId` — third-party base | **167** | Included from the profile; not among the current editable stage fields or manual-ID overrides. Hull's key whitelist removes it. | Config `:106`; `service:1893`; confirm the required contract/codebook and source. |
|
||||
| `CulpritLicenceTypeId` — base, both products | **2** | Included from the profile. The resolved driver identity includes `licenseType`, but the payload does not use it. Hull checks whether 2 is active, not whether it is the driver's licence category. | Config `:107`; `service:4679` vicinity; map the actual stored driver's selection. |
|
||||
| `LicenceTypeId` — third-party damage | **2** | Always assigned from `defaults.CulpritLicenceTypeId`, ignoring the damaged driver's stored licence type. | `service:3253`. |
|
||||
| `CulpritTypeId` — third-party base | **337 / 338** | Final value comes from a static map: policyholder/driver same national code → 337, different → 338. Missing role information can default to 337. It is no longer simply the profile's 337. | `fanavaran-party-roles.ts:205–226`; `service:4687`; resolve current tenant IDs by confirmed role meaning and reject unknown roles. |
|
||||
| `AccidentVehicleUsedId` — third-party base and damage | **1** | Fallback when inquiry/group resolution is unresolved; an expert's approved use type can override it. Hull base has removed this numeric fallback. | `service:4771`, `3208`; preserve the actual vehicle use or require a selection. |
|
||||
| `DmgCaseTypeId` — third-party damage | **175** | Unconditionally taken from the profile. No current expert stage field for it. | `service:3235`; determine the actual damage-case classification. |
|
||||
| `DmgHistoryStatus` — third-party damage | **5214** | Profile default unless reviewed. | `service:3231–3233`; actual history/explicit selection. |
|
||||
| `PlaqueKindId` / `PlaqueSampleId` — third-party damage | **8 / 10** | National-plate fallback when matched Fanavaran vehicle has no kind. Even with a real kind, a missing sample still falls back to 10 and is labelled `vehicle-inquiry`. | `src/lookups/fanavaran-last-car-policy.ts:391–392`, `450–470`; require sourced plate IDs with compatible kind/sample. |
|
||||
| `PlaqueMiddleCodeId` — third-party damage | Static **1–24** letter map | Used when the matched vehicle does not provide a middle code. These are explicit fixed mappings rather than a default letter, but are still tenant-unverified numeric codes. | `service:424–449`, `3266`; map through the tenant's plate-letter catalogue. |
|
||||
| `PoliceOfficerId` — third-party base | **1** | Assigned directly; hull explicitly replaces it with null. | `service:1857`; `fanavaran-hull-base-claim.ts:164`; real officer selection or null if permitted. |
|
||||
| `InspectionPlaceId` — third-party expertise | **282** | Default unless reviewed. Fetching the inspection-place list does not select or validate this fallback at the write boundary. | `service:6014–6020`; explicit inspection place. |
|
||||
| `DropAmountStatus` — third-party expertise | **5458** | Always assigned directly, even though `drop-amount-status` is fetched. Not a current editable stage field. | `service:6015–6020`; derive from confirmed depreciation outcome or require selection. |
|
||||
| `DmgSections[].AccidentLevel` — third-party expertise | **5456** | Any nonnumeric `typeOfDamage` falls back to 5456. **The ordinary expert UI sends `تعمیر` / `تعویض`, so normal UI replies take this fallback.** Those values express repair/replacement, not damage severity. | `service:5888–5899`; expert `damagePartTable.tsx:2292–2305`, `claimReplySubmit.tsx:183–192`; add a separate severity field rather than treating repair method as severity. |
|
||||
| `FileTypeId`, including `Files[].FileTypeId` — attachments | **Parsian 63 / Tejaratno 23 / Moallem 17** | One configured type is assigned across collected document/photo categories. Hull checks that the ID is active, not that its meaning matches each document. | Config `:155`, `181`, `201` vicinity; `service:5126`, `5329`, `5495–5497`; per-document semantic mapping to current tenant catalogue. |
|
||||
| `CityId` — GEN.44 person creation | **9131** | Fallback if a person's explicit city and caption lookup cannot resolve it; shared helper has no tenant argument. This remains despite the **HTTP Location** fix. | `fanavaran-other-people.ts:95`, `251–254`; actual person city, never a Parsian city ID for another tenant. |
|
||||
| `PersonKindId` — GEN.44 | **46** | Natural-person caption lookup fallback; shared across all clients. | `fanavaran-other-people.ts:96`, `265–268`; resolve correct person kind for the tenant/person. |
|
||||
| `IsIranian` — GEN.44 | **1 / 0** | Fallback when `ans` lookup is unavailable. The helper assumes Iranian unless explicitly false or a naturalized code is present. | `fanavaran-other-people.ts:214–215`, `259–261`; encode confirmed nationality using the proper contract. |
|
||||
|
||||
`ClaimFileTypeId` also has a startup migration: Moallem's stored **23 → 17**
|
||||
(`fanavaran-client-config.service.ts:40–45`). Editing a stored value back to 23
|
||||
does not survive that startup migration.
|
||||
|
||||
The static plate-letter map is:
|
||||
`الف=1، ب=2، پ=3، ج=4، د=5، س=6، ص=7، ط=8، ع=9، ق=10، ل=11، م=12، ن=13، و=14، ه=15، ی=16، ک=17، ژ=18، ت=19، ث=20، ز=21، ش=22، ف=23، گ=24`.
|
||||
|
||||
## 2. Default values that are not lookup IDs but still assert case facts
|
||||
|
||||
| Field | Current assumption | Source / consequence |
|
||||
|---|---|---|
|
||||
| `AccidentLocationAddress` | **`استان تهران شهر تهران`** | `service:404`, `1910`, `5690`. Location coordinates are accepted by the builder but not used here. Expert review/manual text can replace it. **This address default is separate from the fixed HTTP `Location` header.** |
|
||||
| `CulpritLicenceNo`, damage `LicenceNo` | Environment dummy, else **`9705463515`** | `service:412–413`, `1812`, `1818`, `3250`, `7570`. Real licence preferred, but missing/empty values and even empty manual overrides are replaced by a fabricated number. |
|
||||
| `CulpritLicenceIssuDate`, damage `LicenceIssuDate` | **`1394/10/13`** | `fanavaran-party-roles.ts:11`, `237–242`; shared builder also initializes it at `service:1835`. Real stored date wins if available. |
|
||||
| `EstimateAmount` | **1000 rials** | `service:407`, `1770`, `3238`. Base uses it when no positive calculated estimate exists; damage builder always initializes to it, with manual amount override available. |
|
||||
| `FaultPercent` — damage | **100** | Profile default, `service:3239`; does not derive an actual percentage. |
|
||||
| `CustomerFaultPercent` — hull | **100** | `service:2642`, `fanavaran-hull-base-claim.ts:59`, `154–157`; expert stage review can replace it. |
|
||||
| `RepairDuration` — hull expertise | **3 days** | `service:2844–2846`, `fanavaran-hull-expertise.ts:80`, `121–122`; review can replace it. Optional `HullExpertiseRepairDuration` exists in the profile interface but this builder does not use it. |
|
||||
| `DamagedCount` — third-party base | **1** | `service:1838`. Current two-party flow has one beneficiary, but this is a fixed scenario assumption. |
|
||||
| `IsLicenseMatchWithVehicleKind` | **1** | `service:1842`; no actual licence/category compatibility calculation here. |
|
||||
| `HasOtherCulprit`, `IsAccidentOutOfBorder`, `IsFatalAccident`, `IsPlaqueChanged`, `IsLicenseReplacement` — third-party base | **0** | `service:1843–1848`, `1865`; assertions of “no”, not inferred accident facts. |
|
||||
| `IsLicenseReplaced` — hull | **Always 0** | `fanavaran-hull-base-claim.ts:126–129`; forced even if the incoming builder value differs. Current code intentionally implements the previous contract decision. |
|
||||
| `IsOwnerChanged`, `CostSeparationToDmgSections` — hull | **0 when absent** | `fanavaran-hull-base-claim.ts:135–142`. Encoded through `ans`, validated for membership on hull writes. |
|
||||
| `Count` — hull damage section | **1** | `fanavaran-hull-expertise.ts:156`; one item per selected part row. Must be explicit if quantities can differ. |
|
||||
| `ComponentReplacementTaxAndToll` — third-party expertise | **0** | `service:6051`; not computed from an expert-entered tax value. |
|
||||
| `PoliceReportDesc` | **`شرح گزارش`** | `service:1858`; arbitrary placeholder, manual text override possible. |
|
||||
|
||||
Calculated sums starting at zero, optional nulls, empty collections, retry counts,
|
||||
timeouts and pagination limits are not themselves guessed business IDs. They
|
||||
must be distinguished from asserting “zero tax”, “100% fault”, or “no fatality”.
|
||||
|
||||
## 3. Implicit guesses that still violate the intention
|
||||
|
||||
These no longer necessarily use a numeric fallback, but still choose a business
|
||||
meaning without evidence from the case:
|
||||
|
||||
1. **Vehicle use:** `fanavaran-accident-vehicle-used.ts:37–80` preserves a valid
|
||||
preferred use, otherwise chooses a caption containing `شخص`, otherwise the
|
||||
first active row in the vehicle group. A live row is not proof of actual use.
|
||||
Used by third-party base/damage; hull base now bypasses this substitution.
|
||||
2. **Vehicle model:** `service:2029–2065` can select the first caption matching a
|
||||
broad body type such as sedan/SUV. This is a fallback in the damage builder;
|
||||
an approved exact vehicle kind has priority. A broad type is not a model.
|
||||
3. **Hull accident/culprit/authority:** `service:2642–2653` selects
|
||||
`تصادف(حادثه)`, `بیمهگذار`, and an authority caption containing `بیمهگذار`
|
||||
unless review supplies alternatives. IDs come from current lookup responses,
|
||||
but the scenario is still assumed.
|
||||
4. **Hull damage kind/cost kind:** `service:2746–2752` chooses `تخریب` and
|
||||
`مجموع لوازم` for the sections. The removed 5485/1 numeric fallbacks are gone,
|
||||
but the same two meanings are still automatically applied to all parts.
|
||||
5. **Hull accessory:** `fanavaran-hull-expertise-lookups.ts:77–102` first matches
|
||||
the part's accessory kind; otherwise picks the policy's factory-parts bundle.
|
||||
This is a policy-sourced fallback, not a fixed record ID, but bundle
|
||||
applicability still requires a business rule.
|
||||
6. **Hull culprit identity/value:** policy `CustomerId` can substitute for the
|
||||
driver when person inquiry misses (`service:2625` vicinity), and insured
|
||||
`VehicleValue` can substitute for market/current value. Neither is a fixed
|
||||
number, but policyholder is not necessarily driver and insured value is not
|
||||
necessarily current market value.
|
||||
|
||||
## 4. Cross-stage default leakage in the base payload
|
||||
|
||||
`fanavaranPayloadDefaultsWithoutExpertIds` (`service:3426–3437`) removes only
|
||||
`ClaimExpertId` and `ExpertiseClaimExpertId`. The base builder spreads **all
|
||||
remaining profile defaults** (`service:1892–1894`).
|
||||
|
||||
For **Parsian/Moallem third-party** payloads, unlike the hull and Tejarat V15
|
||||
whitelists, this can leave these extra defaults on the outgoing base object:
|
||||
|
||||
- `DmgCaseTypeId=175`
|
||||
- `DmgHistoryStatus=5214`
|
||||
- `DriverIsOwner=0`
|
||||
- `FaultPercent=100`
|
||||
- `ClaimFileTypeId=63` (Parsian) / `17` (Moallem)
|
||||
- Optional `HullExpertiseRepairDuration`, if present in stored defaults.
|
||||
|
||||
The numbers reflect seeds and may differ in Mongo. The defect is the unrestricted
|
||||
spread, regardless of values. These fields belong to other stages; approval of
|
||||
the base accident fields does not fix their leakage. Each product/stage needs an
|
||||
explicit outbound key whitelist.
|
||||
|
||||
## 5. What the recent fixes actually solved
|
||||
|
||||
- **Claim HTTP `Location`: fixed for application claim writes.**
|
||||
`service:3375–3423` requests `requireStaffLocation: true`; the location service
|
||||
uses assigned staff `locations[].id` or that staff member's branch **code**,
|
||||
and throws `FANAVARAN_STAFF_LOCATION_MISSING` when none exists. This is used
|
||||
by claim base, damage, attachment, expertise, hull update, and claim-linked
|
||||
GEN.44 writes. The branch Mongo `_id` is not sent as the OpBUId.
|
||||
- **General lookup/read headers still have a tenant Location fallback.**
|
||||
`fanavaran-auth.service.ts:281` uses `auth.location` when no explicit override
|
||||
exists. Generic `FanavaranLookupService.postToFanavaran` also uses those
|
||||
headers, although its `createOtherPerson` wrapper currently has no production
|
||||
caller in `src`. This does not undo the strict claim-write resolver.
|
||||
- **Hull base `UsedId`: fixed.** Exact policy vehicle/version is used; a missing
|
||||
value blocks the write rather than falling back to 1.
|
||||
- **Hull `VehicleHullAccessoryId=3043330`: removed.** It now comes from the
|
||||
current policy's accessories, with exact-part/factory-bundle resolution.
|
||||
- **Hull numeric accident/culprit/authority/damage/cost fallbacks:** the old
|
||||
2/300/first-row-or-1/5485/1 substitutions have been removed. Caption-derived
|
||||
defaults and other fields listed above remain.
|
||||
- **`PoliceOfficerId=1`: removed for hull**, still present for third-party.
|
||||
- **Assessor/case-owner expert IDs: fixed in application payloads.** Assigned
|
||||
staff's product-specific codes are required; profile `ClaimExpertId` and
|
||||
`ExpertiseClaimExpertId` seeds are stripped rather than used as write fallbacks.
|
||||
Their numeric presence in config alone must not be reported as an active
|
||||
application expert-ID fallback.
|
||||
|
||||
## 6. Standalone Fanavaran flow UI has separate defaults
|
||||
|
||||
The file currently open in the IDE, `scripts/fanavaran-flow-ui-server.js`, launches
|
||||
`scripts/fanavaran-flow-test.sh` (`:962–970`). It does **not** call the Nest claim
|
||||
builder. Fixing one implementation does not automatically fix the other.
|
||||
|
||||
| Tool / location | Defaults or fixed choices |
|
||||
|---|---|
|
||||
| Flow shell `:409–448` | City701, report155, third-party use1, compensation167, licence2, culprit337, cause6, damage type175, history5214, plate8/10, fault100, estimate1000, inspection282, drop5458, severity5456, Tehran address, dummy licence/date, hull repair3. Environment values override these; absent ones silently use the defaults. |
|
||||
| Flow shell `:352–380` | Fixed tenant CorpId/ContractId and Location: Tejaratno **3539/263/100**, Parsian **543/28/210050**, Moallem **5650/304/30900**. Shell hull contract falls back to the configured third-party contract if a hull contract is not supplied. |
|
||||
| Flow HTML `:1052–1092`, `:1316–1399` | Static expert/branch lists. Tejaratno auto-selects case-owner2721 and assessor2709 at location100; Moallem defaults to first case-owner5347 and assessor5350 at location30900; Parsian chooses branch210110 and the first listed maker32/reviewer3989 when no preference exists. Other static choices remain in these tables. |
|
||||
| Flow HTML `:789–790`, `:1611–1619` | Static culprit337/338 mapping by role scenario. |
|
||||
| Flow HTML `:851–853`, `:879–900` | Prefilled GEN.44 city9131/person-kind46/Iranian1, example amounts, repair3, fault100, example vehicle current value0. Also contains sample identity/plate/licence values; do not treat these as real inquiry evidence. |
|
||||
| Flow server `:1168` | Party inquiry falls back to Location **100** if neither environment nor query supplies it. |
|
||||
| Auth shell `scripts/fanavaran-auth.sh:26–55` | Independent hardcoded tenant auth scope/location defaults. |
|
||||
| Car-parts GET shell | Prompts for business credentials/scope; defaults the connection URL. It does not build claim/damage/expertise payloads. |
|
||||
|
||||
The flow UI now requires live active hull lookup selections for relevant stages;
|
||||
that does not remove the shell's underlying defaults, nor static staff/branch
|
||||
choices. It can still write real records when its submission actions are run.
|
||||
|
||||
## 7. Fixed identifiers that need a different treatment
|
||||
|
||||
- `InsuranceLineId=5` (third-party) / **4** (car-body): explicit product routing
|
||||
constants in `src/lookups/fanavaran-last-car-policy.ts:5–6`. These encode the
|
||||
selected product; they are not a fallback to a random policy/person record.
|
||||
- Role IDs161/166 (and the defined owner role163) identify accepted response
|
||||
roles. `fanavaran-driver-inquiry.ts` selects actual returned person IDs rather
|
||||
than sending 161/166 as `DriverId` or falling back to the first arbitrary row.
|
||||
- Tejarat notifier lists in `src/fanavaran/tejarat-notifier.ts` contain the
|
||||
tenant-supplied IDs5516/5517 and5519–5526. They are allowed choices, **not an
|
||||
automatic notifier selection**; review is required. The shared DB lookup's
|
||||
tenant provenance still needs attention.
|
||||
- Tenant CorpId/ContractId, authentication identities and API URL roots are
|
||||
deployment configuration. They must be configured for the deployment rather
|
||||
than deleted as though they were guessed accident data. Auth material also
|
||||
exists in seed/tool source; no secret values are reproduced in this report.
|
||||
- Seed expert IDs still exist (Parsian154/29, Tejaratno2721/2709,
|
||||
Moallem5347/5350; shared4543092/2709). As noted above, the application excludes
|
||||
them from outbound expert-ID resolution; the standalone HTML does not.
|
||||
- Runtime auth-location seeds are Parsian110011 / Tejaratno100 / Moallem1;
|
||||
standalone auth/flow tools have different Parsian/Moallem defaults. Scope them
|
||||
explicitly when using those tools.
|
||||
|
||||
## 8. Catalogue/cache provenance also needs to be fixed
|
||||
|
||||
Removing numeric `?? default` statements alone is insufficient:
|
||||
|
||||
1. `getLiveFanavaranCatalogItems` (`service:774–784`) falls back to the shared
|
||||
static car-component list when lookup rows are empty. This helper is used for
|
||||
selections, despite the snapshot comment saying it is legacy-only. Stored
|
||||
`partId` is then passed into `DmgSectionId` / `AccessoryKindId`. Hull validates
|
||||
membership against live rows; third-party has no equivalent complete guard.
|
||||
2. Mongo `lookups` is keyed by `name` without tenant/product scope; vehicle-kinds
|
||||
has globally unique `Id` without tenant scope. DB-first/cache fallback can
|
||||
therefore produce a real code from the wrong insurer. Lookup startup sync
|
||||
can also populate a tenant's disk cache from that shared DB.
|
||||
3. `getRemoteLookup` accepts any non-null parsed cache value, including an API
|
||||
error object; callers may turn it into an empty list and then use defaults.
|
||||
4. Vehicle/stage review validation at save time is not comprehensive proof of
|
||||
current-tenant outbound validity. Hull validates many codebook IDs immediately
|
||||
before writing; third-party lacks an equivalent complete validation layer.
|
||||
5. Offline/mock inquiry data is another explicit source of seeded values:
|
||||
`src/offline-inquiry/`, SandHub and global system settings. Offline inquiries
|
||||
default to enabled, and live SandHub requires an explicit true setting.
|
||||
Production configuration must be verified separately; this audit did not read
|
||||
production settings or treat fixture IDs as evidence of live inquiries.
|
||||
|
||||
## 9. Recommended implementation order
|
||||
|
||||
1. Whitelist every stage/product payload. Eliminate cross-stage default leakage.
|
||||
2. Remove invented cause/licence/person/city/plate values and preserve actual
|
||||
stored inquiry selections with tenant/product provenance. Missing required
|
||||
values must produce an actionable Persian preview/submit error before any
|
||||
remote write; optional unresolved values should be null/omitted per contract.
|
||||
3. Add explicit expert fields for genuinely unavailable data: cause, licence
|
||||
type, compensation reference, damage-case type, separate damage severity,
|
||||
depreciation status, relevant flags, and document category as needed. Reuse
|
||||
existing city/report/history/inspection controls, initially unselected.
|
||||
4. Resolve tenant codes by selected meaning and current lookup response. Never
|
||||
fall back to first/personal row, fixed record ID, or another insurer's code.
|
||||
Keep a deliberate, documented distinction for product/role protocol constants.
|
||||
5. Make lookup and vehicle-kind storage tenant-scoped. Reject invalid cache
|
||||
shapes and refetch/review old unsourced IDs rather than migrating by number.
|
||||
6. Apply the same strict rules to both standalone flow tools and application
|
||||
writes. Replace static staff/branch defaults with explicit selections.
|
||||
7. Update tests that currently assert defaults; add tests that missing, stale,
|
||||
inactive, wrong-tenant and semantically unrelated IDs never trigger remote
|
||||
POST/PUT. Test normal `تعمیر`/`تعویض` replies with independent severity data.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
- Stashed tracked/untracked local changes, fast-forwarded API to `90bdc51`, and
|
||||
restored the stash without conflicts. Other checked non-rewrite repositories
|
||||
were already current; earlier stashes were preserved.
|
||||
- The backend Jest run completed successfully: **94 suites, 823 tests** in the
|
||||
restored worktree. Existing tests include intentional fallback expectations
|
||||
(for example GEN.44 city9131/person-kind46); passing does not prove absence of
|
||||
guessed values. External providers are mocked in these tests.
|
||||
- An isolated local probe executed source-extracted builder methods without
|
||||
initializing Nest/Mongo or calling HTTP. A supplied cause999 still produced
|
||||
cause6; Parsian/Moallem shared base objects retained the cross-stage fields
|
||||
listed above; both `تعمیر` and `تعویض` produced accident level5456. This probes
|
||||
the builder before product filtering, not a complete production HTTP exchange.
|
||||
- Source tracing covered the application's Fanavaran write builders and their
|
||||
shared submission paths plus standalone tools. No Fanavaran write, real SMS,
|
||||
production database change, or live tenant lookup was performed for this audit.
|
||||
- Application behavior has not been changed. The table is a remediation worklist,
|
||||
not a statement that the “no default codes” policy is already implemented.
|
||||
@@ -1,5 +1,9 @@
|
||||
# Fanavaran lookup coding audit
|
||||
|
||||
**Update (2026-11-11):** The latest hull/accessory/location changes supersede
|
||||
several findings below. See [the current hardcoded-payload audit](./hardcoded-payload-audit.md)
|
||||
for what remains, including exact outbound defaults and standalone tool behavior.
|
||||
|
||||
Date: 2026-11-10. Clients: Moallem, Tejaratno, Parsian. Scope: current base,
|
||||
damage-case, attachment, expertise and other-person payload builders shared by
|
||||
app flows V1–V6. This is a code and local-snapshot audit, not a live acceptance
|
||||
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -20,20 +20,32 @@ 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` |
|
||||
| Edit staff | `PATCH /super-admin/management/staff/:role/:id?clientId=...` | `PATCH /expert-insurer/management/staff/:role/:id` |
|
||||
| Activate/deactivate a staff role account | `PATCH /super-admin/management/staff/:role/:id/status?clientId=...` | Unavailable |
|
||||
| List/create branches | `GET/POST /super-admin/management/branches?clientId=...` | `GET/POST /expert-insurer/management/branches` |
|
||||
| Edit branch | `PATCH /super-admin/management/branches/:id?clientId=...` | `PATCH /expert-insurer/management/branches/:id` |
|
||||
|
||||
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.
|
||||
|
||||
Staff creation requires `firstName`, `lastName`, a ten-digit `nationalCode` and a password of at least six characters. Email and mobile are optional for field experts, file makers, file reviewers and call-center agents, matching the seed format. Blame and claim experts require email and mobile to match their existing account contracts. Seed-style accounts without email log in using their national code. National-code and email aliases cannot be duplicated across new managed accounts.
|
||||
Staff creation requires `firstName`, `lastName`, a ten-digit `nationalCode` and a password of at least six characters. Email and mobile are optional for claim experts, field experts, file makers, file reviewers and call-center agents, matching the seed format. Blame experts still require email and mobile. Seed-style accounts without email log in using their national code. National-code and email aliases can be reused across different roles; they remain unique within a role because login has no tenant selector. Create each required role with the same credentials to let one person use several flows. Existing records and passwords are preserved. The remaining-experts seed prepares sparse email indexes for older claim-expert databases before inserting email-less accounts.
|
||||
|
||||
Staff lists include `isActive`, treating older records with no flag as active. Only super-admins can change this flag using the status endpoint and a boolean body, e.g. `{"isActive": false}`. Disabled accounts cannot log in or reuse existing JWTs. Status belongs to the selected role account; the same person's other assignments are unaffected. See [expert access and optional voice](expert-access-and-optional-voice.md).
|
||||
|
||||
Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `state`, `address` and `expertCode`. A branch, when supplied, must belong to the account's insurer. `expertCode` and the role-specific Fanavaran IDs are positive integer strings, matching existing persistence and mapping contracts.
|
||||
|
||||
@@ -71,6 +83,6 @@ PATCH sends only changed fields. Omit `password` to preserve it; supply a replac
|
||||
|
||||
## Verification
|
||||
|
||||
`npm test -- --runInBand` includes schema-backed management tests for all six roles, optional seed fields, role-specific IDs, locations, tenant isolation, branch updates, account passwords, protected fields and strict DTO validation. The route contract keeps the 383 existing routes and adds 18 guarded management routes.
|
||||
`npm test -- --runInBand` includes schema-backed management tests for all six roles, optional seed fields, role-specific IDs, locations, tenant isolation, branch updates, account passwords, protected fields and strict DTO validation. The route contract retains the existing routes and records the additional super-admin status endpoint. HTTP tests cover cross-role login, activation, status permissions, and rejection of existing sessions after deactivation.
|
||||
|
||||
The expert UI's `npm run test:ui` includes management proxy and payload regression checks. Desktop/mobile browser checks use mocked local API responses, rather than modifying a real insurer. Live credential login, database indexes under concurrent writes and outbound Fanavaran submission remain integration QA responsibilities.
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Accident location without GPS
|
||||
|
||||
Location steps accept either a real latitude/longitude pair or a written accident
|
||||
address. Existing coordinate clients remain supported. No migration is needed.
|
||||
|
||||
```json
|
||||
{ "address": "تهران، خیابان آزادی، روبهروی دانشگاه" }
|
||||
```
|
||||
|
||||
```json
|
||||
{ "lat": 35.6892, "lon": 51.389 }
|
||||
```
|
||||
|
||||
An address is trimmed and must contain 10–1000 characters. Both coordinates must
|
||||
be finite numbers within valid ranges if supplied. Empty input, incomplete
|
||||
coordinates and invalid addresses produce Persian errors. Unknown properties
|
||||
are discarded. The existing party ownership, role and workflow checks still run.
|
||||
|
||||
The same contract covers the normal user/v6 location endpoint, the expert
|
||||
mirror endpoints (v2/v3) and optional v4/v5 location submissions. The expert panel
|
||||
IN_PERSON endpoint wraps the value as `{ "location": { "address": "..." } }`.
|
||||
V4/v5 still skip location and do not gain a new mandatory step.
|
||||
|
||||
The user form always offers a written-address field, including while GPS is
|
||||
pending or denied and when map tiles fail. Typed addresses take precedence over
|
||||
GPS, since the current device position may differ from the accident scene.
|
||||
The initial map centre is only a viewport and is never automatically submitted.
|
||||
Dragging or clicking the map is an explicit selection. Pending location data is
|
||||
reset when switching cases or parties; saved addresses count as completed
|
||||
location evidence on resume.
|
||||
|
||||
`parties[].location.address` persists through the shared location schema, claim
|
||||
snapshots and detail responses. The expert panel and exported case report show
|
||||
the address even without coordinates. The Fanavaran address review is populated
|
||||
from the recorded address when available; previously reviewed/sent values keep
|
||||
precedence. Existing GPS-only Fanavaran behavior is unchanged.
|
||||
|
||||
Checks: `accident-location.spec.ts`, `call-center-v6-workflow.spec.ts`,
|
||||
`file-maker-blame-v4-workflow.spec.ts`, `case-expert-report.builder.spec.ts`,
|
||||
`fanavaran-stage-fields.spec.ts`; UI `test-location-fallback.cjs` and
|
||||
`test-accident-detail.cjs` cover GPS errors, late GPS, saved addresses and user/
|
||||
expert location orchestration across v1/v2/v3/v6.
|
||||
@@ -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,37 @@
|
||||
# Recovering already-saved photos during capture
|
||||
|
||||
The capture-requirements endpoint now reads `requiredDocuments` from both
|
||||
Mongoose Maps and ordinary objects. The object case previously returned
|
||||
`uploaded: false` even for a saved chassis/engine photo, causing the UI to
|
||||
request it again and encounter the duplicate-document conflict.
|
||||
|
||||
Initial `upload-document` retries now acknowledge an existing uploaded document
|
||||
when a saved file path/URL is present. The response contains the existing
|
||||
`fileUrl`, the current persisted workflow step and `alreadyUploaded: true`.
|
||||
Ownership/tenant checks still run first. This does not replace the saved image,
|
||||
create a second document reference, append duplicate history, or resend the
|
||||
attachment to Fanavaran. A flag without file evidence is not acknowledged.
|
||||
Expert resends and active in-person replacement uploads keep their existing
|
||||
validation paths. Expert capture-document retries after the capture phase
|
||||
advanced can reuse confirmed evidence after the same ownership checks.
|
||||
|
||||
The user camera and gallery pages read saved part/angle/document flags, offer
|
||||
Continue for those slots without requiring another photo, and keep locally
|
||||
successful photo uploads separate from video completion. If the last photo
|
||||
saves but video upload fails, retrying completion only retries the video; it
|
||||
cannot re-upload the chassis image and encounter a duplicate error. Local photo
|
||||
receipts are scoped to the claim, and field-expert uploads await the selected
|
||||
API promise before recording success or advancing. The version was previously
|
||||
awaited instead of the upload promise in several conditional API calls.
|
||||
|
||||
The camera still records and submits the required walk-around video. Missing
|
||||
images and actual API failures remain blocking; error text or HTTP 409 alone is
|
||||
never treated as evidence of a successful upload.
|
||||
|
||||
Verification:
|
||||
|
||||
- API: `upload-document-idempotency.spec.ts`, `capture-part-concurrency.spec.ts`,
|
||||
`claim-capture-phase.spec.ts`, `ai-capture-integration.spec.ts`.
|
||||
- UI: `scripts/test-capture-upload-recovery.cjs`, included in `npm run test:ui`;
|
||||
covers saved chassis/parts, failed-video retry, awaited/rejected expert
|
||||
requests, case isolation and camera/gallery implementations.
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -0,0 +1,106 @@
|
||||
# User-selected claim branch (flows 1 and 6)
|
||||
|
||||
Before accepting the blame report/signature, the damaged party selects a city and an active branch of the insurer **paying** the claim. In third-party cases the payer is the guilty party's insurer, even if the damaged vehicle has another insurer. In car-body cases it is the first/only party's insurer. Both guilty-party positions and call-center cases are supported.
|
||||
|
||||
Expert/registrar/FileMaker-created flows retain their existing branch/ownership rules. The server determines applicability from the stored case flags, not a browser version parameter. Administrative insurer/super-admin oversight is unchanged.
|
||||
|
||||
## API
|
||||
|
||||
All routes below use existing user authentication and the user-role guard:
|
||||
|
||||
- `GET /v2/blame-request-management/:requestId/claim-branches`: authorize case access, resolve the beneficiary/payer, and return `{required, branchId, locked, branches, claimRequestId?}`. `claimRequestId` is included when a claim already exists for the beneficiary so reloading claim entry can resume it. Locked claims do not fetch branch options. Only the beneficiary receives branch options. Each option contains `id`, `name`, `code`, `city`, `state`, `address`, and optional `phoneNumber`. Options are active branches from the payer only; the client cannot supply an insurer ID.
|
||||
- `PUT /v2/blame-request-management/:requestId/claim-branch`: `{branchId}` saves a validated branch while waiting for signatures or after signing, before any claim exists. This supports historical cases that were already signed when the feature deployed. Other parties cannot select a branch. Existing claims freeze routing; this endpoint cannot move them to another branch.
|
||||
- Existing `PUT /v2/blame-request-management/sign/:requestId` accepts an additional multipart `branchId`. When the damaged user accepts in a user-led flow, a valid branch is mandatory (either supplied now or previously saved). Branch validation occurs before creating the signature record. Confirmation and branch ID are saved in the same blame update. The guilty party signs normally without choosing a branch. Rejection does not require a branch.
|
||||
|
||||
Invalid IDs, inactive branches and branches from another insurer are rejected with Persian errors. The API checks the insurer relationship; UI filtering alone is insufficient. If there are no active branches, the user sees a support message and cannot confirm acceptance/create a new claim until the insurer provisions its branches.
|
||||
|
||||
`GET /v2/blame-request-management/:requestId` includes `claimBranch: {required, branchId}` for the current viewer.
|
||||
|
||||
## Claim creation and expert access
|
||||
|
||||
`createClaimFromBlameV2` revalidates the active branch and copies `blame.branchId` to `claim.branchId`. Missing/invalid selection prevents creation and automatic Fanavaran submission. Changing browser state or calling the creation endpoint directly cannot omit branch validation. This adds no Fanavaran lookup ID or payload field.
|
||||
|
||||
Flow 1 skips automatic Fanavaran submission during local claim creation. Later staged submission hooks remain enabled and can create the base Fanavaran claim when needed. Flow 6 and expert/registrar/FileMaker-created flows retain their existing submission timing.
|
||||
|
||||
The existing expert claim list filter and detail/assignment/action authorization compare the claim branch with the expert's stored branch, in addition to insurer/tenant isolation. Thus a new routed claim appears in that branch's queue and is rejected for damage experts from another branch, including direct access by case ID. Missing expert branch assignments are already denied. Insurer administrators should assign claim experts to the appropriate branches before rollout.
|
||||
|
||||
Existing claims are not migrated or reassigned. Their current access/ownership rules remain in effect. Already-signed blame cases without a claim select their branch on the final screen before entering claim creation. Direct entry into `/claim` also checks selection and returns to that screen if necessary. Deactivation between signing and creation requires choosing another active branch.
|
||||
|
||||
## User interface
|
||||
|
||||
The city and branch selectors appear above the signature canvas, only for the damaged user. A city change clears the branch selection. Same-named cities in different provinces have separate choices. The selected branch's address and phone are displayed. Loading, fetch failure/retry, empty lists and locked routing have explicit Persian states. Confirmation is disabled until the selection is valid. The signature dialog scrolls vertically on small screens.
|
||||
|
||||
The final screen displays the saved branch by name. It only shows the selector for signed cases without a valid active selection (including historical cases); the backend selection rule also protects direct claim entry. Later v6 claim-result signing no longer asks for another branch, avoiding a competing choice. Existing expert-created flows retain their existing result-signing UI.
|
||||
|
||||
## Deployment and verification
|
||||
|
||||
Deploy API and `ui-user` together. No environment variables or database migration are required: the existing `branchId` fields and branch indexes are reused. Configure active branches, city/state/address and expert branch membership in the management panels. `ui-expert` already implements the required branch checks; no UI change there is needed.
|
||||
|
||||
Backend tests cover beneficiary/payer resolution, car-body and both third-party guilty positions, active insurer-scoped options, rejected foreign/inactive IDs, signature enforcement/persistence, culprit restrictions, legacy pre-claim selection, immutable existing claims, claim inheritance and branch access. Existing v6 workflow and authorization tests remain in place. Frontend tests cover city grouping, actor/case partitioning, loading/error/empty states, signature navigation and claim-entry compatibility.
|
||||
|
||||
Production QA should exercise each product in v1 and v6, both signature orders, a signed historical case, no active branches, deactivation before creation, and experts from two branches in the same insurer. Verify the selected branch sees the submitted claim and the other branch cannot list/open/assign it. Repeat expert-created flows 2–5 to confirm their creator ownership is preserved.
|
||||
|
||||
## Combined verification — 2026-11-11
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Complete API unit/regression suite | 90 suites, 774 tests passed |
|
||||
| HTTP branch/signature/claim integration | 16 scenarios passed (`npm run test:e2e`) |
|
||||
| User and expert frontend regression suites | Both passed |
|
||||
| Browser scenarios | 14 passed on real v1/v6 pages: desktop/mobile positive paths, legacy entry and guilty-party signing |
|
||||
| TypeScript | API, user UI and expert UI checked |
|
||||
|
||||
The integration test is `test/claim-branch-flows.e2e-spec.ts`. It uses the production controllers, JWT verification, role guards, Persian error filter, branch service, signature service and claim creation method. Repository operations are isolated in-memory implementations that return fresh documents and apply persisted updates; media policy and external SMS/Fanavaran delivery are mocked. Generated test signature files are removed afterward. The resulting claim is passed through the actual expert tenant/branch authorization and queue-filter methods.
|
||||
|
||||
The matrix covers v1 car-body, v6 car-body, both possible v1 third-party damaged parties, v6's second/damaged party, and both valid third-party signature orders. It asserts the insurer comes from the paying party, validates branch inheritance, prevents guilty-party claim creation, rejects foreign/inactive branches, requires both signatures, preserves existing expert-created LINK branches, handles signed legacy cases, rechecks deactivation, blocks missing authentication/wrong roles/non-participants, freezes existing claim routing, and prevents duplicate sequential creation.
|
||||
|
||||
Browser tests draw a signature, verify its multipart request includes the selected branch, continue to claim creation once, and verify the claim can proceed. Changing city clears the previous branch. Existing signed cases entering `/claim` without a branch return to the branch picker. Separate v1/v6 guilty-party checks confirm no branch selection is requested and no claim-creation button appears. Existing suites cover the flow 2–5 ownership and file-maker/reviewer handoff rules.
|
||||
|
||||
No new application defect was found in this verification pass; the additional HTTP integration tests/configuration were retained as regression coverage. External-provider availability, production branch/staff configuration, real database connectivity/indexes and live SMS delivery were not exercised. Those still require deployment QA; these results do not claim an exhaustive proof of every possible application state.
|
||||
|
||||
## Reliability corrections — 2026-11-16
|
||||
|
||||
The original implementation hydrated the complete case (voice/video URLs, expert profile and claim hints) just to authorize branch loading, then loaded that case again. The branch endpoint now reuses the exact authorization, user binding and workflow recovery logic directly, with no media/profile hydration. Legacy branch city/state values are normalized before sorting.
|
||||
|
||||
The frontend branch query has a 15-second timeout and explicit retry. A disabled query no longer renders a loader; an unparseable local JWT no longer silently disables the query forever. Options are cached for 30 seconds by actor and case; every save/signature and claim creation still validates the selected branch on the server. Empty active-branch lists remain a real setup error, with an explicit Persian explanation. They cannot be bypassed by accepting an arbitrary branch.
|
||||
|
||||
Accepting a signature now returns the persisted status, the viewer's `nextAction`, their confirmation, `claimBranch`, and `claimCreation`. The frontend applies that acknowledgement to both the case and branch caches immediately. It does not wait for an additional case GET before navigating. That cache update is essential: without it the next screen still has the pre-signature `branchId: null` and asks for the same branch again. A normal signed case therefore has one city/branch selection, on the blame-signature screen. Later acceptance of the financial assessment remains a separate legal decision and does not ask v1/v6 users for another branch.
|
||||
|
||||
User-led signatures use conditional writes: the case must still be waiting and the viewer must not already have a confirmation. A repeated identical acceptance returns the stored confirmation and branch without replacing them. A conflicting decision cannot overwrite an existing signature. Signature upload filenames use UUIDs so two users uploading `signature.png` in the same millisecond cannot overwrite each other's image. Completing the case is conditional on the persisted required signatures and waiting status; it uses `$addToSet` for workflow history. The same completion logic recovers interrupted records where all required accepted signatures exist but status remains waiting, on detail/list/branch reads or a safe retry. Stopped files and expert-created flows are excluded from this recovery. A notification failure after saving cannot turn a persisted signature into a failed submission.
|
||||
|
||||
Case status polling continues while waiting for the other party, and the next action switches to claim creation only for the beneficiary. The culprit can sign without a branch and cannot create the claim. Case-detail requests are cancellable and bounded; intentional cancellation does not show a false error toast. Failed signing shows the actual Persian error and preserves the canvas while rechecking the saved state. Closing the signature dialog returns to a page with a signing link. Claim entry offers retry, and an existing claim returned by the branch preflight is resumed instead of creating a second claim.
|
||||
|
||||
### Regression commands
|
||||
|
||||
```bash
|
||||
# API unit/regression suite, plus authenticated HTTP scenarios (mock repositories/providers).
|
||||
npm test -- --runInBand
|
||||
npm run test:e2e -- --runInBand
|
||||
|
||||
# In ui-user:
|
||||
npm run test:ui
|
||||
npx tsc --noEmit
|
||||
```
|
||||
|
||||
The HTTP suite also has an optional combined browser tier. Start the user UI with a temporary test-only API URL, then run the test with Playwright installed. The browser forwards only that mock API prefix to the actual test HTTP controllers; JWT/role guards, case/branch/signature services and claim creation run normally. Database operations and SMS/Fanavaran remain isolated fixtures.
|
||||
|
||||
```bash
|
||||
# ui-user terminal (use a separate dev build if another dev server is running):
|
||||
NEXT_PUBLIC_BASE_URL=http://127.0.0.1:3217/mock-api NEXT_PUBLIC_BASE_PATH='' npm run dev -- --hostname 127.0.0.1 --port 3217
|
||||
|
||||
# api terminal; PLAYWRIGHT_MODULE may point to a locally installed Playwright package.
|
||||
CLAIM_BRANCH_UI_URL=http://127.0.0.1:3217 PLAYWRIGHT_MODULE=/path/to/playwright npm run test:e2e -- --runInBand
|
||||
# Optional: CLAIM_BRANCH_BROWSER_EXECUTABLE=/path/to/chrome-or-brave
|
||||
```
|
||||
|
||||
Deploy API and ui-user together. No environment/schema migration is needed. Existing active branches and expert branch assignments are still required. No production data, real provider availability or live SMS delivery is exercised by these isolated tests.
|
||||
|
||||
### Verification of the corrections
|
||||
|
||||
- API: **97 suites / 874 tests passed**.
|
||||
- Authenticated HTTP + combined mobile browser tier: **30 scenarios passed**, including four real UI → controller → persistence scenarios for v1/v6 × car-body/third-party. Database repositories and providers are mocked.
|
||||
- Additional isolated browser matrix: **13 normal/legacy/error scenarios and 6 recovery scenarios passed**, covering desktop/mobile layouts, delayed GETs after signing, guilty-party access, historic signed cases, branch errors/timeouts, empty options, waiting for the other signature, failed signing, double-clicks and cancellation. These use Chromium/Brave with emulated desktop/mobile viewports and drawn canvas signatures.
|
||||
- Complete user UI regression script, API/user TypeScript checks and whitespace checks passed.
|
||||
- The default Next.js production build (`npm run build`) passed with normal build-worker permissions. The initial sandboxed compilation was stopped after stalling; no deployment configuration was changed.
|
||||
|
||||
The tests do not change production data or contact SMS/Fanavaran. The browser tier is intentionally opt-in so a developer without Playwright can still run all HTTP tests; use the command above to include it.
|
||||
Binary file not shown.
@@ -14,6 +14,8 @@
|
||||
"start:prod": "node dist/main",
|
||||
"sms:test:mic": "ts-node -r tsconfig-paths/register scripts/test-mic-sms.ts",
|
||||
"seed:parsian-tehran": "ts-node scripts/seed-parsian-tehran.ts",
|
||||
"seed:parsian-remaining": "node scripts/data/parsian-tehran/seed-remaining-experts.js",
|
||||
"seed:parsian-all": "node scripts/data/parsian-tehran/seed-remaining-experts.js",
|
||||
"seed:reports-fixtures": "ts-node scripts/seed-insurer-reports-fixtures.ts",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
|
||||
@@ -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>
|
||||
@@ -881,6 +889,7 @@
|
||||
<label class="car-body-only"><b>RepairDuration (روز)</b><input id="REPAIR_DURATION" type="number" min="1" max="255" value="3" required /></label>
|
||||
<label><b>COMPONENT_REPLACEMENT_COST</b><input id="COMPONENT_REPLACEMENT_COST" value="500000" /></label>
|
||||
<label><b>WASTE_VALUE</b><input id="WASTE_VALUE" value="0" /></label>
|
||||
<label class="car-body-only s2"><b>شرح گزارش (ضروری برای بدنه)</b><textarea id="POLICE_REPORT_DESC" required></textarea></label>
|
||||
<label class="car-body-only"><b>کد ملی بیمهگذار بدنه</b><input id="CAR_BODY_POLICYHOLDER_NC" value="" /></label>
|
||||
<label class="car-body-only"><b>AccidentCauseId</b><select id="ACCIDENT_CAUSE_ID"></select></label>
|
||||
<label class="car-body-only"><b>AccidentCityId</b><select id="ACCIDENT_CITY_ID"></select></label>
|
||||
@@ -1084,13 +1093,7 @@ node scripts/fanavaran-flow-ui-server.js</pre>
|
||||
APP_NAME:"", APP_SECRET:"", FANAVARAN_USERNAME:"", FANAVARAN_PASSWORD:"", CORP_ID:"", CONTRACT_ID:"",
|
||||
CURL_PROXY:"",
|
||||
};
|
||||
const BRANCHES = {
|
||||
"210110":{name:"شعبه پونک (210110)",makers:[{name:"احمد بستان پیرا",claim:"32"},{name:"مهسا وطن نیا",claim:"34"}],reviewers:[{name:"مهدی روشن دل",tp:"3989"},{name:"مهدی شاملوفرد",tp:"72"}]},
|
||||
"210050":{name:"شعبه غرب تهران (210050)",makers:[{name:"رسول کرکی",claim:"4662"},{name:"اسماعیل سلطانمحمدی",claim:"4221"},{name:"علیرضا گودرزی پور",claim:"4663"},{name:"مهیار کیایی",claim:"1004"}],reviewers:[{name:"رسول کرکی",tp:"29"},{name:"علیرضا گودرزی پور",tp:"16"},{name:"مهدی شاملوفرد",tp:"72"}]},
|
||||
"210040":{name:"شعبه شرق تهران (210040)",makers:[{name:"اسداله نجفی پور",claim:"91"},{name:"سهیلا شکوری",claim:"88"},{name:"ناصر عیوضی",claim:"228"}],reviewers:[{name:"مجید امیری",tp:"3985"}]},
|
||||
"210120":{name:"شعبه والفجر (210120)",makers:[{name:"علیرضا درگاهی",claim:"57"},{name:"داود صدیق",claim:"222"},{name:"مهدی معمارباشی",claim:"216"}],reviewers:[{name:"حسین جعفری",tp:"3542"},{name:"مجید کاظمی",tp:"3992"}]},
|
||||
"110011":{name:"ستاد مرکزی (110011)",makers:[{name:"اکبر بیگ محمدی",claim:"278"}],reviewers:[{name:"فرهاد ملکی",tp:"60"}]}
|
||||
};
|
||||
const BRANCHES = /* PARSIAN_BRANCH_SEEDS */ {};
|
||||
|
||||
const ID_KEYS = ["POLICY_ID","CLAIM_ID","CLAIM_NO","DRIVER_ID","DMG_CASE_ID","EXPERTISE_ID","DMG_NOTIFICATION_ID","INSURANCE_CORP_ID_NUM","ACCIDENT_CULPRIT_ID"];
|
||||
/** Cleared when starting a new Fanavaran submit; person/lookup ids like ACCIDENT_CULPRIT_ID stay. */
|
||||
@@ -1351,20 +1354,20 @@ node scripts/fanavaran-flow-ui-server.js</pre>
|
||||
return;
|
||||
}
|
||||
const b = BRANCHES[$("LOCATION").value];
|
||||
(b && b.makers || []).forEach((m, i) => {
|
||||
const o = document.createElement("option");
|
||||
o.value = m.claim;
|
||||
o.textContent = m.claim + " — " + m.name;
|
||||
if ((preferredClaim && preferredClaim === m.claim) || (!preferredClaim && i === 0)) o.selected = true;
|
||||
claim.appendChild(o);
|
||||
});
|
||||
(b && b.reviewers || []).filter((r) => r.tp).forEach((r, i) => {
|
||||
const o = document.createElement("option");
|
||||
o.value = r.tp;
|
||||
o.textContent = r.tp + " — " + r.name;
|
||||
if ((preferredExp && preferredExp === r.tp) || (!preferredExp && i === 0)) o.selected = true;
|
||||
exp.appendChild(o);
|
||||
});
|
||||
const hull = q("FANAVARAN_PRODUCT") === "CAR_BODY";
|
||||
[[claim, b?.makers || [], hull ? "body" : "claim", preferredClaim],
|
||||
[exp, b?.reviewers || [], hull ? "body" : "tp", preferredExp]]
|
||||
.forEach(([select, experts, codeField, preferred]) => {
|
||||
experts.forEach((expert) => {
|
||||
const code = expert[codeField] || "";
|
||||
const option = document.createElement("option");
|
||||
option.value = code;
|
||||
option.textContent = (code || "❌ کد موجود نیست") + " — " + expert.name;
|
||||
option.disabled = !code;
|
||||
if (code && String(preferred || "") === code) option.selected = true;
|
||||
select.appendChild(option);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function fillBranches() {
|
||||
@@ -1689,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"),
|
||||
@@ -1731,6 +1735,7 @@ node scripts/fanavaran-flow-ui-server.js</pre>
|
||||
REPAIR_DURATION:q("REPAIR_DURATION"),
|
||||
COMPONENT_REPLACEMENT_COST:q("COMPONENT_REPLACEMENT_COST"),
|
||||
WASTE_VALUE:q("WASTE_VALUE"),
|
||||
POLICE_REPORT_DESC:q("POLICE_REPORT_DESC").trim(),
|
||||
CAR_BODY_POLICYHOLDER_NC:q("CAR_BODY_POLICYHOLDER_NC"),
|
||||
ACCIDENT_CAUSE_ID:lookupValue("ACCIDENT_CAUSE_ID"),
|
||||
ACCIDENT_CITY_ID:lookupValue("ACCIDENT_CITY_ID"),
|
||||
@@ -1823,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;
|
||||
@@ -2029,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");
|
||||
@@ -2075,7 +2080,7 @@ node scripts/fanavaran-flow-ui-server.js</pre>
|
||||
set("REPAIR_DURATION","REPAIR_DURATION");
|
||||
set("COMPONENT_REPLACEMENT_COST","COMPONENT_REPLACEMENT_COST");
|
||||
set("WASTE_VALUE","WASTE_VALUE");
|
||||
["CAR_BODY_POLICYHOLDER_NC","ACCIDENT_CAUSE_ID","ACCIDENT_CITY_ID","ACCIDENT_REPORT_TYPE_ID","HULL_ACCIDENT_TYPE_ID","HULL_CULPRIT_TYPE_ID","HULL_AUTHORITY_CULPRIT_ID","CULPRIT_LICENCE_TYPE_ID","ACCIDENT_VEHICLE_USED_ID","POLICE_OFFICER_ID","HULL_IS_ACCIDENT_OUT_OF_BORDER","HULL_CUSTOMER_FAULT_PERCENT","HULL_COST_SEPARATION","HULL_IS_OWNER_CHANGED","HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW","HULL_GLASS_BREAK_REASON_ID","VEHICLE_CURRENT_VALUE","HULL_DMG_KIND_ID","HULL_DMG_COST_KIND_ID","VEHICLE_HULL_ACCESSORY_ID","COLOR_ID","PLAQUE_DESIGN_ID","PLAQUE_CITY_ID","ACCIDENT_PERCENT"].forEach((id) => set(id,id));
|
||||
["POLICE_REPORT_DESC","CAR_BODY_POLICYHOLDER_NC","ACCIDENT_CAUSE_ID","ACCIDENT_CITY_ID","ACCIDENT_REPORT_TYPE_ID","HULL_ACCIDENT_TYPE_ID","HULL_CULPRIT_TYPE_ID","HULL_AUTHORITY_CULPRIT_ID","CULPRIT_LICENCE_TYPE_ID","ACCIDENT_VEHICLE_USED_ID","POLICE_OFFICER_ID","HULL_IS_ACCIDENT_OUT_OF_BORDER","HULL_CUSTOMER_FAULT_PERCENT","HULL_COST_SEPARATION","HULL_IS_OWNER_CHANGED","HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW","HULL_GLASS_BREAK_REASON_ID","VEHICLE_CURRENT_VALUE","HULL_DMG_KIND_ID","HULL_DMG_COST_KIND_ID","VEHICLE_HULL_ACCESSORY_ID","COLOR_ID","PLAQUE_DESIGN_ID","PLAQUE_CITY_ID","ACCIDENT_PERCENT"].forEach((id) => set(id,id));
|
||||
syncProduct();
|
||||
ID_KEYS.forEach((k) => { stateIds[k] = env[k] || ""; });
|
||||
if (env.CULPRIT_TYPE_ID === "337") $("guiltyRoleMode").value = "1";
|
||||
@@ -2327,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;
|
||||
@@ -2339,6 +2350,12 @@ node scripts/fanavaran-flow-ui-server.js</pre>
|
||||
return;
|
||||
}
|
||||
if (q("FANAVARAN_PRODUCT") === "CAR_BODY" && (stage === "base" || stage === "all")) {
|
||||
if (!q("POLICE_REPORT_DESC").trim()) {
|
||||
setStatus("شرح گزارش برای ثبت پرونده بدنه ضروری است.", "err");
|
||||
showFormTab("accident");
|
||||
$("POLICE_REPORT_DESC").focus();
|
||||
return;
|
||||
}
|
||||
const requiredLookups = [
|
||||
["accident-causes", "ACCIDENT_CAUSE_ID"],
|
||||
["cities", "ACCIDENT_CITY_ID"],
|
||||
@@ -2406,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);
|
||||
@@ -2442,6 +2464,7 @@ node scripts/fanavaran-flow-ui-server.js</pre>
|
||||
$("LOCATION").addEventListener("change", () => refreshExperts());
|
||||
$("FANAVARAN_PRODUCT").addEventListener("change", () => {
|
||||
syncProduct();
|
||||
refreshExperts();
|
||||
$("envOut").value = envToText(collectEnv());
|
||||
});
|
||||
["CLAIM_EXPERT_ID", "EXPERTISE_CLAIM_EXPERT_ID"].forEach((id) => {
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Combined Parsian expert seed
|
||||
|
||||
The seed merges the original `branches.json`, `file-reviewers.json`, `file-makers.json`, the assessor records in `field-experts.json`, and the fixed `remaining-experts.json`. No Excel reader or generation step is needed.
|
||||
|
||||
Run from `api/`, using that API's `.env`:
|
||||
|
||||
```bash
|
||||
npm run seed:parsian-all -- --dry-run
|
||||
npm run seed:parsian-all
|
||||
```
|
||||
|
||||
`npm run seed:parsian-remaining` runs the same combined seed, so the previous command also works. Use this combined seed instead of rerunning the old Tehran seed.
|
||||
|
||||
Combined source totals: **120 people, 50 branches, 88 claim experts, 88 file reviewers and 39 file makers**. Actual inserts depend on the accounts/branches already in the database.
|
||||
|
||||
Merge rules:
|
||||
|
||||
- A national code identifies a person; role + national code identifies an account. Existing account IDs, passwords, email/username aliases and activation states are retained. New accounts use national-code usernames and the hashed password `123321`.
|
||||
- Existing primary branches stay unchanged. Additional source locations are merged and deduplicated into `locations`; differing branch lists no longer abort the import. This does not grant multiple primary branches in the application's branch-based authorization.
|
||||
- A new claim/reviewer counterpart inherits the existing counterpart's valid primary branch and assessment codes. File makers retain their own role-specific source locations.
|
||||
- Original JSON product codes take precedence over conflicting values in the remaining list. Existing database codes take precedence over imported values. Missing codes are filled; differing existing codes are kept and reported as merge notes, without stopping the batch.
|
||||
- Missing branches are created. Existing branch data is preserved, and missing details can be filled from the original directory. New branches without an address keep it blank. No address, contact or Fanavaran code is invented.
|
||||
- Ambiguous duplicate accounts, identities belonging to another insurer, incorrect stored roles, or unresolved primary branches are skipped with an explicit note. They are not silently moved, deleted or merged across insurers; the rest of the batch can continue.
|
||||
- No cases, case owners, signatures, SMS or Fanavaran requests are changed.
|
||||
|
||||
The reported reviewer ending **8521** remains at their existing primary branch and gains the additional source location. The assessment-code differences for the reviewer ending **8118** preserve existing/original codes rather than choosing the new conflicting values.
|
||||
|
||||
The historical `field-experts.json` contains assessor titles; those become claim experts + file reviewers, not FIELD_EXPERT accounts. Generic assessors are included without guessing product-specific codes. File-responsible / مسئول خسارت / ثبات titles create file makers only.
|
||||
|
||||
Excel row **37** remains excluded because its national code has 11 digits. The remaining source's `skippedRows` records it. National-code checksum warnings for rows 11, 26 and 27 retain the supplied ten-digit values for verification.
|
||||
|
||||
`--dry-run` performs reads only and prints planned creates, updates, skips and merge notes. Applying ensures the role identity indexes and sparse unique email indexes needed for email-less accounts, with a temporary uniqueness guard during legacy email-index replacement (MongoDB 5.0+). Keep the corresponding API changes supporting claim experts without email/mobile.
|
||||
|
||||
The seed is resumable. If an unexpected database/index error occurs, earlier successful writes remain. Conditional updates reject concurrent edits instead of overwriting them. Re-running merges the data again without resetting passwords or duplicating accounts.
|
||||
|
||||
Regression tests: `node scripts/data/parsian-tehran/seed-remaining-experts.test.cjs`.
|
||||
@@ -137,7 +137,8 @@
|
||||
"branchName": "شعبه والفجر",
|
||||
"city": "کاشان",
|
||||
"state": "اصفهان",
|
||||
"title": "كارشناس ارزياب خسارت بدنه"
|
||||
"title": "كارشناس ارزياب خسارت بدنه",
|
||||
"expertCode": "3705"
|
||||
},
|
||||
{
|
||||
"nationalCode": "3781847039",
|
||||
@@ -150,4 +151,4 @@
|
||||
"title": "كارشناس ارزياب خسارت ثالث مالي"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "91",
|
||||
@@ -37,7 +37,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4221",
|
||||
@@ -47,7 +47,7 @@
|
||||
"nationalCode": "0492295557",
|
||||
"mobile": "09125409101",
|
||||
"firstName": "اکبر",
|
||||
"lastName": "بيگ محمدي",
|
||||
"lastName": "بيگ محمدي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "111130",
|
||||
@@ -64,7 +64,7 @@
|
||||
"nationalCode": "3220096573",
|
||||
"mobile": "09104933206",
|
||||
"firstName": "پدرام",
|
||||
"lastName": "حاتمي",
|
||||
"lastName": "حاتمي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210120",
|
||||
@@ -81,7 +81,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "739",
|
||||
@@ -95,7 +95,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "3215",
|
||||
@@ -119,11 +119,11 @@
|
||||
"nationalCode": "0084130938",
|
||||
"mobile": "09392558640",
|
||||
"firstName": "رسول",
|
||||
"lastName": "کرکي",
|
||||
"lastName": "کرکي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4662"
|
||||
@@ -136,7 +136,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4245",
|
||||
@@ -150,7 +150,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "89",
|
||||
@@ -164,7 +164,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4455",
|
||||
@@ -178,7 +178,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "742",
|
||||
@@ -220,7 +220,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4652",
|
||||
@@ -244,11 +244,11 @@
|
||||
"nationalCode": "0066868521",
|
||||
"mobile": "09129344240",
|
||||
"firstName": "عليرضا",
|
||||
"lastName": "گودرزي پور",
|
||||
"lastName": "گودرزي پور ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4663"
|
||||
@@ -261,7 +261,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4220",
|
||||
@@ -275,7 +275,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4452",
|
||||
@@ -299,11 +299,11 @@
|
||||
"nationalCode": "0056888082",
|
||||
"mobile": "09122406750",
|
||||
"firstName": "قاسم",
|
||||
"lastName": "نصراللهي",
|
||||
"lastName": "نصراللهي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4664"
|
||||
@@ -330,7 +330,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4092",
|
||||
@@ -344,7 +344,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "1010",
|
||||
@@ -354,11 +354,11 @@
|
||||
"nationalCode": "0493217789",
|
||||
"mobile": "09126966943",
|
||||
"firstName": "مصطفي",
|
||||
"lastName": "محمدزاده قورقچي",
|
||||
"lastName": "محمدزاده قورقچي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4665"
|
||||
@@ -371,7 +371,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "745",
|
||||
@@ -381,11 +381,11 @@
|
||||
"nationalCode": "0078209129",
|
||||
"mobile": "09126038117",
|
||||
"firstName": "مهدي",
|
||||
"lastName": "شاملوفرد",
|
||||
"lastName": "شاملوفرد ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4666"
|
||||
@@ -426,7 +426,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "1004",
|
||||
@@ -440,7 +440,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4646",
|
||||
@@ -454,7 +454,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "228",
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "29",
|
||||
@@ -50,7 +50,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyExpertiseClaim": "15",
|
||||
@@ -74,11 +74,11 @@
|
||||
"nationalCode": "0056888082",
|
||||
"mobile": "09122406750",
|
||||
"firstName": "قاسم",
|
||||
"lastName": "نصراللهي",
|
||||
"lastName": "نصراللهي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "4645"
|
||||
@@ -91,7 +91,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "3985",
|
||||
@@ -119,7 +119,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "3545",
|
||||
@@ -147,7 +147,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
},
|
||||
{
|
||||
"id": "210110",
|
||||
@@ -156,6 +156,43 @@
|
||||
],
|
||||
"CarBodyExpertiseClaim": "73",
|
||||
"ThirdPartyExpertiseClaim": "72"
|
||||
},
|
||||
{
|
||||
"nationalCode": "3781847039",
|
||||
"firstName": "اکبر",
|
||||
"lastName": "ديني ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nationalCode": "0759153981",
|
||||
"firstName": "رضا",
|
||||
"lastName": "صالحي زاده ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nationalCode": "0013480261",
|
||||
"firstName": "عليرضا",
|
||||
"lastName": "خازني ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران"
|
||||
},
|
||||
{
|
||||
"id": "210110",
|
||||
"name": "شعبه پونک"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,663 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
// Merge the original Parsian JSON directory and the fixed remaining-experts data.
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const crypto = require("node:crypto");
|
||||
const { promisify } = require("node:util");
|
||||
const mongoose = require("mongoose");
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
const roles = {
|
||||
damage_expert: {
|
||||
collection: "damage-expert",
|
||||
codes: [
|
||||
"ThirdPartyClaimExpertId",
|
||||
"CarBodyClaimExpertId",
|
||||
"ThirdPartyExpertiseClaim",
|
||||
"CarBodyExpertiseClaim",
|
||||
],
|
||||
},
|
||||
file_reviewer: {
|
||||
collection: "file-reviewer",
|
||||
codes: ["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"],
|
||||
},
|
||||
file_maker: {
|
||||
collection: "file-maker",
|
||||
codes: ["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
|
||||
},
|
||||
};
|
||||
const string = (value) => String(value ?? "");
|
||||
const empty = (value) => value == null || value === "";
|
||||
class SeedError extends Error {}
|
||||
|
||||
function mergeLocations(...lists) {
|
||||
const merged = new Map();
|
||||
for (const location of lists.flat()) {
|
||||
const id = string(location?.id).trim();
|
||||
if (id && !merged.has(id))
|
||||
merged.set(id, { id, name: string(location.name).trim() });
|
||||
}
|
||||
return [...merged.values()];
|
||||
}
|
||||
|
||||
function loadMergedData(
|
||||
sources = {
|
||||
branches: require("./branches.json"),
|
||||
reviewers: require("./file-reviewers.json"),
|
||||
makers: require("./file-makers.json"),
|
||||
legacy: require("./field-experts.json"),
|
||||
remaining: require("./remaining-experts.json"),
|
||||
},
|
||||
) {
|
||||
if (Object.values(sources).some((source) => source.clientCode !== 8))
|
||||
throw new SeedError(
|
||||
"All input JSON files must belong to Parsian (clientCode=8).",
|
||||
);
|
||||
const branches = new Map(),
|
||||
experts = new Map(),
|
||||
notes = [];
|
||||
// The established branch directory wins; new data fills missing details only.
|
||||
for (const branch of [
|
||||
...sources.branches.branches,
|
||||
...sources.remaining.branches,
|
||||
]) {
|
||||
const code = string(branch.code),
|
||||
current = branches.get(code);
|
||||
if (!current) branches.set(code, { ...branch, code });
|
||||
else
|
||||
for (const [field, value] of Object.entries(branch))
|
||||
if (empty(current[field]) && !empty(value)) current[field] = value;
|
||||
}
|
||||
const allCodeFields = [
|
||||
...new Set(Object.values(roles).flatMap((role) => role.codes)),
|
||||
];
|
||||
function addExpert(record, assignedRoles, locations, source) {
|
||||
const nationalCode = string(record.nationalCode);
|
||||
let expert = experts.get(nationalCode);
|
||||
if (!expert) {
|
||||
expert = {
|
||||
nationalCode,
|
||||
firstName: record.firstName,
|
||||
lastName: record.lastName,
|
||||
roles: [],
|
||||
locations: [],
|
||||
roleLocations: {},
|
||||
};
|
||||
experts.set(nationalCode, expert);
|
||||
}
|
||||
for (const field of ["firstName", "lastName", "mobile"])
|
||||
if (empty(expert[field]) && !empty(record[field]))
|
||||
expert[field] = record[field];
|
||||
expert.locations = mergeLocations(expert.locations, locations);
|
||||
expert.branchCode = expert.locations[0]?.id;
|
||||
for (const role of assignedRoles) {
|
||||
if (!expert.roles.includes(role)) expert.roles.push(role);
|
||||
expert.roleLocations[role] = mergeLocations(
|
||||
expert.roleLocations[role] ?? [],
|
||||
locations,
|
||||
);
|
||||
}
|
||||
for (const field of allCodeFields)
|
||||
if (!empty(record[field])) {
|
||||
const value = string(record[field]);
|
||||
if (empty(expert[field])) expert[field] = value;
|
||||
else if (expert[field] !== value)
|
||||
notes.push({
|
||||
nationalCode: `******${nationalCode.slice(-4)}`,
|
||||
field,
|
||||
source,
|
||||
action: "kept-original-source-code",
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const record of sources.reviewers.fileReviewers)
|
||||
addExpert(
|
||||
record,
|
||||
["damage_expert", "file_reviewer"],
|
||||
record.locations,
|
||||
"file-reviewers.json",
|
||||
);
|
||||
for (const record of sources.makers.fileMakers)
|
||||
addExpert(record, ["file_maker"], record.locations, "file-makers.json");
|
||||
// This older file contains assessor titles, rather than FIELD_EXPERT accounts.
|
||||
for (const record of sources.legacy.fieldExperts) {
|
||||
const title = string(record.title).replace(/ي/g, "ی").replace(/ك/g, "ک");
|
||||
if (!title.includes("ارزیاب") || !title.includes("خسارت")) continue;
|
||||
const mapped = { ...record };
|
||||
if (record.expertCode) {
|
||||
if (/ثالث|مالی/.test(title))
|
||||
mapped.ThirdPartyExpertiseClaim = string(record.expertCode);
|
||||
if (/بدنه/.test(title))
|
||||
mapped.CarBodyExpertiseClaim = string(record.expertCode);
|
||||
}
|
||||
addExpert(
|
||||
mapped,
|
||||
["damage_expert", "file_reviewer"],
|
||||
[{ id: record.branchCode, name: record.branchName }],
|
||||
"field-experts.json",
|
||||
);
|
||||
}
|
||||
for (const record of sources.remaining.experts)
|
||||
addExpert(
|
||||
record,
|
||||
record.roles,
|
||||
[{ id: record.branchCode, name: branches.get(record.branchCode)?.name }],
|
||||
"remaining-experts.json",
|
||||
);
|
||||
const result = {
|
||||
clientCode: 8,
|
||||
branches: [...branches.values()],
|
||||
experts: [...experts.values()],
|
||||
skippedRows: sources.remaining.skippedRows,
|
||||
notes,
|
||||
};
|
||||
validateData(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function validateData(seed) {
|
||||
if (seed.clientCode !== 8)
|
||||
throw new SeedError("This seed is for Parsian (clientCode=8) only.");
|
||||
const branches = new Set(seed.branches.map((branch) => branch.code));
|
||||
if (branches.size !== seed.branches.length)
|
||||
throw new SeedError("Duplicate branch codes in JSON.");
|
||||
for (const branch of seed.branches)
|
||||
if (
|
||||
!/^\d+$/.test(branch.code) ||
|
||||
!branch.name ||
|
||||
!branch.city ||
|
||||
!branch.state
|
||||
)
|
||||
throw new SeedError("Invalid branch data in JSON.");
|
||||
const identities = new Set();
|
||||
for (const expert of seed.experts) {
|
||||
if (
|
||||
!/^\d{10}$/.test(expert.nationalCode) ||
|
||||
!expert.firstName ||
|
||||
!expert.lastName ||
|
||||
!branches.has(expert.branchCode)
|
||||
)
|
||||
throw new SeedError("Invalid expert identity or branch in JSON.");
|
||||
if (
|
||||
!expert.roles?.length ||
|
||||
new Set(expert.roles).size !== expert.roles.length ||
|
||||
expert.roles.some((role) => !Object.hasOwn(roles, role))
|
||||
)
|
||||
throw new SeedError("Invalid or repeated expert role in JSON.");
|
||||
if (expert.mobile && !/^09\d{9}$/.test(expert.mobile))
|
||||
throw new SeedError("Invalid mobile in JSON.");
|
||||
for (const location of [
|
||||
...(expert.locations ?? []),
|
||||
...Object.values(expert.roleLocations ?? {}).flat(),
|
||||
])
|
||||
if (!branches.has(location.id))
|
||||
throw new SeedError(
|
||||
"Expert location has no matching branch in the combined JSON data.",
|
||||
);
|
||||
for (const role of expert.roles) {
|
||||
const identity = `${role}:${expert.nationalCode}`;
|
||||
if (identities.has(identity))
|
||||
throw new SeedError("Duplicate role/national code in JSON.");
|
||||
identities.add(identity);
|
||||
for (const field of roles[role].codes)
|
||||
if (
|
||||
expert[field] != null &&
|
||||
(!/^\d+$/.test(expert[field]) ||
|
||||
!Number.isSafeInteger(Number(expert[field])) ||
|
||||
Number(expert[field]) <= 0)
|
||||
)
|
||||
throw new SeedError("Invalid Fanavaran expert code in JSON.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function databaseConfig() {
|
||||
const env = { ...process.env },
|
||||
filename = path.resolve(__dirname, "../../../.env");
|
||||
if (fs.existsSync(filename))
|
||||
for (const line of fs.readFileSync(filename, "utf8").split(/\r?\n/)) {
|
||||
const match = line.match(/^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=\s*(.*)$/);
|
||||
if (!match || Object.hasOwn(env, match[1])) continue;
|
||||
let value = match[2].trim();
|
||||
if (/^["']/.test(value))
|
||||
value = value.slice(1, value.lastIndexOf(value[0]));
|
||||
else value = value.replace(/\s+#.*$/, "").trim();
|
||||
env[match[1]] = value;
|
||||
}
|
||||
let uri = env.MONGO_URI ?? "";
|
||||
for (let pass = 0; pass < 10 && /\$\{/.test(uri); pass++)
|
||||
uri = uri.replace(/\$\{([^}]+)\}/g, (_, key) => env[key] ?? "");
|
||||
if (!/^mongodb(?:\+srv)?:\/\//.test(uri) || /\$\{/.test(uri))
|
||||
throw new SeedError(
|
||||
"MONGO_URI is missing or invalid in the API environment.",
|
||||
);
|
||||
return {
|
||||
uri,
|
||||
options: {
|
||||
tls: env.MONGO_TLS === "true",
|
||||
tlsAllowInvalidCertificates: env.MONGO_TLS_ALLOW_INVALID_CERTS === "true",
|
||||
serverSelectionTimeoutMS: 10000,
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function buildPlan(db, seed = loadMergedData()) {
|
||||
validateData(seed);
|
||||
const clients = await db
|
||||
.collection("clients")
|
||||
.find({ clientCode: 8 }, { projection: { _id: 1 } })
|
||||
.toArray();
|
||||
if (clients.length !== 1)
|
||||
throw new SeedError(
|
||||
"Exactly one existing Parsian insurer (clientCode=8) is required.",
|
||||
);
|
||||
const clientKey = clients[0]._id;
|
||||
const branches = await db
|
||||
.collection("branches")
|
||||
.find({ clientKey: { $in: [clientKey, string(clientKey)] } })
|
||||
.toArray();
|
||||
const branchIds = new Map(),
|
||||
plan = [];
|
||||
plan.notes = [...(seed.notes ?? [])];
|
||||
function conditionalUpdate(record, changes) {
|
||||
const filter = { _id: record._id, clientKey: record.clientKey };
|
||||
for (const field of Object.keys(changes))
|
||||
filter[field] = Object.hasOwn(record, field)
|
||||
? record[field]
|
||||
: { $exists: false };
|
||||
return filter;
|
||||
}
|
||||
for (const branch of seed.branches) {
|
||||
const matches = branches.filter(
|
||||
(record) => string(record.code) === branch.code,
|
||||
);
|
||||
if (matches.length > 1) {
|
||||
plan.notes.push({
|
||||
branchCode: branch.code,
|
||||
action: "skipped-ambiguous-database-branch",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const current = matches[0],
|
||||
_id = current?._id ?? new mongoose.Types.ObjectId();
|
||||
branchIds.set(branch.code, _id);
|
||||
if (!current) {
|
||||
plan.push({
|
||||
kind: "branch",
|
||||
collection: "branches",
|
||||
document: {
|
||||
...branch,
|
||||
_id,
|
||||
clientKey,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const changes = {};
|
||||
for (const [field, value] of Object.entries(branch))
|
||||
if (field !== "code" && empty(current[field]) && !empty(value))
|
||||
changes[field] = value;
|
||||
if (Object.keys(changes).length)
|
||||
plan.push({
|
||||
kind: "branchUpdate",
|
||||
collection: "branches",
|
||||
filter: conditionalUpdate(current, changes),
|
||||
changes,
|
||||
});
|
||||
}
|
||||
const identifiers = seed.experts.map((expert) => expert.nationalCode);
|
||||
const storedCodes = [
|
||||
...new Set([
|
||||
...identifiers,
|
||||
...identifiers.map((value) => String(Number(value))),
|
||||
...identifiers.map(Number),
|
||||
]),
|
||||
];
|
||||
const existingByRole = {};
|
||||
for (const [role, config] of Object.entries(roles))
|
||||
existingByRole[role] = await db
|
||||
.collection(config.collection)
|
||||
.find(
|
||||
{
|
||||
$or: [
|
||||
{ nationalCode: { $in: storedCodes } },
|
||||
{ username: { $in: identifiers } },
|
||||
{ email: { $in: identifiers } },
|
||||
],
|
||||
},
|
||||
{ projection: { password: 0, otp: 0, personalDocs: 0 } },
|
||||
)
|
||||
.toArray();
|
||||
|
||||
for (const expert of seed.experts) {
|
||||
const matches = {};
|
||||
for (const role of Object.keys(roles))
|
||||
matches[role] = existingByRole[role].filter(
|
||||
(record) =>
|
||||
string(record.nationalCode).padStart(10, "0") ===
|
||||
expert.nationalCode ||
|
||||
record.username === expert.nationalCode ||
|
||||
record.email === expert.nationalCode,
|
||||
);
|
||||
const validExisting = (role) => {
|
||||
const records = matches[role];
|
||||
const record = records.length === 1 ? records[0] : null;
|
||||
return record &&
|
||||
string(record.clientKey) === string(clientKey) &&
|
||||
string(record.nationalCode).padStart(10, "0") === expert.nationalCode &&
|
||||
(!record.role || record.role === role)
|
||||
? record
|
||||
: null;
|
||||
};
|
||||
for (const role of expert.roles) {
|
||||
const config = roles[role],
|
||||
records = matches[role];
|
||||
const note = (action, details = {}) =>
|
||||
plan.notes.push({
|
||||
nationalCode: `******${expert.nationalCode.slice(-4)}`,
|
||||
role,
|
||||
action,
|
||||
...details,
|
||||
});
|
||||
if (
|
||||
records.length > 1 ||
|
||||
records.some((record) => string(record.clientKey) !== string(clientKey))
|
||||
) {
|
||||
note("skipped-ambiguous-or-foreign-insurer-account");
|
||||
continue;
|
||||
}
|
||||
const current = records[0];
|
||||
if (current && !validExisting(role)) {
|
||||
note("skipped-different-identity-or-role");
|
||||
continue;
|
||||
}
|
||||
const sourceLocations = expert.roleLocations?.[role] ??
|
||||
expert.locations ?? [
|
||||
{
|
||||
id: expert.branchCode,
|
||||
name: seed.branches.find(
|
||||
(branch) => branch.code === expert.branchCode,
|
||||
)?.name,
|
||||
},
|
||||
];
|
||||
const counterpart =
|
||||
role === "damage_expert"
|
||||
? validExisting("file_reviewer")
|
||||
: role === "file_reviewer"
|
||||
? validExisting("damage_expert")
|
||||
: null;
|
||||
const inheritedBranch =
|
||||
!current?.branchId &&
|
||||
counterpart?.branchId &&
|
||||
branches.find(
|
||||
(branch) => string(branch._id) === string(counterpart.branchId),
|
||||
);
|
||||
const branchId =
|
||||
current?.branchId ??
|
||||
(inheritedBranch
|
||||
? inheritedBranch._id
|
||||
: branchIds.get(sourceLocations[0]?.id));
|
||||
const primaryBranch =
|
||||
branches.find((branch) => string(branch._id) === string(branchId)) ??
|
||||
seed.branches.find(
|
||||
(branch) => string(branchIds.get(branch.code)) === string(branchId),
|
||||
);
|
||||
if (!branchId || !primaryBranch) {
|
||||
note("skipped-unresolved-primary-branch");
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
current?.branchId &&
|
||||
string(primaryBranch.code) !== sourceLocations[0]?.id
|
||||
)
|
||||
note("kept-existing-primary-branch", {
|
||||
primaryBranchCode: string(primaryBranch.code),
|
||||
addedBranchCodes: sourceLocations.map((location) => location.id),
|
||||
});
|
||||
const locations = mergeLocations(
|
||||
current?.locations ?? [],
|
||||
[{ id: primaryBranch.code, name: primaryBranch.name }],
|
||||
sourceLocations,
|
||||
!current ? (counterpart?.locations ?? []) : [],
|
||||
);
|
||||
const codes = {};
|
||||
for (const field of config.codes) {
|
||||
const candidates = field.endsWith("ExpertiseClaim")
|
||||
? [validExisting("file_reviewer"), validExisting("damage_expert")]
|
||||
: [validExisting("file_maker"), validExisting("damage_expert")];
|
||||
const inherited = candidates
|
||||
.map((record) => record?.[field])
|
||||
.find(
|
||||
(value) =>
|
||||
/^\d+$/.test(string(value)) &&
|
||||
Number(value) > 0 &&
|
||||
Number.isSafeInteger(Number(value)),
|
||||
);
|
||||
if (!empty(inherited) || !empty(expert[field]))
|
||||
codes[field] = string(inherited ?? expert[field]);
|
||||
if (
|
||||
!empty(current?.[field]) &&
|
||||
!empty(expert[field]) &&
|
||||
string(current[field]) !== expert[field]
|
||||
)
|
||||
note("kept-existing-code", { field });
|
||||
}
|
||||
const values = {
|
||||
firstName: expert.firstName,
|
||||
lastName: expert.lastName,
|
||||
username: expert.nationalCode,
|
||||
nationalCode: expert.nationalCode,
|
||||
role,
|
||||
clientKey,
|
||||
branchId,
|
||||
locations,
|
||||
city: primaryBranch.city,
|
||||
state: primaryBranch.state,
|
||||
...(expert.mobile ? { mobile: expert.mobile } : {}),
|
||||
...(role === "damage_expert"
|
||||
? { userType: "legal", insuActivityCo: string(clientKey) }
|
||||
: {}),
|
||||
...codes,
|
||||
};
|
||||
if (!current) {
|
||||
plan.push({
|
||||
kind: "create",
|
||||
collection: config.collection,
|
||||
role,
|
||||
document: {
|
||||
...values,
|
||||
isActive: true,
|
||||
otp: "",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const changes = {};
|
||||
for (const [field, value] of Object.entries(values)) {
|
||||
if (field === "clientKey") continue;
|
||||
if (field === "locations") {
|
||||
if (JSON.stringify(current.locations ?? []) !== JSON.stringify(value))
|
||||
changes.locations = value;
|
||||
} else if (
|
||||
(field === "nationalCode" &&
|
||||
current.nationalCode !== expert.nationalCode) ||
|
||||
empty(current[field])
|
||||
)
|
||||
changes[field] = value;
|
||||
}
|
||||
plan.push({
|
||||
kind: Object.keys(changes).length ? "update" : "keep",
|
||||
collection: config.collection,
|
||||
role,
|
||||
filter: conditionalUpdate(current, changes),
|
||||
changes,
|
||||
});
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
async function indexes(collection) {
|
||||
try {
|
||||
return await collection.indexes();
|
||||
} catch (error) {
|
||||
if (error.code === 26) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function ensureEmailIndex(collection) {
|
||||
const emailKey = (index) =>
|
||||
Object.keys(index.key ?? {}).length === 1 && index.key.email === 1;
|
||||
const legacy = (await indexes(collection)).filter(
|
||||
(index) =>
|
||||
emailKey(index) &&
|
||||
index.unique &&
|
||||
!index.sparse &&
|
||||
!index.partialFilterExpression,
|
||||
);
|
||||
const guard = "remaining_experts_email_guard";
|
||||
if (legacy.length) {
|
||||
// Preserve uniqueness of real emails while allowing multiple email-less logins.
|
||||
await collection.createIndex(
|
||||
{ email: 1 },
|
||||
{
|
||||
name: guard,
|
||||
unique: true,
|
||||
partialFilterExpression: { email: { $type: "string" } },
|
||||
},
|
||||
);
|
||||
for (const index of legacy) await collection.dropIndex(index.name);
|
||||
}
|
||||
if (
|
||||
!(await indexes(collection)).some(
|
||||
(index) => emailKey(index) && index.unique && index.sparse,
|
||||
)
|
||||
)
|
||||
await collection.createIndex(
|
||||
{ email: 1 },
|
||||
{ name: "email_1", unique: true, sparse: true },
|
||||
);
|
||||
if (
|
||||
(await indexes(collection)).some(
|
||||
(index) =>
|
||||
index.name === guard &&
|
||||
emailKey(index) &&
|
||||
index.unique &&
|
||||
JSON.stringify(index.partialFilterExpression) ===
|
||||
JSON.stringify({ email: { $type: "string" } }),
|
||||
)
|
||||
)
|
||||
await collection.dropIndex(guard);
|
||||
}
|
||||
async function hashPassword() {
|
||||
const salt = crypto.randomBytes(16).toString("hex");
|
||||
const derived = await scrypt("123321", salt, 64);
|
||||
return `${salt}:${derived.toString("hex")}`;
|
||||
}
|
||||
async function applyPlan(db, plan, hash = hashPassword) {
|
||||
await db
|
||||
.collection("branches")
|
||||
.createIndex({ clientKey: 1, code: 1 }, { unique: true });
|
||||
for (const role of new Set(
|
||||
plan.filter((action) => action.role).map((action) => action.role),
|
||||
)) {
|
||||
const collection = db.collection(roles[role].collection);
|
||||
await ensureEmailIndex(collection);
|
||||
await collection.createIndex(
|
||||
role === "damage_expert"
|
||||
? { nationalCode: 1 }
|
||||
: { clientKey: 1, nationalCode: 1 },
|
||||
role === "damage_expert"
|
||||
? { unique: true }
|
||||
: { unique: true, sparse: true },
|
||||
);
|
||||
}
|
||||
for (const action of plan) {
|
||||
const collection = db.collection(action.collection);
|
||||
if (action.kind === "branch") await collection.insertOne(action.document);
|
||||
if (action.kind === "create")
|
||||
await collection.insertOne({
|
||||
...action.document,
|
||||
password: await hash(),
|
||||
});
|
||||
if (["update", "branchUpdate"].includes(action.kind)) {
|
||||
const result = await collection.updateOne(action.filter, {
|
||||
$set: { ...action.changes, updatedAt: new Date() },
|
||||
});
|
||||
if (result.matchedCount !== 1)
|
||||
throw new SeedError(
|
||||
"An account changed after preflight. Import stopped instead of overwriting it; rerun after reviewing.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main(argv = process.argv.slice(2)) {
|
||||
if (argv.some((arg) => arg !== "--dry-run"))
|
||||
throw new SeedError("Usage: npm run seed:parsian-remaining -- [--dry-run]");
|
||||
const dryRun = argv.includes("--dry-run");
|
||||
const data = loadMergedData();
|
||||
const config = databaseConfig(),
|
||||
connection = mongoose.createConnection(config.uri, config.options);
|
||||
try {
|
||||
try {
|
||||
await connection.asPromise();
|
||||
} catch {
|
||||
throw new SeedError(
|
||||
"Could not connect to MongoDB. Check the API environment and TLS settings.",
|
||||
);
|
||||
}
|
||||
const plan = await buildPlan(connection.db);
|
||||
console.log({
|
||||
dryRun,
|
||||
clientCode: data.clientCode,
|
||||
people: data.experts.length,
|
||||
branchesToCreate: plan.filter((action) => action.kind === "branch")
|
||||
.length,
|
||||
branchesToFill: plan.filter((action) => action.kind === "branchUpdate")
|
||||
.length,
|
||||
accountsToCreate: plan.filter((action) => action.kind === "create")
|
||||
.length,
|
||||
accountsToFill: plan.filter((action) => action.kind === "update").length,
|
||||
accountsUnchanged: plan.filter((action) => action.kind === "keep").length,
|
||||
skippedAccounts: plan.notes.filter(
|
||||
(note) => note.role && note.action.startsWith("skipped-"),
|
||||
).length,
|
||||
mergeNotes: plan.notes,
|
||||
skippedSpreadsheetRows: data.skippedRows.flatMap((row) => row.rows),
|
||||
});
|
||||
if (dryRun) return;
|
||||
await applyPlan(connection.db, plan);
|
||||
console.log(
|
||||
"Combined Parsian experts seeded successfully. Existing passwords, primary branches, codes and active states were preserved.",
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
if (require.main === module)
|
||||
main().catch((error) => {
|
||||
console.error(
|
||||
error instanceof SeedError
|
||||
? error.message
|
||||
: "Seed stopped because of a database/index error. Existing passwords were not reset. Review a dry-run before retrying.",
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
module.exports = {
|
||||
validateData,
|
||||
loadMergedData,
|
||||
mergeLocations,
|
||||
buildPlan,
|
||||
applyPlan,
|
||||
hashPassword,
|
||||
ensureEmailIndex,
|
||||
main,
|
||||
};
|
||||
@@ -0,0 +1,390 @@
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { isDeepStrictEqual } = require("node:util");
|
||||
const mongoose = require("mongoose");
|
||||
const {
|
||||
loadMergedData,
|
||||
buildPlan,
|
||||
applyPlan,
|
||||
} = require("./seed-remaining-experts");
|
||||
|
||||
const nationalCode = "0012345678";
|
||||
const branch = (code, name, address = "") => ({
|
||||
code,
|
||||
name,
|
||||
city: "تهران",
|
||||
state: "تهران",
|
||||
address,
|
||||
isActive: true,
|
||||
});
|
||||
const west = branch("210050", "شعبه غرب", "نشانی اصلی");
|
||||
const poonak = branch("210110", "شعبه پونک");
|
||||
function sources() {
|
||||
return {
|
||||
branches: { clientCode: 8, branches: [west] },
|
||||
reviewers: {
|
||||
clientCode: 8,
|
||||
fileReviewers: [
|
||||
{
|
||||
nationalCode,
|
||||
firstName: "نام",
|
||||
lastName: "آزمایشی",
|
||||
locations: [{ id: west.code, name: west.name }],
|
||||
ThirdPartyExpertiseClaim: "11",
|
||||
CarBodyExpertiseClaim: "12",
|
||||
},
|
||||
],
|
||||
},
|
||||
makers: {
|
||||
clientCode: 8,
|
||||
fileMakers: [
|
||||
{
|
||||
nationalCode,
|
||||
firstName: "نام",
|
||||
lastName: "آزمایشی",
|
||||
locations: [{ id: poonak.code, name: poonak.name }],
|
||||
ThirdPartyClaimExpertId: "21",
|
||||
},
|
||||
],
|
||||
},
|
||||
legacy: { clientCode: 8, fieldExperts: [] },
|
||||
remaining: {
|
||||
clientCode: 8,
|
||||
branches: [poonak, { ...west, address: "" }],
|
||||
skippedRows: [],
|
||||
experts: [
|
||||
{
|
||||
nationalCode,
|
||||
firstName: "نام",
|
||||
lastName: "آزمایشی",
|
||||
branchCode: poonak.code,
|
||||
roles: ["damage_expert", "file_reviewer"],
|
||||
ThirdPartyExpertiseClaim: "99",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
const same = (a, b) =>
|
||||
Array.isArray(a) || Array.isArray(b)
|
||||
? isDeepStrictEqual(a, b)
|
||||
: String(a ?? "") === String(b ?? "");
|
||||
function matches(record, filter) {
|
||||
return Object.entries(filter).every(([key, value]) => {
|
||||
if (key === "$or") return value.some((part) => matches(record, part));
|
||||
if (value?.$in) return value.$in.some((entry) => same(record[key], entry));
|
||||
if (value?.$exists !== undefined)
|
||||
return (record[key] !== undefined) === value.$exists;
|
||||
return same(record[key], value);
|
||||
});
|
||||
}
|
||||
function database() {
|
||||
const clientKey = new mongoose.Types.ObjectId();
|
||||
const store = {
|
||||
clients: [{ _id: clientKey, clientCode: 8 }],
|
||||
branches: [],
|
||||
"damage-expert": [],
|
||||
"file-reviewer": [],
|
||||
"file-maker": [],
|
||||
};
|
||||
const writes = [],
|
||||
indexMap = {};
|
||||
return {
|
||||
clientKey,
|
||||
store,
|
||||
writes,
|
||||
collection(name) {
|
||||
assert.ok(
|
||||
Object.hasOwn(store, name),
|
||||
`The seed must not access case/history collections: ${name}`,
|
||||
);
|
||||
indexMap[name] ??= [{ key: { email: 1 }, name: "email_1", unique: true }];
|
||||
return {
|
||||
find: (filter) => ({
|
||||
toArray: async () =>
|
||||
store[name].filter((record) => matches(record, filter)),
|
||||
}),
|
||||
indexes: async () => indexMap[name],
|
||||
createIndex: async (key, options) => {
|
||||
const label =
|
||||
options.name ??
|
||||
Object.entries(key)
|
||||
.map(([field, order]) => `${field}_${order}`)
|
||||
.join("_");
|
||||
writes.push({ action: "index", name, label });
|
||||
if (!indexMap[name].some((index) => index.name === label))
|
||||
indexMap[name].push({ key, name: label, ...options });
|
||||
},
|
||||
dropIndex: async (label) => {
|
||||
writes.push({ action: "drop", name, label });
|
||||
indexMap[name] = indexMap[name].filter(
|
||||
(index) => index.name !== label,
|
||||
);
|
||||
},
|
||||
insertOne: async (record) => {
|
||||
store[name].push({
|
||||
...record,
|
||||
_id: record._id ?? new mongoose.Types.ObjectId(),
|
||||
});
|
||||
writes.push({ action: "insert", name });
|
||||
},
|
||||
updateOne: async (filter, update) => {
|
||||
const record = store[name].find((row) => matches(row, filter));
|
||||
if (!record) return { matchedCount: 0 };
|
||||
Object.assign(record, update.$set);
|
||||
writes.push({ action: "update", name });
|
||||
return { matchedCount: 1 };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
function existingReviewer(db) {
|
||||
const existingWest = {
|
||||
...west,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
isActive: false,
|
||||
address: "",
|
||||
};
|
||||
db.store.branches.push(existingWest);
|
||||
const reviewer = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
nationalCode,
|
||||
role: "file_reviewer",
|
||||
clientKey: db.clientKey,
|
||||
branchId: existingWest._id,
|
||||
locations: [{ id: west.code, name: west.name }],
|
||||
password: "kept-password",
|
||||
username: "kept-alias",
|
||||
isActive: false,
|
||||
ThirdPartyExpertiseClaim: "77",
|
||||
};
|
||||
db.store["file-reviewer"].push(reviewer);
|
||||
return { existingWest, reviewer };
|
||||
}
|
||||
|
||||
test("merges all real JSON sources and resolves the reported branch/code disagreements", () => {
|
||||
const merged = loadMergedData();
|
||||
assert.equal(merged.experts.length, 120);
|
||||
assert.equal(merged.branches.length, 50);
|
||||
for (const [role, expected] of [
|
||||
["damage_expert", 88],
|
||||
["file_reviewer", 88],
|
||||
["file_maker", 39],
|
||||
])
|
||||
assert.equal(
|
||||
merged.experts.filter((expert) => expert.roles.includes(role)).length,
|
||||
expected,
|
||||
);
|
||||
const reported = merged.experts.find((expert) =>
|
||||
expert.nationalCode.endsWith("8521"),
|
||||
);
|
||||
assert.deepEqual(
|
||||
reported.roleLocations.file_reviewer.map((location) => location.id),
|
||||
["210050", "210110"],
|
||||
);
|
||||
const codes = merged.experts.find((expert) =>
|
||||
expert.nationalCode.endsWith("8118"),
|
||||
);
|
||||
assert.equal(codes.ThirdPartyExpertiseClaim, "3985");
|
||||
assert.equal(codes.CarBodyExpertiseClaim, "3986");
|
||||
assert.ok(
|
||||
merged.notes.some((note) => note.action === "kept-original-source-code"),
|
||||
);
|
||||
});
|
||||
|
||||
test("retains role-specific source branches and the original address when building a fresh database", async () => {
|
||||
const db = database(),
|
||||
seed = loadMergedData(sources());
|
||||
const plan = await buildPlan(db, seed);
|
||||
assert.equal(
|
||||
db.writes.length,
|
||||
0,
|
||||
"Planning/dry-run must not write indexes or documents",
|
||||
);
|
||||
await applyPlan(db, plan, async () => "new-hash");
|
||||
assert.equal(
|
||||
db.store.branches.find((record) => record.code === west.code).address,
|
||||
west.address,
|
||||
);
|
||||
const claim = db.store["damage-expert"][0],
|
||||
maker = db.store["file-maker"][0];
|
||||
assert.equal(
|
||||
String(claim.branchId),
|
||||
String(db.store.branches.find((record) => record.code === west.code)._id),
|
||||
);
|
||||
assert.equal(
|
||||
String(maker.branchId),
|
||||
String(db.store.branches.find((record) => record.code === poonak.code)._id),
|
||||
);
|
||||
assert.equal(claim.ThirdPartyExpertiseClaim, "11");
|
||||
assert.equal(claim.ThirdPartyClaimExpertId, "21");
|
||||
assert.equal(maker.ThirdPartyExpertiseClaim, undefined);
|
||||
});
|
||||
|
||||
test("reconciles the complete original Tehran seed with the remaining list without aborting", async () => {
|
||||
const db = database();
|
||||
for (const record of require("./branches.json").branches)
|
||||
db.store.branches.push({
|
||||
...record,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
});
|
||||
for (const [file, key, role, collection] of [
|
||||
[
|
||||
"./file-reviewers.json",
|
||||
"fileReviewers",
|
||||
"file_reviewer",
|
||||
"file-reviewer",
|
||||
],
|
||||
["./file-makers.json", "fileMakers", "file_maker", "file-maker"],
|
||||
])
|
||||
for (const record of require(file)[key]) {
|
||||
db.store[collection].push({
|
||||
...record,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
branchId: db.store.branches.find(
|
||||
(branch) => branch.code === record.locations[0].id,
|
||||
)._id,
|
||||
username: record.nationalCode,
|
||||
password: "preserved",
|
||||
role,
|
||||
isActive: true,
|
||||
});
|
||||
}
|
||||
const reviewer = db.store["file-reviewer"].find((record) =>
|
||||
record.nationalCode.endsWith("8521"),
|
||||
);
|
||||
const before = {
|
||||
id: String(reviewer._id),
|
||||
branchId: String(reviewer.branchId),
|
||||
};
|
||||
const plan = await buildPlan(db);
|
||||
assert.equal(plan.filter((action) => action.kind === "branch").length, 44);
|
||||
assert.equal(plan.filter((action) => action.kind === "create").length, 171);
|
||||
assert.ok(!plan.notes.some((note) => note.action.startsWith("skipped-")));
|
||||
await applyPlan(db, plan, async () => "new-hash");
|
||||
assert.equal(db.store.branches.length, 50);
|
||||
assert.equal(db.store["damage-expert"].length, 88);
|
||||
assert.equal(db.store["file-reviewer"].length, 88);
|
||||
assert.equal(db.store["file-maker"].length, 39);
|
||||
assert.equal(String(reviewer._id), before.id);
|
||||
assert.equal(String(reviewer.branchId), before.branchId);
|
||||
assert.equal(reviewer.password, "preserved");
|
||||
assert.deepEqual(
|
||||
reviewer.locations.map((location) => location.id),
|
||||
["210050", "210110"],
|
||||
);
|
||||
const again = await buildPlan(db);
|
||||
assert.ok(again.every((action) => action.kind === "keep"));
|
||||
});
|
||||
|
||||
test("merges existing reviewer locations/codes without moving it or replacing credentials; new claim inherits its branch/codes", async () => {
|
||||
const db = database(),
|
||||
{ existingWest, reviewer } = existingReviewer(db);
|
||||
const previousId = String(reviewer._id);
|
||||
const seed = loadMergedData(sources()),
|
||||
plan = await buildPlan(db, seed);
|
||||
assert.ok(
|
||||
plan.notes.some(
|
||||
(note) => note.action === "kept-existing-primary-branch",
|
||||
) === false,
|
||||
);
|
||||
assert.ok(plan.notes.some((note) => note.action === "kept-existing-code"));
|
||||
await applyPlan(db, plan, async () => "new-hash");
|
||||
assert.equal(String(reviewer._id), previousId);
|
||||
assert.equal(String(reviewer.branchId), String(existingWest._id));
|
||||
assert.equal(reviewer.password, "kept-password");
|
||||
assert.equal(reviewer.username, "kept-alias");
|
||||
assert.equal(reviewer.isActive, false);
|
||||
assert.equal(reviewer.ThirdPartyExpertiseClaim, "77");
|
||||
assert.equal(reviewer.CarBodyExpertiseClaim, "12");
|
||||
assert.deepEqual(
|
||||
reviewer.locations.map((location) => location.id),
|
||||
[west.code, poonak.code],
|
||||
);
|
||||
assert.equal(existingWest.isActive, false);
|
||||
assert.equal(existingWest.address, west.address);
|
||||
const claim = db.store["damage-expert"][0];
|
||||
assert.equal(String(claim.branchId), String(reviewer.branchId));
|
||||
assert.equal(claim.ThirdPartyExpertiseClaim, "77");
|
||||
assert.equal(claim.username, nationalCode);
|
||||
assert.equal(claim.password, "new-hash");
|
||||
const again = await buildPlan(db, seed);
|
||||
assert.ok(again.every((action) => action.kind === "keep"));
|
||||
await applyPlan(db, again, async () => {
|
||||
throw new Error("Rerun must not create/reset passwords");
|
||||
});
|
||||
assert.equal(db.store["file-reviewer"].length, 1);
|
||||
assert.equal(db.store["damage-expert"].length, 1);
|
||||
});
|
||||
|
||||
test("an existing primary branch absent from the imported primary is preserved and reported", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
db.store.branches.push({
|
||||
...poonak,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
});
|
||||
reviewer.branchId = db.store.branches[1]._id;
|
||||
reviewer.locations = [{ id: poonak.code, name: poonak.name }];
|
||||
const plan = await buildPlan(db, loadMergedData(sources()));
|
||||
assert.ok(
|
||||
plan.notes.some((note) => note.action === "kept-existing-primary-branch"),
|
||||
);
|
||||
await applyPlan(db, plan, async () => "hash");
|
||||
assert.equal(String(reviewer.branchId), String(db.store.branches[1]._id));
|
||||
assert.deepEqual(
|
||||
reviewer.locations.map((location) => location.id),
|
||||
[poonak.code, west.code],
|
||||
);
|
||||
});
|
||||
|
||||
test("skips cross-insurer and ambiguous accounts while importing unrelated roles/accounts", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
reviewer.clientKey = new mongoose.Types.ObjectId();
|
||||
const before = { ...reviewer };
|
||||
const plan = await buildPlan(db, loadMergedData(sources()));
|
||||
assert.ok(
|
||||
plan.notes.some(
|
||||
(note) =>
|
||||
note.role === "file_reviewer" && note.action.startsWith("skipped-"),
|
||||
),
|
||||
);
|
||||
await applyPlan(db, plan, async () => "hash");
|
||||
assert.deepEqual(reviewer, before);
|
||||
assert.equal(db.store["damage-expert"].length, 1);
|
||||
assert.equal(db.store["file-maker"].length, 1);
|
||||
});
|
||||
|
||||
test("normalizes a stored numeric national code without changing its account ID", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
reviewer.nationalCode = Number(nationalCode);
|
||||
const id = reviewer._id;
|
||||
await applyPlan(
|
||||
db,
|
||||
await buildPlan(db, loadMergedData(sources())),
|
||||
async () => "hash",
|
||||
);
|
||||
assert.equal(reviewer.nationalCode, nationalCode);
|
||||
assert.equal(reviewer._id, id);
|
||||
});
|
||||
|
||||
test("concurrent location edits are not overwritten by a stale merge", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
const plan = await buildPlan(db, loadMergedData(sources()));
|
||||
reviewer.locations = [{ id: "999999", name: "ویرایش همزمان" }];
|
||||
await assert.rejects(
|
||||
applyPlan(db, plan, async () => "hash"),
|
||||
/changed after preflight/,
|
||||
);
|
||||
assert.deepEqual(reviewer.locations, [
|
||||
{ id: "999999", name: "ویرایش همزمان" },
|
||||
]);
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -51,7 +51,7 @@ function loadRootDotEnv() {
|
||||
|
||||
function httpJson(method, url, body, headers) {
|
||||
return new Promise((resolve) => {
|
||||
const args = ["-sS", "--max-time", "45", "-X", method, url, "-H", "Accept: application/json"];
|
||||
const args = ["-sS", "--max-time", "45", "-w", "\n%{http_code}", "-X", method, url, "-H", "Accept: application/json"];
|
||||
for (const [k, v] of Object.entries(headers || {})) {
|
||||
args.push("-H", `${k}: ${v}`);
|
||||
}
|
||||
@@ -68,13 +68,16 @@ function httpJson(method, url, body, headers) {
|
||||
stderr += d.toString();
|
||||
});
|
||||
child.on("close", (code) => {
|
||||
const statusAt = stdout.lastIndexOf("\n");
|
||||
const status = Number(stdout.slice(statusAt + 1));
|
||||
stdout = stdout.slice(0, statusAt);
|
||||
let json = null;
|
||||
try {
|
||||
json = JSON.parse(stdout || "null");
|
||||
} catch {
|
||||
json = null;
|
||||
}
|
||||
resolve({ code, stdout, stderr, json });
|
||||
resolve({ code, status, stdout, stderr, json });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -105,10 +108,12 @@ function pickVehicleFields(src) {
|
||||
const built =
|
||||
data.BuiltYear || data.PrdDte || data.ModelField || data.ModelCii || data.builtYear || "";
|
||||
const policyNo =
|
||||
data.PolicyNo || data.PrntCmpDocNo || data.PrntPlcyCmpDocNo || data.printNumber || "";
|
||||
data.PolicyNo || data.PrntCmpDocNo || data.PrntPlcyCmpDocNo || data.printNumber ||
|
||||
data.insuranceNumber || data.LastCompanyDocumentNumber || data.lastCompanyInsuranceNumber || data.policyNumber || "";
|
||||
const policyCi = data.PolicyCINumber || data.PlcyUnqCod || data.ThirdPolicyCode || "";
|
||||
const begin = data.BeginDate || data.HBgnDte || data.StartDate || "";
|
||||
const end = data.EndDate || data.HEndDte || "";
|
||||
const begin = data.BeginDate || data.HBgnDte || data.StartDate || data.SatrtDate ||
|
||||
data.beginDate || data.persianStartDate || "";
|
||||
const end = data.EndDate || data.HEndDte || data.endDate || data.persianEndDate || "";
|
||||
return {
|
||||
MOTOR_NO: String(motor || ""),
|
||||
CHASSIS_NO: String(chassis || ""),
|
||||
@@ -121,6 +126,29 @@ function pickVehicleFields(src) {
|
||||
};
|
||||
}
|
||||
|
||||
function validateVehicleInquiry(res) {
|
||||
const root = res.json;
|
||||
const records = [root, root?.data].filter((r) => r && typeof r === "object");
|
||||
const failed = records.some((r) =>
|
||||
r.Error || r.error || r.HasError === true || r.hasError === true ||
|
||||
r.success === false || r.isSuccess === false || r.IsSuccess === false ||
|
||||
r.IsSucceed === false || r.ReturnValue === false ||
|
||||
Number(r.statusCode ?? r.status) >= 400,
|
||||
);
|
||||
if (res.code !== 0 || res.status >= 400 || !root || failed) {
|
||||
const detail = records.flatMap((r) => [
|
||||
r.messageFa, r.Error?.Message, r.error?.message, r.Message, r.message,
|
||||
]).find((message) => typeof message === "string" && message.trim());
|
||||
throw new Error(detail || res.stderr || "Vehicle inquiry failed");
|
||||
}
|
||||
}
|
||||
|
||||
function requireVehicleFields(vehicle) {
|
||||
if (!Object.values(vehicle).some((value) => String(value).trim())) {
|
||||
throw new Error("استعلام هیچ اطلاعات خودرو یا بیمهنامهای برنگرداند؛ پلاک و کد ملی و پاسخ سرویس را بررسی کنید.");
|
||||
}
|
||||
}
|
||||
|
||||
function findOfflinePlate(input) {
|
||||
if (!fs.existsSync(OFFLINE_SEEDS)) return null;
|
||||
const rows = JSON.parse(fs.readFileSync(OFFLINE_SEEDS, "utf8"));
|
||||
@@ -204,7 +232,15 @@ async function livePlateInquiry(input) {
|
||||
},
|
||||
{ Authorization: `Bearer ${token}` },
|
||||
);
|
||||
if (res.json && !res.json.Error) {
|
||||
let usable = false;
|
||||
try {
|
||||
validateVehicleInquiry(res);
|
||||
requireVehicleFields(pickVehicleFields(res.json));
|
||||
usable = true;
|
||||
} catch {
|
||||
// Try the existing Tejarat fallback when ESG has no usable result.
|
||||
}
|
||||
if (usable) {
|
||||
return {
|
||||
source: "ESG_carByPlate",
|
||||
mode: "plate",
|
||||
@@ -229,17 +265,7 @@ async function livePlateInquiry(input) {
|
||||
},
|
||||
{ Authorization: `Bearer ${token}` },
|
||||
);
|
||||
if (!res.json) {
|
||||
throw new Error(res.stderr || "empty inquiry response");
|
||||
}
|
||||
if (res.json.Error || res.json.HasError) {
|
||||
const msg =
|
||||
res.json.Error?.Message ||
|
||||
res.json.Message ||
|
||||
res.json.message ||
|
||||
"plate inquiry failed";
|
||||
throw new Error(String(msg));
|
||||
}
|
||||
validateVehicleInquiry(res);
|
||||
const vehicle = pickVehicleFields(res.json);
|
||||
return {
|
||||
source: "TEJARAT_block-inquiry",
|
||||
@@ -282,15 +308,7 @@ async function liveVinInquiry(input) {
|
||||
},
|
||||
{ Authorization: `Bearer ${token}` },
|
||||
);
|
||||
if (!res.json) throw new Error(res.stderr || "empty VIN inquiry response");
|
||||
if (res.json.Error || res.json.HasError) {
|
||||
const msg =
|
||||
res.json.Error?.Message ||
|
||||
res.json.Message ||
|
||||
res.json.message ||
|
||||
"VIN inquiry failed";
|
||||
throw new Error(String(msg));
|
||||
}
|
||||
validateVehicleInquiry(res);
|
||||
return {
|
||||
source: "ESG_carByChassis",
|
||||
mode: "vin",
|
||||
@@ -307,6 +325,7 @@ async function inquireVehicle(input) {
|
||||
try {
|
||||
const live =
|
||||
mode === "vin" ? await liveVinInquiry(payload) : await livePlateInquiry(payload);
|
||||
requireVehicleFields(live.vehicle);
|
||||
return { ok: true, ...live };
|
||||
} catch (err) {
|
||||
return { ok: false, error: String(err.message || err), mode };
|
||||
@@ -767,6 +786,7 @@ function envObjectToText(obj) {
|
||||
"DRIVER_BIRTH_DAY",
|
||||
"DRIVER_IS_INSURER",
|
||||
"DRIVER_IS_OWNER",
|
||||
"PERSON_ROLE_ID",
|
||||
"DRIVER_MOBILE",
|
||||
"DRIVER_TEL",
|
||||
"DRIVER_ADDRESS",
|
||||
@@ -999,12 +1019,38 @@ function runStage(stage, options = {}) {
|
||||
});
|
||||
}
|
||||
|
||||
function parsianBranchSeeds() {
|
||||
const dir = path.join(__dirname, "data", "parsian-tehran");
|
||||
const read = (file) => JSON.parse(fs.readFileSync(path.join(dir, file), "utf8"));
|
||||
const branches = Object.fromEntries(read("branches.json").branches.map((b) => [
|
||||
b.code, { name: `${b.name} (${b.code})`, makers: [], reviewers: [] },
|
||||
]));
|
||||
for (const [file, key, role, thirdParty, body] of [
|
||||
["file-makers.json", "fileMakers", "makers", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
|
||||
["file-reviewers.json", "fileReviewers", "reviewers", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"],
|
||||
]) {
|
||||
for (const expert of read(file)[key]) {
|
||||
for (const location of expert.locations || []) {
|
||||
if (!branches[location.id]) continue;
|
||||
branches[location.id][role].push({
|
||||
name: `${expert.firstName} ${expert.lastName}`,
|
||||
[role === "makers" ? "claim" : "tp"]: expert[thirdParty] || "",
|
||||
body: expert[body] || "",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return branches;
|
||||
}
|
||||
|
||||
const server = http.createServer(async (req, res) => {
|
||||
const url = new URL(req.url, `http://${HOST}:${PORT}`);
|
||||
|
||||
try {
|
||||
if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) {
|
||||
send(res, 200, fs.readFileSync(UI_HTML, "utf8"), "text/html; charset=utf-8");
|
||||
const seeds = JSON.stringify(parsianBranchSeeds()).replace(/</g, "\\u003c");
|
||||
const html = fs.readFileSync(UI_HTML, "utf8").replace("/* PARSIAN_BRANCH_SEEDS */ {}", () => seeds);
|
||||
send(res, 200, html, "text/html; charset=utf-8");
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
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");
|
||||
|
||||
// Exercise the inquiry entry point without starting the UI or contacting a provider.
|
||||
function inquiryContext(response) {
|
||||
const source = fs.readFileSync(path.join(__dirname, "fanavaran-flow-ui-server.js"), "utf8")
|
||||
.split("const server = http.createServer")[0];
|
||||
const context = vm.createContext({ require, __dirname, process: { env: {} }, Buffer });
|
||||
vm.runInContext(source, context);
|
||||
context.response = response;
|
||||
vm.runInContext(`
|
||||
findOfflinePlate = () => null;
|
||||
getSandhubToken = async () => "test-token";
|
||||
httpJson = async () => response;
|
||||
`, context);
|
||||
return context;
|
||||
}
|
||||
|
||||
for (const [name, json, status] of [
|
||||
["HTTP error JSON", { statusCode: 401, message: "Unauthorized" }, 401],
|
||||
["provider failure", { success: false, message: "No policy found" }, 200],
|
||||
["nested provider failure", { data: { hasError: true, message: "Not found" } }, 200],
|
||||
["empty result", { data: {} }, 200],
|
||||
]) {
|
||||
test(`${name} must not report success with empty vehicle inputs`, async () => {
|
||||
const context = inquiryContext({ code: 0, status, json });
|
||||
const result = await vm.runInContext('inquireVehicle({ client: "tejaratno" })', context);
|
||||
assert.equal(result.ok, false);
|
||||
assert.ok(result.error);
|
||||
});
|
||||
}
|
||||
|
||||
test("successful Tejarat inquiry fills vehicle and policy fields", async () => {
|
||||
const context = inquiryContext({ code: 0, status: 200, json: { data: {
|
||||
mtrnum: "ENGINE-1", shsNam: "CHASSIS-1", vin: "VIN-1", ModelField: "1400",
|
||||
insuranceNumber: "POLICY-1", PlcyUnqCod: "12345",
|
||||
persianStartDate: "1404/01/01", persianEndDate: "1405/01/01",
|
||||
} } });
|
||||
const result = await vm.runInContext('inquireVehicle({ client: "tejaratno" })', context);
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(result.vehicle)), {
|
||||
MOTOR_NO: "ENGINE-1", CHASSIS_NO: "CHASSIS-1", VIN: "VIN-1", BUILT_YEAR: "1400",
|
||||
POLICY_NO: "POLICY-1", POLICY_CI_NUMBER: "12345",
|
||||
BEGIN_DATE: "1404/01/01", END_DATE: "1405/01/01",
|
||||
});
|
||||
});
|
||||
|
||||
test("policy aliases used by existing inquiry mappings populate all three fields", async () => {
|
||||
const context = inquiryContext({ code: 0, status: 200, json: {
|
||||
MtrNum: "ENGINE-1", LastCompanyDocumentNumber: "POLICY-2",
|
||||
SatrtDate: "1404/02/01", endDate: "1405/02/01",
|
||||
} });
|
||||
const result = await vm.runInContext('inquireVehicle({ client: "tejaratno" })', context);
|
||||
assert.equal(result.vehicle.POLICY_NO, "POLICY-2");
|
||||
assert.equal(result.vehicle.BEGIN_DATE, "1404/02/01");
|
||||
assert.equal(result.vehicle.END_DATE, "1405/02/01");
|
||||
});
|
||||
|
||||
test("flow UI includes every seed expert in each assigned branch and both Kazemi codes", () => {
|
||||
const context = inquiryContext({});
|
||||
const branches = vm.runInContext("parsianBranchSeeds()", context);
|
||||
for (const [file, key, role] of [
|
||||
["file-makers.json", "fileMakers", "makers"],
|
||||
["file-reviewers.json", "fileReviewers", "reviewers"],
|
||||
]) {
|
||||
const seeds = JSON.parse(fs.readFileSync(path.join(__dirname, "data/parsian-tehran", file)))[key];
|
||||
for (const expert of seeds) {
|
||||
for (const location of expert.locations) {
|
||||
assert.ok(branches[location.id][role].some(r => r.name === `${expert.firstName} ${expert.lastName}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
const kazemi = branches["210120"].reviewers.find(r => r.name.includes("کاظمي دولت سرا"));
|
||||
assert.equal(kazemi.tp, "3992");
|
||||
assert.equal(kazemi.body, "3991");
|
||||
});
|
||||
|
||||
test("hull flow derives all three licence replacement states from dates", () => {
|
||||
const script = fs.readFileSync(path.join(__dirname, "fanavaran-flow-test.sh"), "utf8");
|
||||
const start = script.indexOf('const e=process.env, n=(k)=>Number(e[k]), nullable=');
|
||||
const builder = script.slice(start, script.indexOf('\nNODE', start));
|
||||
for (const [issue, expected] of [
|
||||
["1404/08/24", 0], ["1401/08/24", null], ["1394/08/24", 1],
|
||||
["1402/08/24", 0], ["1395/08/24", null],
|
||||
]) {
|
||||
let output = "";
|
||||
vm.runInNewContext(builder, { process: {
|
||||
env: { POLICE_REPORT_DESC: "شرح حادثه", CULPRIT_LICENCE_ISSU_DATE: issue, ACCIDENT_DATE: "1405/08/24" },
|
||||
stdout: { write: text => { output += text; } },
|
||||
} });
|
||||
assert.equal(JSON.parse(output).IsLicenseReplaced, expected, issue);
|
||||
}
|
||||
});
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -183,7 +183,9 @@ export class ActorAuthService {
|
||||
dbService: { findOne: (filter: any) => Promise<any> },
|
||||
identifier: string,
|
||||
) {
|
||||
const id = identifier.trim();
|
||||
const id = identifier.includes("@")
|
||||
? identifier.trim().toLowerCase()
|
||||
: identifier.trim();
|
||||
const or: Record<string, string>[] = [{ email: id }, { username: id }];
|
||||
if (/^\d{10}$/.test(id)) {
|
||||
or.push({ nationalCode: id });
|
||||
@@ -234,9 +236,47 @@ export class ActorAuthService {
|
||||
if (!(await this.hashService.compare(pass, user.password))) {
|
||||
throw new UnauthorizedException("نام کاربری یا رمز عبور اشتباه است");
|
||||
}
|
||||
this.assertActive(user);
|
||||
return user;
|
||||
}
|
||||
|
||||
private assertActive(actor: { isActive?: boolean }) {
|
||||
// Legacy accounts have no flag and remain active.
|
||||
if (actor.isActive === false)
|
||||
throw new UnauthorizedException(
|
||||
"حساب کاری شما غیرفعال شده است. با مدیر سامانه تماس بگیرید.",
|
||||
);
|
||||
}
|
||||
|
||||
/** Recheck persisted status so a disabled account cannot reuse an old JWT. */
|
||||
async assertActorActive(payload: { role?: string; sub?: string }) {
|
||||
if (
|
||||
![
|
||||
RoleEnum.EXPERT,
|
||||
RoleEnum.DAMAGE_EXPERT,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
RoleEnum.CALL_CENTER,
|
||||
].includes(payload?.role as RoleEnum)
|
||||
)
|
||||
return;
|
||||
if (!payload.sub || !Types.ObjectId.isValid(payload.sub))
|
||||
throw new UnauthorizedException(
|
||||
"حساب کاربری معتبر نیست. دوباره وارد شوید.",
|
||||
);
|
||||
const actor = await this.dynamicDbController(
|
||||
payload.role,
|
||||
null,
|
||||
payload.sub,
|
||||
);
|
||||
if (!actor)
|
||||
throw new UnauthorizedException(
|
||||
"حساب کاربری یافت نشد. دوباره وارد شوید.",
|
||||
);
|
||||
this.assertActive(actor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticates an actor from a login request body (role, username/email, password).
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { ExecutionContext, UnauthorizedException } from "@nestjs/common";
|
||||
import { Types } from "mongoose";
|
||||
import { ActorAuthService } from "./actor.auth.service";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { GlobalGuard } from "../guards/global.guard";
|
||||
import { LocalActorAuthGuard } from "../guards/actor-local.guard";
|
||||
import { SettingsJwtGuard } from "../guards/settings-jwt.guard";
|
||||
import { AuthGuard } from "src/common/auth/guards/auth.guard";
|
||||
import { ClaimAccessGuard } from "../guards/claim-access.guard";
|
||||
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||
|
||||
const roles = [
|
||||
RoleEnum.EXPERT,
|
||||
RoleEnum.DAMAGE_EXPERT,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
RoleEnum.CALL_CENTER,
|
||||
];
|
||||
const dbNames = [
|
||||
"expertDbService",
|
||||
"damageExpertDbService",
|
||||
"fieldExpertDbService",
|
||||
"fileMakerDbService",
|
||||
"fileReviewerDbService",
|
||||
"callCenterAgentDbService",
|
||||
];
|
||||
|
||||
function setup() {
|
||||
const service = new (ActorAuthService as any)() as ActorAuthService;
|
||||
const actors = roles.map((role) => ({
|
||||
_id: new Types.ObjectId(),
|
||||
role,
|
||||
email: "person@example.test",
|
||||
nationalCode: "0012345678",
|
||||
password: "hash:shared-password",
|
||||
}));
|
||||
const dbs = actors.map((actor, index) => {
|
||||
const db = {
|
||||
findOne: jest.fn().mockResolvedValue(actor),
|
||||
findByLoginIdentifier: jest.fn().mockResolvedValue(actor),
|
||||
};
|
||||
(service as any)[dbNames[index]] = db;
|
||||
return db;
|
||||
});
|
||||
(service as any).hashService = {
|
||||
compare: jest.fn(async (plain, hashed) => `hash:${plain}` === hashed),
|
||||
};
|
||||
return { service, actors, dbs };
|
||||
}
|
||||
|
||||
describe("expert role identities and activation", () => {
|
||||
it.each(["person@example.test", "0012345678"])(
|
||||
"authenticates the same %s and password in every assigned role",
|
||||
async (identifier) => {
|
||||
const { service, actors, dbs } = setup();
|
||||
for (const [index, role] of roles.entries()) {
|
||||
expect(
|
||||
await service.validateActor(identifier, "shared-password", role),
|
||||
).toBe(actors[index]);
|
||||
expect(
|
||||
dbs[index].findOne.mock.calls.length +
|
||||
dbs[index].findByLoginIdentifier.mock.calls.length,
|
||||
).toBe(1);
|
||||
}
|
||||
for (const db of dbs)
|
||||
expect(
|
||||
db.findOne.mock.calls.length +
|
||||
db.findByLoginIdentifier.mock.calls.length,
|
||||
).toBe(1);
|
||||
},
|
||||
);
|
||||
it.each(roles)(
|
||||
"blocks inactive %s login and tokens, with legacy-active and reactivation support",
|
||||
async (role) => {
|
||||
const { service, actors } = setup();
|
||||
const actor: any = actors[roles.indexOf(role)];
|
||||
const token = { role, sub: String(actor._id) };
|
||||
await expect(
|
||||
service.validateActor(actor.email, "shared-password", role),
|
||||
).resolves.toBe(actor);
|
||||
await expect(service.assertActorActive(token)).resolves.toBeUndefined();
|
||||
actor.isActive = false;
|
||||
await expect(
|
||||
service.validateActor(actor.email, "shared-password", role),
|
||||
).rejects.toThrow("غیرفعال");
|
||||
await expect(service.assertActorActive(token)).rejects.toThrow("غیرفعال");
|
||||
actor.isActive = true;
|
||||
await expect(
|
||||
service.validateActor(actor.nationalCode, "shared-password", role),
|
||||
).resolves.toBe(actor);
|
||||
},
|
||||
);
|
||||
it("disabling the maker leaves the reviewer's credentials and access intact", async () => {
|
||||
const { service, actors } = setup();
|
||||
(actors[3] as any).isActive = false;
|
||||
await expect(
|
||||
service.validateActor(
|
||||
"0012345678",
|
||||
"shared-password",
|
||||
RoleEnum.FILE_MAKER,
|
||||
),
|
||||
).rejects.toThrow("غیرفعال");
|
||||
await expect(
|
||||
service.validateActor(
|
||||
"0012345678",
|
||||
"shared-password",
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
),
|
||||
).resolves.toBe(actors[4]);
|
||||
await expect(
|
||||
service.validateActor(
|
||||
"0012345678",
|
||||
"wrong-password",
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
it("does not resolve ordinary user, insurer or super-admin JWTs through expert storage", async () => {
|
||||
const { service, dbs } = setup();
|
||||
for (const role of [RoleEnum.USER, RoleEnum.COMPANY, RoleEnum.SUPER_ADMIN])
|
||||
await service.assertActorActive({ role, sub: "existing-subject" });
|
||||
for (const db of dbs) expect(db.findOne).not.toHaveBeenCalled();
|
||||
});
|
||||
it("rejects missing/deleted expert subjects", async () => {
|
||||
const { service, dbs } = setup();
|
||||
await expect(
|
||||
service.assertActorActive({ role: RoleEnum.EXPERT, sub: "bad-id" }),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
dbs[0].findOne.mockResolvedValue(null);
|
||||
await expect(
|
||||
service.assertActorActive({
|
||||
role: RoleEnum.EXPERT,
|
||||
sub: String(new Types.ObjectId()),
|
||||
}),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
});
|
||||
|
||||
describe("expert access status at every JWT entry point", () => {
|
||||
it.each(["actor", "user-panel", "settings", "common", "claim"])(
|
||||
"checks current account state in %s guard",
|
||||
async (entry) => {
|
||||
const auth = { assertActorActive: jest.fn() };
|
||||
const payload = {
|
||||
role: entry === "claim" ? RoleEnum.DAMAGE_EXPERT : RoleEnum.FILE_MAKER,
|
||||
sub: String(new Types.ObjectId()),
|
||||
};
|
||||
const jwt = { verifyAsync: jest.fn().mockResolvedValue(payload) };
|
||||
const guard =
|
||||
entry === "actor"
|
||||
? new LocalActorAuthGuard(auth as any, jwt as any)
|
||||
: entry === "user-panel"
|
||||
? new GlobalGuard(jwt as any, auth as any)
|
||||
: entry === "settings"
|
||||
? new SettingsJwtGuard(jwt as any, auth as any)
|
||||
: entry === "claim"
|
||||
? new ClaimAccessGuard(jwt as any, {} as any, auth as any)
|
||||
: new AuthGuard(jwt as any, auth as any);
|
||||
const request = {
|
||||
headers: { authorization: "Bearer existing-token" },
|
||||
url: "/protected",
|
||||
};
|
||||
const context = {
|
||||
switchToHttp: () => ({ getRequest: () => request }),
|
||||
} as ExecutionContext;
|
||||
await expect(guard.canActivate(context)).resolves.toBe(true);
|
||||
expect(auth.assertActorActive).toHaveBeenCalledWith(payload);
|
||||
auth.assertActorActive.mockRejectedValue(
|
||||
new UnauthorizedException("حساب کاری غیرفعال است."),
|
||||
);
|
||||
await expect(guard.canActivate(context)).rejects.toThrow("غیرفعال");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("older insurer expert-creation endpoints", () => {
|
||||
it.each([RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT])(
|
||||
"limits duplicate checks to the selected %s role",
|
||||
async (role) => {
|
||||
const service = new (ExpertInsurerService as any)() as any;
|
||||
const key = new Types.ObjectId();
|
||||
service.getClientId = () => key;
|
||||
service.assertBranchBelongsToClient = async () => ({
|
||||
_id: new Types.ObjectId(),
|
||||
name: "شعبه",
|
||||
});
|
||||
service.hashService = { hash: async () => "hash:password" };
|
||||
service.sanitizeExpertResponse = (value) => ({ role: value.role });
|
||||
const makeDb = () => ({
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
create: jest.fn(async (body) => body),
|
||||
});
|
||||
service.expertDbService = makeDb();
|
||||
service.damageExpertDbService = makeDb();
|
||||
const selected =
|
||||
role === RoleEnum.EXPERT
|
||||
? service.expertDbService
|
||||
: service.damageExpertDbService;
|
||||
const other =
|
||||
role === RoleEnum.EXPERT
|
||||
? service.damageExpertDbService
|
||||
: service.expertDbService;
|
||||
other.findOne.mockResolvedValue({
|
||||
nationalCode: "0012345678",
|
||||
email: "person@example.test",
|
||||
});
|
||||
await service.createExpertForInsurer(
|
||||
String(key),
|
||||
{
|
||||
email: "person@example.test",
|
||||
nationalCode: "0012345678",
|
||||
password: "password",
|
||||
branchId: String(new Types.ObjectId()),
|
||||
firstName: "علی",
|
||||
lastName: "احمدی",
|
||||
},
|
||||
role,
|
||||
);
|
||||
expect(selected.create).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ role, email: "person@example.test" }),
|
||||
);
|
||||
expect(other.findOne).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -4,15 +4,17 @@ import { LocalActorAuthGuard } from "./actor-local.guard";
|
||||
|
||||
describe("LocalActorAuthGuard", () => {
|
||||
const credentials = { username: "new-account", password: "test-password" };
|
||||
let auth: { loginFromCredentials: jest.Mock };
|
||||
let auth: { loginFromCredentials: jest.Mock; assertActorActive: jest.Mock };
|
||||
let jwt: { verifyAsync: jest.Mock };
|
||||
let guard: LocalActorAuthGuard;
|
||||
|
||||
const context = (request: Record<string, unknown>) =>
|
||||
({ switchToHttp: () => ({ getRequest: () => request }) }) as ExecutionContext;
|
||||
({
|
||||
switchToHttp: () => ({ getRequest: () => request }),
|
||||
}) as ExecutionContext;
|
||||
|
||||
beforeEach(() => {
|
||||
auth = { loginFromCredentials: jest.fn() };
|
||||
auth = { loginFromCredentials: jest.fn(), assertActorActive: jest.fn() };
|
||||
jwt = { verifyAsync: jest.fn() };
|
||||
guard = new LocalActorAuthGuard(auth as any, jwt as any);
|
||||
});
|
||||
@@ -38,14 +40,19 @@ describe("LocalActorAuthGuard", () => {
|
||||
|
||||
it("does not let a previous token bypass failed credentials or captcha", async () => {
|
||||
auth.loginFromCredentials.mockRejectedValue(new UnauthorizedException());
|
||||
jwt.verifyAsync.mockResolvedValue({ sub: "old-account", role: RoleEnum.EXPERT });
|
||||
jwt.verifyAsync.mockResolvedValue({
|
||||
sub: "old-account",
|
||||
role: RoleEnum.EXPERT,
|
||||
});
|
||||
|
||||
await expect(
|
||||
guard.canActivate(context({
|
||||
route: { path: "/actor/login" },
|
||||
headers: { authorization: "Bearer previous-session" },
|
||||
body: credentials,
|
||||
})),
|
||||
guard.canActivate(
|
||||
context({
|
||||
route: { path: "/actor/login" },
|
||||
headers: { authorization: "Bearer previous-session" },
|
||||
body: credentials,
|
||||
}),
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
expect(jwt.verifyAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -58,9 +65,31 @@ describe("LocalActorAuthGuard", () => {
|
||||
headers: { authorization: "Bearer current-session" },
|
||||
};
|
||||
await expect(guard.canActivate(context(request))).resolves.toBe(true);
|
||||
expect(jwt.verifyAsync).toHaveBeenCalledWith("current-session", expect.any(Object));
|
||||
expect(jwt.verifyAsync).toHaveBeenCalledWith(
|
||||
"current-session",
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(auth.loginFromCredentials).not.toHaveBeenCalled();
|
||||
expect(request["user"]).toBe(payload);
|
||||
expect(auth.assertActorActive).toHaveBeenCalledWith(payload);
|
||||
});
|
||||
|
||||
it("rejects a previously issued token after the account is disabled", async () => {
|
||||
jwt.verifyAsync.mockResolvedValue({
|
||||
sub: "expert-id",
|
||||
role: RoleEnum.EXPERT,
|
||||
});
|
||||
auth.assertActorActive.mockRejectedValue(
|
||||
new UnauthorizedException("حساب کاری شما غیرفعال شده است."),
|
||||
);
|
||||
const request = {
|
||||
url: "/actor/profile",
|
||||
headers: { authorization: "Bearer old-session" },
|
||||
};
|
||||
await expect(guard.canActivate(context(request))).rejects.toThrow(
|
||||
"غیرفعال",
|
||||
);
|
||||
expect(request).not.toHaveProperty("user");
|
||||
});
|
||||
|
||||
it("rejects protected actor routes without a token", async () => {
|
||||
@@ -73,10 +102,12 @@ describe("LocalActorAuthGuard", () => {
|
||||
it("rejects expired tokens on protected routes", async () => {
|
||||
jwt.verifyAsync.mockRejectedValue(new Error("expired"));
|
||||
await expect(
|
||||
guard.canActivate(context({
|
||||
url: "/actor/profile",
|
||||
headers: { authorization: "Bearer expired-session" },
|
||||
})),
|
||||
guard.canActivate(
|
||||
context({
|
||||
url: "/actor/profile",
|
||||
headers: { authorization: "Bearer expired-session" },
|
||||
}),
|
||||
),
|
||||
).rejects.toBeInstanceOf(UnauthorizedException);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -55,9 +55,11 @@ export class LocalActorAuthGuard implements CanActivate {
|
||||
throw new UnauthorizedException("User role is not authorized");
|
||||
}
|
||||
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
request.user = payload;
|
||||
request.identity = request.user;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error;
|
||||
throw new UnauthorizedException("Invalid token");
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import { JwtService } from "@nestjs/jwt";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service";
|
||||
import { Types } from "mongoose";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
/**
|
||||
* Guard that allows:
|
||||
@@ -20,6 +21,7 @@ export class ClaimAccessGuard implements CanActivate {
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly claimDbService: ClaimRequestManagementDbService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
@@ -33,6 +35,7 @@ export class ClaimAccessGuard implements CanActivate {
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: `${process.env.JWT_SECRET}`,
|
||||
});
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
|
||||
// Allow users to pass through (they will be checked by service methods)
|
||||
if (payload.role === RoleEnum.USER) {
|
||||
|
||||
@@ -7,18 +7,22 @@ import {
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
const GLOBAL_GUARD_ROLES = new Set<string>([
|
||||
RoleEnum.USER,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.REGISTRAR,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
]);
|
||||
|
||||
@Injectable()
|
||||
export class GlobalGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest();
|
||||
@@ -39,6 +43,7 @@ export class GlobalGuard implements CanActivate {
|
||||
);
|
||||
}
|
||||
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
request.user = payload;
|
||||
request.identity = request.user;
|
||||
} catch (error) {
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
} from "@nestjs/common";
|
||||
import { JwtService } from "@nestjs/jwt";
|
||||
import { Request } from "express";
|
||||
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||
|
||||
/**
|
||||
* Verifies Bearer JWT for platform settings routes. Does not restrict by role;
|
||||
@@ -13,7 +14,10 @@ import { Request } from "express";
|
||||
*/
|
||||
@Injectable()
|
||||
export class SettingsJwtGuard implements CanActivate {
|
||||
constructor(private readonly jwtService: JwtService) {}
|
||||
constructor(
|
||||
private readonly jwtService: JwtService,
|
||||
private readonly actorAuthService: ActorAuthService,
|
||||
) {}
|
||||
|
||||
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||
const request = context.switchToHttp().getRequest<Request>();
|
||||
@@ -26,10 +30,12 @@ export class SettingsJwtGuard implements CanActivate {
|
||||
const payload = await this.jwtService.verifyAsync(token, {
|
||||
secret: `${process.env.JWT_SECRET}`,
|
||||
});
|
||||
await this.actorAuthService.assertActorActive(payload);
|
||||
(request as any).user = payload;
|
||||
(request as any).identity = payload;
|
||||
return true;
|
||||
} catch {
|
||||
} catch (error) {
|
||||
if (error instanceof UnauthorizedException) throw error;
|
||||
throw new UnauthorizedException("Invalid token");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,14 @@ describe("buildInsurerFileReport", () => {
|
||||
return field?.value;
|
||||
};
|
||||
|
||||
it("shows an address-only accident location in the exported report", () => {
|
||||
const address = "تهران، خیابان آزادی، مقابل دانشگاه";
|
||||
const report = buildInsurerFileReport({
|
||||
blame: { type: "CAR_BODY", parties: [{ role: "FIRST", location: { address } }] },
|
||||
});
|
||||
expect(getFieldValue(report, PR.accidentSection, PR.location)).toBe(address);
|
||||
});
|
||||
|
||||
it("separates insurance blocks and exposes Fanavaran/timeline/evaluation data", () => {
|
||||
const fileCreatedAt = new Date("2026-08-10T09:53:23.588Z");
|
||||
const evaluationSubmittedAt = new Date("2026-08-10T12:30:45.000Z");
|
||||
@@ -289,10 +297,10 @@ describe("buildInsurerFileReport", () => {
|
||||
"سپر جلو",
|
||||
);
|
||||
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
|
||||
"۲٬۵۰۰٬۰۰۰ تومان",
|
||||
"۲٬۵۰۰٬۰۰۰ ریال",
|
||||
);
|
||||
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / مبلغ کل")).toBe(
|
||||
"۳٬۰۰۰٬۰۰۰ تومان",
|
||||
"۳٬۰۰۰٬۰۰۰ ریال",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -344,7 +352,7 @@ describe("buildInsurerFileReport", () => {
|
||||
"چراغ جلو",
|
||||
);
|
||||
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
|
||||
"۴٬۰۰۰٬۰۰۰ تومان",
|
||||
"۴٬۰۰۰٬۰۰۰ ریال",
|
||||
);
|
||||
});
|
||||
|
||||
@@ -384,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" },
|
||||
},
|
||||
},
|
||||
@@ -411,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" },
|
||||
},
|
||||
},
|
||||
@@ -562,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",
|
||||
@@ -37,7 +39,7 @@ type ReportParty = ReportRecord & {
|
||||
insurance?: ReportRecord & { carBodyInsurance?: ReportRecord };
|
||||
vehicle?: ReportRecord;
|
||||
statement?: ReportRecord;
|
||||
location?: { lat?: number; lon?: number };
|
||||
location?: { lat?: number; lon?: number; address?: string };
|
||||
participants?: ReportRecord[];
|
||||
participantRoles?: ReportRecord;
|
||||
};
|
||||
@@ -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}`,
|
||||
@@ -1016,9 +1024,9 @@ function buildAccidentReportSection(
|
||||
{
|
||||
label: PR.location,
|
||||
value:
|
||||
location?.lat != null && location?.lon != null
|
||||
asString(location?.address) ?? (location?.lat != null && location?.lon != null
|
||||
? `${location.lat}، ${location.lon}`
|
||||
: undefined,
|
||||
: undefined),
|
||||
},
|
||||
{
|
||||
label: PR.weather,
|
||||
@@ -1109,7 +1117,7 @@ export function buildInsurerFileReport(file: {
|
||||
? (resolveClaimOwnerParty(blameContext as any) as ReportParty | null)
|
||||
: null;
|
||||
const isCarBody =
|
||||
String((blameContext?.type as string | undefined) ?? "") === "CAR_BODY";
|
||||
(blameContext?.type ?? overview.type ?? claim?.blameRequestType) === "CAR_BODY";
|
||||
const includeGuiltySections =
|
||||
!!guiltyParty && !(isCarBody && sameParty(damagedParty, guiltyParty));
|
||||
|
||||
@@ -1173,7 +1181,7 @@ export function buildInsurerFileReport(file: {
|
||||
)
|
||||
: undefined,
|
||||
buildFanavaranCodesSection(claim),
|
||||
buildEvaluationSection(claim),
|
||||
buildEvaluationSection(claim, isCarBody),
|
||||
buildEvaluationPartsSection(claim),
|
||||
buildAccidentReportSection(blameContext, claim, damagedParty),
|
||||
]);
|
||||
|
||||
@@ -1,10 +1,16 @@
|
||||
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { RequestManagementModule } from "src/request-management/request-management.module";
|
||||
import { ExpertInsurerModule } from "src/expert-insurer/expert-insurer.module";
|
||||
import { CaseExpertReportInsurerController } from "./case-expert-report.controller";
|
||||
import { CaseExpertReportService } from "./case-expert-report.service";
|
||||
|
||||
@Module({
|
||||
imports: [ExpertInsurerModule],
|
||||
imports: [
|
||||
ExpertInsurerModule,
|
||||
RequestManagementModule,
|
||||
ClaimRequestManagementModule,
|
||||
],
|
||||
controllers: [CaseExpertReportInsurerController],
|
||||
providers: [CaseExpertReportService],
|
||||
exports: [CaseExpertReportService],
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Injectable, NotFoundException } from "@nestjs/common";
|
||||
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
|
||||
import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.db.service";
|
||||
import { Types } from "mongoose";
|
||||
import { BlameDocumentDbService } from "src/request-management/entities/db-service/blame-document.db.service";
|
||||
import { buildReportAttachments, buildReportSignatures } from "./report-media";
|
||||
import { buildInsurerFileReport } from "./case-expert-report.builder";
|
||||
import { InsurerFileReportViewModel } from "./case-expert-report.types";
|
||||
|
||||
@@ -7,6 +11,8 @@ import { InsurerFileReportViewModel } from "./case-expert-report.types";
|
||||
export class CaseExpertReportService {
|
||||
constructor(
|
||||
private readonly expertInsurerService: ExpertInsurerService,
|
||||
private readonly blameDocumentDbService: BlameDocumentDbService,
|
||||
private readonly factorImageDbService: ClaimFactorsImageDbService,
|
||||
) {}
|
||||
|
||||
async generateForInsurer(
|
||||
@@ -21,7 +27,28 @@ export class CaseExpertReportService {
|
||||
const file = await this.expertInsurerService.retrieveFileDetailsByPublicId(
|
||||
clientKey,
|
||||
publicId,
|
||||
true,
|
||||
);
|
||||
return buildInsurerFileReport(file);
|
||||
const blame = file.reportBlame ?? file.blame;
|
||||
const blameId = String(blame?._id ?? "");
|
||||
const claimId = String(file.claim?.claimRequestId ?? "");
|
||||
const [blameDocuments, invoices] = await Promise.all([
|
||||
Types.ObjectId.isValid(blameId)
|
||||
? this.blameDocumentDbService.findByRequestId(blameId)
|
||||
: [],
|
||||
Types.ObjectId.isValid(claimId)
|
||||
? this.factorImageDbService.findByClaimId(claimId)
|
||||
: [],
|
||||
]);
|
||||
return {
|
||||
...buildInsurerFileReport({ ...file, blame }),
|
||||
attachments: buildReportAttachments(
|
||||
file.claim,
|
||||
blame,
|
||||
blameDocuments,
|
||||
invoices,
|
||||
),
|
||||
signatures: buildReportSignatures(blame, file.claim),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,13 @@ export type InsurerFileReportSection = {
|
||||
fields: InsurerFileReportField[];
|
||||
};
|
||||
|
||||
export type ReportAttachment = { label: string; url?: string; image?: string };
|
||||
|
||||
export type InsurerFileReportViewModel = {
|
||||
title: string;
|
||||
publicId: string;
|
||||
requestNo?: string;
|
||||
sections: InsurerFileReportSection[];
|
||||
signatures?: ReportAttachment[];
|
||||
attachments?: ReportAttachment[];
|
||||
};
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
PR,
|
||||
persianFieldPath,
|
||||
persianReportValue,
|
||||
persianStatus,
|
||||
} from "./persian-report-labels";
|
||||
import { buildInsurerFileReport } from "./case-expert-report.builder";
|
||||
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
|
||||
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
|
||||
|
||||
describe("Persian report presentation", () => {
|
||||
it.each([...Object.values(ClaimCaseStatus), ...Object.values(CaseStatus)])(
|
||||
"translates persisted status %s",
|
||||
(status) => expect(persianStatus(status)).not.toMatch(/[a-z]/i),
|
||||
);
|
||||
it("uses meaningful Persian labels and suppresses unknown provider field keys", () => {
|
||||
expect(persianFieldPath("party.vehicle.vin")).toBe(
|
||||
"خودرو / شماره شناسایی خودرو",
|
||||
);
|
||||
expect(
|
||||
persianFieldPath("party.vehicle.inquiry.unmappedProviderField"),
|
||||
).toBe("");
|
||||
expect(persianReportValue("vehicle.expedited", true)).toBe("فوری");
|
||||
expect(persianReportValue("vehicle.carType", "sedan")).toBe("سواری");
|
||||
expect(persianReportValue("vehicle.status", "NEW_UNKNOWN_STATUS")).toBe(
|
||||
"وضعیت نامشخص",
|
||||
);
|
||||
});
|
||||
it("keeps factual identifiers intact, uses phones for unnamed users and keeps driver/owner identities separate", () => {
|
||||
const vin = "IR1ABC23456789012";
|
||||
const report = buildInsurerFileReport({
|
||||
overview: { publicId: "QA-1" },
|
||||
blame: {
|
||||
type: "CAR_BODY",
|
||||
status: "COMPLETED",
|
||||
parties: [
|
||||
{
|
||||
role: "FIRST",
|
||||
person: {
|
||||
userId: "650000000000000000000001",
|
||||
fullName: "1234567890",
|
||||
phoneNumber: "09120000000",
|
||||
driverIsInsurer: false,
|
||||
nationalCodeOfDriver: "1111111111",
|
||||
driverLicense: "987654321",
|
||||
},
|
||||
participants: [
|
||||
{
|
||||
participantId: "driver",
|
||||
fullName: "حسن احمدی",
|
||||
nationalCode: "1111111111",
|
||||
birthday: "1370/01/01",
|
||||
},
|
||||
],
|
||||
participantRoles: { driver: "driver" },
|
||||
vehicle: {
|
||||
vin,
|
||||
carType: "sedan",
|
||||
unknownProviderField: "DO_NOT_SHOW",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
claim: {
|
||||
owner: { userId: "650000000000000000000001" },
|
||||
evaluation: {
|
||||
damageExpertReply: {
|
||||
parts: [
|
||||
{
|
||||
carPartDamage: { label_fa: "گلگیر جلو" },
|
||||
typeOfDamage: "تعویض",
|
||||
price: "2000000",
|
||||
totalPayment: "3000000",
|
||||
factorNeeded: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const fields = report.sections.flatMap((section) => section.fields);
|
||||
expect(fields.every((field) => !/[a-z]/i.test(field.label))).toBe(true);
|
||||
expect(fields.some((field) => field.value === vin)).toBe(true);
|
||||
expect(fields.some((field) => field.value === "DO_NOT_SHOW")).toBe(false);
|
||||
expect(
|
||||
report.sections
|
||||
.find((section) => section.title === PR.ownerSection)
|
||||
?.fields.find((field) => field.label === PR.name)?.value,
|
||||
).toBe("09120000000");
|
||||
const driver = report.sections.find(
|
||||
(section) => section.title === PR.driverSection,
|
||||
);
|
||||
expect(driver?.fields.find((field) => field.label === PR.name)?.value).toBe(
|
||||
"حسن احمدی",
|
||||
);
|
||||
expect(
|
||||
driver?.fields.find((field) => field.label === PR.licenseDate),
|
||||
).toBeUndefined();
|
||||
expect(fields.some((field) => field.value === "۲٬۰۰۰٬۰۰۰ ریال")).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { UNIFIED_FILE_STATUS_CATALOG } from "src/helpers/unified-file-status";
|
||||
export const PR = {
|
||||
reportTitle: "گزارش پرونده بیمه گر",
|
||||
reportTitle: "گزارش پرونده بیمهگر",
|
||||
publicId: "شناسه عمومی",
|
||||
requestNo: "شماره درخواست",
|
||||
empty: "-",
|
||||
@@ -21,17 +22,20 @@ export const PR = {
|
||||
fanavaranSection: "کدهای فناوران",
|
||||
evaluationSection: "نتیجه ارزیابی",
|
||||
accidentSection: "گزارش حادثه",
|
||||
name: "نام",
|
||||
name: "نام و نام خانوادگی",
|
||||
phone: "شماره تلفن",
|
||||
nationalCode: "کد ملی",
|
||||
birthDate: "تاریخ تولد",
|
||||
sheba: "شماره شبا",
|
||||
licenseType: "نوع گواهینامه",
|
||||
licenseDate: "تاریخ گواهینامه",
|
||||
licenseDate: "تاریخ صدور گواهینامه",
|
||||
licenseNumber: "شماره گواهینامه",
|
||||
hasDrivingLicense: "گواهینامه دارد",
|
||||
driverLicense: "گواهینامه راننده",
|
||||
insuranceCompany: "شرکت بیمه",
|
||||
expedited: "رسیدگی فوری",
|
||||
status: "وضعیت",
|
||||
color: "رنگ",
|
||||
policyNumber: "شماره بیمهنامه",
|
||||
policyStartDate: "تاریخ شروع بیمهنامه",
|
||||
policyEndDate: "تاریخ پایان بیمهنامه",
|
||||
@@ -40,8 +44,8 @@ export const PR = {
|
||||
fileRegisteredAt: "تاریخ و ساعت ثبت پرونده",
|
||||
evaluationRegisteredAt: "تاریخ و ساعت ثبت نتیجه ارزیابی",
|
||||
fanavaranClaimNo: "شماره پرونده فناوران",
|
||||
fanavaranClaimId: "کد پرونده فناوران",
|
||||
fanavaranDamageCaseId: "کد کیس خسارت فناوران",
|
||||
fanavaranClaimId: "کد رایانه پرونده فناوران",
|
||||
fanavaranDamageCaseId: "کد پرونده خسارت فناوران",
|
||||
fanavaranExpertiseId: "کد کارشناسی فناوران",
|
||||
fanavaranPolicyId: "کد بیمهنامه فناوران",
|
||||
fanavaranDriverId: "کد راننده فناوران",
|
||||
@@ -78,9 +82,9 @@ export const PR = {
|
||||
weather: "وضعیت آب و هوا",
|
||||
road: "وضعیت جاده",
|
||||
light: "وضعیت نور",
|
||||
blameStatus: "وضعیت مقصر",
|
||||
blameStatus: "وضعیت پرونده تعیین مقصر",
|
||||
claimStatus: "وضعیت خسارت",
|
||||
expertDecision: "نظر کارشناس مقصر",
|
||||
expertDecision: "نظر کارشناس تصادف",
|
||||
accidentWay: "نحوه برخورد",
|
||||
accidentReason: "علت حادثه",
|
||||
accidentType: "نوع حادثه",
|
||||
@@ -89,7 +93,11 @@ export const PR = {
|
||||
partyDescription: "توضیحات طرف",
|
||||
} as const;
|
||||
|
||||
const KEY_LABELS: Record<string, string> = {
|
||||
export const KEY_LABELS: Record<string, string> = {
|
||||
hasEndorsement: "دارای الحاقیه",
|
||||
expedited: "رسیدگی فوری",
|
||||
status: "وضعیت",
|
||||
color: "رنگ",
|
||||
policyNumber: "شماره بیمهنامه",
|
||||
company: "شرکت بیمه",
|
||||
insurerCompany: "شرکت بیمهگر",
|
||||
@@ -140,8 +148,8 @@ const KEY_LABELS: Record<string, string> = {
|
||||
MapTypNam: "نام نوع خودرو",
|
||||
MtrNum: "شماره موتور",
|
||||
ShsNum: "شماره شاسی",
|
||||
vin: "VIN",
|
||||
VinNumberField: "VIN",
|
||||
vin: "شماره شناسایی خودرو",
|
||||
VinNumberField: "شماره شناسایی خودرو",
|
||||
DisFnYrPrcnt: "درصد تخفیف مالی",
|
||||
DisLfYrPrcnt: "درصد تخفیف جانی",
|
||||
DisPrsnYrPrcnt: "درصد تخفیف شخص ثالث",
|
||||
@@ -209,7 +217,7 @@ const KEY_LABELS: Record<string, string> = {
|
||||
previousPlate: "پلاک قبلی",
|
||||
previousPlateId: "پلاک قبلی",
|
||||
previousPolicyholderNationalCode: "کد ملی بیمهگذار پلاک قبلی",
|
||||
vehicleVin: "شماره شاسی (VIN)",
|
||||
vehicleVin: "شماره شناسایی خودرو",
|
||||
driver: "راننده",
|
||||
vehicleOwner: "مالک وسیله نقلیه",
|
||||
thirdPartyPolicyholder: "بیمهگذار شخص ثالث",
|
||||
@@ -222,7 +230,27 @@ const KEY_LABELS: Record<string, string> = {
|
||||
error: "خطا",
|
||||
};
|
||||
|
||||
const STATUS_LABELS: Record<string, string> = {
|
||||
export const STATUS_LABELS: Record<string, string> = {
|
||||
...Object.fromEntries(UNIFIED_FILE_STATUS_CATALOG.map(item => [item.key,item.labelFa])),
|
||||
OPEN: "پرونده باز",
|
||||
CREATED: "ثبتشده",
|
||||
SELECTING_OUTER_PARTS: "در حال انتخاب قطعات آسیبدیده",
|
||||
SELECTING_OTHER_PARTS: "در حال ثبت سایر قطعات",
|
||||
UPLOADING_REQUIRED_DOCUMENTS: "در حال بارگذاری مدارک",
|
||||
CAPTURING_PART_DAMAGES: "در حال ثبت تصاویر خسارت",
|
||||
WAITING_FOR_EXPERT: "در انتظار کارشناس تصادف",
|
||||
WAITING_FOR_USER_RESEND: "در انتظار تکمیل اطلاعات کاربر",
|
||||
IN_PERSON_VISIT_PENDING: "در انتظار مراجعه حضوری",
|
||||
WAITING_FOR_INSURER_APPROVAL: "در انتظار تأیید پرونده",
|
||||
INSURER_REVIEW_AWAITING_OWNER_SIGN: "در انتظار امضای مالک",
|
||||
INSURER_REVIEW_MIXED_FACTORS_PENDING: "در انتظار تأیید مبالغ و بارگذاری فاکتورها",
|
||||
OWNER_REPAIR_FACTOR_UPLOAD_PENDING: "در انتظار بارگذاری فاکتورها",
|
||||
EXPERT_VALIDATING_REPAIR_FACTORS: "در انتظار بررسی فاکتورها توسط کارشناس",
|
||||
WAITING_FOR_FILE_REVIEWER: "در انتظار کارشناس ارزیاب",
|
||||
WAITING_FOR_FILE_MAKER_APPROVAL: "در انتظار تأیید کارشناس مسئول پرونده",
|
||||
FILE_MAKER_REJECTED: "نیازمند اصلاح توسط کارشناس ارزیاب",
|
||||
AUTO_CLOSED: "بستهشده خودکار",
|
||||
|
||||
AGREED: "توافق",
|
||||
DISAGREEMENT: "اختلاف نظر",
|
||||
UNKNOWN: "نامشخص",
|
||||
@@ -333,7 +361,9 @@ export function persianFieldPath(path: string): string {
|
||||
if (!path) return PR.data;
|
||||
const parts = path.split(".").filter(Boolean);
|
||||
const last = parts[parts.length - 1] ?? path;
|
||||
const translatedLast = KEY_LABELS[last] ?? last;
|
||||
const translate = (key: string) => KEY_LABELS[key] ?? (/^\d+$/.test(key) ? Number(key).toLocaleString("fa-IR") : /[a-z]/i.test(key) ? "" : key);
|
||||
const translatedLast = translate(last);
|
||||
if (!translatedLast) return "";
|
||||
|
||||
const inquiryRoot = parts.find(
|
||||
(p) => p === "thirdParty" || p === "carBody" || p === "mapped",
|
||||
@@ -386,7 +416,7 @@ export function persianFieldPath(path: string): string {
|
||||
|
||||
if (parts.length === 1) return translatedLast;
|
||||
|
||||
const translated = parts.map((part) => KEY_LABELS[part] ?? part);
|
||||
const translated = parts.map(translate).filter(Boolean);
|
||||
return translated.join(" / ");
|
||||
}
|
||||
|
||||
@@ -399,36 +429,37 @@ export function persianReportValue(
|
||||
value: unknown,
|
||||
): unknown {
|
||||
if (value === undefined || value === null || value === "") return value;
|
||||
if (typeof value === "boolean") return value ? "بله" : "خیر";
|
||||
if (typeof value === "boolean") return path.endsWith("expedited") ? value ? "فوری" : "عادی" : value ? "بله" : "خیر";
|
||||
if (typeof value !== "string" && typeof value !== "number") return value;
|
||||
|
||||
const raw = String(value).trim();
|
||||
const key = raw.toUpperCase().replace(/[\s-]+/g, "_");
|
||||
const field = path.split(".").filter(Boolean).pop() ?? "";
|
||||
|
||||
if (field === "expedited") return raw === "true" || raw === "1" ? "فوری" : "عادی";
|
||||
if (field === "licenseType" || field === "LicenseType") {
|
||||
return LICENSE_TYPE_LABELS[key] ?? raw;
|
||||
return LICENSE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "عنوان گواهینامه ثبت نشده است" : raw);
|
||||
}
|
||||
if (field === "registrationState") {
|
||||
return REGISTRATION_STATE_LABELS[key] ?? raw;
|
||||
return REGISTRATION_STATE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
|
||||
}
|
||||
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? raw;
|
||||
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
|
||||
if (field === "role" || field.endsWith("Role")) {
|
||||
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? raw;
|
||||
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نقش ثبتنشده" : raw);
|
||||
}
|
||||
if (field === "blameRequestType" || field === "fileType") {
|
||||
return CASE_TYPE_LABELS[key] ?? raw;
|
||||
return CASE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع پرونده ثبت نشده است" : raw);
|
||||
}
|
||||
if (
|
||||
(field === "carType" || field === "type") &&
|
||||
path.toLowerCase().includes("vehicle")
|
||||
) {
|
||||
return VEHICLE_TYPE_LABELS[key] ?? raw;
|
||||
return VEHICLE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع خودرو ثبت نشده است" : raw);
|
||||
}
|
||||
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? raw;
|
||||
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? raw;
|
||||
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? (/[a-z]/i.test(raw) ? "نوع خسارت ثبت نشده است" : raw);
|
||||
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "استعلام ناموفق بود" : raw);
|
||||
if (/status$/i.test(field)) {
|
||||
return STATUS_LABELS[raw] ?? VALIDITY_LABELS[key] ?? raw;
|
||||
return STATUS_LABELS[key] ?? VALIDITY_LABELS[key] ?? (/[a-z]/i.test(raw) ? "وضعیت نامشخص" : raw);
|
||||
}
|
||||
|
||||
if (raw === "true" || raw === "false") return STATUS_LABELS[raw];
|
||||
@@ -438,7 +469,7 @@ export function persianReportValue(
|
||||
export function persianStatus(value: unknown): string | undefined {
|
||||
if (value === undefined || value === null || value === "") return undefined;
|
||||
const key = String(value);
|
||||
return STATUS_LABELS[key] ?? key;
|
||||
return STATUS_LABELS[key] ?? STATUS_LABELS[key.toLowerCase()] ?? (/[a-z]/i.test(key) ? "وضعیت نامشخص" : key);
|
||||
}
|
||||
|
||||
export function persianAccidentCondition(
|
||||
@@ -454,5 +485,5 @@ export function persianAccidentCondition(
|
||||
: kind === "road"
|
||||
? ROAD_LABELS
|
||||
: LIGHT_LABELS;
|
||||
return labels[normalized] ?? raw;
|
||||
return labels[normalized] ?? (/[a-z]/i.test(raw) ? "ثبت نشده است" : raw);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { buildFileLink } from "src/helpers/urlCreator";
|
||||
import { personDisplayName } from "src/helpers/person-display-name";
|
||||
import type { ReportAttachment } from "./case-expert-report.types";
|
||||
|
||||
const documentLabels: Record<string, string> = {
|
||||
accident_sketch: "کروکی",
|
||||
car_green_card: "برگه سبز خودرو",
|
||||
car_certificate: "سند خودرو",
|
||||
national_card: "کارت ملی",
|
||||
damaged_driving_license_front: "روی گواهینامه زیاندیده",
|
||||
damaged_driving_license_back: "پشت گواهینامه زیاندیده",
|
||||
damaged_chassis_number: "شماره شاسی",
|
||||
damaged_engine_photo: "شماره موتور",
|
||||
damaged_car_card_front: "روی کارت خودروی زیاندیده",
|
||||
damaged_car_card_back: "پشت کارت خودروی زیاندیده",
|
||||
damaged_metal_plate: "پلاک خودروی زیاندیده",
|
||||
guilty_driving_license_front: "روی گواهینامه مقصر",
|
||||
guilty_driving_license_back: "پشت گواهینامه مقصر",
|
||||
guilty_car_card_front: "روی کارت خودروی مقصر",
|
||||
guilty_car_card_back: "پشت کارت خودروی مقصر",
|
||||
guilty_metal_plate: "پلاک خودروی مقصر",
|
||||
guilty_damage_area: "آسیب خودروی مقصر",
|
||||
drivingLicense: "گواهینامه",
|
||||
nationalCertificate: "مدرک هویتی",
|
||||
carCertificate: "سند خودرو",
|
||||
carGreenCard: "برگه سبز خودرو",
|
||||
};
|
||||
const angleLabels: Record<string, string> = {
|
||||
front: "نمای جلو",
|
||||
back: "نمای عقب",
|
||||
left: "نمای چپ",
|
||||
right: "نمای راست",
|
||||
};
|
||||
|
||||
export function buildReportAttachments(
|
||||
claim: any,
|
||||
blame: any,
|
||||
blameDocuments: { path: string; documentType: string }[],
|
||||
invoices: { path: string }[],
|
||||
): ReportAttachment[] {
|
||||
const attachments = new Map<string, ReportAttachment>();
|
||||
function add(label: string, url: unknown) {
|
||||
if (typeof url !== "string" || !/(?:^|\/)files\/[^?#]+/.test(url)) return;
|
||||
const path =
|
||||
url
|
||||
.split(/[?#]/)[0]
|
||||
.split(/(?:^|\/)files\//)
|
||||
.at(-1) ?? "";
|
||||
if (!attachments.has(path)) attachments.set(path, { label, url });
|
||||
}
|
||||
|
||||
for (const [key, value] of Object.entries(claim?.carAngles ?? {})) {
|
||||
const angle = value as { url?: string };
|
||||
add(angleLabels[key] ?? "نمای خودرو", angle.url);
|
||||
}
|
||||
for (const part of claim?.damagedParts ?? []) {
|
||||
const name =
|
||||
typeof part.label_fa === "string" && /[\u0600-\u06ff]/.test(part.label_fa)
|
||||
? part.label_fa
|
||||
: "تصویر قطعه آسیبدیده";
|
||||
add(name, part.url);
|
||||
}
|
||||
for (const [key, value] of Object.entries(claim?.requiredDocuments ?? {})) {
|
||||
add(
|
||||
documentLabels[key] ?? "مدرک خسارت",
|
||||
(value as { fileUrl?: string }).fileUrl,
|
||||
);
|
||||
}
|
||||
for (const party of blame?.parties ?? []) {
|
||||
for (const image of party.evidence?.images ?? []) {
|
||||
if (typeof image === "string" && /(?:^|\/)files\//.test(image)) {
|
||||
add("تصویر حادثه", buildFileLink(image));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const document of blameDocuments) {
|
||||
if (document.path)
|
||||
add(
|
||||
documentLabels[document.documentType] ?? "مدرک حادثه",
|
||||
buildFileLink(document.path),
|
||||
);
|
||||
}
|
||||
|
||||
const evaluation = claim?.evaluation;
|
||||
for (const invoice of invoices) {
|
||||
if (invoice.path) add("فاکتور قطعه", buildFileLink(invoice.path));
|
||||
}
|
||||
for (const invoice of evaluation?.objection?.invoices ?? [])
|
||||
add("فاکتور اعتراض", invoice.url);
|
||||
return [...attachments.values()];
|
||||
}
|
||||
|
||||
export function buildReportSignatures(
|
||||
blame: any,
|
||||
claim: any,
|
||||
): ReportAttachment[] {
|
||||
const parties: any[] = blame?.parties ?? claim?.snapshot?.parties ?? [];
|
||||
const signatures: ReportAttachment[] = [];
|
||||
for (const [index, party] of parties.entries()) {
|
||||
const signature = party.confirmation?.signature;
|
||||
const url =
|
||||
signature?.link ||
|
||||
(signature?.fileUrl ? buildFileLink(signature.fileUrl) : undefined);
|
||||
if (!url) continue;
|
||||
const isSecond = party.role ? party.role === "SECOND" : index === 1;
|
||||
const role = isSecond ? "طرف دوم" : "طرف اول";
|
||||
const name = personDisplayName(party.person);
|
||||
signatures.push({
|
||||
label: name ? `امضای ${role} · ${name}` : `امضای ${role}`,
|
||||
url,
|
||||
});
|
||||
}
|
||||
const ownerSign =
|
||||
claim?.evaluation?.ownerInsurerApproval?.signLink ??
|
||||
claim?.evaluation?.ownerPricedPartsApproval?.signLink;
|
||||
if (ownerSign)
|
||||
signatures.push({
|
||||
label: "امضای زیاندیده برای تأیید خسارت",
|
||||
url: ownerSign,
|
||||
});
|
||||
const expert = claim?.fanavaranExpertSignature;
|
||||
if (expert?.image) {
|
||||
signatures.push({
|
||||
label:
|
||||
expert.name && expert.name !== "کارشناس پرونده"
|
||||
? `امضای کارشناس · ${expert.name}`
|
||||
: "امضای کارشناس",
|
||||
image: expert.image,
|
||||
});
|
||||
}
|
||||
return signatures;
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
@@ -55,6 +55,7 @@ function serviceFor(blame: any): any {
|
||||
findOne: jest.fn().mockResolvedValue(null),
|
||||
create: jest.fn().mockResolvedValue({ _id: claimId }),
|
||||
};
|
||||
service.userClaimBranchService = { validate: jest.fn().mockResolvedValue("650000000000000000000099") };
|
||||
service.userDbService = { findAllByPhone: jest.fn().mockResolvedValue([]) };
|
||||
service.generateUniqueClaimNumber = jest.fn().mockResolvedValue("C100");
|
||||
service.autoSubmitToFanavaranV2OnClaimCreated = jest
|
||||
@@ -89,10 +90,50 @@ describe("claim beneficiary authorization across shared user flows", () => {
|
||||
expect(saved.owner.userClientKey).toBe(payer);
|
||||
expect(
|
||||
service.autoSubmitToFanavaranV2OnClaimCreated,
|
||||
).toHaveBeenCalledTimes(1);
|
||||
).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["THIRD_PARTY", "CAR_BODY"])(
|
||||
"defers Flow 1 %s submission at creation while retaining the selected branch",
|
||||
async (type) => {
|
||||
const blame = source();
|
||||
blame.type = type;
|
||||
blame.branchId = "650000000000000000000099";
|
||||
if (type === "CAR_BODY") blame.parties = [blame.parties[0]];
|
||||
const service = serviceFor(blame);
|
||||
|
||||
const result = await service.createClaimFromBlameV2(
|
||||
blameId,
|
||||
type === "CAR_BODY" ? firstId : secondId,
|
||||
);
|
||||
|
||||
expect(result.fanavaran).toMatchObject({
|
||||
attempted: false,
|
||||
submitted: false,
|
||||
skipped: true,
|
||||
});
|
||||
expect(service.autoSubmitToFanavaranV2OnClaimCreated).not.toHaveBeenCalled();
|
||||
expect(service.userClaimBranchService.validate).toHaveBeenCalledWith(blame, blame.branchId);
|
||||
expect(String(service.claimCaseDbService.create.mock.calls[0][0].branchId)).toBe(blame.branchId);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ callCenterInitiated: true },
|
||||
{ expertInitiated: true, creationMethod: "LINK" },
|
||||
{ expertInitiated: true, creationMethod: "IN_PERSON" },
|
||||
{ registrarInitiated: true },
|
||||
{ isMadeByFileMaker: true },
|
||||
])("preserves early submission for other flows: %j", async (flags) => {
|
||||
const service = serviceFor({ ...source(), ...flags });
|
||||
|
||||
await service.createClaimFromBlameV2(blameId, secondId);
|
||||
|
||||
expect(service.autoSubmitToFanavaranV2OnClaimCreated).toHaveBeenCalledTimes(1);
|
||||
expect(service.autoSubmitToFanavaranV2OnClaimCreated).toHaveBeenCalledWith(claimId);
|
||||
});
|
||||
|
||||
it("blocks incomplete, unsigned, rejected, and unresolved cases without creating or submitting a claim", async () => {
|
||||
const invalid = [
|
||||
{ ...source(), status: "WAITING_FOR_SIGNATURES" },
|
||||
@@ -189,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
|
||||
@@ -205,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();
|
||||
});
|
||||
|
||||
@@ -260,4 +305,18 @@ describe("claim beneficiary authorization across shared user flows", () => {
|
||||
service.assertEffectiveUserIsDamagedPartyOnClaim(claim, effectiveId),
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
it("copies the validated branch into the claim and blocks creation when branch validation fails", async () => {
|
||||
const blame = source();
|
||||
blame.branchId = "650000000000000000000099";
|
||||
const service = serviceFor(blame);
|
||||
await service.createClaimFromBlameV2(blameId, secondId);
|
||||
expect(service.userClaimBranchService.validate).toHaveBeenCalledWith(blame, blame.branchId);
|
||||
expect(String(service.claimCaseDbService.create.mock.calls[0][0].branchId)).toBe(blame.branchId);
|
||||
const blocked = serviceFor(source());
|
||||
blocked.userClaimBranchService.validate.mockRejectedValue(new BadRequestException("شعبه را انتخاب کنید"));
|
||||
await expect(blocked.createClaimFromBlameV2(blameId, secondId)).rejects.toBeInstanceOf(BadRequestException);
|
||||
expect(blocked.claimCaseDbService.create).not.toHaveBeenCalled();
|
||||
expect(blocked.autoSubmitToFanavaranV2OnClaimCreated).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
@@ -850,17 +852,13 @@ Returns status of each item (uploaded/captured or not).
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: "Document uploaded successfully",
|
||||
description: "Document uploaded, or an earlier stored image acknowledged on retry",
|
||||
type: UploadRequiredDocumentV2ResponseDto,
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 400,
|
||||
description: "Invalid workflow step",
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 409,
|
||||
description: "Document already uploaded",
|
||||
})
|
||||
async uploadDocument(
|
||||
@Param("claimRequestId") claimRequestId: string,
|
||||
@Body() body: UploadRequiredDocumentV2Dto,
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -29,6 +29,8 @@ export class UploadRequiredDocumentV2Dto {
|
||||
* Response DTO for upload required document V2
|
||||
*/
|
||||
export class UploadRequiredDocumentV2ResponseDto {
|
||||
@ApiPropertyOptional({ description: "An earlier saved image was reused without replacing it." })
|
||||
alreadyUploaded?: boolean;
|
||||
@ApiProperty({
|
||||
description: "Claim request ID",
|
||||
example: "507f1f77bcf86cd799439011",
|
||||
|
||||
@@ -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,
|
||||
@@ -90,10 +91,17 @@ export class FanavaranSyncStage {
|
||||
@Prop({ type: Number })
|
||||
driverId?: number;
|
||||
|
||||
/** Cached GEN.44 other-people Id when the person was created because inquiry missed. */
|
||||
/** Cached GEN.44 other-people Id when registration was required. */
|
||||
@Prop({ type: Number })
|
||||
otherPersonId?: number;
|
||||
|
||||
/** Identity associated with a hull GEN.44 registration, including pending role verification. */
|
||||
@Prop({ type: String })
|
||||
otherPersonNationalCode?: string;
|
||||
|
||||
@Prop({ type: String })
|
||||
otherPersonBirthday?: string;
|
||||
|
||||
/** Cached Fanavaran VehicleKindId. */
|
||||
@Prop({ type: Number })
|
||||
vehicleKindId?: number;
|
||||
@@ -304,7 +312,7 @@ export class ClaimCase {
|
||||
@Prop({ type: Types.ObjectId, index: true })
|
||||
initiatedByFieldExpertId?: Types.ObjectId;
|
||||
|
||||
/** Branch snapshot inherited from the originating expert-created blame. */
|
||||
/** Routing branch inherited from the blame (user selection or expert-created branch). */
|
||||
@Prop({ type: Types.ObjectId, index: true })
|
||||
branchId?: Types.ObjectId;
|
||||
|
||||
@@ -343,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,
|
||||
@@ -429,11 +431,10 @@ Returns status of each item (uploaded/captured or not).
|
||||
})
|
||||
@ApiResponse({
|
||||
status: 200,
|
||||
description: "Document uploaded successfully",
|
||||
description: "Document uploaded, or an earlier stored image acknowledged on retry",
|
||||
type: UploadRequiredDocumentV2ResponseDto,
|
||||
})
|
||||
@ApiResponse({ status: 400, description: "Invalid workflow step" })
|
||||
@ApiResponse({ status: 409, description: "Document already uploaded" })
|
||||
async uploadDocument(
|
||||
@Param("claimRequestId") claimRequestId: string,
|
||||
@Body() body: UploadRequiredDocumentV2Dto,
|
||||
@@ -566,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}`);
|
||||
|
||||
@@ -12,6 +12,7 @@ describe("fanavaranClaimReferences", () => {
|
||||
expertiseId: 22,
|
||||
}),
|
||||
).toEqual({
|
||||
submissionCompleted: true,
|
||||
claimId: 987654,
|
||||
claimNo: 123456,
|
||||
dmgCaseId: 11,
|
||||
@@ -40,6 +41,7 @@ describe("fanavaranClaimReferences", () => {
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
submissionCompleted: true,
|
||||
claimId: 100,
|
||||
claimNo: 101,
|
||||
dmgCaseId: 102,
|
||||
@@ -64,11 +66,30 @@ describe("fanavaranClaimReferences", () => {
|
||||
expertiseId: 22,
|
||||
}),
|
||||
).toEqual({
|
||||
submissionCompleted: true,
|
||||
claimId: 987654,
|
||||
expertiseId: 22,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps partial stage codes retryable", () => {
|
||||
expect(fanavaranClaimReferences({ status: ClaimCaseStatus.COMPLETED, claimId: 1, dmgCaseId: 2 }))
|
||||
.not.toHaveProperty("submissionCompleted");
|
||||
});
|
||||
|
||||
it("exposes final acceptance independently of local workflow status", () => {
|
||||
expect(fanavaranClaimReferences({ status: ClaimCaseStatus.EXPERT_REVIEWING, expertiseId: 22 }))
|
||||
.toEqual({ submissionCompleted: true });
|
||||
expect(fanavaranClaimReferences({
|
||||
status: ClaimCaseStatus.COMPLETED,
|
||||
fanavaranSync: { expertise: { status: "success" } },
|
||||
})).toEqual({ submissionCompleted: true });
|
||||
expect(fanavaranClaimReferences({
|
||||
status: ClaimCaseStatus.COMPLETED,
|
||||
fanavaranSync: { expertise: { status: "failed" } },
|
||||
})).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined before the claim is completed", () => {
|
||||
expect(
|
||||
fanavaranClaimReferences({
|
||||
|
||||
@@ -5,6 +5,8 @@ import {
|
||||
} from "./fanavaran-attachment-status";
|
||||
|
||||
export type FanavaranClaimReferences = {
|
||||
/** Final expertise has been accepted; earlier stage codes alone are insufficient. */
|
||||
submissionCompleted?: boolean;
|
||||
claimId?: number;
|
||||
claimNo?: number;
|
||||
dmgCaseId?: number;
|
||||
@@ -21,7 +23,8 @@ export type FanavaranClaimReferences = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Claim reference codes appear on COMPLETED. Upload receipts/status are visible earlier.
|
||||
* Claim reference codes appear on COMPLETED. Upload receipts and final-submission
|
||||
* acceptance are visible independently of local workflow status.
|
||||
*/
|
||||
export function fanavaranClaimReferences(claim: {
|
||||
status?: string;
|
||||
@@ -33,9 +36,16 @@ export function fanavaranClaimReferences(claim: {
|
||||
baseClaim?: FanavaranReferenceStage | null;
|
||||
damageCase?: FanavaranReferenceStage | null;
|
||||
attachments?: FanavaranAttachmentStage | null;
|
||||
expertise?: { status?: string; expertiseId?: number | null } | null;
|
||||
} | null;
|
||||
}): FanavaranClaimReferences | undefined {
|
||||
const refs: FanavaranClaimReferences = {};
|
||||
if (
|
||||
claim.expertiseId != null ||
|
||||
claim.fanavaranSync?.expertise?.status === "success"
|
||||
) {
|
||||
refs.submissionCompleted = true;
|
||||
}
|
||||
const attachments = fanavaranAttachmentStatus(
|
||||
claim.fanavaranSync?.attachments,
|
||||
);
|
||||
@@ -44,7 +54,7 @@ export function fanavaranClaimReferences(claim: {
|
||||
refs.attachments = attachments;
|
||||
}
|
||||
if (claim.status !== ClaimCaseStatus.COMPLETED) {
|
||||
return attachments ? refs : undefined;
|
||||
return Object.keys(refs).length ? refs : undefined;
|
||||
}
|
||||
if (claim.claimId != null) refs.claimId = claim.claimId;
|
||||
if (claim.claimNo != null) refs.claimNo = claim.claimNo;
|
||||
|
||||
@@ -87,6 +87,13 @@ export function selectFanavaranDriverId(
|
||||
});
|
||||
}
|
||||
|
||||
/** Hull driver registration must resolve specifically to GEN.44's سایر role. */
|
||||
export function selectFanavaranOtherPersonId(rows: unknown): number | null {
|
||||
return selectFanavaranIdByRoles(rows, [FANAVARAN_DRIVER_ROLE_ID], {
|
||||
allowFallbackToFirst: false,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* OwnerId for GEN.12: same accepted roles as DriverId (161 / 166 only).
|
||||
* Prefer بیمهگذار then سایر. RoleId 162/163/… → null → GEN.44 on submit.
|
||||
|
||||
@@ -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 }],
|
||||
"car-components": [1, 9, 13, 112, 10, 48, 76, 29, 100, 37].map(Id => ({ Id })),
|
||||
})[name] ?? [],
|
||||
);
|
||||
service.fanavaranLookupService = {
|
||||
@@ -19,26 +19,55 @@ 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,
|
||||
priceDropCarPrice: null,
|
||||
warnings: [],
|
||||
infoWarnings: [],
|
||||
});
|
||||
return { service, build };
|
||||
}
|
||||
|
||||
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: "سپر جلو" },
|
||||
@@ -76,16 +105,19 @@ describe("hull expertise policy accessory mapping", () => {
|
||||
AccessoryDesc: "کليه قطعات فابريک",
|
||||
},
|
||||
]);
|
||||
const { payload, warnings } = await build();
|
||||
const { payload, warnings, infoWarnings } = await build();
|
||||
expect(
|
||||
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
|
||||
).toEqual([3061139, 3061139]);
|
||||
expect(payload.DmgSections.map((row: any) => row.AccessoryKindId)).toEqual([
|
||||
9, 13,
|
||||
]);
|
||||
expect(warnings).toEqual(
|
||||
expect(warnings).toEqual([]);
|
||||
expect(infoWarnings).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.stringContaining("using factory bundle VehicleHullAccessoryId=3061139"),
|
||||
expect.stringContaining(
|
||||
"mapped to factory bundle VehicleHullAccessoryId=3061139; preserving AccessoryKindId=9",
|
||||
),
|
||||
]),
|
||||
);
|
||||
});
|
||||
@@ -155,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,
|
||||
@@ -166,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",
|
||||
@@ -85,7 +85,7 @@ describe("fanavaran hull base claim", () => {
|
||||
|
||||
expect(hull.PolicyId).toBe(13764408);
|
||||
expect(hull.AccidentTypeId).toBeNull();
|
||||
expect(hull.IsLicenseReplaced).toBeNull();
|
||||
expect(hull.IsLicenseReplaced).toBe(0);
|
||||
expect(hull.CostSeparationToDmgSections).toBe(0);
|
||||
expect(hull.IsOwnerChanged).toBe(0);
|
||||
expect(hull.CulpritTypeId).toBeNull();
|
||||
|
||||
@@ -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") {
|
||||
// Fanavaran conditional: >10y since issue → 1; else null (never 0).
|
||||
// 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,
|
||||
);
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
import { ClaimRequestManagementService } from "./claim-request-management.service";
|
||||
|
||||
const insurer = {
|
||||
Id: 41,
|
||||
RoleId: 161,
|
||||
NationalCode: "0012345678",
|
||||
Name: "تست",
|
||||
LastName: "راننده",
|
||||
};
|
||||
const driver = { ...insurer, RoleId: 166 };
|
||||
|
||||
function setup() {
|
||||
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
|
||||
service.fanavaranLookupService = {
|
||||
bodyPolicyById: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ CustomerId: insurer.Id, TotalPremium: 76391920 }),
|
||||
inquiryByUniqueIdentifier: jest.fn().mockResolvedValue([insurer]),
|
||||
};
|
||||
service.getFanavaranLookupRows = jest.fn().mockResolvedValue([]);
|
||||
service.resolveDriverFanavaranId = jest.fn().mockResolvedValue(insurer.Id);
|
||||
service.loadFanavaranOtherPeopleLookups = jest.fn().mockResolvedValue({});
|
||||
service.postFanavaranJson = jest
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { Id: insurer.Id } });
|
||||
service.fanavaranAuditService = {
|
||||
generateTrackingCode: jest.fn().mockReturnValue("test"),
|
||||
recordStep: jest.fn(),
|
||||
};
|
||||
service.claimCaseDbService = {
|
||||
findByIdAndUpdate: jest.fn().mockResolvedValue({}),
|
||||
};
|
||||
const input = {
|
||||
clientKey: "parsian",
|
||||
payload: { PolicyId: 15708843 } as Record<string, unknown>,
|
||||
blameCase: {},
|
||||
firstParty: {
|
||||
person: {
|
||||
nationalCodeOfDriver: "0012345678",
|
||||
driverBirthday: "1360/01/02",
|
||||
driverIsInsurer: true,
|
||||
},
|
||||
},
|
||||
claimCaseId: "case-1",
|
||||
logPrefix: "test",
|
||||
registerMissingDriver: true,
|
||||
};
|
||||
return { service, input };
|
||||
}
|
||||
|
||||
describe("hull role-166 registration", () => {
|
||||
it("registers a policyholder-only driver through GEN.44 before filling the hull person reference", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValue([insurer, driver]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(service.postFanavaranJson).toHaveBeenCalledWith(
|
||||
expect.stringContaining("/common/other-people"),
|
||||
expect.objectContaining({
|
||||
NationalCode: "0012345678",
|
||||
BirthYear: 1360,
|
||||
BirthMonth: 1,
|
||||
BirthDay: 2,
|
||||
PersonKindId: 46,
|
||||
}),
|
||||
"parsian",
|
||||
expect.anything(),
|
||||
"case-1",
|
||||
);
|
||||
expect(input.payload.AccidentCulpritId).toBe(insurer.Id);
|
||||
});
|
||||
|
||||
it("keeps a policyholder-only preview read-only and leaves the driver unresolved", async () => {
|
||||
const { service, input } = setup();
|
||||
input.registerMissingDriver = false;
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||
expect(input.payload.AccidentCulpritId).toBeNull();
|
||||
});
|
||||
it("reuses an existing role-166 person without a registration POST", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockResolvedValue([
|
||||
insurer,
|
||||
{ ...driver, Id: 42 },
|
||||
]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(input.payload.AccidentCulpritId).toBe(42);
|
||||
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not use the returned create ID until role 166 is verified", async () => {
|
||||
const { service, input } = setup();
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
|
||||
expect(input.payload.AccidentCulpritId).toBeNull();
|
||||
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
|
||||
"case-1",
|
||||
{
|
||||
$set: {
|
||||
"fanavaranSync.baseClaim.otherPersonId": 41,
|
||||
"fanavaranSync.baseClaim.otherPersonNationalCode": "0012345678",
|
||||
"fanavaranSync.baseClaim.otherPersonBirthday": "1360/1/2",
|
||||
},
|
||||
},
|
||||
);
|
||||
const retry = {
|
||||
...input,
|
||||
cachedRegistration: {
|
||||
otherPersonId: 41,
|
||||
otherPersonNationalCode: "0012345678",
|
||||
otherPersonBirthday: "1360/1/2",
|
||||
},
|
||||
};
|
||||
await service.enrichCarBodyHullBaseClaimPayload(retry);
|
||||
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockResolvedValue([
|
||||
insurer,
|
||||
driver,
|
||||
]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(retry);
|
||||
expect(input.payload.AccidentCulpritId).toBe(41);
|
||||
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("keeps a registration cached when the verification request fails", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockRejectedValue(new Error("ECONNRESET"));
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(input.payload.AccidentCulpritId).toBeNull();
|
||||
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
|
||||
"case-1",
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
"fanavaranSync.baseClaim.otherPersonId": 41,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not create a person when initial inquiry fails", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockRejectedValue(
|
||||
new Error("ECONNRESET"),
|
||||
);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||
expect(input.payload.AccidentCulpritId).toBeNull();
|
||||
});
|
||||
|
||||
it("does not replace failed registration with the policy customer's role 161", async () => {
|
||||
const { service, input } = setup();
|
||||
service.postFanavaranJson.mockRejectedValue(
|
||||
new Error("Registration failed"),
|
||||
);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(input.payload.AccidentCulpritId).toBeNull();
|
||||
expect(service.resolveDriverFanavaranId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rechecks the role before POST to avoid registering a role that already appeared", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValue([insurer, driver]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(input.payload.AccidentCulpritId).toBe(41);
|
||||
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not use a pending registration for a different driver", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValue([driver]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload({
|
||||
...input,
|
||||
cachedRegistration: {
|
||||
otherPersonId: 999,
|
||||
otherPersonNationalCode: "9999999999",
|
||||
otherPersonBirthday: "1360/1/2",
|
||||
},
|
||||
});
|
||||
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
|
||||
expect(input.payload.AccidentCulpritId).toBe(41);
|
||||
});
|
||||
it("recovers from a duplicate-create response only after the role-166 inquiry succeeds", async () => {
|
||||
const { service, input } = setup();
|
||||
service.postFanavaranJson.mockRejectedValue(
|
||||
new Error("Duplicate national code"),
|
||||
);
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValueOnce([insurer])
|
||||
.mockResolvedValue([insurer, driver]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload(input);
|
||||
expect(input.payload.AccidentCulpritId).toBe(41);
|
||||
expect(service.resolveDriverFanavaranId).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not substitute the policyholder when the actual driver identity is missing", async () => {
|
||||
const { service, input } = setup();
|
||||
await service.enrichCarBodyHullBaseClaimPayload({
|
||||
...input,
|
||||
firstParty: {
|
||||
person: {
|
||||
nationalCodeOfInsurer: "0012345678",
|
||||
insurerBirthday: "1360/01/02",
|
||||
driverIsInsurer: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(input.payload.AccidentCulpritId).toBeNull();
|
||||
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||
expect(
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier,
|
||||
).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the explicitly shared identity for legacy driver-is-policyholder cases", async () => {
|
||||
const { service, input } = setup();
|
||||
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockResolvedValue([
|
||||
driver,
|
||||
]);
|
||||
await service.enrichCarBodyHullBaseClaimPayload({
|
||||
...input,
|
||||
firstParty: {
|
||||
person: {
|
||||
nationalCodeOfInsurer: "0012345678",
|
||||
insurerBirthday: "1360/01/02",
|
||||
driverIsInsurer: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(input.payload.AccidentCulpritId).toBe(41);
|
||||
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -153,3 +153,35 @@ describe("Hull base-claim vehicle use from policy inquiry", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Hull preview and submission driver-role gate", () => {
|
||||
it("reports unresolved role 166 in preview without enabling registration", async () => {
|
||||
const service = previewSetup({ UsedId: 42, VehicleKindId: 8671 });
|
||||
const result = await service.previewFanavaranSubmitV2("claim", "moallem", {
|
||||
debug: true,
|
||||
});
|
||||
expect(service.enrichCarBodyHullBaseClaimPayload).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ registerMissingDriver: false }),
|
||||
);
|
||||
expect(result.previewWarnings).toContainEqual(
|
||||
expect.objectContaining({ code: "FANAVARAN_HULL_DRIVER_ROLE_REQUIRED" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("blocks submission when the driver's role remains unresolved after registration", async () => {
|
||||
const service = previewSetup({ UsedId: 42, VehicleKindId: 8671 });
|
||||
await expect(
|
||||
service.previewFanavaranSubmitV2("claim", "moallem", {
|
||||
requirePolicyId: true,
|
||||
registerMissingHullDriver: true,
|
||||
}),
|
||||
).rejects.toMatchObject({
|
||||
response: expect.objectContaining({
|
||||
code: "FANAVARAN_HULL_DRIVER_ROLE_REQUIRED",
|
||||
}),
|
||||
});
|
||||
expect(service.enrichCarBodyHullBaseClaimPayload).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ registerMissingDriver: true }),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -74,7 +74,7 @@ describe("fanavaran-party-roles", () => {
|
||||
expect(resolveFanavaranLicenceIssuDate(driver)).toBe(
|
||||
FANAVARAN_DUMMY_LICENCE_ISSU_DATE,
|
||||
);
|
||||
expect(FANAVARAN_DUMMY_LICENCE_ISSU_DATE).toBe("1404/08/20");
|
||||
expect(FANAVARAN_DUMMY_LICENCE_ISSU_DATE).toBe("1400/01/01");
|
||||
});
|
||||
|
||||
it("marks licence replaced only when issue date is more than 10 years before accident", () => {
|
||||
@@ -86,7 +86,19 @@ describe("fanavaran-party-roles", () => {
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveFanavaranIsLicenseReplaced("1404/08/20", "1405/08/20"),
|
||||
).toBeNull();
|
||||
).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["1402/08/21", 0],
|
||||
["1402/08/20", 0],
|
||||
["1402/08/19", null],
|
||||
["1395/08/21", null],
|
||||
["1395/08/20", null],
|
||||
["1395/08/19", 1],
|
||||
["1380/08/20", 1],
|
||||
])("uses the exact anniversary for issue date %s", (issueDate, expected) => {
|
||||
expect(resolveFanavaranIsLicenseReplaced(issueDate, "1405/08/20")).toBe(expected);
|
||||
});
|
||||
|
||||
it("marks DriverIsOwner false when driver and owner differ", () => {
|
||||
|
||||
@@ -35,14 +35,11 @@ export function isJalaliDateOlderThanYears(
|
||||
const issue = parseJalaliDateParts(issueDate);
|
||||
const reference = parseJalaliDateParts(referenceDate);
|
||||
if (!issue || !reference) return false;
|
||||
let age = reference.year - issue.year;
|
||||
if (
|
||||
reference.month < issue.month ||
|
||||
(reference.month === issue.month && reference.day < issue.day)
|
||||
) {
|
||||
age -= 1;
|
||||
}
|
||||
return age > years;
|
||||
const anniversary =
|
||||
(issue.year + years) * 10000 + issue.month * 100 + issue.day;
|
||||
const referenceDay =
|
||||
reference.year * 10000 + reference.month * 100 + reference.day;
|
||||
return referenceDay > anniversary;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { selectLatestActiveFanavaranPolicy } from "./fanavaran-policy-selection";
|
||||
import {
|
||||
selectLatestActiveFanavaranPolicy,
|
||||
selectFanavaranPolicyForAccident,
|
||||
} from "./fanavaran-policy-selection";
|
||||
|
||||
describe("selectLatestActiveFanavaranPolicy", () => {
|
||||
const today = "2026-06-30";
|
||||
@@ -61,3 +64,29 @@ describe("selectLatestActiveFanavaranPolicy", () => {
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
});
|
||||
|
||||
describe("car-body accident policy selection", () => {
|
||||
const policies = [
|
||||
{ PolicyId: 2, BeginDate: "1401/01/02", EndDate: "1402/01/02" },
|
||||
{ PolicyId: 1, BeginDate: "1400/01/01", EndDate: "1401/01/01" },
|
||||
];
|
||||
it("selects the previous renewal covering the accident, even when both expired today", () => {
|
||||
expect(
|
||||
selectFanavaranPolicyForAccident(policies, "1400/12/28").policyId,
|
||||
).toBe(1);
|
||||
});
|
||||
it.each(["1400/01/01", "1401/01/01"])(
|
||||
"includes the coverage boundary %s",
|
||||
(date) => {
|
||||
expect(selectFanavaranPolicyForAccident(policies, date).policyId).toBe(1);
|
||||
},
|
||||
);
|
||||
it.each(["1399/12/29", "1402/01/03", "invalid", undefined])(
|
||||
"rejects an uncovered or missing accident date %s",
|
||||
(date) => {
|
||||
expect(() => selectFanavaranPolicyForAccident(policies, date)).toThrow(
|
||||
BadRequestException,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
isPolicyActiveOn,
|
||||
policyAccidentDate,
|
||||
selectLastAmongCarMatches,
|
||||
} from "src/lookups/fanavaran-last-car-policy";
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { jalaliToGregorianDate } from "src/helpers/date-jalali";
|
||||
import { gregorianDateInIran } from "src/helpers/iran-datetime";
|
||||
@@ -93,3 +98,34 @@ export function selectLatestActiveFanavaranPolicy(
|
||||
|
||||
return { ...latest, policyId };
|
||||
}
|
||||
|
||||
/** Hull renewals must be selected for the loss date, regardless of submission date. */
|
||||
export function selectFanavaranPolicyForAccident(
|
||||
policies: unknown,
|
||||
accidentDate: unknown,
|
||||
): SelectedFanavaranPolicy {
|
||||
const date = policyAccidentDate(accidentDate);
|
||||
if (!date)
|
||||
throw new BadRequestException(
|
||||
"A valid accidentDate is required for car-body policy selection.",
|
||||
);
|
||||
if (!Array.isArray(policies) || policies.length === 0) {
|
||||
throw new BadRequestException(NO_POLICY_MESSAGE);
|
||||
}
|
||||
const matches = policies
|
||||
.filter((row) => row && typeof row === "object")
|
||||
.map((row) => ({
|
||||
policyId: parsePolicyId(row.PolicyId) ?? 0,
|
||||
beginDate: row.BeginDate,
|
||||
endDate: row.EndDate,
|
||||
policy: row,
|
||||
vehicle: null,
|
||||
}));
|
||||
const selected = selectLastAmongCarMatches(matches, date);
|
||||
if (!selected || !isPolicyActiveOn(selected, date)) {
|
||||
throw new BadRequestException(
|
||||
"No Fanavaran car-body policy covers the accident date.",
|
||||
);
|
||||
}
|
||||
return selectLatestActiveFanavaranPolicy([selected.policy], date);
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user