Compare commits

..
8 Commits
Author SHA1 Message Date
s.alikhani d2676d65d1 fix(ci): allow buildx writes and publish latest
Mount only the registry login file so Buildx can write temporary state. Build and deploy the latest image tag.
2026-11-22 15:02:19 +03:30
s.alikhani 6e56d0fa2e ci(deployment): build the maintenance api on parspack
Compile NestJS on Parspack and deploy the commit-tagged image from the existing API directory.
2026-11-22 14:43:23 +03:30
s.yahyaee 7b23262fd2 Merge pull request 'fix(workflows): resolve QA blockers and protect case evidence' (#410) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#410
2026-11-22 12:51:27 +03:30
SepehrYahyaee 6b968c0952 fix(workflows): resolve QA blockers and protect case evidence
Fix registrar signing, reviewer re-entry, replacement evidence freshness, owner decision and rating races, multipart objections, vehicle serialization and product reporting.

Validate uploaded media with FFmpeg, serve evidence through expiring signed links, and add targeted regressions plus a dry-run repair for prematurely completed visit cases.
2026-11-22 12:50:22 +03:30
s.yahyaee abc40df199 Merge pull request 'fix(claims): reuse saved Sheba across claim workflow steps' (#409) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#409
2026-11-21 16:48:57 +03:30
SepehrYahyaee 90f290154c fix(claims): reuse saved Sheba across claim workflow steps 2026-11-21 16:36:34 +03:30
s.yahyaee be364d94fe Merge pull request 'fix(inquiries): route all tenants through ESG and Fanavaran' (#408) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#408
2026-11-21 15:27:53 +03:30
SepehrYahyaee 1a38b98829 fix(inquiries): route all tenants through ESG and Fanavaran 2026-11-21 15:27:06 +03:30
61 changed files with 2259 additions and 1133 deletions
+10 -4
View File
@@ -46,7 +46,16 @@ JWT_EXPIRY =
CAPTCHA_ENABLED = true
# ---------------------------------------------
# 🧩 SanHub Microservice
# 🧩 ESG — third-party plate/VIN, personal identity and Sheba (all tenants)
# Include the gateway prefix in ESG_URL when one is required; no fallback URL.
# ---------------------------------------------
ESG_URL =
ESG_USERNAME =
ESG_PASSWORD =
# ---------------------------------------------
# Optional driving-licence and legal vehicle-ownership inquiries only
# ESG does not currently expose equivalent endpoints for these two checks.
# ---------------------------------------------
SANHUB_BASE_URL =
SANHUB_URL_LOGIN =
@@ -101,9 +110,6 @@ AUTO_CLIENT_KEY_ENABLED =
# ---------------------------------------------
# 🔗 Other Internal Services
# ---------------------------------------------
TEJARAT_INQUIRY_EMAIL =
TEJARAT_INQUIRY_PASSWORD =
PARSIAN_API_KEY =
PARSIAN_BASIC_TOKEN =
PARSIAN_SMS_URL =
+32
View File
@@ -0,0 +1,32 @@
when:
- event: push
branch: main
- event: manual
branch: main
labels:
hostname: build-parspack
steps:
build:
image: docker.arvancloud.ir/docker:24-cli
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /home/opsadmin/.docker/config.json:/root/.docker/config.json:ro
commands:
- export YARA_IMAGE="registry.ittalie.com/yara724-maintenance-api:latest"
- docker build -t "$YARA_IMAGE" .
- docker push "$YARA_IMAGE"
notify-failure:
image: docker.arvancloud.ir/alpine:3.20
environment:
ROCKETCHAT_WEBHOOK:
from_secret: rocketchat_webhook
when:
- status: failure
commands:
- apk add --no-cache curl jq > /dev/null
- |
jq -n --arg text "Yara724 api build failed. $CI_PIPELINE_URL" '{text: $text}' |
curl -fsS -H 'Content-Type: application/json' --data-binary @- "$ROCKETCHAT_WEBHOOK"
+12 -6
View File
@@ -1,11 +1,11 @@
# yara724/api — development deployment (Deploy-Develop)
# Manual tasks: see ci-cd/TASK.md
# Requires: repo marked Trusted in Woodpecker (host volume mounts)
when:
- event: push
branch: main
- event: manual
branch: main
depends_on:
- build
labels:
hostname: build-node-01
@@ -40,7 +40,10 @@ steps:
- git config --global --add safe.directory /workspace
- mkdir -p /tmp && ssh-keyscan -H git.ittalie.com >> /tmp/known_hosts
- cd /workspace
- git pull origin main
- git fetch origin main
- test "$(git rev-parse FETCH_HEAD)" = "$CI_COMMIT_SHA"
- git merge --ff-only FETCH_HEAD
- test "$(git rev-parse HEAD)" = "$CI_COMMIT_SHA"
- date +%s > /workspace/.wp-deploy-start
deploy:
@@ -49,10 +52,13 @@ steps:
<<: *pipeline_env
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /home/talieh/.docker:/root/.docker:ro
- *workspace_volume
commands:
- cd /workspace
- docker compose -f docker-compose.yml up -d --build
- export YARA_IMAGE="registry.ittalie.com/yara724-maintenance-api:latest"
- docker compose -f docker-compose.yml pull
- docker compose -f docker-compose.yml up -d --no-build
notify-success:
image: docker.arvancloud.ir/alpine:3.20
+5 -1
View File
@@ -1,6 +1,8 @@
# Use the official Node.js image as the base image
FROM docker.arvancloud.ir/node:20-alpine
RUN apk add --no-cache ffmpeg
WORKDIR /app
COPY package*.json ./
@@ -15,8 +17,10 @@ RUN npm i --force --verbose --no-scripts
COPY . .
RUN npm run build && test -f dist/src/main.js
# Expose the port on which your NestJS application will run
EXPOSE 3002
# Start the NestJS application
CMD ["npm", "start"]
CMD ["node", "dist/src/main.js"]
+6
View File
@@ -0,0 +1,6 @@
.git
node_modules
dist
.env
.env.*
*.env
+1
View File
@@ -3,6 +3,7 @@
## 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)
Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md).
+1 -1
View File
@@ -6,7 +6,7 @@ services:
context: .
dockerfile: Dockerfile
container_name: yara724-main-api-dev
image: yara724-main-api:dev
image: ${YARA_IMAGE:-yara724-main-api:dev}
restart: unless-stopped
volumes:
- yara724-main-api-dev-files:/app/files/:rw
+18 -120
View File
@@ -319,81 +319,21 @@ curl -X POST "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims" \
--data @fanavaran-claim-submit.json
```
## Tejarat Inquiry Provider
Default base URL:
```sh
TEJARAT_INQUIRY_BASE_URL="${TEJARAT_INQUIRY_BASE_URL:-http://82.99.202.245:3027}"
TEJARAT_INQUIRY_EMAIL='xxx@example.com'
TEJARAT_INQUIRY_PASSWORD='123321'
```
Used by `src/sand-hub/sand-hub.service.ts` for third-party plate and car-body plate inquiries when ESG is not selected.
### Sequence
1. Login to `/user/login`.
2. Use returned `accessToken` as `Authorization: Bearer ...`.
3. Call inquiry endpoint.
### Login
```sh
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/user/login" \
-H "Accept: */*" \
-H "Content-Type: application/json" \
--data '{
"email": "'"$TEJARAT_INQUIRY_EMAIL"'",
"password": "'"$TEJARAT_INQUIRY_PASSWORD"'"
}'
```
```sh
TEJARAT_ACCESS_TOKEN="<response accessToken>"
```
### Third-Party Plate / Policy Block Inquiry
```sh
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat" \
-H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"leftTwoDigits": "12",
"serialLetter": "ب",
"threeDigits": "345",
"rightTwoDigits": "67",
"nationalCode": "0012345678"
}'
```
### Car-Body Plate Inquiry
```sh
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat/badane" \
-H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"part1": 12,
"part2": "ب",
"part3": 345,
"part4": 67,
"nationalCode": "0012345678"
}'
```
## ESG Inquiry Provider
Default/fallback base URL in some call sites:
Used by `src/sand-hub/sand-hub.service.ts` for third-party plate/VIN, identity
and Sheba inquiries in **every tenant**, including Moalem (`CLIENT_ID=7`).
```sh
ESG_URL="${ESG_URL:-http://192.168.20.22:8085}"
ESG_URL="https://<gateway-host>/<optional-prefix>"
ESG_USERNAME="<gateway-username>"
ESG_PASSWORD="<gateway-password>"
```
Used by `src/sand-hub/sand-hub.service.ts` for selected tenants, for example when `CLIENT_ID=8`.
There is no fallback URL or fallback to the deprecated Tejarat provider.
Car-body plate and VIN inquiries use the tenant’s Fanavaran profile through
`LookupsService.findLastProcessedCarPolicy("car-body", query)`, not ESG.
See [inquiry provider routing](inquiry-provider-routing.md) for deployment notes.
### Sequence
@@ -417,7 +357,7 @@ curl -X POST "$ESG_URL/auth/login" \
ESG_ACCESS_TOKEN="<response accessToken>"
```
### Car By Plate (canonical Parsian third-party plate inquiry)
### Car By Plate (third-party inquiry for all tenants)
```sh
curl -X POST "$ESG_URL/inquiry/carByPlate" \
@@ -483,15 +423,18 @@ curl -X POST "$ESG_URL/inquiry/sheba" \
## SandHub Provider
Used by `src/sand-hub/sand-hub.service.ts` for legacy inquiry flows.
Used only for the optional driving-licence and legal vehicle-ownership checks.
The current ESG API has no equivalent contract for these checks. Plate/VIN,
personal identity and Sheba inquiries do not use this adapter. Configure these
settings only when the optional checks are enabled.
Environment:
```sh
SANHUB_BASE_URL='http://82.99.202.245:3027'
SANHUB_URL_LOGIN='http://82.99.202.245:3027/user/login'
SANHUB_USERNAME='default@admin.com'
SANHUB_PASSWORD='123321'
SANHUB_BASE_URL='https://<optional-check-provider>'
SANHUB_URL_LOGIN='https://<optional-check-provider>/<login-path>'
SANHUB_USERNAME='<optional-check-username>'
SANHUB_PASSWORD='<optional-check-password>'
```
### Sequence
@@ -515,37 +458,6 @@ curl -X POST "$SANHUB_URL_LOGIN" \
SANHUB_ACCESS_TOKEN="<response accessToken>"
```
### Third-Party Plate / Policy Block Inquiry
```sh
curl -X POST "$SANHUB_BASE_URL/block-inquiry-tejarat" \
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"leftTwoDigits": "12",
"serialLetter": "ب",
"threeDigits": "345",
"rightTwoDigits": "67",
"nationalCode": "0012345678"
}'
```
### Personal Inquiry
The app converts Jalali birth dates to Gregorian before sending to SandHub.
```sh
curl -X POST "$SANHUB_BASE_URL/personal-inquiry/tejarat-no" \
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"nationalCode": "0012345678",
"birthdate": "1999-02-13"
}'
```
### Driving License Check
```sh
@@ -575,20 +487,6 @@ curl -X POST "$SANHUB_BASE_URL/ownership" \
}'
```
### Sheba Validation
```sh
curl -X POST "$SANHUB_BASE_URL/sheba/sheba-tejaratno" \
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
--data '{
"AccountOwnerType": "1",
"NationalId": "0012345678",
"ShebaId": "IR000000000000000000000000"
}'
```
## Map.ir Reverse Geocoding
Used by `src/claim-request-management/claim-request-management.service.ts`.
+84
View File
@@ -0,0 +1,84 @@
# Inquiry provider routing
The running NestJS API routes inquiries through `src/sand-hub/sand-hub.service.ts`.
The class name remains for existing dependency injection; it does not select the
provider by tenant anymore.
| Inquiry | Provider | Entry point |
| --- | --- | --- |
| Third-party policy by plate | ESG `/inquiry/carByPlate` | `getCarByPlateInquiry` |
| Third-party policy by national code + VIN | ESG `/inquiry/carByChassis` | `getCarByChassisInquiry` |
| Person identity | ESG `/inquiry/person` | `getPersonalInquiry` |
| Sheba ownership | ESG `/inquiry/sheba` | `getShebaValidation` |
| Car-body policy by plate or VIN | Tenant-specific Fanavaran processed policy lookup | `getCarBodyInquiry` |
| Optional driving-licence / legal vehicle ownership | Existing configured `SANHUB_*` adapter | `getDrivingLicenseInfo` / `getCarOwnershipInfo` |
The ESG endpoints above apply to every tenant. Existing per-client live/mock
settings still apply. Disabled inquiries retain their mock behavior; offline
third-party plate records are consulted only in disabled mode. No mock or
deprecated provider is used as a fallback when a live ESG inquiry fails.
## Why Moalem reached the retired login
Previously only `CLIENT_ID=8` selected ESG. `CLIENT_ID=7` therefore selected the
old Tejarat transport for third-party plate inquiries, and the old configurable
hub for identity and Sheba. Car-body plate inquiries also used the Tejarat
transport unless the Fanavaran profile was Parsian. Car-body VIN inquiries
already used Fanavaran.
The retired `getTejaratAccessToken`, `/user/login` transport and
`TEJARAT_INQUIRY_*` configuration have been removed from the running API.
Both car-body input formats now use the existing Fanavaran lookup. The mapper
uses the selected source insurer rather than assuming every car-body result
belongs to Parsian. Explicit conflicting insurer codes are rejected.
## Deployment settings
Supply these through the API environment, then restart the API:
```dotenv
CLIENT_ID=7
FANAVARAN_CLIENT=moallem
ESG_URL=https://<gateway-host>/<optional-prefix>
ESG_USERNAME=<gateway-username>
ESG_PASSWORD=<gateway-password>
```
`moallem` is the existing Fanavaran profile spelling. The explicit
`FANAVARAN_CLIENT` setting takes precedence; when absent, `CLIENT_ID=7` now
resolves to `moallem`, and `CLIENT_ID=8` still resolves to `parsian`. Other
deployments must select their own Fanavaran profile as before. The selected
profile must have its existing Fanavaran credentials/contracts configured.
`ESG_URL` is the base **before** `/auth/login` and `/inquiry/...`; include any
gateway prefix in that value. Trailing slashes are normalized. No internal-IP
default is used. The ESG user needs access to all four inquiry types. Birth
dates are sent in Jalali `YYYY-MM-DD`, with `dateHasPostfix: 0`. The cached ESG
token is reused, and an inquiry HTTP 401 clears it before the existing retry.
`TEJARAT_INQUIRY_BASE_URL`, `TEJARAT_INQUIRY_EMAIL` and
`TEJARAT_INQUIRY_PASSWORD` are no longer read by the running API and can be
removed from deployment configuration. Do not repoint `SANHUB_*` to ESG: their
optional licence/ownership payloads differ, and the ESG repository currently
has no matching endpoints. Those two checks keep their existing settings
until an explicit replacement contract is provided.
## Compatibility and verification
The mapped inquiry fields consumed by the UI remain unchanged. The old
`getSandHubResponse` entry point delegates to ESG and returns the mapped result.
New car-body audit records identify their source as
`FANAVARAN_CAR_BODY_INQUIRY` or `FANAVARAN_CAR_BODY_VIN_INQUIRY`. Historical raw
inquiries, audit records and database documents are not rewritten.
`scripts/refresh-blame-inquiries.js` and `scripts/fanavaran-flow-ui-server.js`
are separate manually run diagnostic tools with their own legacy provider
settings. They are not invoked by the running application and have not been
migrated by this change; do not use their inquiry shortcuts as evidence of the
application's current routing.
Regression tests in `sand-hub.esg-routing.spec.ts` cover tenant IDs 7, 8 and 15,
ESG token reuse/401 refresh, missing configuration, disabled inquiries,
Fanavaran plate/VIN routing, source-company checks and optional-check
compatibility. Provider HTTP calls in these tests are mocked; deployment still
requires valid gateway credentials and connectivity.
@@ -0,0 +1,85 @@
{
"date": "2026-11-22",
"environment": "isolated local MongoDB, synthetic accounts and generated media; external providers mocked",
"httpFlowMatrix": {
"v1-CAR_BODY": {
"status": "COMPLETED"
},
"v1-THIRD_PARTY": {
"status": "COMPLETED"
},
"v2-CAR_BODY": {
"status": "COMPLETED"
},
"v2-THIRD_PARTY": {
"status": "COMPLETED"
},
"v3-CAR_BODY": {
"status": "COMPLETED"
},
"v3-THIRD_PARTY": {
"status": "COMPLETED"
},
"v4-CAR_BODY": {
"status": "COMPLETED"
},
"v4-THIRD_PARTY": {
"status": "COMPLETED"
},
"v5-CAR_BODY": {
"status": "COMPLETED"
},
"v5-THIRD_PARTY": {
"status": "COMPLETED"
},
"v6-CAR_BODY": {
"status": "COMPLETED"
},
"v6-THIRD_PARTY": {
"status": "COMPLETED"
}
},
"negativeControls": {
"malformedId": 400,
"createRace": {
"success": 1,
"conflict": 5
},
"invalidMedia": 400,
"invalidEnums": 400,
"foreignFieldMutation": 403
},
"signedMedia": {
"expertCapture": 200,
"ownerDocument": true,
"blameEvidence": true,
"bareFile": 401,
"duplicateSignature": 401
},
"browserChecks": [
"v6 login retains blame context",
"five formerly denied versioned routes render",
"repair-only objection form renders",
"Persian-locale expert assessment renders",
"written blame resend submits without an image",
"instruction-only claim resend acknowledgment reaches expert queue"
],
"historicalRepair": {
"dryRunMatched": 2,
"applied": 2,
"signedControlUnchanged": true,
"pricedControlUnchanged": true
},
"automatedChecks": {
"apiSuites": 111,
"apiTestsPassed": 1070,
"httpE2ePassed": 26,
"httpE2eSkipped": 4,
"userUiSuite": "passed",
"expertUiSuite": "passed",
"apiBuild": "passed",
"userUiBuild": "passed",
"expertUiBuild": "passed",
"uiHardeningDetectorFindings": 0
}
}
+107
View File
@@ -0,0 +1,107 @@
# QA remediation — 22 November 2026
Scope: the 28 distinct findings in `QA_REPORT_2026-11-22.txt`,
`QA_REPORT_2026-11-22_CONTINUED.txt`, `QA_REPORT_2026-11-22_EXTENDED.txt`, and
`qa-reports/`. The extended report repeats several continued findings; its
reconciliation supplies IDs 25–28. Changes cover `api`, `ui-user`, and
`ui-expert`. No production database changes or external provider writes were
performed. `rewrite` and `esg` are outside this change.
## Findings and changes
| ID | Resolution | Verification |
| --- | --- | --- |
| 1 | All V3 claim evidence/selection entry points authorize the actor against the case before changing it. | Authorization regression; real foreign-field-expert 403 and positive V3 HTTP filing/capture. |
| 2 | Reviewer assignment distinguishes initial capture from subsequent assessment after maker rejection. An assigned reviewer can acquire an assessment lock again. | HTTP V5: two reject/review cycles, rejection limit, final maker approval. |
| 3 | Both UIs spell rial amounts using locale-independent integer grouping instead of the library recursion triggered by Persian grouping. | Both UI suites; real Persian-locale expert assessment browser. |
| 4 | Added the ordinary-user V6 login page; the incoming blame token survives login redirection. | Real mobile browser link and URL assertion. |
| 5 | Labor-only lines tolerate absent prices; objection payloads omit absent optional monetary values and submission failures remain visible. | Real mobile browser protest form; UI regression suite. |
| 6 | Expired V6 ordinary-user sessions return to `/v6/login`; call-center sessions retain their expert login route. | Role-aware redirect regression. |
| 7 | Multipart nested objection rows become DTO instances and are validated explicitly at the service boundary, including deployments without a global validation pipe. | DTO tests and a real multipart objection through HTTP/MongoDB. |
| 8 | Vehicle subdocuments are serialized before merging resolved identity fields, exposing saved vehicle prices without Mongoose internals or parent documents. | HTTP detail assertions for price and absence of `_doc`/`$__parent`. |
| 9 | Unique-index conflicts during concurrent claim creation become HTTP 409 rather than 500. The database uniqueness constraint remains intact. | Real six-way creation race: one success, five HTTP 409 responses. |
| 10 | Owner claim-detail rejects malformed ObjectIds before querying MongoDB. | Real malformed-ID HTTP 400 control and explicit ID guard. |
| 11 | Upload policy verifies readable media streams and decodes content; text disguised as MP4, wrong media kinds and unreadable content cannot satisfy evidence steps. | Generated image/video/audio controls and corrupt/wrong-kind regression tests. |
| 12 | Shared description handlers enforce the declared weather, road and light enums, including expert form variants. | HTTP invalid-enum rejection without advancement, then valid filing; full API suite. |
| 13 | Expert cards recognize rejected cases and treat rejected/cancelled/stopped cases as view-only. | Expert UI status regressions. |
| 14 | Sheba masking preserves the existing prefix rather than prepending another `IR`. | Response mapping review and full API suite. |
| 15 | Car-body video instructions describe the vehicle and accident scene without requiring two vehicles. | User production build and UI source check. |
| 16 | Evidence is served through a signed, expiring read route, replacing anonymous static serving. Authorized case responses supply links usable by image/video/PDF elements. Arbitrary description text does not mint links. | Bare link 401; signed link 200; altered/expired/cross-path capability tests. See proxy requirements below. |
| 17 | Owner acceptance/rejection uses one conditional atomic update; only its winner records the decision and invokes integrations. Concurrent losing signature records are removed. Signature upload names use UUIDs. | Six-way unit and real MongoDB/HTTP race. |
| 18 | Registrar signatures accept registrar-created cases and follow the same signatures-before-accident-fields order as the shared V2 contract. | HTTP registrar CAR_BODY and THIRD_PARTY through signatures and accident fields. |
| 19 | Instruction-only claim resends display the instruction and offer acknowledgment through the existing endpoint. | Actual mobile browser acknowledgment and persisted queue transition. |
| 20 | Part resends send a stable catalog key/ID, independent of an optional English label. | Client key mapping and HTTP catalog-ID capture. |
| 21 | In-person visits have a pending status, owner instructions and a resumable expert review lock. They no longer imply completion/acceptance. Historical repair is provided separately. | HTTP visit → owner guidance → reassignment → assessment; V4/V5 visit controls; repair dry-run/apply controls. |
| 22 | Expert portfolio queries retain linked blame product type for product filters. | HTTP product counts: both products nonzero and their sum equals the total. |
| 23 | Insurer expert reports use linked blame product types. Missing types for roster-owned claims are resolved in one batch after claim scoping. | Reporting regression, including a linked blame outside the party-insurer list. |
| 24 | Satisfaction rating is written only if no rating exists, in one conditional atomic update. | Six-way concurrent rating regression and real HTTP/MongoDB race: one successful rating. |
| 25 | Versioned user route allowlists use real end anchors instead of requiring a literal `$`. | Browser assertions on five formerly denied routes. |
| 26 | Written blame resends use the text field; voice and document requests render their respective controls. The old duplicate page reuses the shared implementation. | Real browser text-only resend and successful navigation after submission. |
| 27 | Every requested replacement must have a timestamp at or after the current resend request. A partial upload cannot reuse old evidence to finish the request. | Real three-item replacement replay plus timestamp regression; original evidence stays intact. |
| 28 | Legacy top-rated-file normalization preserves root `userRating`, with a fallback for old nested records. | Reporting regression. |
## Verification
Sanitized results: [verification JSON](qa-remediation-2026-11-22-verification.json).
- API: **111 suites, 1,070 tests passed** (`npm test -- --runInBand`).
- API HTTP E2E suite: **26 passed, 4 skipped** (`npm run test:e2e -- --runInBand`).
The four opt-in browser scenarios were not enabled in that runner; independent
browser replays were run separately as described above.
- Both UI regression suites passed (`npm run test:ui`).
- All three production builds passed (`npm run build` in each repository).
- Browser checks used Chromium/Brave, Persian locale, a 390×844 user viewport
and a desktop expert viewport. The UI hardening detector reported no findings
on the changed user-facing views.
- **All 12 flow/product combinations** (v1–v6 × CAR_BODY/THIRD_PARTY) reached
completed claims through filing, capture and assessment. V1/V6 included owner
acceptance; V5 included maker approval. V4/V5 also resumed after a visit.
- Additional HTTP replays used the actual updated Nest process and a disposable
local MongoDB database, synthetic users and generated media. External inquiry,
SMS, AI and Fanavaran requests were intercepted with offline provider fixtures.
These checks do not verify customer WAF/proxy configuration or real provider
acceptance.
## Deployment requirements
Deploy the API and both UIs together, because the pending-visit status and signed
evidence links span their contracts.
1. **Media tools:** the API Dockerfile now installs `ffmpeg`, which includes
`ffprobe`. For deployments outside that Dockerfile, install both binaries in
the API runtime and verify that its service account can execute them. Missing
binaries will correctly reject uploads as unreadable; do not bypass validation.
2. **Evidence proxy:** remove any public Nginx `alias`/`root`/static/CDN rule that
directly exposes the API's `files` directory. Proxy `/files/*` (including its
deployed `/car-damage/api/` prefix, if applicable) to Nest, preserving the
query string and Range headers. A reverse-proxy static bypass would leave the
original anonymous-access issue unresolved. Purge previously cached public
evidence responses. Keep the existing API prefix/rewrite conventions; do not
copy a new `proxy_pass` prefix blindly.
3. **Signing secret:** all API instances serving the same files must share the
existing `JWT_SECRET`. File URLs expire after one hour; reopening/refetching
the authorized case returns fresh URLs. No additional signing secret or
public access switch is introduced. Old cached bare links require a refresh.
4. **Historical visits:** back up the database and preview the narrow repair
from the `api` directory with the intended deployment's environment:
```bash
node scripts/repair-premature-visit-completions.js
# After checking the matched count:
node scripts/repair-premature-visit-completions.js --apply
```
Dry-run is the default. The script only changes `COMPLETED` +
`NEEDS_REVISION` records with an in-person-visit history event and no
submitted assessment, priced parts or recorded owner approvals. It unlocks
review and writes a repair history event. It does not invent an address or
change evidence, payment amounts, signatures or other completed cases.
Dry-run and apply were exercised on synthetic records, with signed/priced
controls left closed. More ambiguous old records need individual review.
5. **Historical races:** overwritten satisfaction ratings or contradictory
owner decisions already recorded before this change cannot be reliably
reconstructed automatically. Review their history and provider submission
records; the code prevents new overlapping writes but does not guess which
old decision was intended.
No commits or pushes are included in this remediation task.
+51
View File
@@ -0,0 +1,51 @@
# Sheba is entered once per claim
| UI flow | Bank information is collected at |
| --- | --- |
| v1, user-created, third-party or car-body | Claim other-parts/bank-information step |
| v2, field expert | Claim other-parts/bank-information step |
| v3, field expert | Damaged party's inquiry: first party for car-body, second party for third-party |
| v4/v5, file maker and reviewer | File maker's damaged-party inquiry; reviewer reuses the claim's bank information |
| v6, call centre and user | User's claim other-parts/bank-information step; call centre never collects Sheba |
The v1/v6 initial-form endpoints do not persist a Sheba. The shared inquiry UI
previously requested it for v1, and then requested it again during the claim.
It now asks only on inquiry endpoints that actually validate and save it.
At the claim step, the UI fetches the current claim before showing bank inputs.
It requests only missing fields, reuses an already uploaded green card, and
shows a Persian confirmation when Sheba is already available. A failed or
pending fetch does not display empty bank fields. Values are not copied between
cases or kept in browser storage. User-facing bank values remain masked.
The claim snapshot adds `bankInformation.shebaProvided` and
`bankInformation.ownerNationalCodeProvided`. These booleans let the UI reuse
saved data without receiving unmasked account numbers. The owner national code
can come from the linked blame's vehicle-owner participant.
`selectOtherPartsV2` accepts omitted bank fields when the claim already has
them. It normalizes IR-prefixed and digits-only Sheba consistently and validates
new or changed bank details. It retains beneficiary authorization and rejects
another owner's saved account. Unchanged saved bank details do not trigger a
second inquiry. Explicit replacement remains available during expert resend;
an ordinary parts submission cannot silently replace an existing account.
The expert panel renders one claim-entry form for the damaged vehicle rather
than independent forms for both vehicles. It passes saved bank details into
that form. The expert claim-completion service also recognizes an IR-prefixed
saved Sheba when advancing the workflow.
No database migration is required. A Sheba entered into an old initial form and
discarded by the old endpoint cannot be recovered; those cases still need it
once at the claim step.
## Regression checks
- API: `npm test -- --runInBand claim-bank-information.spec.ts claim-beneficiary-access.spec.ts`
- User UI: `node scripts/test-claim-bank-information.cjs` (also run by `npm run test:ui`)
- Expert UI: `node scripts/test-claim-bank-information.cjs` (also run by `npm run test:ui`)
Tests cover every flow/role/party/case-type collection combination, saved and
missing values, stale/loading/error states, legacy aliases and formats,
resends, vehicle-owner mismatches, masked responses and the single expert
claim-entry form. HTTP and database dependencies are mocked.
@@ -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.
+2 -9
View File
@@ -1,3 +1,4 @@
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 +9,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 +44,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,
@@ -392,7 +392,7 @@ describe("buildInsurerFileReport", () => {
vehicle: {
isNew: true,
hasEndorsement: false,
source: "ESG_CAR_BODY_INQUIRY",
source: "FANAVARAN_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
},
},
@@ -419,7 +419,7 @@ describe("buildInsurerFileReport", () => {
role: "FIRST",
person: { userId: "damaged", fullName: "بیمه‌گذار" },
vehicle: {
source: "ESG_CAR_BODY_INQUIRY",
source: "FANAVARAN_CAR_BODY_INQUIRY",
inquiry: { source: "TEJARAT_BLOCK_INQUIRY" },
},
},
@@ -0,0 +1,247 @@
import {
BadRequestException,
ConflictException,
ForbiddenException,
} from "@nestjs/common";
import { validate } from "class-validator";
import { Types } from "mongoose";
import { ClaimRequestManagementService } from "./claim-request-management.service";
import { savedClaimBankInformation } from "./claim-bank-information";
import { SelectOtherPartsV2Dto } from "./dto/select-other-parts-v2.dto";
const claimId = "650000000000000000000001";
const userId = "650000000000000000000002";
const blameId = "650000000000000000000003";
const sheba = "IR" + "1".repeat(24);
const ownerCode = "0012345678";
function fixture(
money: any = undefined,
type = "CAR_BODY",
step = "SELECT_OTHER_PARTS",
) {
const claim: any = {
_id: new Types.ObjectId(claimId),
publicId: "TEST",
blameRequestId: blameId,
owner: { userId, fullName: "نمونه" },
money,
workflow: { currentStep: step },
};
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue(claim),
findByIdAndUpdate: jest.fn().mockResolvedValue(claim),
};
service.blameRequestDbService = {
findById: jest.fn().mockResolvedValue({ type }),
};
service.resolveClaimEffectiveUserId = jest.fn().mockResolvedValue(userId);
service.assertEffectiveUserIsDamagedPartyOnClaim = jest
.fn()
.mockResolvedValue(undefined);
service.resolveVehicleOwnerNationalCodeForClaim = jest
.fn()
.mockReturnValue(ownerCode);
service.resolveOwnershipPlateForClaim = jest
.fn()
.mockReturnValue({ leftDigits: 12 });
service.sandHubService = {
getShebaValidation: jest.fn().mockResolvedValue({ ReturnValue: true }),
};
service.logger = { log: jest.fn(), error: jest.fn() };
return { service, claim };
}
describe("single-entry claim bank information", () => {
it.each(["CAR_BODY", "THIRD_PARTY"])(
"reuses saved bank information for %s, including resend",
async (type) => {
for (const step of ["SELECT_OTHER_PARTS", "USER_EXPERT_RESEND"]) {
for (const storedSheba of [sheba, sheba.slice(2)]) {
const { service } = fixture(
{ sheba: storedSheba, nationalCodeOfInsurer: ownerCode },
type,
step,
);
const result = await service.selectOtherPartsV2(
claimId,
{ otherParts: ["engine"] },
userId,
);
expect(result.currentStep).toBe("CAPTURE_PART_DAMAGES");
expect(
service.claimCaseDbService.findByIdAndUpdate,
).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"money.nationalCodeOfInsurer": ownerCode,
"damage.otherParts": ["engine"],
}),
);
expect(
service.sandHubService.getShebaValidation,
).not.toHaveBeenCalled();
}
}
},
);
it.each(["sheba", "shebaNumber"])(
"collects a new %s once and derives the vehicle owner identity",
async (field) => {
const { service } = fixture();
await service.selectOtherPartsV2(claimId, { [field]: sheba }, userId);
expect(service.sandHubService.getShebaValidation).toHaveBeenCalledWith(
ownerCode,
sheba,
);
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"money.nationalCodeOfInsurer": ownerCode,
}),
);
},
);
it("retains a saved Sheba when only the legacy owner identity was missing", async () => {
const { service } = fixture({ sheba });
await service.selectOtherPartsV2(claimId, {}, userId);
expect(service.sandHubService.getShebaValidation).toHaveBeenCalledWith(
ownerCode,
sheba,
);
});
it("accepts the same previously saved number with a different IR/whitespace representation", async () => {
const { service } = fixture({
sheba: sheba.slice(2),
nationalCodeOfInsurer: ownerCode,
});
await service.selectOtherPartsV2(
claimId,
{ sheba: " ir " + sheba.slice(2) },
userId,
);
expect(service.sandHubService.getShebaValidation).not.toHaveBeenCalled();
});
it("still requires and validates bank information when none was saved", async () => {
const { service } = fixture();
for (const value of [undefined, "IR", "invalid", "123"]) {
await expect(
service.selectOtherPartsV2(claimId, { sheba: value }, userId),
).rejects.toBeInstanceOf(BadRequestException);
}
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("does not silently replace saved bank information outside an explicit resend", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: ownerCode });
await expect(
service.selectOtherPartsV2(
claimId,
{ sheba: "IR" + "2".repeat(24) },
userId,
),
).rejects.toBeInstanceOf(ConflictException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("does not reuse another owner’s bank information", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: "0098765432" });
await expect(
service.selectOtherPartsV2(claimId, {}, userId),
).rejects.toBeInstanceOf(BadRequestException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
expect(
savedClaimBankInformation(
{ sheba, nationalCodeOfInsurer: "0098765432" },
ownerCode,
),
).toMatchObject({
shebaProvided: false,
ownerNationalCodeProvided: true,
});
});
it("rejects a submitted national code that differs from the vehicle owner", async () => {
const { service } = fixture();
await expect(
service.selectOtherPartsV2(
claimId,
{ sheba, nationalCodeOfInsurer: "0098765432" },
userId,
),
).rejects.toBeInstanceOf(BadRequestException);
});
it("keeps beneficiary authorization before reusing saved bank information", async () => {
const { service } = fixture({ sheba, nationalCodeOfInsurer: ownerCode });
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(
new ForbiddenException(),
);
await expect(
service.selectOtherPartsV2(claimId, {}, userId),
).rejects.toBeInstanceOf(ForbiddenException);
expect(service.claimCaseDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it.each([sheba, sheba.slice(2)])(
"lets the expert continue with saved bank information (%s)",
async (storedSheba) => {
const { service } = fixture({
sheba: storedSheba,
nationalCodeOfInsurer: ownerCode,
});
service.assertFieldExpertInPersonBlameForClaimCase = jest
.fn()
.mockResolvedValue(undefined);
await service.expertCompleteClaimData(
claimId,
{ sub: userId },
{ otherParts: [] },
);
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
claimId,
expect.objectContaining({
"money.sheba": sheba,
"workflow.currentStep": "CAPTURE_PART_DAMAGES",
}),
);
},
);
it("allows omitted bank fields through DTO validation but rejects malformed field types", async () => {
expect(
await validate(
Object.assign(new SelectOtherPartsV2Dto(), { otherParts: [] }),
),
).toHaveLength(0);
expect(
await validate(
Object.assign(new SelectOtherPartsV2Dto(), { sheba: 123 }),
),
).not.toHaveLength(0);
});
it("recognizes incomplete and malformed saved details without exposing them", () => {
expect(savedClaimBankInformation()).toMatchObject({
shebaProvided: false,
ownerNationalCodeProvided: false,
});
expect(
savedClaimBankInformation({
sheba: "IR123",
nationalCodeOfInsurer: "123",
}),
).toMatchObject({ shebaProvided: false, ownerNationalCodeProvided: false });
expect(savedClaimBankInformation({ sheba })).toMatchObject({
shebaProvided: true,
ownerNationalCodeProvided: false,
});
});
});
@@ -0,0 +1,30 @@
export function normalizeClaimSheba(value: unknown): string | undefined {
const digits = String(value ?? "")
.replace(/\s/g, "")
.replace(/^IR/i, "");
return /^\d{24}$/.test(digits) ? `IR${digits}` : undefined;
}
export function normalizeClaimNationalCode(value: unknown): string | undefined {
const code = String(value ?? "").replace(/\s/g, "");
return /^\d{10}$/.test(code) ? code : undefined;
}
/** Saved bank details belong to this claim's vehicle owner, never another party. */
export function savedClaimBankInformation(
money?: { sheba?: string; nationalCodeOfInsurer?: string } | null,
vehicleOwnerNationalCode?: string,
) {
const savedOwner = normalizeClaimNationalCode(money?.nationalCodeOfInsurer);
const currentOwner = normalizeClaimNationalCode(vehicleOwnerNationalCode);
const ownerChanged =
!!savedOwner && !!currentOwner && savedOwner !== currentOwner;
const sheba = ownerChanged ? undefined : normalizeClaimSheba(money?.sheba);
const nationalCode = currentOwner ?? savedOwner;
return {
sheba,
nationalCode,
shebaProvided: !!sheba,
ownerNationalCodeProvided: !!nationalCode,
};
}
@@ -230,6 +230,7 @@ describe("claim beneficiary authorization across shared user flows", () => {
owner: { userId: firstId },
damagedPartyUserId: secondId,
status: "SELECTING_OUTER_PARTS",
money: { sheba: "IR" + "1".repeat(24), nationalCodeOfInsurer: "0012345678" },
};
service.claimCaseDbService.findById = jest.fn().mockResolvedValue(claim);
service.blameRequestDbService.find = jest
@@ -246,6 +247,9 @@ describe("claim beneficiary authorization across shared user flows", () => {
role: RoleEnum.USER,
});
expect(damaged.canAct).toBe(true);
expect(damaged.bankInformation).toEqual({ shebaProvided: true, ownerNationalCodeProvided: true });
expect(damaged.money.sheba).toContain("*");
expect(damaged.money.sheba).not.toBe(claim.money.sheba);
expect(damaged.ownerGuidance).toBeDefined();
});
@@ -1,3 +1,11 @@
import { unlink } from "node:fs/promises";
import { plainToInstance } from "class-transformer";
import { validateSync } from "class-validator";
import {
normalizeClaimSheba,
normalizeClaimNationalCode,
savedClaimBankInformation,
} from './claim-bank-information';
import { UserClaimBranchService, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import {
hasReviewedTejaratNotifier,
@@ -1227,7 +1235,7 @@ export class ClaimRequestManagementService {
);
}
const mergedSheba = dto.sheba != null ? dto.sheba : fresh.money?.sheba;
const mergedSheba = normalizeClaimSheba(dto.sheba ?? fresh.money?.sheba);
const mergedNational =
dto.nationalCodeOfInsurer != null
? dto.nationalCodeOfInsurer
@@ -1236,7 +1244,7 @@ export class ClaimRequestManagementService {
if (
fresh.money?.sheba &&
dto.sheba != null &&
dto.sheba !== fresh.money.sheba
normalizeClaimSheba(dto.sheba) !== normalizeClaimSheba(fresh.money.sheba)
) {
throw new ConflictException('Sheba is already set for this claim.');
}
@@ -1264,7 +1272,7 @@ export class ClaimRequestManagementService {
const bankComplete =
mergedSheba &&
mergedNational &&
/^[0-9]{24}$/.test(String(mergedSheba).replace(/\s/g, '')) &&
!!normalizeClaimSheba(mergedSheba) &&
/^[0-9]{10}$/.test(String(mergedNational).replace(/\s/g, ''));
if (bankComplete) {
@@ -8411,6 +8419,9 @@ export class ClaimRequestManagementService {
fanavaran,
};
} catch (error) {
if ((error as {code?: number})?.code === 11000) {
throw new ConflictException('درخواست خسارت این پرونده قبلاً ثبت شده است. پرونده‌های من را باز کنید.');
}
if (error instanceof HttpException) throw error;
this.logger.error(
'createClaimFromBlameV2 failed',
@@ -9095,7 +9106,7 @@ export class ClaimRequestManagementService {
* - Claim case must exist
* - User must be the claim owner (damaged party)
* - Current workflow step must be SELECT_OTHER_PARTS (step 3)
* - Other parts and bank info must not have been submitted previously
* - Saved bank info is reused; only missing fields must be supplied
*/
async selectOtherPartsV2(
claimRequestId: string,
@@ -9138,17 +9149,6 @@ export class ClaimRequestManagementService {
);
}
// 4. Validate other parts and bank info haven't been submitted yet
if (
claimCase.money?.sheba &&
claimCase.money?.nationalCodeOfInsurer &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new ConflictException(
'Bank information has already been submitted for this claim',
);
}
// 5. Prepare data
// Backward compatibility aliases:
// - shebaNumber <- sheba
@@ -9168,22 +9168,12 @@ export class ClaimRequestManagementService {
otherParts = [];
}
}
const shebaInput = String(
((body as any).shebaNumber ?? (body as any).sheba ?? '') as string,
).replace(/\s/g, '');
const shebaDigits = shebaInput.replace(/^IR/i, '');
const shebaNumber = `IR${shebaDigits}`;
const submittedShebaInput = String(
body.shebaNumber ?? body.sheba ?? '',
).trim();
const submittedNationalCode = String(
((body as any).nationalCodeOfOwner ??
(body as any).nationalCodeOfInsurer ??
'') as string,
body.nationalCodeOfOwner ?? body.nationalCodeOfInsurer ?? '',
).replace(/\s/g, '');
if (!/^[0-9]{24}$/.test(shebaDigits)) {
throw new BadRequestException(
'shebaNumber is required and must be valid (IR + 24 digits or only 24 digits)',
);
}
const blameRequest = claimCase.blameRequestId
? await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
@@ -9200,10 +9190,34 @@ export class ClaimRequestManagementService {
'Submitted national code does not match the vehicle owner saved on the blame case.',
);
}
const nationalCode = storedOwnerNationalCode ?? submittedNationalCode;
if (!/^[0-9]{10}$/.test(nationalCode)) {
const savedBank = savedClaimBankInformation(
claimCase.money,
storedOwnerNationalCode,
);
const shebaNumber = submittedShebaInput
? normalizeClaimSheba(submittedShebaInput)
: savedBank.sheba;
if (!shebaNumber) {
throw new BadRequestException(
'Vehicle owner national code is unavailable; a 10-digit nationalCodeOfOwner is required only for legacy claims.',
'شماره شبا باید شامل IR و ۲۴ رقم یا فقط ۲۴ رقم باشد.',
);
}
if (
savedBank.sheba &&
submittedShebaInput &&
shebaNumber !== savedBank.sheba &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new ConflictException(
'شماره شبا قبلاً برای این پرونده ثبت شده است؛ نیازی به ورود مجدد آن نیست.',
);
}
const shebaDigits = shebaNumber.slice(2);
const nationalCode =
storedOwnerNationalCode ?? (submittedNationalCode || savedBank.nationalCode);
if (!normalizeClaimNationalCode(nationalCode)) {
throw new BadRequestException(
'کد ملی ۱۰ رقمی مالک خودرو برای ثبت اطلاعات حساب الزامی است.',
);
}
const ownershipPlate = this.resolveOwnershipPlateForClaim(
@@ -9216,13 +9230,17 @@ export class ClaimRequestManagementService {
);
}
let step = claimCase.workflow?.currentStep;
// External inquiry checks before moving workflow:
// 1) ownership check for nationalCode + plate
// await this.sandHubService.getCarOwnershipInfo(ownershipPlate, nationalCode);
// 2) sheba check for nationalCode + sheba
const bankUnchanged =
normalizeClaimSheba(claimCase.money?.sheba) === shebaNumber &&
normalizeClaimNationalCode(claimCase.money?.nationalCodeOfInsurer) ===
nationalCode;
if (!bankUnchanged) {
await this.sandHubService.getShebaValidation(nationalCode, shebaNumber);
}
const updatePayload: any = {
'damage.otherParts': otherParts.length > 0 ? otherParts : undefined,
@@ -9621,7 +9639,11 @@ export class ClaimRequestManagementService {
if (!claim || !canFinalizeExpertResend(claim)) {
return;
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
await this.claimCaseDbService.findOneAndUpdate({
_id: claim._id, status: ClaimCaseStatus.WAITING_FOR_USER_RESEND,
'workflow.currentStep': ClaimWorkflowStep.USER_EXPERT_RESEND,
'evaluation.damageExpertResend.fulfilledAt': null,
}, {
$set: {
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
claimStatus: ClaimStatus.PENDING,
@@ -10801,6 +10823,12 @@ export class ClaimRequestManagementService {
'Only the claim owner can submit an objection',
);
// Multipart body fields are strings. This service is also called by
// mirror controllers, so normalize and validate here rather than relying
// on a global ValidationPipe (the app deliberately has none).
body = plainToInstance(UserObjectionV2Dto, body);
if (validateSync(body).length) throw new BadRequestException('اطلاعات اعتراض معتبر نیست. قطعه، توضیح اعتراض و مبالغ پیشنهادی را بررسی کنید.');
if (claimCase.evaluation?.objection?.submittedAt) {
throw new ConflictException(
'An objection has already been submitted for this claim.',
@@ -11063,7 +11091,10 @@ export class ClaimRequestManagementService {
createdAt: new Date(),
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
const saved = await this.claimCaseDbService.findOneAndUpdate({
_id: claimCase._id, status: ClaimCaseStatus.COMPLETED,
'userRating.createdAt': null,
}, {
$set: { userRating },
$push: {
history: {
@@ -11079,6 +11110,7 @@ export class ClaimRequestManagementService {
},
});
if (!saved) throw new ConflictException("امتیاز این پرونده قبلاً ثبت شده است یا وضعیت پرونده تغییر کرده است.");
return userRating;
}
@@ -11188,139 +11220,48 @@ export class ClaimRequestManagementService {
}
const signDoc = await this.claimSignDbService.create({
fileName: signFile.filename,
userId: effectiveUserId,
path: signFile.path,
fileName: signFile.filename, userId: effectiveUserId, path: signFile.path,
requestId: new Types.ObjectId(claimRequestId),
} as any);
const signId = new Types.ObjectId(String((signDoc as any)._id));
const signedAt = new Date();
const scopedApprovalPayload = {
agree,
signDetailId: signId,
signedAt,
};
const historyActor = {
actorId: new Types.ObjectId(effectiveUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
};
/** Mixed reply: priced lines acceptance before factor uploads */
if (isMixedPartialGate) {
if (!agree) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
const approvalField = isMixedPartialGate ? 'ownerPricedPartsApproval' : 'ownerInsurerApproval';
const nextStatus = !agree ? ClaimCaseStatus.REJECTED : isMixedPartialGate ? claimCase.status : ClaimCaseStatus.COMPLETED;
const nextStep = agree ? (isMixedPartialGate ? ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS : ClaimWorkflowStep.CLAIM_COMPLETED) : claimCase.workflow.currentStep;
// The state change and decision are one compare-and-set. Only its winner may
// call external services; overlapping accept/reject requests cannot overwrite it.
const saved = await this.claimCaseDbService.findOneAndUpdate({
_id: claimCase._id, status: claimCase.status, claimStatus: claimCase.claimStatus,
'workflow.currentStep': ClaimWorkflowStep.INSURER_REVIEW,
[`evaluation.${approvalField}.signedAt`]: null,
'evaluation.ownerInsurerApproval.signedAt': null,
}, {
$set: {
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
'evaluation.ownerPricedPartsApproval': scopedApprovalPayload,
'workflow.nextStep': null,
},
$push: {
history: {
type: 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
status: nextStatus,
claimStatus: !agree ? ClaimStatus.REJECTED : isMixedPartialGate ? ClaimStatus.NEEDS_REVISION : ClaimStatus.APPROVED,
[`evaluation.${approvalField}`]: { agree, signDetailId: new Types.ObjectId(String((signDoc as any)._id)), signedAt },
'workflow.currentStep': nextStep,
'workflow.nextStep': !agree ? null : isMixedPartialGate ? ClaimWorkflowStep.EXPERT_COST_EVALUATION : ClaimWorkflowStep.CLAIM_COMPLETED,
},
$push: { history: {
type: isMixedPartialGate ? (agree ? 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD' : 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS') : (agree ? 'OWNER_SIGNED_INSURER_APPROVAL' : 'OWNER_REJECTED_INSURER_APPROVAL_PRICING'),
actor: { actorId: new Types.ObjectId(effectiveUserId), actorName: claimCase.owner?.fullName || 'User', actorType: 'user' },
timestamp: signedAt, metadata: {},
} },
...(!isMixedPartialGate && agree ? {$addToSet: {'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW}} : {}),
});
return {
message:
'Your rejection has been recorded. This claim is marked rejected and will not proceed.',
claimRequestId,
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
currentStep: claimCase.workflow?.currentStep,
accepted: false,
phase: 'PRICED_PARTS_FOR_FACTORS',
};
if (!saved) {
await this.claimSignDbService.deleteById(String((signDoc as any)._id));
await unlink(signFile.path).catch(() => undefined);
throw new ConflictException('تصمیم این پرونده قبلاً ثبت شده است یا وضعیت پرونده تغییر کرده است. پرونده را دوباره باز کنید.');
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
claimStatus: ClaimStatus.NEEDS_REVISION,
'evaluation.ownerPricedPartsApproval': scopedApprovalPayload,
'workflow.currentStep':
ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS,
'workflow.nextStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION,
},
$push: {
history: {
type: 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Priced repair lines accepted. Upload repair factor files for each factor-needed part; the claim will return to the damage expert for cost validation.',
claimRequestId,
status: claimCase.status,
claimStatus: ClaimStatus.NEEDS_REVISION,
currentStep: ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS,
accepted: true,
phase: 'PRICED_PARTS_FOR_FACTORS',
if (isMixedPartialGate || !agree) return {
message: !agree ? 'عدم تأیید شما ثبت شد. پرونده رد شده است.' : 'تأیید مبالغ ثبت شد. فاکتور قطعات درخواستی را بارگذاری کنید.',
claimRequestId, status: nextStatus,
claimStatus: !agree ? ClaimStatus.REJECTED : ClaimStatus.NEEDS_REVISION,
currentStep: nextStep, accepted: agree,
phase: isMixedPartialGate ? 'PRICED_PARTS_FOR_FACTORS' : 'FINAL_APPROVAL',
};
}
/** Final accept / reject (no outstanding factor gate at this step) */
if (!agree) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
'evaluation.ownerInsurerApproval': scopedApprovalPayload,
'workflow.nextStep': null,
},
$push: {
history: {
type: 'OWNER_REJECTED_INSURER_APPROVAL_PRICING',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Your rejection has been recorded. This claim is marked rejected and will not proceed.',
claimRequestId,
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
currentStep: claimCase.workflow?.currentStep,
accepted: false,
phase: 'FINAL_APPROVAL',
};
}
// Submit Fanavaran expertise when owner accepts the expert reply
const fanavaranExpertise =
await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.COMPLETED,
claimStatus: ClaimStatus.APPROVED,
'evaluation.ownerInsurerApproval': scopedApprovalPayload,
'workflow.currentStep': ClaimWorkflowStep.CLAIM_COMPLETED,
'workflow.nextStep': ClaimWorkflowStep.CLAIM_COMPLETED,
},
$push: {
'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW,
history: {
type: 'OWNER_SIGNED_INSURER_APPROVAL',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
const fanavaranExpertise = await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId);
const fanavaran =
await this.autoSubmitToFanavaranV2OnClaimCompleted(claimRequestId);
@@ -11603,6 +11544,7 @@ export class ClaimRequestManagementService {
actor?: { sub: string; role?: string; username?: string },
): Promise<ClaimDetailsV2ResponseDto> {
try {
if (!Types.ObjectId.isValid(claimRequestId)) throw new BadRequestException("شناسه پرونده خسارت معتبر نیست.");
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException('Claim request not found');
@@ -11613,7 +11555,7 @@ export class ClaimRequestManagementService {
? ((
await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{ lean: true, select: 'type creationMethod' },
{ lean: true, select: 'type creationMethod parties expert' },
)
)[0] ?? null)
: null;
@@ -11731,7 +11673,7 @@ export class ClaimRequestManagementService {
: undefined;
const maskSheba = (s?: string) =>
s ? s.replace(/^(.{4})(.*)(.{4})$/, 'IR$1************$3') : undefined;
s ? s.replace(/^(.{4})(.*)(.{4})$/, '$1************$3') : undefined;
const maskNationalCode = (s?: string) =>
s ? s.replace(/^(.{2})(.*)(.{2})$/, '$1******$3') : undefined;
const isExpertViewer =
@@ -11763,6 +11705,10 @@ export class ClaimRequestManagementService {
fullName: claim.owner.fullName,
}
: undefined;
const savedBank = savedClaimBankInformation(
claim.money,
this.resolveVehicleOwnerNationalCodeForClaim(blameForDetail),
);
const moneyForUser = claim.money
? {
sheba: maskSheba(claim.money.sheba),
@@ -11801,6 +11747,10 @@ export class ClaimRequestManagementService {
selectedParts: selectedNormDetails,
otherParts: claim.damage?.otherParts,
money: isExpertViewer ? moneyForExpert : moneyForUser,
bankInformation: {
shebaProvided: savedBank.shebaProvided,
ownerNationalCodeProvided: savedBank.ownerNationalCodeProvided,
},
requiredDocuments:
Object.keys(requiredDocumentsStatus).length > 0
? requiredDocumentsStatus
@@ -11809,6 +11759,7 @@ export class ClaimRequestManagementService {
damagedParts,
damagedPartsHistory,
expertResend,
visitLocation: claim.evaluation?.visitLocation,
fanavaran: fanavaranClaimReferences(claim),
evaluation: mappedEvaluation
? {
@@ -12215,6 +12166,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
const skipMetalPlate = !!(blame as any).isMadeByFileMaker;
const isV4FileMaker =
@@ -12330,6 +12282,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
if (this.isV3InitialDocumentsPhase(claimCase)) {
@@ -12362,6 +12315,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
await this.advanceV3ClaimToOuterPartsIfReady(claimCase, blame);
@@ -12395,6 +12349,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
@@ -12472,7 +12427,7 @@ export class ClaimRequestManagementService {
? {
shebaNumber: String(shebaNumber).replace(
/^(.{4})(.*)(.{4})$/,
'IR$1************$3',
'$1************$3',
),
}
: {}),
@@ -12503,6 +12458,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
const skipMetalPlate = !!(blame as any).isMadeByFileMaker;
@@ -12656,6 +12612,7 @@ export class ClaimRequestManagementService {
`Claim case with ID ${claimRequestId} not found`,
);
}
await this.assertActorCanViewClaimV2(claimCase, currentUserId, actor);
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import {
Controller,
HttpException,
@@ -375,7 +376,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 +622,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 +657,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 +672,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 +693,7 @@ Optional: upload car green card file in the same step.
})
@ApiResponse({
status: 409,
description: "Bank information already submitted",
description: "Conflicting bank information",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@@ -182,6 +182,15 @@ export class ClaimDetailsV2ResponseDto {
nationalCodeOfOwner?: string;
};
@ApiPropertyOptional({
description: 'Whether bank fields can be reused from this claim or its vehicle-owner identity. Does not expose bank details.',
example: { shebaProvided: true, ownerNationalCodeProvided: true },
})
bankInformation?: {
shebaProvided: boolean;
ownerNationalCodeProvided: boolean;
};
@ApiPropertyOptional({
description: "Required documents status (link instead of id)",
})
@@ -254,6 +263,9 @@ export class ClaimDetailsV2ResponseDto {
})
expertResend?: ExpertResendDetailsV2Dto;
@ApiPropertyOptional()
visitLocation?: string;
@ApiPropertyOptional({
description:
"Fanavaran codes and image upload receipts. Claim codes appear on COMPLETED; fileIds and attachments upload status/errors are available earlier when recorded.",
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger';
import { IsArray, IsEnum, IsNotEmpty, IsOptional, IsString, Matches, Length, ArrayMaxSize } from 'class-validator';
import { IsArray, IsEnum, IsOptional, IsString, Matches, Length, ArrayMaxSize } from 'class-validator';
/**
* Enum for valid other (non-body) car parts that can be damaged
@@ -40,13 +40,13 @@ export class SelectOtherPartsV2Dto {
})
otherParts?: OtherCarPart[];
@ApiProperty({
description: 'Sheba number (IBAN). Accepted: IR + 24 digits OR only 24 digits',
@ApiPropertyOptional({
description: 'Sheba number (IBAN). Required only if not already saved on this claim. Accepted: IR + 24 digits OR only 24 digits',
example: 'IR123456789012345678901234',
})
@IsNotEmpty({ message: 'sheba is required' })
@IsOptional()
@IsString({ message: 'sheba must be a string' })
sheba: string;
sheba?: string;
@ApiPropertyOptional({
description: 'Legacy alias of sheba for backward compatibility',
@@ -0,0 +1,26 @@
import { plainToInstance } from "class-transformer";
import { validate } from "class-validator";
import { UserObjectionV2Dto } from "./user-objection-v2.dto";
describe("objection JSON and multipart parity", () => {
it.each([true, false])(
"validates nested entries for multipart=%s",
async (multipart) => {
const entries = [{ partId: 101, reason: "اعتراض به قیمت" }];
const dto = plainToInstance(UserObjectionV2Dto, {
objectionParts: multipart ? JSON.stringify(entries) : entries,
});
expect(await validate(dto)).toEqual([]);
},
);
it("still rejects invalid entries and malformed multipart JSON", async () => {
for (const raw of ["{", '[{"partId":"wrong"}]']) {
expect(
(
await validate(
plainToInstance(UserObjectionV2Dto, { objectionParts: raw }),
)
).length,
).toBeGreaterThan(0);
}
});
});
@@ -1,11 +1,6 @@
import { ApiPropertyOptional } from "@nestjs/swagger";
import { Type, Transform } from "class-transformer";
import {
IsArray,
IsOptional,
Validate,
ValidateNested,
} from "class-validator";
import { Type, Transform, plainToInstance } from "class-transformer";
import { IsArray, IsOptional, Validate, ValidateNested } from "class-validator";
import { HasObjectionEntriesConstraint } from "src/common/validators/has-objection-entries.validator";
import { NewPartDto, UserObjectionPartDto } from "./user-objection.dto";
@@ -28,7 +23,10 @@ export class UserObjectionV2Dto {
@Transform(({ value }) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? plainToInstance(UserObjectionPartDto, parsed)
: parsed;
} catch {
return value;
}
@@ -50,7 +48,10 @@ export class UserObjectionV2Dto {
@Transform(({ value }) => {
if (typeof value === "string") {
try {
return JSON.parse(value);
const parsed = JSON.parse(value);
return Array.isArray(parsed)
? plainToInstance(NewPartDto, parsed)
: parsed;
} catch {
return value;
}
@@ -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);
}
@@ -218,6 +218,8 @@ export const ClaimUserObjectionPayloadSchema =
@Schema({ _id: false })
export class ClaimResendRequest {
@Prop({ type: Date })
requestedAt?: Date;
@Prop({ type: String })
resendDescription?: string;
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import { extname } from "node:path";
import {
@@ -241,8 +242,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 +276,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 +291,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 +305,7 @@ Optional: upload car green card file in the same step.
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({
status: 409,
description: "Bank information already submitted",
description: "Conflicting bank information",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@@ -565,7 +565,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}`);
@@ -8,7 +8,7 @@ describe("owner insurer approval without branch selection", () => {
const service = Object.create(
ClaimRequestManagementService.prototype,
) as ClaimRequestManagementService;
const findByIdAndUpdate = jest.fn().mockResolvedValue(undefined);
const findOneAndUpdate = jest.fn().mockResolvedValue({});
(service as any).claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
@@ -21,7 +21,7 @@ describe("owner insurer approval without branch selection", () => {
damageExpertReply: { submittedAt: new Date(), parts: [] },
},
}),
findByIdAndUpdate,
findOneAndUpdate,
};
(service as any).resolveClaimEffectiveUserId = jest
.fn()
@@ -48,8 +48,8 @@ describe("owner insurer approval without branch selection", () => {
status: ClaimCaseStatus.REJECTED,
});
expect(findByIdAndUpdate).toHaveBeenCalledWith(
"507f1f77bcf86cd799439011",
expect(findOneAndUpdate).toHaveBeenCalledWith(
expect.objectContaining({_id: "507f1f77bcf86cd799439011", "evaluation.ownerInsurerApproval.signedAt": null}),
expect.objectContaining({
$set: expect.objectContaining({
"evaluation.ownerInsurerApproval": expect.not.objectContaining({
@@ -0,0 +1,105 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
const id = "507f1f77bcf86cd799439011",
uid = "507f1f77bcf86cd799439012";
/** Simulated shared document: each conditional update is atomic, as Mongo is. */
function serviceFor(initial: any) {
const s: any = Object.create(ClaimRequestManagementService.prototype);
const doc = { _id: id, owner: { userId: uid }, ...initial };
s.claimCaseDbService = {
findById: jest.fn(async () => ({
...doc,
workflow: { ...doc.workflow },
evaluation: { ...doc.evaluation },
})),
findOneAndUpdate: jest.fn(async (filter, update) => {
if (filter.status !== doc.status) return null;
if (filter["userRating.createdAt"] === null && doc.userRating)
return null;
if (
filter["evaluation.ownerInsurerApproval.signedAt"] === null &&
doc.evaluation.ownerInsurerApproval
)
return null;
for (const [k, v] of Object.entries(update.$set || {})) {
const parts = k.split(".");
let target = doc;
for (const key of parts.slice(0, -1)) target = target[key] ??= {};
target[parts.at(-1)!] = v;
}
return doc;
}),
};
s.resolveClaimEffectiveUserId = jest.fn(async () => uid);
s.assertEffectiveUserIsDamagedPartyOnClaim = jest.fn(async () => {});
s.claimSignDbService = {
create: jest.fn(async () => ({ _id: "507f1f77bcf86cd799439013" })),
deleteById: jest.fn(async () => {}),
};
s.autoSubmitFanavaranExpertiseOnExpertReply = jest.fn(async () => ({
submitted: false,
}));
s.autoSubmitToFanavaranV2OnClaimCompleted = jest.fn(async () => ({
submitted: false,
}));
return { s, doc };
}
describe("one winning owner action", () => {
it("never records contradictory final decisions or duplicate integration calls", async () => {
const { s, doc } = serviceFor({
status: "INSURER_REVIEW_AWAITING_OWNER_SIGN",
claimStatus: "APPROVED",
workflow: { currentStep: "INSURER_REVIEW" },
evaluation: { damageExpertReply: { submittedAt: new Date(), parts: [] } },
});
const results = await Promise.allSettled(
[true, false, true, false, true, false].map((agree) =>
s.submitOwnerInsurerApprovalSignV2(
id,
agree,
{ filename: "a.jpg", path: "files/a.jpg" },
uid,
),
),
);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(s.claimSignDbService.deleteById).toHaveBeenCalledTimes(5);
expect(s.autoSubmitToFanavaranV2OnClaimCompleted).toHaveBeenCalledTimes(1);
expect(doc.status).toBe("COMPLETED");
expect(doc.evaluation.ownerInsurerApproval.agree).toBe(true);
});
it("allows exactly one satisfaction rating under concurrent submissions", async () => {
const { s } = serviceFor({
status: "COMPLETED",
workflow: {},
evaluation: {},
});
const results = await Promise.allSettled(
[0, 1, 2, 3, 4, 5].map((n) =>
s.addUserRatingV2(
id,
{ progressSpeed: n, registrationEase: n, overallEvaluation: n },
uid,
),
),
);
expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
expect(results.filter((r) => r.status === "rejected")).toHaveLength(5);
});
it("authorizes V3 selection before changing workflow or parts", async () => {
const { s } = serviceFor({
status: "SELECTING_OTHER_PARTS",
workflow: {},
evaluation: {},
});
s.assertActorCanViewClaimV2 = jest.fn(async () => {
throw Error("forbidden");
});
await expect(
s.selectOtherPartsV3(id, { otherParts: ["engine"] }, uid, {
sub: uid,
role: "field_expert",
}),
).rejects.toThrow("forbidden");
expect(s.claimCaseDbService.findOneAndUpdate).not.toHaveBeenCalled();
});
});
@@ -241,7 +241,7 @@ Optional: upload car green card file in the same step.
)
@ApiBody({
description:
"Other parts + bank information. Use `sheba` and `nationalCodeOfInsurer`. Optional file can be uploaded as car green card.",
"Other parts + optional bank information. Saved Sheba and vehicle-owner identity are reused; supply missing fields only. Optional car green card file.",
schema: {
type: "object",
properties: {
@@ -256,7 +256,6 @@ Optional: upload car green card file in the same step.
nationalCodeOfInsurer: { type: "string", example: "1234567890" },
file: { type: "string", format: "binary" },
},
required: ["sheba", "nationalCodeOfInsurer"],
},
})
@ApiResponse({
@@ -266,7 +265,7 @@ Optional: upload car green card file in the same step.
})
@ApiResponse({ status: 400, description: "Invalid workflow step or validation failed" })
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({ status: 409, description: "Bank information already submitted" })
@ApiResponse({ status: 409, description: "Conflicting bank information" })
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@Body() body: SelectOtherPartsV2Dto,
@@ -218,6 +218,9 @@ export function resolveFanavaranClientKey(): FanavaranClientKey {
}
// Optional deployment hint when FANAVARAN_CLIENT is not set.
if (String(process.env.CLIENT_ID ?? '').trim() === '7') {
return 'moallem';
}
if (String(process.env.CLIENT_ID ?? '') === '8') {
return 'parsian';
}
@@ -0,0 +1,75 @@
import {
CallHandler,
Controller,
ExecutionContext,
Get,
Injectable,
Module,
NestInterceptor,
Param,
Query,
Res,
ForbiddenException,
} from "@nestjs/common";
import { APP_INTERCEPTOR } from "@nestjs/core";
import {
EvidenceAccessService,
evidenceRequestScope,
} from "./evidence-access.service";
export { EvidenceAccessService } from "./evidence-access.service";
import { realpath } from "node:fs/promises";
import { resolve, sep } from "node:path";
import { Response } from "express";
import { map, Observable } from "rxjs";
@Injectable()
class EvidenceLinksInterceptor implements NestInterceptor {
constructor(private readonly access: EvidenceAccessService) {}
intercept(context: ExecutionContext, next: CallHandler) {
const req = context.switchToHttp().getRequest();
if (!req.user?.sub) return next.handle();
return new Observable((observer) =>
evidenceRequestScope.run(true, () =>
next
.handle()
.pipe(map((value) => this.access.project(value)))
.subscribe(observer),
),
);
}
}
@Controller("files")
class EvidenceController {
constructor(private readonly access: EvidenceAccessService) {}
@Get("*path")
async read(
@Param("path") raw: string | string[],
@Query("expires") expires: string,
@Query("signature") signature: string,
@Res() res: Response,
) {
const path = Array.isArray(raw) ? raw.join("/") : raw;
this.access.verify(path, expires, signature);
const root = await realpath(resolve("files"));
let target: string;
try {
target = await realpath(resolve(root, path));
} catch {
res.status(404).end();
return;
}
if (!target.startsWith(root + sep)) throw new ForbiddenException();
res.setHeader("Cache-Control", "private, no-store");
res.setHeader("X-Content-Type-Options", "nosniff");
// sendFile retains Range/HEAD support needed by video players.
res.sendFile(target);
}
}
@Module({
controllers: [EvidenceController],
providers: [
EvidenceAccessService,
{ provide: APP_INTERCEPTOR, useClass: EvidenceLinksInterceptor },
],
})
export class EvidenceAccessModule {}
@@ -0,0 +1,118 @@
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { createHmac, timingSafeEqual } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
/** Short-lived read capabilities, minted only inside authenticated API responses.
* Browser image/video/PDF elements cannot attach an Authorization header. */
@Injectable()
export class EvidenceAccessService {
private digest(path: string, expires: string): string {
const secret = process.env.JWT_SECRET;
if (!secret) throw new Error("JWT_SECRET is required for evidence access");
return createHmac("sha256", secret)
.update(`evidence\n${path}\n${expires}`)
.digest("hex");
}
sign(value: string): string {
const match = value.match(
/^(?:https?:\/\/[^/?#]+\/(?:[^?#]*\/)?|(?:\.?\/)?(?:[^\s/?#]+\/)*)files\/([^?#]+)(?:[?#].*)?$/,
);
if (!match || !/\.[a-z0-9]+$/i.test(match[1])) return value;
const path = match[1];
// Signing uses the same canonical URL path that Express decodes on read.
let decoded: string;
try {
decoded = decodeURIComponent(path);
} catch {
return value;
}
const expires = String(Math.floor(Date.now() / 1000) + 3600);
return `${value.split(/[?#]/)[0]}?expires=${expires}&signature=${this.digest(decoded, expires)}`;
}
verify(path: string, expires: string, signature: string): void {
if (
typeof path !== "string" ||
typeof expires !== "string" ||
typeof signature !== "string"
)
throw new UnauthorizedException("نشانی مدرک معتبر نیست.");
const exp = Number(expires);
if (
!Number.isSafeInteger(exp) ||
exp <= Date.now() / 1000 ||
exp > Date.now() / 1000 + 3660 ||
!/^[a-f0-9]{64}$/.test(signature || "")
)
throw new UnauthorizedException(
"نشانی مدرک معتبر نیست یا منقضی شده است. پرونده را دوباره باز کنید.",
);
if (
!timingSafeEqual(
Buffer.from(signature, "hex"),
Buffer.from(this.digest(path, expires), "hex"),
)
)
throw new UnauthorizedException("دسترسی به این مدرک مجاز نیست.");
}
/** Only mirror a capability already minted by the trusted file-link builder.
* Reflected form fields or arbitrary URL-shaped text cannot mint access. */
project(value: unknown): unknown {
const allowed = new Set<string>();
const walk = (
v: unknown,
convert: (text: string, field: string) => unknown,
field = "",
): unknown => {
if (v && typeof (v as any).toObject === "function")
return walk((v as any).toObject(), convert, field);
if (typeof v === "string") return convert(v, field);
if (Array.isArray(v)) return v.map((item) => walk(item, convert, field));
if (v instanceof Map)
return Object.fromEntries(
[...v].map(([k, item]) => [k, walk(item, convert, String(k))]),
);
if (
v &&
typeof v === "object" &&
Object.getPrototypeOf(v) === Object.prototype
)
return Object.fromEntries(
Object.entries(v).map(([k, item]) => [k, walk(item, convert, k)]),
);
return v;
};
walk(value, (text) => {
if (!text.includes("signature=")) return text;
try {
const url = new URL(text, "https://evidence.invalid");
const path = decodeURIComponent(url.pathname.split("/files/")[1] || "");
this.verify(
path,
url.searchParams.get("expires")!,
url.searchParams.get("signature")!,
);
allowed.add(path);
} catch {
/* Ordinary text and untrusted links never grant access. */
}
return text;
});
return walk(value, (text, field) => {
if (!/(?:url|urls|path|paths|link|links)$/i.test(field)) return text;
try {
const url = new URL(text, "https://evidence.invalid");
const path = decodeURIComponent(url.pathname.split("/files/")[1] || "");
return allowed.has(path) ? this.sign(text) : text;
} catch {
return text;
}
});
}
}
export const evidenceRequestScope = new AsyncLocalStorage<boolean>();
const links = new EvidenceAccessService();
/** Called only when constructing a link from server-owned file metadata. */
export function signAuthorizedEvidenceLink(value: string): string {
return evidenceRequestScope.getStore() ? links.sign(value) : value;
}
@@ -0,0 +1,65 @@
import { EvidenceAccessService } from "./evidence-access.module";
describe("evidence read capabilities", () => {
const secret = process.env.JWT_SECRET;
beforeEach(() => {
process.env.JWT_SECRET = "test-only-evidence-key";
});
afterEach(() => {
if (secret == null) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secret;
});
it("rejects bare, expired, altered and cross-path links but accepts its own signature", () => {
const service = new EvidenceAccessService();
const signed = new URL(
service.sign("https://example.test/car-damage/api/files/signs/a.jpg"),
);
const exp = signed.searchParams.get("expires")!;
const sig = signed.searchParams.get("signature")!;
expect(() => service.verify("signs/a.jpg", exp, sig)).not.toThrow();
expect(() => service.verify("signs/b.jpg", exp, sig)).toThrow();
expect(() => service.verify("signs/a.jpg", "1", sig)).toThrow();
expect(() => service.verify("signs/a.jpg", exp, "")).toThrow();
expect(() => service.verify("signs/a.jpg", exp, [sig] as any)).toThrow();
expect(() => service.verify("signs/a.jpg", exp, "0".repeat(64))).toThrow();
});
it("signs nested evidence without changing ordinary links, dates, or policy text", () => {
const service = new EvidenceAccessService();
const projected: any = service.project({
files: [
{ url: service.sign("files/car/a.jpg"), path: "files/car/a.jpg" },
],
reflected: { url: "files/car/private.jpg" },
site: "https://example.test/auth",
note: "files/car/private.jpg",
description: "https://example.test/files/signs/private.png",
});
expect(projected.files[0].url).toContain("?expires=");
expect(projected.files[0].path).toContain("?expires=");
expect(projected.reflected.url).toBe("files/car/private.jpg");
expect(projected.site).toBe("https://example.test/auth");
expect(projected.note).toBe("files/car/private.jpg");
expect(projected.description).toBe(
"https://example.test/files/signs/private.png",
);
expect(service.sign("See https://example.test/files/private.jpg")).toBe(
"See https://example.test/files/private.jpg",
);
});
});
it("mints links only while an authenticated request constructs them from stored media", () => {
const { evidenceRequestScope } = require("./evidence-access.service");
const { buildFileLink } = require("src/helpers/urlCreator");
const secret = process.env.JWT_SECRET;
process.env.JWT_SECRET = "qa-test-only";
try {
expect(buildFileLink("files/car/a.jpg")).not.toContain("signature=");
expect(
evidenceRequestScope.run(true, () => buildFileLink("files/car/a.jpg")),
).toContain("signature=");
expect(buildFileLink("files/car/a.jpg")).not.toContain("signature=");
} finally {
if (secret == null) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = secret;
}
});
+21 -10
View File
@@ -1374,7 +1374,15 @@ export class ExpertClaimService {
: null;
const blameStatus = (reviewerBlame as any).status as string;
if (blameStatus === "WAITING_FOR_FILE_REVIEWER") {
const isReviewerCapturePhase = [
ClaimCaseStatus.CREATED,
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
ClaimCaseStatus.SELECTING_OUTER_PARTS,
ClaimCaseStatus.SELECTING_OTHER_PARTS,
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
].includes(claim.status as ClaimCaseStatus);
if (blameStatus === "WAITING_FOR_FILE_REVIEWER" && isReviewerCapturePhase) {
if (assignedReviewerId && assignedReviewerId === actor.sub) {
// Phase 1 is intentionally idempotent. The linked claim can still be
// in a data-capture status here, so falling through to the damage
@@ -1417,7 +1425,8 @@ export class ExpertClaimService {
const isFactorValidationLock =
claimIsAwaitingExpertFactorValidationV2(claim);
const isDamageReviewLock =
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
claim.status === ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT ||
claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING;
const isExpertReviewingReentry =
claim.status === ClaimCaseStatus.EXPERT_REVIEWING;
const isResendPending =
@@ -1612,7 +1621,7 @@ export class ExpertClaimService {
assignFilter.initiatedByFieldExpertId = expertOid;
assignFilter.status = claim.status;
} else {
assignFilter.status = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
assignFilter.status = claim.status;
}
const updated = await this.claimCaseDbService.findOneAndUpdate(
@@ -1842,6 +1851,7 @@ export class ExpertClaimService {
"workflow.currentStep": ClaimWorkflowStep.USER_EXPERT_RESEND,
"workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
"evaluation.damageExpertResend": {
requestedAt: new Date(),
resendDescription: desc || undefined,
resendDocuments: uniqueDocs,
resendCarParts: normalizedParts,
@@ -2338,7 +2348,7 @@ export class ExpertClaimService {
* - Status must be EXPERT_REVIEWING
*
* On success:
* - Sets status = EXPERT_REVIEWING (remains), claimStatus = NEEDS_REVISION
* - Sets status = IN_PERSON_VISIT_PENDING, claimStatus = NEEDS_REVISION
* - Sets evaluation.visitLocation (optional note)
* - Records history event IN_PERSON_VISIT_REQUESTED
* - Unlocks the workflow so user can act
@@ -2355,7 +2365,7 @@ export class ExpertClaimService {
throw new NotFoundException("Claim request not found");
}
assertClaimCaseForTenant(claim, actor);
await this.assertExpertActorOnClaim(claim, actor);
if (claim.status !== ClaimCaseStatus.EXPERT_REVIEWING) {
throw new BadRequestException(
@@ -2377,7 +2387,7 @@ export class ExpertClaimService {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
claimStatus: ClaimStatus.NEEDS_REVISION,
status: ClaimCaseStatus.COMPLETED,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
"workflow.locked": false,
$unset: {
"workflow.lockedAt": "",
@@ -2385,7 +2395,7 @@ export class ExpertClaimService {
"workflow.lockedBy": "",
"workflow.preLockQueueSnapshot": "",
},
...(note ? { "evaluation.visitLocation": note } : {}),
"evaluation.visitLocation": note?.trim() || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
...(visitSnapshot && {
"evaluation.inPersonVisitExpertProfileSnapshot": visitSnapshot,
}),
@@ -2415,7 +2425,7 @@ export class ExpertClaimService {
return {
claimRequestId,
status: ClaimCaseStatus.COMPLETED,
status: ClaimCaseStatus.IN_PERSON_VISIT_PENDING,
claimStatus: ClaimStatus.NEEDS_REVISION,
message: "In-person visit requested. User will be notified.",
};
@@ -2635,7 +2645,7 @@ export class ExpertClaimService {
{
_id: { $in: blameIds.map((id) => new Types.ObjectId(id)) },
},
{ lean: true, select: "status publicId" },
{ lean: true, select: "status publicId type" },
)) as any[])
: [];
const blameById = new Map<string, any>(
@@ -3856,7 +3866,8 @@ export class ExpertClaimService {
new Map(blameLean ? [[String(claim.blameRequestId), blameLean]] : []),
);
const vehiclePayload = {
...((claim.vehicle as any) ?? {}),
...(typeof (claim.vehicle as any)?.toObject === "function"
? (claim.vehicle as any).toObject() : (claim.vehicle ?? {})),
...resolvedVehicle,
};
@@ -173,11 +173,12 @@ describe("Expert Fanavaran stage fields", () => {
management.fanavaranLookupService = {
bodyPolicyById: jest.fn().mockResolvedValue({ TotalPremium: 123456 }),
};
const payload = await management.previewFanavaranSubmitV2(id, clientKey, {
const preview = await management.previewFanavaranSubmitV2(id, clientKey, {
persistPayload: false,
forceRefreshPolicy: false,
requireClaimExpertId: false,
});
const payload = preview.payload ?? preview;
expect(payload.ClaimExpertId).toBe(154);
expect(payload).toMatchObject({
AccidentLocationAddress: "نشانی واقعی",
+15 -1
View File
@@ -166,7 +166,7 @@ export class ExpertInsurerService {
carPlate: claim.vehicle?.plate,
claimStatus: claim.status,
rating: claim.evaluation?.rating,
userRating: claim.evaluation?.userRating,
userRating: claim.userRating ?? claim.evaluation?.userRating,
damageExpertReply: claim.evaluation?.damageExpertReply,
damageExpertReplyFinal: claim.evaluation?.damageExpertReplyFinal,
damageExpertResend: claim.evaluation?.damageExpertResend,
@@ -1065,6 +1065,19 @@ export class ExpertInsurerService {
range.toDate,
);
const blameTypes = new Map(blameFiles.map((file) => [String(file._id), file.type]));
// Roster-owned claims can belong to another party insurer. Resolve only the
// missing linked types in one batch, after claims have already been scoped.
const missingBlameIds = [...new Set(claimFiles.map((file) => String(file.blameRequestId || "")))]
.filter((id) => Types.ObjectId.isValid(id) && !blameTypes.has(id));
if (missingBlameIds.length) {
const linked = await this.blameRequestDbService.find(
{_id: {$in: missingBlameIds.map((id) => new Types.ObjectId(id))}},
{lean: true, select: "type"},
);
for (const file of linked) blameTypes.set(String(file._id), file.type);
}
const blameFilesInRange = blameFiles.filter((file) =>
this.isInDateRange(file?.createdAt, range.fromDate, range.toDate),
);
@@ -1098,6 +1111,7 @@ export class ExpertInsurerService {
.filter((expertId): expertId is string => !!expertId)
.filter((expertId) => rosterById.has(expertId));
const fileType = String(
blameTypes.get(String(file.blameRequestId)) ??
file?.snapshot?.accident?.type ??
file?.blameFile?.type ??
BlameRequestType.THIRD_PARTY,
@@ -0,0 +1,61 @@
import { ExpertInsurerService } from "./expert-insurer.service";
import { Types } from "mongoose";
describe("QA reporting regressions", () => {
it("classifies a roster-owned claim by its linked blame even when that blame is outside the party-insurer list", async () => {
const s: any = Object.create(ExpertInsurerService.prototype);
const clientKey = String(new Types.ObjectId()),
expertId = new Types.ObjectId(),
blameId = new Types.ObjectId();
s.expertDbService = { findAll: jest.fn().mockResolvedValue([]) };
s.damageExpertDbService = {
findAll: jest
.fn()
.mockResolvedValue([
{ _id: expertId, firstName: "QA", lastName: "Expert" },
]),
};
s.fieldExpertDbService = { findAll: jest.fn().mockResolvedValue([]) };
s.getClientBlameFiles = jest.fn().mockResolvedValue([]);
s.getClientClaimFiles = jest
.fn()
.mockResolvedValue([
{
_id: new Types.ObjectId(),
blameRequestId: blameId,
createdAt: new Date(),
},
]);
s.expertFileActivityDbService = {
findByTenant: jest.fn().mockResolvedValue([]),
};
s.claimDamageExpertActorId = jest.fn().mockReturnValue(String(expertId));
s.blameRequestDbService = {
find: jest.fn().mockResolvedValue([{ _id: blameId, type: "CAR_BODY" }]),
};
const result = await s.buildExpertReportRows({ clientKey });
expect(result.experts[0]).toMatchObject({
totalFiles: 1,
carBodyFiles: 1,
thirdPartyFiles: 0,
});
expect(s.blameRequestDbService.find).toHaveBeenCalledWith(
{ _id: { $in: [blameId] } },
{ lean: true, select: "type" },
);
});
it("preserves current root user ratings and falls back to legacy nested ratings", () => {
const s: any = Object.create(ExpertInsurerService.prototype);
const current = { overallEvaluation: 5 },
legacy = { overallEvaluation: 1 };
expect(
s.normalizeClaimCase({
userRating: current,
evaluation: { userRating: legacy },
}).userRating,
).toBe(current);
expect(
s.normalizeClaimCase({ evaluation: { userRating: legacy } }).userRating,
).toBe(legacy);
});
});
@@ -103,6 +103,12 @@ export function buildClaimDetailsV2OwnerGuidance(
const objectionAllowed = ownerMaySubmitObjectionForClaimDetails(claim);
const objectionHint = objectionHintWhen(objectionAllowed);
if (claim.status === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return {
phaseKey: "IN_PERSON_VISIT_PENDING", headline: "مراجعه حضوری درخواست شده است",
detail: claim.evaluation?.visitLocation || "برای ادامه ارزیابی، به شعبه رسیدگی پرونده مراجعه کنید.",
nextActions: [], objectionAllowed: false,
};
if (claim.status === ClaimCaseStatus.COMPLETED) {
return {
phaseKey: "COMPLETED",
+58
View File
@@ -0,0 +1,58 @@
import { canFinalizeExpertResend } from "./claim-expert-resend";
describe("current resend evidence", () => {
it("requires every replacement to be newer than this request, without discarding original evidence", () => {
const c: any = {
status: "WAITING_FOR_USER_RESEND",
workflow: { currentStep: "USER_EXPERT_RESEND" },
evaluation: {
damageExpertResend: {
requestedAt: new Date("2026-11-22T10:00:00Z"),
resendDocuments: [
"damaged_driving_license_front",
"damaged_car_card_front",
],
resendCarParts: [{ id: 101, name: "101", catalogKey: "101" }],
},
},
damage: {
selectedParts: [
{ id: 101, name: "101", catalogKey: "101", label_fa: "سپر" },
],
},
requiredDocuments: {
damaged_driving_license_front: {
uploaded: true,
uploadedAt: new Date("2026-11-21"),
},
damaged_car_card_front: {
uploaded: true,
uploadedAt: new Date("2026-11-21"),
},
},
media: {
damagedParts: [
{
id: 101,
name: "101",
catalogKey: "101",
path: "files/old.jpg",
capturedAt: new Date("2026-11-21"),
},
],
},
};
expect(canFinalizeExpertResend(c)).toBe(false);
c.requiredDocuments.damaged_driving_license_front.uploadedAt = new Date(
"2026-11-22T10:01:00Z",
);
expect(canFinalizeExpertResend(c)).toBe(false);
c.requiredDocuments.damaged_car_card_front.uploadedAt = new Date(
"2026-11-22T10:02:00Z",
);
expect(canFinalizeExpertResend(c)).toBe(false);
c.media.damagedParts[0].capturedAt = new Date("2026-11-22T10:03:00Z");
expect(canFinalizeExpertResend(c)).toBe(true);
c.evaluation.damageExpertResend.fulfilledAt = new Date();
expect(canFinalizeExpertResend(c)).toBe(false);
});
});
+16 -15
View File
@@ -260,28 +260,18 @@ export function canFinalizeExpertResend(claim: any): boolean {
claim?.damage?.selectedParts,
);
console.log("[canFinalizeExpertResend]", {
docKeys,
partKeys,
docResults: docKeys.map((k) => ({
k,
uploaded: isRequiredDocumentUploaded(claim, k),
})),
partResults: partKeys.map((k) => ({
k,
captured: hasDamagedPartCapture(claim, k),
})),
});
if (docKeys.length === 0 && partKeys.length === 0) {
return String(r.resendDescription || "").trim() !== "";
}
for (const k of docKeys) {
if (!isRequiredDocumentUploaded(claim, k)) return false;
const entry = getRequiredDocEntry(claim, k) as {uploadedAt?: Date};
if (!isRequiredDocumentUploaded(claim, k) || !isCurrentResendEvidence(claim, entry?.uploadedAt)) return false;
}
for (const k of partKeys) {
if (!hasDamagedPartCapture(claim, k)) return false;
const norm = normalizeDamageSelectedParts(claim?.damage?.selectedParts, carType, claim?.damage?.selectedOuterParts);
const capture = getDamagedPartCaptureBlob(claim?.media?.damagedParts, k, norm) as {capturedAt?: Date};
if (!hasDamagedPartCapture(claim, k) || !isCurrentResendEvidence(claim, capture?.capturedAt)) return false;
}
return true;
}
@@ -334,3 +324,14 @@ export function partKeyAllowedForExpertResend(
return directMatch || (resolvedKey != null && allowedKeys.has(resolvedKey));
}
/** Legacy pending resends use their recorded request event as the cutoff. */
export function isCurrentResendEvidence(claim: any, uploadedAt: unknown): boolean {
const requestedAt = claim?.evaluation?.damageExpertResend?.requestedAt ??
[...(claim?.history ?? [])].reverse().find((h: any) => h.type === 'EXPERT_RESEND_REQUESTED')?.timestamp;
// Old rows without a cutoff must receive fresh uploads rather than implicitly
// satisfying a replacement request using evidence from initial submission.
const cutoff = new Date(requestedAt ?? claim?.updatedAt ?? 0).getTime();
const received = new Date(uploadedAt as string).getTime();
return Number.isFinite(received) && received >= cutoff;
}
+4
View File
@@ -44,3 +44,7 @@ describe("resolveUnifiedFileStatus", () => {
expect(counts.IN_PROGRESS).toBe(2);
});
});
it("keeps a pending in-person review out of completed/user-capture buckets", () => {
expect(resolveUnifiedFileStatus({blameStatus: CaseStatus.COMPLETED, claimStatus: ClaimCaseStatus.IN_PERSON_VISIT_PENDING})).toBe("EXPERT_REVIEWING");
});
+1 -1
View File
@@ -172,7 +172,7 @@ export function resolveUnifiedFileStatus(
return "WAITING_FOR_DOCUMENT_RESEND";
}
if (claim === ClaimCaseStatus.EXPERT_REVIEWING) return "EXPERT_REVIEWING";
if (claim === ClaimCaseStatus.EXPERT_REVIEWING || claim === ClaimCaseStatus.IN_PERSON_VISIT_PENDING) return "EXPERT_REVIEWING";
if (claim === ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS) {
return "EXPERT_VALIDATING_FACTORS";
}
+4 -2
View File
@@ -1,3 +1,5 @@
import { signAuthorizedEvidenceLink } from "src/evidence-access/evidence-access.service";
type StoredFileCapture = {
url?: string;
path?: string;
@@ -41,9 +43,9 @@ export function buildFileLink(path: string): string {
const baseUrl = (process.env.URL ?? "").replace(/\/+$/, "");
if (process.env.NODE_ENV === "local") {
return `${baseUrl}/${relative}`;
return signAuthorizedEvidenceLink(`${baseUrl}/${relative}`);
}
return `${baseUrl}/api/${relative}`;
return signAuthorizedEvidenceLink(`${baseUrl}/api/${relative}`);
}
/**
+13 -2
View File
@@ -1,3 +1,4 @@
import { validateMedia } from "./validate-media";
import { BadRequestException, Injectable, Logger } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { Model, Types } from "mongoose";
@@ -106,7 +107,7 @@ export class MediaPolicyService {
kind: MediaKind,
): Promise<void> {
const limits = await this.clientService.getMediaLimits(clientId, kind);
const violation = this.checkLimits(file, limits, kind);
const violation = this.checkLimits(file, limits, kind) ?? await this.contentViolation(file, kind);
if (!violation) return;
await this.tryDelete(file?.path);
@@ -133,7 +134,7 @@ export class MediaPolicyService {
const kind = fieldKindMap[field];
if (!kind) continue;
const limits = await getLimits(kind);
const violation = this.checkLimits(file, limits, kind, field);
const violation = this.checkLimits(file, limits, kind, field) ?? await this.contentViolation(file, kind);
if (!violation) continue;
// The request is being rejected — clean up all uploaded files so we
@@ -143,6 +144,16 @@ export class MediaPolicyService {
}
}
private async contentViolation(file: NonNullable<UploadedFileLike>, kind: MediaKind) {
try {
if (!file.path) throw new Error('Missing file');
await validateMedia(file.path, kind);
return null;
} catch {
return {code: 'MEDIA_CONTENT_INVALID', kind, message: 'محتوای فایل قابل خواندن نیست یا با نوع مدرک مطابقت ندارد. فایل سالم و مناسب را دوباره انتخاب کنید.'};
}
}
private checkLimits(
file: NonNullable<UploadedFileLike>,
{ minBytes, maxBytes }: MediaLimits,
+68
View File
@@ -0,0 +1,68 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { mkdtemp, writeFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { validateMedia } from "./validate-media";
describe("uploaded media content", () => {
it("rejects text spoofed as mp4 and accepts valid document PDFs", async () => {
const dir = await mkdtemp(join(tmpdir(), "media-test-"));
try {
const path = join(dir, "spoof.mp4");
await writeFile(path, "This is not a video.");
await expect(validateMedia(path, "video")).rejects.toThrow();
const pdf = join(dir, "document.pdf");
await writeFile(pdf, "%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF");
await expect(validateMedia(pdf, "image")).resolves.toBeUndefined();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
});
it("accepts real images, videos and audio but rejects a still image posing as a video", async () => {
const dir = await mkdtemp(join(tmpdir(), "media-content-"));
const run = promisify(execFile);
try {
const image = join(dir, "photo.png"),
video = join(dir, "clip.mp4"),
audio = join(dir, "voice.wav");
await run("ffmpeg", [
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=s=32x32",
"-frames:v",
"1",
image,
]);
await run("ffmpeg", [
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=s=32x32:d=0.2",
video,
]);
await run("ffmpeg", [
"-v",
"error",
"-f",
"lavfi",
"-i",
"sine=duration=0.2",
audio,
]);
await expect(validateMedia(image, "image")).resolves.toBeUndefined();
await expect(validateMedia(video, "video")).resolves.toBeUndefined();
await expect(validateMedia(audio, "voice")).resolves.toBeUndefined();
await expect(validateMedia(image, "video")).rejects.toThrow();
await expect(validateMedia(video, "image")).rejects.toThrow();
await expect(validateMedia(image, "voice")).rejects.toThrow();
} finally {
await rm(dir, { recursive: true, force: true });
}
});
+76
View File
@@ -0,0 +1,76 @@
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { readFile } from "node:fs/promises";
import type { MediaKind } from "src/client/client.service";
const run = promisify(execFile);
/** Inspect bytes/streams, never the user-controlled filename or Content-Type. */
export async function validateMedia(
path: string,
kind: MediaKind,
): Promise<void> {
if (kind === "image" || kind === "chassisNumber" || kind === "carPlate") {
const bytes = await readFile(path);
// Documents also accept PDFs. Require both the header and end marker.
if (bytes.subarray(0, 5).toString() === "%PDF-") {
if (!bytes.subarray(-2048).includes(Buffer.from("%%EOF")))
throw new Error("Invalid PDF");
return;
}
}
const { stdout } = await run(
"ffprobe",
[
"-v",
"error",
"-protocol_whitelist",
"file,pipe",
"-show_streams",
"-show_format",
"-of",
"json",
path,
],
{ timeout: 15000, maxBuffer: 1024 * 1024 },
);
const metadata = JSON.parse(stdout);
const imageFormat = String(metadata.format?.format_name || "")
.split(",")
.some((f: string) =>
/^(?:image2|image2pipe|.*_pipe|gif|apng|ico|heif)$/.test(f),
);
if (
(kind === "video" && imageFormat) ||
((kind === "image" || kind === "chassisNumber" || kind === "carPlate") &&
!imageFormat)
)
throw new Error("Wrong media container");
const streams = metadata.streams as Array<{
codec_type?: string;
width?: number;
height?: number;
}>;
const type = kind === "voice" ? "audio" : "video";
if (!streams?.some((s) => s.codec_type === type))
throw new Error("Missing media stream");
if (type === "video" && !streams.some((s) => s.width > 0 && s.height > 0))
throw new Error("Invalid dimensions");
await run(
"ffmpeg",
[
"-v",
"error",
"-protocol_whitelist",
"file,pipe",
"-nostdin",
"-i",
path,
"-map",
`0:${type === "audio" ? "a" : "v"}:0`,
...(type === "audio" ? ["-t", "0.1"] : ["-frames:v", "1"]),
"-f",
"null",
"-",
],
{ timeout: 15000, maxBuffer: 1024 * 1024 },
);
}
@@ -234,9 +234,9 @@ describe("V6 call-center workflow", () => {
Object.assign(body, {
accidentDate: "1405/08/18",
accidentTime: "12:00",
weatherCondition: 1,
roadCondition: 1,
lightCondition: 1,
weatherCondition: "صاف",
roadCondition: "خشک",
lightCondition: "روز",
});
await service.addDescriptionV2(id, body, first);
if (type === Kind.THIRD_PARTY) {
@@ -33,7 +33,7 @@ describe("car-body coverage when the accident date is collected after inquiry",
it("reselects and stores the earlier renewal for the supplied accident date", async () => {
const { service, party, inquiry } = setup("1401/01/02", "1402/01/02");
inquiry.mockResolvedValue({
source: "ESG_CAR_BODY_INQUIRY",
source: "FANAVARAN_CAR_BODY_INQUIRY",
mapped: {
policyId: 1,
StartDate: "1400/01/01",
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { extname } from "node:path";
import {
BadRequestException,
@@ -382,7 +383,7 @@ export class FileReviewerBlameV4Controller {
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}`);
@@ -1,3 +1,4 @@
import { randomUUID } from "node:crypto";
import { extname } from "node:path";
import {
Body,
@@ -380,7 +381,7 @@ export class FileReviewerBlameV5Controller {
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}`);
@@ -236,7 +236,7 @@ export class InquiryRefreshService {
} else {
await this.waitForRateLimit();
try {
const inquiry = await this.sandHubService.getTejaratBlockInquiry(
const inquiry = await this.sandHubService.getCarByPlateInquiry(
{
plate: {
...plate,
@@ -393,18 +393,6 @@ export class RegistrarBlameMirrorController {
@CurrentUser() registrar: any,
@UploadedFile() sign: Express.Multer.File,
) {
// Guard: accident fields must be filled before signing to prevent the
// double-sign bug where add-accident-fields re-enters WAITING_FOR_SIGNATURES.
const requestData = await this.requestManagementService.getBlameRequestV2(
requestId,
registrar,
);
if (!(requestData?.expert?.decision as any)?.fields?.accidentWay) {
throw new BadRequestException(
"Accident fields (accidentWay, accidentReason, accidentType) must be submitted via add-accident-fields before signing.",
);
}
await this.mediaPolicyService.assertForBlame(sign, requestId, "image");
const partyRole =
body?.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST;
@@ -50,7 +50,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
it("does not fall back from the current plate for third-party insurance", async () => {
const service = Object.create(RequestManagementService.prototype) as any;
service.sandHubService = {
getTejaratBlockInquiry: jest
getCarByPlateInquiry: jest
.fn()
.mockResolvedValueOnce({ raw: {}, mapped: {} })
.mockResolvedValueOnce({
@@ -67,10 +67,10 @@ describe("RequestManagementService policyholder inquiry routing", () => {
"بیمه‌نامه معتبر و فعالی مطابق مشخصات خودرو و کد ملی واردشده یافت نشد.",
);
expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledTimes(
expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledTimes(
1,
);
expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledWith(
expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledWith(
expect.objectContaining({
plate: currentPlate,
nationalCodeOfInsurer: "0022222222",
@@ -82,7 +82,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
it("contextualizes the mapped ESG not-found error for third-party insurance", async () => {
const service = Object.create(RequestManagementService.prototype) as any;
service.sandHubService = {
getTejaratBlockInquiry: jest.fn().mockResolvedValue({
getCarByPlateInquiry: jest.fn().mockResolvedValue({
raw: {
success: false,
error: {
@@ -102,7 +102,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
await expect(service.getThirdPartyPlateInquiry(submission)).rejects.toThrow(
"بیمه‌نامه شخص ثالثی مطابق پلاک و کد ملی واردشده یافت نشد.",
);
expect(service.sandHubService.getTejaratBlockInquiry).toHaveBeenCalledTimes(
expect(service.sandHubService.getCarByPlateInquiry).toHaveBeenCalledTimes(
1,
);
});
@@ -177,7 +177,7 @@ describe("RequestManagementService policyholder inquiry routing", () => {
});
service.sandHubService = {
getCarBodyInquiry: jest.fn().mockResolvedValue({
source: "ESG_CAR_BODY_VIN_INQUIRY",
source: "FANAVARAN_CAR_BODY_VIN_INQUIRY",
raw: { policyId: 123 },
mapped: {
policyNumber: "BODY-1",
@@ -1,3 +1,4 @@
import { WeatherCondition, RoadCondition, LightCondition } from "src/Types&Enums/blame-request-management/accident-conditions.enum";
import { UserClaimBranchService, userClaimBranchContext, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import { normalizeAccidentLocation } from "./accident-location";
import {
@@ -215,6 +216,13 @@ export class RequestManagementService {
}
/** Keep eligibility rejections distinct from an unavailable CAR_BODY provider. */
private assertAccidentConditions(body: {weatherCondition?: unknown; roadCondition?: unknown; lightCondition?: unknown}): void {
for (const [value, choices] of [[body.weatherCondition, WeatherCondition], [body.roadCondition, RoadCondition], [body.lightCondition, LightCondition]] as const) {
if (value != null && !Object.values(choices).includes(value as never))
throw new BadRequestException("شرایط آب‌وهوا، راه یا روشنایی حادثه معتبر نیست. گزینه‌های فرم را دوباره انتخاب کنید.");
}
}
private assertCarBodyDescriptionMinimum(
requestType: BlameRequestType | string | undefined,
description: unknown,
@@ -428,7 +436,7 @@ export class RequestManagementService {
currentPlate: submission.vehicle?.currentPlate ?? submission.dto.plate,
vin: submission.vehicle?.vin,
query: (plate) =>
this.sandHubService.getTejaratBlockInquiry(
this.sandHubService.getCarByPlateInquiry(
{
plate: plate as any,
nationalCodeOfInsurer: subjects.thirdPartyPolicyNationalCode,
@@ -2302,7 +2310,7 @@ export class RequestManagementService {
* 2. Personal identity inquiry (same as the plate path)
*
* The inquiry result is mapped through the same `mapEsgPolicyByPlateToOldFormat`
* normaliser used by `getTejaratBlockInquiry`, so all downstream party/vehicle
* normaliser used by `getCarByPlateInquiry`, so all downstream party/vehicle
* /insurance field assignments are identical.
*/
async initialFormVinV2(
@@ -2910,6 +2918,7 @@ export class RequestManagementService {
);
this.assertCarBodyDescriptionMinimum(req.type, body.desc);
this.assertAccidentConditions(body as DescriptionDto);
// Set userId for party if not already set (important for second party)
if (!party.person) party.person = {} as any;
@@ -5075,6 +5084,7 @@ export class RequestManagementService {
formData?.expertDescription?.desc,
);
this.assertAccidentConditions(formData?.expertDescription ?? {});
const firstPartyUserId = await this.getOrCreateUserByPhoneNumber(
formData.firstPartyPhoneNumber,
);
@@ -5399,6 +5409,7 @@ export class RequestManagementService {
throw new BadRequestException("expertDescription.desc is required.");
}
this.assertAccidentConditions(formData?.expertDescription ?? {});
const firstPartyUserId = await this.getOrCreateUserByPhoneNumber(
formData.firstPartyPhoneNumber,
);
@@ -5846,7 +5857,7 @@ export class RequestManagementService {
const req = await this.blameRequestDbService.findById(requestId);
if (!req) throw new NotFoundException("Request not found");
if (
!req.expertInitiated ||
(!req.expertInitiated && !req.registrarInitiated) ||
req.creationMethod !== CreationMethod.IN_PERSON
) {
throw new BadRequestException(
@@ -5889,7 +5900,7 @@ export class RequestManagementService {
const signatureData = {
fileId: String((signDoc as any)._id),
fileName: signFile.filename,
fileUrl: signFile.path,
fileUrl: buildFileLink(signFile.path),
};
const updatePayload: any = {
$set: {
@@ -6578,7 +6589,7 @@ export class RequestManagementService {
const signatureData = {
fileId: String((signDoc as any)._id),
fileName: signFile.filename,
fileUrl: signFile.path,
fileUrl: buildFileLink(signFile.path),
};
const confirmationPayload = {
@@ -7608,7 +7619,7 @@ export class RequestManagementService {
/**
* VIN variant of `runInquiriesV3`.
* Identical flow, but calls the two-factor `getCarByChassisInquiry` instead of
* `getTejaratBlockInquiry` for the primary policy lookup.
* `getCarByPlateInquiry` for the primary policy lookup.
*/
async runInquiriesVinV3(
requestId: string,
@@ -7751,7 +7762,7 @@ export class RequestManagementService {
/**
* VIN variant of `runPartyInquiriesV3Internal`.
* Calls `getCarByChassisInquiry` (ESG two-factor chassis lookup) instead of
* `getTejaratBlockInquiry` (plate-based). All other inquiries (personal,
* `getCarByPlateInquiry` (plate-based). All other inquiries (personal,
* driving licence, car-body for CAR_BODY) are unchanged.
*/
private async runPartyInquiriesVinV3Internal(
@@ -8203,7 +8214,7 @@ export class RequestManagementService {
const signatureData = {
fileId: String((signDoc as any)._id),
fileName: signFile.filename,
fileUrl: signFile.path,
fileUrl: buildFileLink(signFile.path),
};
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
@@ -8700,6 +8711,7 @@ export class RequestManagementService {
const role = this.resolvePartyRoleV3(req, partyRole);
this.assertBlameV3PartyDetailPhase(req, role);
this.assertCarBodyDescriptionMinimum(req.type, body.desc);
this.assertAccidentConditions(body as DescriptionDto);
// accidentDate and accidentTime are only required for the first (guilty)
// party — the second (damaged) party can skip them.
@@ -8724,8 +8736,6 @@ export class RequestManagementService {
const idx = this.getPartyIndex(req, role);
if (idx === -1) throw new BadRequestException(`${role} party not found`);
this.assertCarBodyDescriptionMinimum(req.type, body.desc);
const party = req.parties[idx];
if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) {
await this.validateCarBodyAccidentCoverage(party, body.accidentDate);
@@ -1,8 +1,34 @@
import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper";
import { mapFanavaranCarBodyPolicyToInquiry } from "./fanavaran-car-body-inquiry.mapper";
describe("mapFanavaranCarBodyPolicyToInquiry", () => {
it("does not assume an insurer when neither the response nor the source identifies one", () => {
expect(mapFanavaranCarBodyPolicyToInquiry({})).toMatchObject({
companyId: null,
CompanyCode: null,
CompanyName: null,
});
});
it("uses the configured source without overwriting an explicit returned insurer", () => {
const source = { companyId: "7", companyName: "بیمه معلم" };
expect(mapFanavaranCarBodyPolicyToInquiry({}, source)).toMatchObject({
companyId: "7",
CompanyCode: "7",
CompanyName: "بیمه معلم",
});
expect(
mapFanavaranCarBodyPolicyToInquiry(
{ policy: { CompanyId: "8", CompanyName: "بیمه پارسیان" } },
source,
),
).toMatchObject({
CompanyCode: "8",
CompanyName: "بیمه پارسیان",
});
});
describe("mapEsgCarBodyPolicyToInquiry", () => {
it("maps the processed CAR_BODY lookup while retaining useful policy, customer, and vehicle fields", () => {
const mapped = mapEsgCarBodyPolicyToInquiry({
const mapped = mapFanavaranCarBodyPolicyToInquiry({
product: "car-body",
insuranceLine: "CAR_BODY",
insuranceLineId: 4,
@@ -1,11 +1,12 @@
/**
* Converts the processed CAR_BODY policy returned by the ESG/Fanavaran lookup
* Converts the processed CAR_BODY policy returned by the Fanavaran lookup
* into the same mapped contract used by the existing car-body inquiry flow.
* The original response is deliberately kept separately as `raw` by the
* caller, so newly exposed provider fields are never discarded.
*/
export function mapEsgCarBodyPolicyToInquiry(
export function mapFanavaranCarBodyPolicyToInquiry(
response: Record<string, any>,
sourceCompany?: { companyId: string; companyName: string },
): Record<string, unknown> {
const policy = response.policy ?? {};
const customer = response.customer ?? {};
@@ -27,9 +28,9 @@ export function mapEsgCarBodyPolicyToInquiry(
insuranceLineId: response.insuranceLineId ?? 4,
// Provider responses do not currently include an insurer company identity.
companyId: policy.CompanyId ?? null,
CompanyCode: policy.CompanyId ?? "8",
CompanyName: policy.CompanyName ?? "بیمه پارسیان",
companyId: policy.CompanyId ?? sourceCompany?.companyId ?? null,
CompanyCode: policy.CompanyId ?? sourceCompany?.companyId ?? null,
CompanyName: policy.CompanyName ?? sourceCompany?.companyName ?? null,
// The lookup's customer is the policyholder/owner, not the insurer.
insurerName: null,
+316
View File
@@ -0,0 +1,316 @@
import {
ForbiddenException,
ServiceUnavailableException,
UnauthorizedException,
} from "@nestjs/common";
import { of, throwError } from "rxjs";
import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config";
import { SandHubService } from "./sand-hub.service";
const keys = [
"CLIENT_ID",
"FANAVARAN_CLIENT",
"ESG_URL",
"ESG_USERNAME",
"ESG_PASSWORD",
"TEJARAT_INQUIRY_BASE_URL",
"TEJARAT_INQUIRY_EMAIL",
"TEJARAT_INQUIRY_PASSWORD",
"SANHUB_URL_LOGIN",
];
const before = Object.fromEntries(keys.map((key) => [key, process.env[key]]));
const detail: any = {
nationalCodeOfInsurer: "0012345678",
plate: {
leftDigits: "12",
centerAlphabet: "ب",
centerDigits: "345",
ir: "67",
},
};
function fixture(code = "7") {
process.env.CLIENT_ID = code;
process.env.ESG_URL = "http://esg.example.test/api/";
process.env.ESG_USERNAME = "fixture-user";
process.env.ESG_PASSWORD = "fixture-password";
process.env.TEJARAT_INQUIRY_BASE_URL = "http://retired.example.test";
process.env.TEJARAT_INQUIRY_EMAIL = "retired-fixture";
process.env.TEJARAT_INQUIRY_PASSWORD = "retired-fixture";
process.env.SANHUB_URL_LOGIN = "http://retired.example.test/user/login";
delete process.env.FANAVARAN_CLIENT;
const http = {
post: jest.fn((url: string) => {
if (url.endsWith("/auth/login"))
return of({ data: { accessToken: "fixture-token", expiresIn: 900 } });
if (url.endsWith("/inquiry/person"))
return of({
data: {
success: true,
data: { Name: "نمونه", Family: "آزمایشی", Nin: "0012345678" },
},
});
if (url.endsWith("/inquiry/sheba"))
return of({
data: { success: true, data: { ReturnValue: true, HasError: false } },
});
if (/\/inquiry\/carBy(Plate|Chassis)$/.test(url))
return of({
data: {
success: true,
data: {
CmpCod: code,
CmpNam: "بیمه نمونه",
PrntCmpDocNo: "POLICY-TEST",
VIN: "NAAR03HFFRDE07024",
},
},
});
throw new Error("Unexpected inquiry provider URL");
}),
};
const settings = {
isInquiryLive: jest.fn().mockResolvedValue(true),
getMockCompanyContext: jest
.fn()
.mockResolvedValue({ companyId: code, companyName: "بیمه نمونه" }),
};
const lookups = {
findLastProcessedCarPolicy: jest.fn().mockResolvedValue({
policy: { CINumber: "BODY-POLICY" },
vehicle: { VIN: "NAAR03HFFRDE07024" },
customer: {},
}),
};
const offline = { findPlateInquiry: jest.fn().mockResolvedValue(null) };
const service = new SandHubService(
http as any,
settings as any,
{ normalizePlateText: (text: string) => text } as any,
offline as any,
lookups as any,
);
return { service, http, settings, lookups, offline };
}
afterEach(() => {
for (const key of keys) {
if (before[key] === undefined) delete process.env[key];
else process.env[key] = before[key];
}
});
describe("tenant-independent ESG routing and Fanavaran car-body policies", () => {
it.each(["7", "8", "15"])(
"uses ESG for plate/VIN, person, Sheba and old mapped callers (CLIENT_ID=%s)",
async (code) => {
const { service, http, offline } = fixture(code);
const plate = await service.getCarByPlateInquiry(detail, {
enforceDeploymentClientMatch: true,
});
const vin = await service.getCarByChassisInquiry({
nationalCode: "0012345678",
chassisNo: "NAAR03HFFRDE07024",
});
const person = await service.getPersonalInquiry("0012345678", "13770101");
const sheba = await service.getShebaValidation(
"0012345678",
"IR000000000000000000000000",
);
const legacyMapped = await service.getSandHubResponse(detail);
expect(plate.mapped.CompanyCode).toBe(code);
expect(vin.mapped.PrntPlcyCmpDocNo).toBe("POLICY-TEST");
expect(person.firstName).toBe("نمونه");
expect(sheba.ReturnValue).toBe(true);
expect(legacyMapped.PrntPlcyCmpDocNo).toBe("POLICY-TEST");
expect(
http.post.mock.calls.filter(([url]) => url.endsWith("/auth/login")),
).toHaveLength(1);
expect(http.post).toHaveBeenCalledWith(
"http://esg.example.test/api/inquiry/person",
{
nationalCode: "0012345678",
birthDate: "1377-01-01",
dateHasPostfix: 0,
},
expect.objectContaining({
headers: expect.objectContaining({
Authorization: "Bearer fixture-token",
}),
}),
);
expect(http.post).toHaveBeenCalledWith(
"http://esg.example.test/api/inquiry/carByPlate",
{
nationalCode: "0012345678",
plk1: "12",
plk2: "ب",
plk3: "345",
plksrl: "67",
},
expect.any(Object),
);
expect(
http.post.mock.calls.every(([url]) =>
url.startsWith("http://esg.example.test/api/"),
),
).toBe(true);
expect(offline.findPlateInquiry).not.toHaveBeenCalled();
},
);
it("keeps disabled inquiry mocks independent of ESG credentials", async () => {
const { service, http, settings } = fixture();
settings.isInquiryLive.mockResolvedValue(false);
delete process.env.ESG_URL;
delete process.env.ESG_USERNAME;
delete process.env.ESG_PASSWORD;
expect(
(await service.getCarByPlateInquiry(detail)).mapped.CompanyCode,
).toBe("7");
expect((await service.getPersonalInquiry("0012345678", 13770101)).nin).toBe(
"0012345678",
);
expect(
(await service.getShebaValidation("0012345678", "IR00")).ReturnValue,
).toBe(true);
expect((await service.getCarBodyInquiry(detail)).mapped.CompanyCode).toBe(
7,
);
expect(http.post).not.toHaveBeenCalled();
});
it.each(
["7", "8", "15"].flatMap((code) =>
[detail.plate, "NAAR03HFFRDE07024"].map((plate) => ({ code, plate })),
),
)(
"uses tenant Fanavaran for car-body without legacy login ($code, $plate)",
async ({ code, plate }) => {
const { service, http, lookups } = fixture(code);
expect(resolveFanavaranClientKey()).toBe(
code === "7" ? "moallem" : code === "8" ? "parsian" : "tejaratno",
);
const result = await service.getCarBodyInquiry({
...detail,
plate,
accidentDate: "1405/08/01",
});
expect(lookups.findLastProcessedCarPolicy).toHaveBeenCalledWith(
"car-body",
{
nationalCode: "0012345678",
accidentDate: "1405/08/01",
...(typeof plate === "string"
? { vin: plate }
: {
plaqueLeft: "12",
plaqueLetter: "ب",
plaqueRight: "345",
plaqueSerial: "67",
}),
},
);
expect(result.source).toBe(
typeof plate === "string"
? "FANAVARAN_CAR_BODY_VIN_INQUIRY"
: "FANAVARAN_CAR_BODY_INQUIRY",
);
expect(result.mapped.CompanyCode).toBe(code);
expect(result.mapped.CompanyName).toBe("بیمه نمونه");
expect(http.post).not.toHaveBeenCalled();
},
);
it("preserves an explicit Fanavaran profile and rejects a mismatched car-body source", async () => {
const { service } = fixture();
process.env.FANAVARAN_CLIENT = "parsian";
expect(resolveFanavaranClientKey()).toBe("parsian");
await expect(service.getCarBodyInquiry(detail)).rejects.toThrow(
ForbiddenException,
);
});
it("does not label another insurer's body policy as Moalem", async () => {
const { service, lookups } = fixture();
lookups.findLastProcessedCarPolicy.mockResolvedValue({
policy: { CompanyId: "8" },
customer: {},
vehicle: {},
});
await expect(service.getCarBodyInquiry(detail)).rejects.toThrow(
ForbiddenException,
);
});
it("fails locally for missing ESG configuration, without trying the old endpoint", async () => {
const { service, http } = fixture();
delete process.env.ESG_URL;
await expect(service.getCarByPlateInquiry(detail)).rejects.toThrow(
ServiceUnavailableException,
);
expect(http.post).not.toHaveBeenCalled();
process.env.ESG_URL = "http://esg.example.test/api";
delete process.env.ESG_PASSWORD;
await expect(service.getCarByPlateInquiry(detail)).rejects.toThrow(
UnauthorizedException,
);
expect(http.post).not.toHaveBeenCalled();
});
it("refreshes an ESG token once on 401 without switching providers", async () => {
const { service, http } = fixture();
const normal = http.post.getMockImplementation()!;
let attempts = 0,
tokens = 0;
http.post.mockImplementation((url: string) => {
if (url.endsWith("/auth/login"))
return of({
data: { accessToken: `fixture-token-${++tokens}`, expiresIn: 900 },
});
if (url.endsWith("/inquiry/person") && attempts++ === 0)
return throwError(() => ({
response: { status: 401, data: { message: "expired" } },
}));
return normal(url);
});
expect(
(await service.getPersonalInquiry("0012345678", "13770101")).firstName,
).toBe("نمونه");
expect(tokens).toBe(2);
expect(
http.post.mock.calls.every(([url]) =>
url.startsWith("http://esg.example.test/api/"),
),
).toBe(true);
});
it("preserves optional licence and ownership behavior until ESG has equivalent contracts", async () => {
const { service, http, settings } = fixture();
settings.isInquiryLive.mockResolvedValue(false);
expect(
(await service.getDrivingLicenseInfo("0012345678", "123")).IsSucceed,
).toBe(true);
expect(
(await service.getCarOwnershipInfo(detail.plate, "0012345678")).data
.IsSuccess,
).toBe(true);
expect(http.post).not.toHaveBeenCalled();
settings.isInquiryLive.mockResolvedValue(true);
const optionalHub = jest.spyOn(service as any, "makeSandHubRequest");
optionalHub.mockResolvedValueOnce({ data: { IsSucceed: true } });
await service.getDrivingLicenseInfo("0012345678", "123");
expect(optionalHub).toHaveBeenCalledWith(
expect.stringContaining("/driver-license-check"),
{ nationalCode: "0012345678", driverLicenseNumber: "123" },
"drivingLicense",
undefined,
);
optionalHub.mockResolvedValueOnce({ data: { IsSuccess: true } });
await service.getCarOwnershipInfo(detail.plate, "0012345678");
expect(optionalHub).toHaveBeenLastCalledWith(
expect.stringContaining("/ownership"),
expect.objectContaining({ nationalCode: "0012345678" }),
"carOwnership",
undefined,
);
});
});
+24 -53
View File
@@ -60,6 +60,7 @@ describe("SandHubService inquiry mocks", () => {
beforeEach(() => {
jest.clearAllMocks();
process.env.CLIENT_ID = "8";
process.env.ESG_URL = "http://esg.example.test";
delete process.env.FANAVARAN_CLIENT;
service = new SandHubService(
httpService as any,
@@ -77,7 +78,7 @@ describe("SandHubService inquiry mocks", () => {
});
it("keeps disabled-live third-party mock policy usable", async () => {
const result = await service.getTejaratBlockInquiry(userDetail, {
const result = await service.getCarByPlateInquiry(userDetail, {
enforceDeploymentClientMatch: true,
});
@@ -87,7 +88,7 @@ describe("SandHubService inquiry mocks", () => {
});
it("returns car-body mock without HTTP when carBodyPlate is off", async () => {
const result = await service.getTejaratCarBodyInquiry(userDetail);
const result = await service.getCarBodyInquiry(userDetail);
expect(httpService.post).not.toHaveBeenCalled();
expect(externalInquirySettings.isInquiryLive).toHaveBeenCalledWith(
@@ -107,7 +108,7 @@ describe("SandHubService inquiry mocks", () => {
expect(result.mapped.platePartThree).toBe(498);
});
it("uses the processed ESG CAR_BODY lookup and preserves it as raw data", async () => {
it("uses the processed Fanavaran CAR_BODY lookup and preserves it as raw data", async () => {
process.env.CLIENT_ID = "8";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({
@@ -140,7 +141,7 @@ describe("SandHubService inquiry mocks", () => {
plaqueSerial: "60",
},
);
expect(result.source).toBe("ESG_CAR_BODY_INQUIRY");
expect(result.source).toBe("FANAVARAN_CAR_BODY_INQUIRY");
expect(result.raw.policyId).toBe(15292336);
expect(result.mapped.policyNumber).toBe("70019846985");
expect(httpService.post).not.toHaveBeenCalled();
@@ -170,7 +171,7 @@ describe("SandHubService inquiry mocks", () => {
data: { PrntCmpDocNo: "REAL-ESG-POLICY" },
});
const result = await service.getTejaratBlockInquiry(userDetail);
const result = await service.getCarByPlateInquiry(userDetail);
expect(esg).toHaveBeenCalled();
expect(result.raw).not.toEqual({ mocked: true });
@@ -185,7 +186,7 @@ describe("SandHubService inquiry mocks", () => {
data: { PrntCmpDocNo: "ESG-PLATE-POLICY" },
});
await service.getTejaratBlockInquiry(userDetail);
await service.getCarByPlateInquiry(userDetail);
expect(esg).toHaveBeenCalledWith(
expect.stringMatching(/\/inquiry\/carByPlate$/),
@@ -236,7 +237,7 @@ describe("SandHubService inquiry mocks", () => {
},
});
const result = await service.getTejaratBlockInquiry(userDetail, {
const result = await service.getCarByPlateInquiry(userDetail, {
enforceDeploymentClientMatch: true,
});
@@ -271,14 +272,14 @@ describe("SandHubService inquiry mocks", () => {
it("rejects a guilty third-party policy issued by another insurer", async () => {
process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service as any, "makeTejaratRequest").mockResolvedValue({
jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({
CompanyCode: "8",
CompanyName: "بیمه پارسیان",
PrntPlcyCmpDocNo: "OTHER-INSURER-POLICY",
});
await expect(
service.getTejaratBlockInquiry(userDetail, {
service.getCarByPlateInquiry(userDetail, {
enforceDeploymentClientMatch: true,
} as any),
).rejects.toBeInstanceOf(ForbiddenException);
@@ -287,12 +288,12 @@ describe("SandHubService inquiry mocks", () => {
it("allows an unchecked third-party policy from another insurer", async () => {
process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service as any, "makeTejaratRequest").mockResolvedValue({
jest.spyOn(service as any, "makeEsgRequest").mockResolvedValue({
CompanyCode: "8",
CompanyName: "بیمه پارسیان",
});
await expect(service.getTejaratBlockInquiry(userDetail)).resolves.toEqual(
await expect(service.getCarByPlateInquiry(userDetail)).resolves.toEqual(
expect.objectContaining({
mapped: expect.objectContaining({ CompanyCode: "8" }),
}),
@@ -344,10 +345,7 @@ describe("SandHubService inquiry mocks", () => {
it("does not accept a policy when CLIENT_ID is not configured", async () => {
delete process.env.CLIENT_ID;
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({
raw: { data: { companyId: "15" } },
mapped: { companyId: "15", CompanyCode: "15" },
});
await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf(
ServiceUnavailableException,
@@ -372,10 +370,8 @@ describe("SandHubService inquiry mocks", () => {
it("rejects a CAR_BODY policy from another insurer on the Tejarat lookup route", async () => {
process.env.CLIENT_ID = "15";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
jest.spyOn(service, "getTejaratCarBodyInquiry").mockResolvedValue({
raw: { data: { companyId: "8" } },
mapped: { companyId: "8", CompanyCode: "8" },
});
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({ policy: { CompanyId: "8" }, customer: {}, vehicle: {} });
await expect(service.getCarBodyInquiry(userDetail)).rejects.toBeInstanceOf(
ForbiddenException,
@@ -393,7 +389,7 @@ describe("SandHubService inquiry mocks", () => {
await expect(service.getCarBodyInquiry(userDetail)).resolves.toEqual(
expect.objectContaining({
source: "ESG_CAR_BODY_INQUIRY",
source: "FANAVARAN_CAR_BODY_INQUIRY",
mapped: expect.objectContaining({ companyId: 15 }),
}),
);
@@ -408,9 +404,7 @@ describe("SandHubService inquiry mocks", () => {
customer: {},
vehicle: {},
});
const tejarat = jest
.spyOn(service, "getTejaratCarBodyInquiry")
.mockResolvedValue({ raw: { mocked: true }, mapped: {} });
const result = await service.getCarBodyInquiry(userDetail);
@@ -418,22 +412,21 @@ describe("SandHubService inquiry mocks", () => {
"car-body",
expect.objectContaining({ nationalCode: "1234567890" }),
);
expect(tejarat).not.toHaveBeenCalled();
expect(result.raw).not.toEqual({ mocked: true });
});
it("keeps ESG car-body inquiry in mock mode when the per-client toggle is off", async () => {
it("keeps Fanavaran car-body inquiry in mock mode when the per-client toggle is off", async () => {
process.env.CLIENT_ID = "8";
const result = await service.getCarBodyInquiry(userDetail);
expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled();
expect(result.source).toBe("ESG_CAR_BODY_INQUIRY");
expect(result.source).toBe("FANAVARAN_CAR_BODY_INQUIRY");
expect(result.raw?.isSuccess).toBe(true);
expect(httpService.post).not.toHaveBeenCalled();
});
it("uses the VIN lookup and VIN audit source for ESG car-body VIN inquiries", async () => {
it("uses the VIN lookup and VIN audit source for Fanavaran car-body VIN inquiries", async () => {
process.env.CLIENT_ID = "8";
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({
@@ -451,7 +444,7 @@ describe("SandHubService inquiry mocks", () => {
"car-body",
{ nationalCode: "1234567890", vin: "NAAR03HFFRDE07024" },
);
expect(result.source).toBe("ESG_CAR_BODY_VIN_INQUIRY");
expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY");
});
it("uses the tenant Fanavaran VIN lookup for non-Parsian car-body inquiries", async () => {
@@ -463,7 +456,6 @@ describe("SandHubService inquiry mocks", () => {
customer: {},
vehicle: { VIN: "NAAR03HFFRDE07024" },
});
const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry");
const result = await service.getCarBodyInquiry({
nationalCodeOfInsurer: "0012345678",
@@ -474,47 +466,26 @@ describe("SandHubService inquiry mocks", () => {
"car-body",
{ nationalCode: "0012345678", vin: "NAAR03HFFRDE07024" },
);
expect(tejarat).not.toHaveBeenCalled();
expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY");
expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY");
});
it("returns a VIN-shaped car-body mock without invoking a plate adapter", async () => {
process.env.CLIENT_ID = "15";
process.env.FANAVARAN_CLIENT = "tejaratno";
const tejarat = jest.spyOn(service, "getTejaratCarBodyInquiry");
const result = await service.getCarBodyInquiry({
nationalCodeOfInsurer: "0012345678",
plate: "NAAR03HFFRDE07024",
});
expect(tejarat).not.toHaveBeenCalled();
expect(lookupsService.findLastProcessedCarPolicy).not.toHaveBeenCalled();
expect(result.source).toBe("TEJARAT_CAR_BODY_VIN_INQUIRY");
expect(result.source).toBe("FANAVARAN_CAR_BODY_VIN_INQUIRY");
expect(result.mapped.VinNumberField).toBe("NAAR03HFFRDE07024");
expect(result.mapped.insurerNationalCode).toBe("0012345678");
});
it("uses car-body mock shape in Tejarat helper when inquiry is off", async () => {
const raw = await (service as any).makeTejaratRequest(
"http://example/block-inquiry-tejarat/badane",
{
part1: 16,
part2: 12,
part3: 498,
part4: 60,
nationalCode: "1234567890",
},
"carBodyPlate",
);
expect(httpService.post).not.toHaveBeenCalled();
expect(raw?.data?.printNumber).toBe("1405/1143-70591/220/1/0");
expect(raw?.data?.companyName).toBe("بیمه پارسیان");
});
it("returns third-party plate mock for block inquiry when inquiry is off", async () => {
const result = await service.getTejaratBlockInquiry(userDetail);
const result = await service.getCarByPlateInquiry(userDetail);
expect(httpService.post).not.toHaveBeenCalled();
expect(result.mapped?.CompanyName).toBe("بیمه پارسیان");
+125 -616
View File
@@ -25,13 +25,12 @@ import {
type InquiryErrorContext,
} from "src/common/utils/inquiry-error";
import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config";
import { jalaliToGregorianDate } from "src/helpers/date-jalali";
import { LookupsService } from "src/lookups/lookups.service";
import { OfflineInquiryService } from "src/offline-inquiry/offline-inquiry.service";
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto";
import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper";
import { mapFanavaranCarBodyPolicyToInquiry } from "./fanavaran-car-body-inquiry.mapper";
type CarBodyInquiryDetail = Omit<SandHubDetailDto, "plate"> & {
plate: Plates | string;
@@ -43,12 +42,7 @@ export class SandHubService {
private readonly logger = new Logger(SandHubService.name);
private loginToken: string | null = null;
private tokenExpiry: Date | null = null;
// Tejarat inquiry auth (82.99.202.245:3027)
private tejaratAccessToken: string | null = null;
private tejaratTokenExpiry: Date | null = null;
// ESG inquiry auth (used for selected tenants, e.g. CLIENT_ID=8)
// ESG inquiry authentication shared by all deployment tenants.
private esgAccessToken: string | null = null;
private esgTokenExpiry: Date | null = null;
@@ -83,19 +77,6 @@ export class SandHubService {
);
}
private shouldUseEsgInquiryProvider(): boolean {
return String(process.env.CLIENT_ID ?? "") === "8";
}
/**
* The processed Fanavaran CAR_BODY lookup belongs only to the Parsian
* Fanavaran profile. Do not use the deployment-wide ESG selector here:
* `FANAVARAN_CLIENT=parsian` is valid even when CLIENT_ID is not 8.
*/
private shouldUseParsianCarBodyLookup(): boolean {
return resolveFanavaranClientKey() === "parsian";
}
private inquiryContext(type: ExternalInquiryType): InquiryErrorContext {
if (type === "vinChassis") return "thirdPartyVin";
return type;
@@ -155,25 +136,6 @@ export class SandHubService {
}
}
/**
* The processed Fanavaran CAR_BODY endpoint is a Parsian-only source and its
* response does not contain a reliable insurer company code. Treat the source
* itself as proof that the returned policy is Parsian.
*/
private assertParsianCarBodyLookupMatchesDeployment(): void {
const expectedClientCode = String(process.env.CLIENT_ID ?? "").trim();
if (!expectedClientCode) {
throw new ServiceUnavailableException(
"تنظیمات شرکت بیمه برای بررسی اعتبار بیمه‌نامه کامل نیست.",
);
}
if (expectedClientCode === "8") return;
throw new ForbiddenException(
"بیمه‌نامه یافت‌شده متعلق به شرکت بیمه این سامانه نیست.",
);
}
/** Fixed plate/insurance inquiry payload used everywhere we mock block-inquiry style APIs. */
private buildMockPlateInquiryRaw(
ctx: MockInquiryCompanyContext,
@@ -254,33 +216,7 @@ export class SandHubService {
};
}
/** Build {@link SandHubDetailDto} from Tejarat badane / block-inquiry request bodies. */
private tejaratPayloadToSandHubDetail(payload: {
nationalCode?: string | number;
part1?: string | number;
part2?: string | number;
part3?: string | number;
part4?: string | number;
leftTwoDigits?: string | number;
serialLetter?: string | number;
threeDigits?: string | number;
rightTwoDigits?: string | number;
}): SandHubDetailDto {
const nationalCode = String(payload.nationalCode ?? "");
return {
nationalCodeOfInsurer: nationalCode,
plate: {
leftDigits: Number(payload.part1 ?? payload.leftTwoDigits ?? 16),
centerAlphabet: this.plateNormalizer.normalizePlateText(
String(payload.part2 ?? payload.serialLetter ?? "12"),
),
centerDigits: Number(payload.part3 ?? payload.threeDigits ?? 498),
ir: Number(payload.part4 ?? payload.rightTwoDigits ?? 60),
nationalCode,
},
};
}
/** Mock shape retained for compatibility with stored car-body inquiry data. */
private buildMockCarBodyInquiryRaw(
userDetail: CarBodyInquiryDetail,
ctx: MockInquiryCompanyContext,
@@ -334,97 +270,6 @@ export class SandHubService {
};
}
private buildMockInquiryRaw(
inquiryType: ExternalInquiryType,
ctx: MockInquiryCompanyContext,
payload?: unknown,
userDetail?: SandHubDetailDto,
): Record<string, unknown> {
if (inquiryType === "carBodyPlate") {
const detail =
userDetail ??
this.tejaratPayloadToSandHubDetail(
(payload ?? {}) as Record<string, unknown>,
);
return this.buildMockCarBodyInquiryRaw(detail, ctx);
}
return this.buildMockPlateInquiryRaw(ctx);
}
/**
* Bodies returned from `makeSandHubRequest` in mock mode (same shape callers expect from real API).
*/
private buildMockSandHubResponseForUrl(
url: string,
payload?: unknown,
plateMock?: Record<string, unknown>,
): any {
const u = (url || "").toLowerCase();
if (u.includes("personal-inquiry")) {
const p = payload as { nationalCode?: string } | undefined;
const nin = typeof p?.nationalCode === "string" ? p.nationalCode : "-";
return {
message: "success",
data: {
firstName: "نام",
lastName: "خانوادگی",
fatherName: "-",
birthCertificateNumber: "-",
nin,
},
};
}
if (u.includes("driver-license-check")) {
return {
data: {
IsSucceed: true,
Message: "mock",
},
};
}
if (u.includes("ownership")) {
return {
data: {
IsSuccess: true,
},
};
}
if (u.includes("sheba")) {
return {
ReturnValue: true,
HasError: false,
Message: "mock-sheba-ok",
};
}
if (u.includes("badane")) {
return (
plateMock ??
this.buildMockCarBodyInquiryRaw(
this.tejaratPayloadToSandHubDetail(
(payload ?? {}) as Record<string, unknown>,
),
{
companyId: process.env.CLIENT_ID ?? "15",
companyName: process.env.CLIENT_NAME ?? "بیمه سامان",
},
)
);
}
if (u.includes("block-inquiry") || u.includes("tejarat")) {
return this.mapNewApiResponseToOldFormat(
plateMock ??
this.buildMockPlateInquiryRaw({
companyId: process.env.CLIENT_ID ?? "15",
companyName: process.env.CLIENT_NAME ?? "بیمه سامان",
}),
);
}
this.logger.warn(
`[MOCK] Unrecognized SandHub URL; returning generic OK: ${url}`,
);
return { data: {}, message: "mock-ok" };
}
private async getAccessToken(): Promise<string> {
if (this.loginToken && this.tokenExpiry && this.tokenExpiry > new Date()) {
return this.loginToken;
@@ -461,66 +306,24 @@ export class SandHubService {
}
}
private async getTejaratAccessToken(): Promise<string> {
if (
this.tejaratAccessToken &&
this.tejaratTokenExpiry &&
this.tejaratTokenExpiry > new Date()
) {
return this.tejaratAccessToken;
}
const baseUrl =
process.env.TEJARAT_INQUIRY_BASE_URL ?? "http://82.99.202.245:3027";
const email = process.env.TEJARAT_INQUIRY_EMAIL;
const password = process.env.TEJARAT_INQUIRY_PASSWORD;
if (!email || !password) {
throw new UnauthorizedException(
"اطلاعات اتصال به سرویس استعلام تجارت نو تنظیم نشده است.",
/** Only optional licence and legal-ownership checks still use their configured hub. */
private buildMockSandHubResponseForUrl(url: string): any {
if (url.includes("driver-license-check"))
return { data: { IsSucceed: true, Message: "mock" } };
if (url.includes("ownership")) return { data: { IsSuccess: true } };
throw new ServiceUnavailableException(
"نوع استعلام در سرویس فعلی پشتیبانی نمی‌شود.",
);
}
this.logger.log(
"Tejarat inquiry token is missing or expired. Fetching a new one...",
);
try {
const response = await firstValueFrom(
this.httpService.post(
`${baseUrl}/user/login`,
{ email, password },
{
headers: {
Accept: "*/*",
"Content-Type": "application/json",
},
timeout: 30000,
},
),
);
const token = response.data?.accessToken;
if (!token) {
throw new Error("No access token returned from Tejarat login");
}
this.tejaratAccessToken = token;
// No explicit expiry in response; keep a conservative cache window.
this.tejaratTokenExpiry = new Date(Date.now() + 55 * 60 * 1000);
return this.tejaratAccessToken;
} catch (er) {
this.logger.error(
"Failed to login to Tejarat inquiry:",
er?.message || er,
);
this.tejaratAccessToken = null;
this.tejaratTokenExpiry = null;
throw new UnauthorizedException(
"احراز هویت سرویس استعلام تجارت نو انجام نشد.",
private esgUrl(path: string): string {
const baseUrl = process.env.ESG_URL?.trim().replace(/\/+$/, "");
if (!baseUrl) {
throw new ServiceUnavailableException(
"نشانی سرویس یکپارچه استعلام تنظیم نشده است.",
);
}
return `${baseUrl}${path}`;
}
private async getEsgAccessToken(): Promise<string> {
@@ -532,11 +335,10 @@ export class SandHubService {
return this.esgAccessToken;
}
const baseUrl = process.env.ESG_URL;
const username = process.env.ESG_USERNAME;
const password = process.env.ESG_PASSWORD;
if (!baseUrl || !username || !password) {
if (!username || !password) {
throw new UnauthorizedException(
"اطلاعات اتصال به سرویس استعلام ESG تنظیم نشده است.",
);
@@ -547,7 +349,7 @@ export class SandHubService {
try {
const response = await firstValueFrom(
this.httpService.post(
`${baseUrl}/auth/login`,
this.esgUrl("/auth/login"),
{ username, password },
{
headers: {
@@ -606,7 +408,7 @@ export class SandHubService {
Message: "mock-sheba-ok",
};
}
return this.buildMockInquiryRaw(inquiryType, ctx, payload);
return this.buildMockPlateInquiryRaw(ctx);
}
const INITIAL_DELAY = 500;
@@ -671,7 +473,7 @@ export class SandHubService {
}
// Real ESG response wraps payload in { success: true, data: { ... } }.
// Mock data and Tejarat-format fallback are flat objects with no .data wrapper —
// Mock data and historical records are flat objects with no .data wrapper —
// in that case use raw itself so CompanyName / CompanyCode are preserved.
const data =
raw?.data != null && typeof raw?.data === "object" ? raw.data : raw;
@@ -708,7 +510,7 @@ export class SandHubService {
/**
* Normalises Jalali birth dates to `YYYY-MM-DD` for ESG person inquiry.
* Unlike Tejarat/SandHub personal inquiry, ESG expects Jalali — not Gregorian.
* ESG expects the Jalali date, not a Gregorian conversion.
*/
private normalizeJalaliBirthDateForEsg(
input: string | number | null | undefined,
@@ -799,72 +601,12 @@ export class SandHubService {
};
}
private async makeTejaratRequest(
url: string,
payload: any,
inquiryType: ExternalInquiryType,
options?: SandHubInquiryOptions,
maxRetries = 2,
) {
if (!(await this.isInquiryLive(inquiryType, options))) {
this.logger.log(`[MOCK] Tejarat POST skipped (${inquiryType}): ${url}`);
const ctx = await this.mockCompanyContext(options);
return this.buildMockInquiryRaw(inquiryType, ctx, payload);
}
const INITIAL_DELAY = 500;
const BACKOFF_FACTOR = 2;
for (let attempt = 0; attempt < maxRetries; attempt++) {
const token = await this.getTejaratAccessToken();
try {
const response = await firstValueFrom(
this.httpService.post(url, payload, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
timeout: 30000,
}),
);
if (!response?.data) throw new Error("EMPTY_RESPONSE");
return response.data;
} catch (err: any) {
const status = err?.response?.status;
const data = err?.response?.data;
this.logger.error(
`Tejarat request failed (attempt ${attempt + 1}/${maxRetries}) to ${url} with status ${
status ?? "NO_STATUS"
}`,
data ? JSON.stringify(data) : err?.message || err,
);
// If unauthorized, clear token and retry once
if (status === 401) {
this.tejaratAccessToken = null;
this.tejaratTokenExpiry = null;
}
if ([400, 404, 409, 422].includes(status)) {
this.throwInquiryError(err, this.inquiryContext(inquiryType));
}
if (attempt === maxRetries - 1) {
this.throwInquiryError(err, this.inquiryContext(inquiryType));
}
const delay = INITIAL_DELAY * Math.pow(BACKOFF_FACTOR, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}
/**
* Tejarat block inquiry (replaces SandHub call for V2 flows).
* ESG plate inquiry for every tenant.
* Returns both raw + mapped (old-format) response.
* Offline seeded hits (per Fanavaran clientKey) are checked first.
* Offline seeded hits are used only when the live inquiry is disabled.
*/
async getTejaratBlockInquiry(
async getCarByPlateInquiry(
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
): Promise<{
@@ -879,7 +621,7 @@ export class SandHubService {
}> {
const live = await this.isInquiryLive("thirdPartyPlate", options);
// Offline records are a fallback for disabled inquiry mode only. They must
// never override a configured live ESG/Tejarat inquiry.
// never override a configured live ESG inquiry.
if (!live) {
const offlineHit = await this.offlineInquiryService.findPlateInquiry({
clientKey: resolveFanavaranClientKey(),
@@ -909,8 +651,6 @@ export class SandHubService {
}
const ctx = await this.mockCompanyContext(options);
if (this.shouldUseEsgInquiryProvider()) {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = {
nationalCode: String(userDetail.nationalCodeOfInsurer),
plk1: String(userDetail.plate.leftDigits),
@@ -919,10 +659,9 @@ export class SandHubService {
plksrl: String(userDetail.plate.ir),
};
const requestUrl = `${baseUrl}/inquiry/carByPlate`;
const raw = live
? await this.makeEsgRequest(
requestUrl,
this.esgUrl("/inquiry/carByPlate"),
requestPayload,
"thirdPartyPlate",
options,
@@ -933,136 +672,67 @@ export class SandHubService {
`[MOCK] getEsgPolicyByPlateInquiry plate=${JSON.stringify(requestPayload)}`,
);
}
const mapped = this.mapEsgPolicyByPlateToOldFormat(
raw,
"thirdPartyPlate",
);
const mapped = this.mapEsgPolicyByPlateToOldFormat(raw, "thirdPartyPlate");
if (!mapped?.Error) {
this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options);
}
return { raw, mapped };
}
const baseUrl =
process.env.TEJARAT_INQUIRY_BASE_URL ?? "http://82.99.202.245:3027";
const requestPayload = {
leftTwoDigits: String(userDetail.plate.leftDigits),
serialLetter: String(userDetail.plate.centerAlphabet),
threeDigits: String(userDetail.plate.centerDigits),
rightTwoDigits: String(userDetail.plate.ir),
nationalCode: userDetail.nationalCodeOfInsurer,
};
const requestUrl = `${baseUrl}/block-inquiry-tejarat`;
const raw = live
? await this.makeTejaratRequest(
requestUrl,
requestPayload,
"thirdPartyPlate",
options,
)
: this.buildMockPlateInquiryRaw(ctx);
if (!live) {
this.logger.debug(
`[MOCK] getTejaratBlockInquiry plate=${JSON.stringify(requestPayload)}`,
);
}
const mapped = isInquiryFailurePayload(raw)
? {
Error: {
Message: getInquiryErrorMessage(raw, "thirdPartyPlate"),
},
}
: this.mapNewApiResponseToOldFormat(raw);
if (!mapped?.Error) {
this.enforceDeploymentClientMatch(mapped, "THIRD_PARTY", options);
}
return { raw, mapped };
}
/**
* CAR_BODY is the only ESG product that uses the processed Fanavaran lookup.
* THIRD_PARTY remains on its established provider-specific inquiry path.
*/
/** Car-body policies always come from the deployment's Fanavaran profile. */
async getCarBodyInquiry(
userDetail: CarBodyInquiryDetail,
options?: SandHubInquiryOptions,
): Promise<{
source:
| "ESG_CAR_BODY_INQUIRY"
| "ESG_CAR_BODY_VIN_INQUIRY"
| "TEJARAT_CAR_BODY_INQUIRY"
| "TEJARAT_CAR_BODY_VIN_INQUIRY";
source: "FANAVARAN_CAR_BODY_INQUIRY" | "FANAVARAN_CAR_BODY_VIN_INQUIRY";
raw: any;
mapped: Record<string, unknown>;
}> {
const useParsianCarBodyLookup = this.shouldUseParsianCarBodyLookup();
const live = await this.isInquiryLive("carBodyPlate", options);
const plateOrVin = userDetail.plate;
const isVinInquiry = typeof plateOrVin === "string";
if (!live) {
// Mock results are generated for the active deployment. They must not be
// treated as evidence of a real insurer and therefore do not go through
// the live-policy insurer gate.
const isVinInquiry = typeof userDetail.plate === "string";
const source = isVinInquiry
? "FANAVARAN_CAR_BODY_VIN_INQUIRY"
: "FANAVARAN_CAR_BODY_INQUIRY";
if (!(await this.isInquiryLive("carBodyPlate", options))) {
const ctx = await this.mockCompanyContext(options);
const raw = this.buildMockCarBodyInquiryRaw(userDetail, ctx);
const result = { raw, mapped: this.mapCarBodyInquiryResponse(raw) };
return {
source: isVinInquiry
? useParsianCarBodyLookup
? "ESG_CAR_BODY_VIN_INQUIRY"
: "TEJARAT_CAR_BODY_VIN_INQUIRY"
: useParsianCarBodyLookup
? "ESG_CAR_BODY_INQUIRY"
: "TEJARAT_CAR_BODY_INQUIRY",
...result,
};
return { source, raw, mapped: this.mapCarBodyInquiryResponse(raw) };
}
if (isVinInquiry) {
let raw: any;
try {
raw = await this.lookupsService.findLastProcessedCarPolicy("car-body", {
nationalCode: String(userDetail.nationalCodeOfInsurer),
vin: plateOrVin,
...(userDetail.accidentDate != null
? { accidentDate: userDetail.accidentDate }
: {}),
});
} catch (error) {
this.throwInquiryError(error, "carBodyVin");
}
if (useParsianCarBodyLookup) {
this.assertParsianCarBodyLookupMatchesDeployment();
}
return {
source: useParsianCarBodyLookup
? "ESG_CAR_BODY_VIN_INQUIRY"
: "TEJARAT_CAR_BODY_VIN_INQUIRY",
raw,
mapped: mapEsgCarBodyPolicyToInquiry(raw),
};
}
if (!useParsianCarBodyLookup) {
const result = await this.getTejaratCarBodyInquiry(
userDetail as SandHubDetailDto,
options,
const clientCode = String(process.env.CLIENT_ID ?? "").trim();
if (!clientCode) {
throw new ServiceUnavailableException(
"تنظیمات شرکت بیمه برای بررسی اعتبار بیمه‌نامه کامل نیست.",
);
this.assertInsuranceMatchesDeployment(result.mapped, "CAR_BODY");
return {
source: "TEJARAT_CAR_BODY_INQUIRY",
...result,
};
}
const clientKey = resolveFanavaranClientKey();
// A scoped provider response must never be labelled as a different insurer.
const knownCode =
clientKey === "parsian" ? "8" : clientKey === "moallem" ? "7" : undefined;
const expectedKey =
clientCode === "7"
? "moallem"
: clientCode === "8"
? "parsian"
: undefined;
if (
(knownCode && knownCode !== clientCode) ||
(expectedKey && expectedKey !== clientKey)
) {
throw new ForbiddenException(
"بیمه‌نامه یافت‌شده متعلق به شرکت بیمه این سامانه نیست.",
);
}
const plate = userDetail.plate;
const query = {
nationalCode: String(userDetail.nationalCodeOfInsurer),
plaqueLeft: String(plateOrVin.leftDigits),
plaqueLetter: String(plateOrVin.centerAlphabet),
plaqueRight: String(plateOrVin.centerDigits),
plaqueSerial: String(plateOrVin.ir),
...(typeof plate === "string"
? { vin: plate }
: {
plaqueLeft: String(plate.leftDigits),
plaqueLetter: String(plate.centerAlphabet),
plaqueRight: String(plate.centerDigits),
plaqueSerial: String(plate.ir),
}),
...(userDetail.accidentDate != null
? { accidentDate: userDetail.accidentDate }
: {}),
@@ -1074,63 +744,23 @@ export class SandHubService {
query,
);
} catch (error) {
this.throwInquiryError(error, "carBodyPlate");
}
this.assertParsianCarBodyLookupMatchesDeployment();
return {
source: "ESG_CAR_BODY_INQUIRY",
raw,
mapped: mapEsgCarBodyPolicyToInquiry(raw),
};
}
async getTejaratCarBodyInquiry(
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
): Promise<{
raw: any;
mapped: Record<string, unknown>;
}> {
const baseUrl =
process.env.TEJARAT_INQUIRY_BASE_URL ?? "http://82.99.202.245:3027";
const requestPayload = {
part1: Number(userDetail.plate.leftDigits),
part2: String(userDetail.plate.centerAlphabet),
part3: Number(userDetail.plate.centerDigits),
part4: Number(userDetail.plate.ir),
nationalCode: String(userDetail.nationalCodeOfInsurer),
};
const requestUrl = `${baseUrl}/block-inquiry-tejarat/badane`;
const live = await this.isInquiryLive("carBodyPlate", options);
if (!live) {
this.logger.debug(
`[MOCK] getTejaratCarBodyInquiry plate=${JSON.stringify(requestPayload)}`,
this.throwInquiryError(
error,
isVinInquiry ? "carBodyVin" : "carBodyPlate",
);
}
const raw = await this.makeTejaratRequest(
requestUrl,
requestPayload,
"carBodyPlate",
options,
);
if (isInquiryFailurePayload(raw)) {
throw new BadRequestException(
getInquiryErrorMessage(raw, "carBodyPlate"),
);
}
const mapped = this.mapCarBodyInquiryResponse(raw);
return { raw, mapped };
const ctx = await this.mockCompanyContext(options);
const mapped = mapFanavaranCarBodyPolicyToInquiry(raw, {
companyId: clientCode,
companyName: ctx.companyName,
});
this.assertInsuranceMatchesDeployment(mapped, "CAR_BODY");
return { source, raw, mapped };
}
/**
* Maps the Tejarat car-body (badane) API response to a consistent
* shape that mirrors the third-party inquiry mapped format.
* Callers should always use `mapped` for display; `raw` is kept for audit.
* Maps the historical car-body shape retained by disabled-mode fixtures.
* Live inquiries use the processed Fanavaran mapper instead.
*/
private mapCarBodyInquiryResponse(raw: any): Record<string, unknown> {
if (!raw) return {};
@@ -1205,8 +835,6 @@ export class SandHubService {
identity: { nationalCode: string; chassisNo: string },
options?: SandHubInquiryOptions,
): Promise<{ raw: any; mapped: any }> {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestUrl = `${baseUrl}/inquiry/carByChassis`;
const requestPayload = {
nationalCode: String(identity.nationalCode),
chassisNo: String(identity.chassisNo),
@@ -1228,7 +856,7 @@ export class SandHubService {
}
const raw = await this.makeEsgRequest(
requestUrl,
this.esgUrl("/inquiry/carByChassis"),
requestPayload,
"vinChassis",
options,
@@ -1240,54 +868,6 @@ export class SandHubService {
return { raw, mapped };
}
private async makeSandHubRequest(
url: string,
payload: any,
inquiryType: ExternalInquiryType,
options?: SandHubInquiryOptions,
maxRetries = 3,
) {
if (!(await this.isInquiryLive(inquiryType, options))) {
this.logger.log(`[MOCK] SandHub POST skipped (${inquiryType}): ${url}`);
const ctx = await this.mockCompanyContext(options);
if (inquiryType === "carBodyPlate") {
return this.buildMockInquiryRaw(inquiryType, ctx, payload);
}
const plateMock =
inquiryType === "thirdPartyPlate"
? this.buildMockPlateInquiryRaw(ctx)
: undefined;
return this.buildMockSandHubResponseForUrl(url, payload, plateMock);
}
const token = await this.getAccessToken();
const INITIAL_DELAY = 1000;
const BACKOFF_FACTOR = 2;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await firstValueFrom(
this.httpService.post(url, payload, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
timeout: 50000,
}),
);
if (!response?.data) throw new Error("EMPTY_RESPONSE");
return response.data;
} catch (err) {
this.handleSandHubError(err, attempt, maxRetries);
const delay = INITIAL_DELAY * Math.pow(BACKOFF_FACTOR, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw new BadGatewayException(
"سرویس استعلام پس از چند تلاش پاسخ نداد. لطفاً کمی بعد دوباره تلاش کنید.",
);
}
/**
* Maps the new SandHub API response format to the old format expected by the application
*/
@@ -1450,56 +1030,12 @@ export class SandHubService {
userDetail: SandHubDetailDto,
options?: SandHubInquiryOptions,
) {
try {
const requestPayload = {
leftTwoDigits: String(userDetail.plate.leftDigits),
serialLetter: String(userDetail.plate.centerAlphabet),
threeDigits: String(userDetail.plate.centerDigits),
rightTwoDigits: String(userDetail.plate.ir),
nationalCode: userDetail.nationalCodeOfInsurer,
};
const base = process.env.SANHUB_BASE_URL ?? "";
const requestUrl = `${base}/block-inquiry-tejarat`;
let response: any;
if (await this.isInquiryLive("thirdPartyPlate", options)) {
response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"thirdPartyPlate",
options,
);
} else {
this.logger.debug(
`[MOCK] getSandHubResponse plate=${JSON.stringify(requestPayload)}`,
);
const ctx = await this.mockCompanyContext(options);
response = this.buildMockPlateInquiryRaw(ctx);
}
const result = this.mapNewApiResponseToOldFormat(response);
this.enforceDeploymentClientMatch(result, "THIRD_PARTY", options);
// if (result.usgCod !== "8") {
// throw new Error("خودرو شما شخصی / سواری نمی باشد")
// }
return result;
} catch (err) {
if (
err instanceof ForbiddenException ||
err instanceof ServiceUnavailableException
) {
throw err;
}
this.throwInquiryError(err, "thirdPartyPlate");
}
const { mapped } = await this.getCarByPlateInquiry(userDetail, options);
return mapped;
}
/**
* Personal identity check.
* - CLIENT_ID=8 (Parsian/ESG): Jalali birth date sent as-is to `/inquiry/person`.
* - Other tenants: Tejarat/SandHub hub with Gregorian conversion.
* Personal identity check for every tenant: ESG expects a Jalali birth date.
*/
async getPersonalInquiry(
nationalCode: string,
@@ -1507,7 +1043,6 @@ export class SandHubService {
options?: SandHubInquiryOptions,
) {
try {
if (this.shouldUseEsgInquiryProvider()) {
const jalaliBirthDate = this.normalizeJalaliBirthDateForEsg(birthDate);
if (!jalaliBirthDate) {
throw new BadRequestException(
@@ -1515,13 +1050,11 @@ export class SandHubService {
);
}
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = {
nationalCode: String(nationalCode),
birthDate: jalaliBirthDate,
dateHasPostfix: 0,
};
const requestUrl = `${baseUrl}/inquiry/person`;
const live = await this.isInquiryLive("personalIdentity", options);
if (!live) {
@@ -1532,52 +1065,60 @@ export class SandHubService {
}
const raw = await this.makeEsgRequest(
requestUrl,
this.esgUrl("/inquiry/person"),
requestPayload,
"personalIdentity",
options,
);
return this.mapEsgPersonInquiryToOldFormat(raw);
}
const requestUrl = `${process.env.SANHUB_BASE_URL}/personal-inquiry/tejarat-no`;
const gregorianBirthdate = jalaliToGregorianDate(birthDate);
if (!gregorianBirthdate) {
throw new BadRequestException(
"تاریخ تولد واردشده برای استعلام هویت معتبر نیست.",
);
}
const requestPayload = {
nationalCode,
birthdate: gregorianBirthdate,
};
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"personalIdentity",
options,
);
if (response?.message?.includes("err.record.not.found")) {
throw new NotFoundException(
getInquiryErrorMessage(response, "personalIdentity"),
);
}
return response.data;
} catch (err) {
if (
err instanceof BadRequestException ||
err instanceof NotFoundException
) {
if (err instanceof BadRequestException) {
throw err;
}
this.throwInquiryError(err, "personalIdentity");
}
}
private async makeSandHubRequest(
url: string,
payload: any,
inquiryType: ExternalInquiryType,
options?: SandHubInquiryOptions,
maxRetries = 3,
) {
if (!(await this.isInquiryLive(inquiryType, options))) {
this.logger.log(`[MOCK] SandHub POST skipped (${inquiryType}): ${url}`);
return this.buildMockSandHubResponseForUrl(url);
}
const token = await this.getAccessToken();
const INITIAL_DELAY = 1000;
const BACKOFF_FACTOR = 2;
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await firstValueFrom(
this.httpService.post(url, payload, {
headers: {
Authorization: `Bearer ${token}`,
"Content-Type": "application/json",
Accept: "application/json",
},
timeout: 50000,
}),
);
if (!response?.data) throw new Error("EMPTY_RESPONSE");
return response.data;
} catch (err) {
this.handleSandHubError(err, attempt, maxRetries);
const delay = INITIAL_DELAY * Math.pow(BACKOFF_FACTOR, attempt);
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
throw new BadGatewayException(
"سرویس استعلام پس از چند تلاش پاسخ نداد. لطفاً کمی بعد دوباره تلاش کنید.",
);
}
async getDrivingLicenseInfo(
nationalCode: string,
driverLicenseNumber: string,
@@ -1661,15 +1202,12 @@ export class SandHubService {
options?: SandHubInquiryOptions,
) {
try {
if (this.shouldUseEsgInquiryProvider()) {
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
const requestPayload = {
accountOwnerType: "1",
nationalCode: String(nationalId),
legalId: "",
sheba: String(shebaId),
};
const requestUrl = `${baseUrl}/inquiry/sheba`;
const live = await this.isInquiryLive("sheba", options);
this.logger.log(
@@ -1688,7 +1226,7 @@ export class SandHubService {
}
const raw = await this.makeEsgRequest(
requestUrl,
this.esgUrl("/inquiry/sheba"),
requestPayload,
"sheba",
options,
@@ -1705,34 +1243,6 @@ export class SandHubService {
);
}
return response;
}
const requestUrl = `${process.env.SANHUB_BASE_URL}/sheba/sheba-tejaratno`;
const requestPayload = {
AccountOwnerType: "1",
NationalId: nationalId,
ShebaId: shebaId,
};
this.logger.log(`Validating Sheba ID for national code: ${nationalId}`);
const response = await this.makeSandHubRequest(
requestUrl,
requestPayload,
"sheba",
options,
);
if (response?.ReturnValue === false || response?.HasError === true) {
this.logger.warn(
`Sheba validation failed for national code ${nationalId}. Response:`,
response,
);
throw new BadRequestException(
"شماره شبا متعلق به کد ملی واردشده نیست.",
);
}
return response;
} catch (err) {
if (err instanceof BadRequestException) {
@@ -1741,7 +1251,6 @@ export class SandHubService {
this.throwInquiryError(err, "sheba");
}
}
private handleSandHubError(
err: any,
attempt: number,