forked from Yara724/api
Compare commits
134
Commits
1e6f1ed759
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4e0e6f83dc | ||
|
|
f29461fa67 | ||
|
|
475780f17e | ||
|
|
297664a9a6 | ||
|
|
187a0ea3a9 | ||
|
|
036d218ebd | ||
|
|
c74b29337e | ||
|
|
3bf6fcc8b0 | ||
|
|
e31e2c7be6 | ||
|
|
70e7edcd19 | ||
|
|
99aba7e0fd | ||
|
|
fb192fd780 | ||
|
|
41a3372225 | ||
|
|
d2676d65d1
|
||
|
|
6e56d0fa2e
|
||
|
|
7b23262fd2 | ||
|
|
6b968c0952 | ||
|
|
abc40df199 | ||
|
|
90f290154c | ||
|
|
be364d94fe | ||
|
|
1a38b98829 | ||
|
|
61ef4faaf4 | ||
|
|
7bff702514 | ||
|
|
99e6fa0850 | ||
|
|
83d7351310 | ||
|
|
ab3ae53ec0 | ||
|
|
bc78bface0 | ||
|
|
e33f5736a2 | ||
|
|
5c6e21dd14 | ||
|
|
8f15040080 | ||
|
|
5818f7f881 | ||
|
|
5242a22c6c | ||
|
|
9197bccceb | ||
|
|
cda424a536 | ||
|
|
68e26920e2 | ||
|
|
c6022a1646 | ||
|
|
b63525c863 | ||
|
|
83376df4ad | ||
|
|
2cdbc35d2e | ||
|
|
7631a94071 | ||
|
|
e5c4b740e7 | ||
|
|
775934c056 | ||
|
|
a15c54d017 | ||
|
|
f021793b00 | ||
|
|
ee40b3e811 | ||
|
|
9178058173 | ||
|
|
457fd0b174 | ||
|
|
7ab6b4c03d | ||
|
|
cbdf4fd2bc | ||
|
|
af9bed3b0d | ||
|
|
3fe897031a | ||
|
|
e215dbdc03 | ||
|
|
8b9dabc9f2 | ||
|
|
84b92eb55a | ||
|
|
90bdc51715 | ||
|
|
54459877a2 | ||
|
|
d469cce463 | ||
|
|
5d84b9697f | ||
|
|
658a8a74cc | ||
|
|
5e3bd02243 | ||
|
|
d53922a1bc | ||
|
|
cc0d69dcb2 | ||
|
|
f33eabeb4f | ||
|
|
c81002da7d | ||
|
|
f49e6b704b | ||
|
|
6775635a81 | ||
|
|
6cc59b1777 | ||
|
|
3073391d79 | ||
|
|
2f00e9cccc | ||
|
|
8da8170787 | ||
|
|
27bd9da54a | ||
|
|
b9e22071bb | ||
|
|
755e921c08 | ||
|
|
a8bb0d8e35 | ||
|
|
2056412efe | ||
|
|
255998097d | ||
|
|
e75a144e50 | ||
|
|
c5aa0f925e | ||
|
|
6e94717cc8 | ||
|
|
c185145394 | ||
|
|
82d204bd66 | ||
|
|
9e158d4e8d | ||
|
|
e56e697e4f | ||
|
|
63b1bb3e2c | ||
|
|
ebd2b62297
|
||
|
|
69a9fc351c | ||
|
|
8d73d4996c | ||
|
|
cdeed1716d | ||
|
|
a553ce5dfe | ||
|
|
fa2b1972a2 | ||
|
|
e414a97c92 | ||
|
|
846355a32f | ||
|
|
340ed5e9b3 | ||
|
|
e4b342cd25 | ||
|
|
2cdf4aba02 | ||
|
|
e7236884db | ||
|
|
887b514983 | ||
|
|
47447d1153 | ||
|
|
06985855e2 | ||
|
|
0c272f1e86 | ||
|
|
4302be8595 | ||
|
|
64d5aa691f | ||
|
|
22ffeed75c | ||
|
|
8f568f379c | ||
|
|
a410655faa | ||
|
|
073dd9792f | ||
|
|
431bdea472 | ||
|
|
4564798db1 | ||
|
|
b11128c638 | ||
|
|
680b619fe1 | ||
|
|
3aec3afa52 | ||
|
|
5110721c62 | ||
|
|
2d532a7177 | ||
|
|
a3f9aab8fb | ||
|
|
0735333467 | ||
|
|
07681cf0b4 | ||
|
|
e438b77e62 | ||
|
|
268258a23c | ||
|
|
91074ca1e5 | ||
|
|
2f92766689 | ||
|
|
18ccfa81e4 | ||
|
|
d9a8ec4b2f | ||
|
|
b20250b4b3 | ||
|
|
6a724abaf7 | ||
|
|
ecf44011f3 | ||
|
|
78ebf3104a | ||
|
|
1e18537b84 | ||
|
|
05e3e6a4d3 | ||
|
|
b7a64596dd | ||
|
|
820b85c418 | ||
|
|
7a8d96ab52 | ||
|
|
5f6c295439 | ||
|
|
efef48d824 | ||
|
|
165afe56ae |
+44
-9
@@ -13,6 +13,9 @@ CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN=53000000
|
||||
# 🌐 Application URLs
|
||||
# ---------------------------------------------
|
||||
URL =
|
||||
# Optional path where the user panel is mounted behind the public URL.
|
||||
# Example: URL=https://chatr.parsianinsurance.com/car-damage and USER_BASE_PATH=user
|
||||
# produces SMS links under https://chatr.parsianinsurance.com/car-damage/user/v1/...
|
||||
USER_BASE_PATH =
|
||||
BASE_URL_DEV =
|
||||
|
||||
@@ -43,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 =
|
||||
@@ -53,19 +65,32 @@ SANHUB_PASSWORD =
|
||||
# ---------------------------------------------
|
||||
# 🤖 AI Services
|
||||
# ---------------------------------------------
|
||||
AI_URL =
|
||||
AI_URL_V2 =
|
||||
AI_USERNAME =
|
||||
AI_PASSWORD =
|
||||
AI_DAMAGE_ENABLED=false
|
||||
AI_DAMAGE_URL=http://79.132.207.77:30531
|
||||
AI_DAMAGE_TIMEOUT_MS=600000
|
||||
|
||||
# Prices come from the assessment service; no OpenAI key is needed here.
|
||||
# minor = all damaged parts, moderate = moderate/severe, severe = severe only.
|
||||
# null is normalized to minor because the provider does not accept a null enum.
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY=severe
|
||||
|
||||
# ---------------------------------------------
|
||||
# 📩 SMS
|
||||
# ---------------------------------------------
|
||||
# kavenegar | parsian | moalem (legacy SMS takes precedence when nonempty)
|
||||
SMS_PROVIDER =
|
||||
SMS_API_KEY =
|
||||
# Display name used in SMS text for this deployment (blank/unset = یارا۷۲۴).
|
||||
# Example for Moalem: SMS_BRAND_NAME="سامانه خسارت اپکس"
|
||||
# Custom Kavenegar branding uses sms/send; the account must allow plain-text SMS.
|
||||
SMS_BRAND_NAME="یارا۷۲۴"
|
||||
AUTH_SMS_TEMPLATE =
|
||||
# Optional OTP pattern; {token} is the code and {brandName} is SMS_BRAND_NAME.
|
||||
# The deployment name is appended automatically when absent from a pattern.
|
||||
AUTH_SMS_MESSAGE="کاربر محترم رمز یکبار مصرف شما در {brandName}: {token}"
|
||||
EXP_OTP_TIME =
|
||||
FAKE_OTP =
|
||||
# Development-only fixed OTP. Production rejects true at startup.
|
||||
FAKE_OTP = false
|
||||
|
||||
# ---------------------------------------------
|
||||
# 🌐 Proxy Configuration (Local Development Only)
|
||||
@@ -92,9 +117,19 @@ AUTO_CLIENT_KEY_ENABLED =
|
||||
# ---------------------------------------------
|
||||
# 🔗 Other Internal Services
|
||||
# ---------------------------------------------
|
||||
TEJARAT_INQUIRY_EMAIL =
|
||||
TEJARAT_INQUIRY_PASSWORD =
|
||||
|
||||
PARSIAN_API_KEY =
|
||||
PARSIAN_BASIC_TOKEN =
|
||||
PARSIAN_SMS_URL =
|
||||
|
||||
# MIC / Moalem SMS (used only when SMS_PROVIDER=moalem or SMS=moalem)
|
||||
MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token
|
||||
MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send
|
||||
MIC_SMS_CLIENT_ID=
|
||||
MIC_SMS_CLIENT_SECRET=
|
||||
MIC_SMS_TOKEN_TTL=86399
|
||||
# Total normal send attempts; a single 401 refresh/resend is additional.
|
||||
MIC_SMS_ATTEMPTS=2
|
||||
MIC_SMS_TIMEOUT_MS=15000
|
||||
|
||||
# Require the submitting expert to sign before final Fanavaran submission.
|
||||
FANAVARAN_REQUIRE_EXPERT_SIGNATURE=false
|
||||
|
||||
+18
@@ -186,3 +186,21 @@ dist
|
||||
*.sh
|
||||
!scripts/fanavaran-flow-test.sh
|
||||
!scripts/fanavaran-auth.sh
|
||||
!scripts/get-fanavaran-car-parts.sh
|
||||
|
||||
# --- local WIP (do not track) ---
|
||||
.agents/
|
||||
.cursor/
|
||||
.mimocode/
|
||||
.vscode/
|
||||
A00191.json
|
||||
test.json
|
||||
skills-lock.json
|
||||
docs/fanavaran/car-body-stage-fields.html
|
||||
docs/fanavaran/third-party-stage-fields.html
|
||||
docs/fanavaran/stage1-hull-body.json
|
||||
docs/fanavaran/stage4-hull-expertise-body.json
|
||||
# scripts/fanavaran-flow-ui-server.js
|
||||
# scripts/data/fanavaran-flow-ui.html
|
||||
scripts/data/fanavaran-flow-cases/
|
||||
scripts/data/offline-plate-seeds.json
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
when:
|
||||
- event: push
|
||||
branch: main
|
||||
- event: manual
|
||||
branch: main
|
||||
|
||||
labels:
|
||||
hostname: build-parspack
|
||||
|
||||
steps:
|
||||
build:
|
||||
image: docker.arvancloud.ir/docker:24-cli
|
||||
volumes:
|
||||
- /var/run/docker.sock:/var/run/docker.sock
|
||||
- /home/opsadmin/.docker/config.json:/root/.docker/config.json:ro
|
||||
commands:
|
||||
- export YARA_IMAGE="registry.ittalie.com/yara724-maintenance-api:latest"
|
||||
- docker build -t "$YARA_IMAGE" .
|
||||
- docker push "$YARA_IMAGE"
|
||||
|
||||
notify-failure:
|
||||
image: docker.arvancloud.ir/alpine:3.20
|
||||
environment:
|
||||
ROCKETCHAT_WEBHOOK:
|
||||
from_secret: rocketchat_webhook
|
||||
when:
|
||||
- status: failure
|
||||
commands:
|
||||
- apk add --no-cache curl jq > /dev/null
|
||||
- |
|
||||
jq -n --arg text "Yara724 api build failed. $CI_PIPELINE_URL" '{text: $text}' |
|
||||
curl -fsS -H 'Content-Type: application/json' --data-binary @- "$ROCKETCHAT_WEBHOOK"
|
||||
@@ -1,11 +1,14 @@
|
||||
# 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
|
||||
|
||||
skip_clone: true
|
||||
|
||||
@@ -37,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:
|
||||
@@ -46,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
|
||||
+10
-7
@@ -1,23 +1,26 @@
|
||||
# Use the official Node.js image as the base image
|
||||
FROM node:20-alpine
|
||||
FROM docker.arvancloud.ir/node:20-alpine
|
||||
|
||||
RUN apk add --no-cache ffmpeg
|
||||
|
||||
# Set the working directory inside the container
|
||||
WORKDIR /app
|
||||
|
||||
# Copy package.json and package-lock.json to the working directory
|
||||
COPY package*.json ./
|
||||
|
||||
# Iran access Repo
|
||||
RUN npm config set registry https://mirror-npm.runflare.com
|
||||
RUN npm config set registry "https://repo.hmirror.ir/npm"
|
||||
|
||||
|
||||
# Install the project dependencies
|
||||
RUN npm i --force
|
||||
RUN npm i --force --verbose --no-scripts
|
||||
|
||||
# Copy the rest of the application code to the working directory
|
||||
|
||||
COPY . .
|
||||
|
||||
RUN npm run build && test -f dist/src/main.js
|
||||
|
||||
# Expose the port on which your NestJS application will run
|
||||
EXPOSE 3002
|
||||
|
||||
# Start the NestJS application
|
||||
CMD ["npm", "start"]
|
||||
CMD ["node", "dist/src/main.js"]
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.git
|
||||
node_modules
|
||||
dist
|
||||
.env
|
||||
.env.*
|
||||
*.env
|
||||
@@ -3,3 +3,18 @@
|
||||
## Documentation
|
||||
|
||||
- [Fanavaran integration](docs/fanavaran/README.md)
|
||||
- [Inquiry providers — ESG for all tenants and Fanavaran car-body policies](docs/inquiry-provider-routing.md)
|
||||
- [AI damage detection and advisory prices — setup and testing](docs/ai-damage-companion.md)
|
||||
- [Deployment-specific SMS display names](docs/sms-deployment-branding.md)
|
||||
|
||||
Insurer setup and staff/branch management: [guide](docs/insurer-staff-management.md).
|
||||
|
||||
### Moalem SMS
|
||||
|
||||
For MIC SMS environment settings, shared token-cache indexes and a test-send command, see [Moalem SMS adapter](docs/MIC/moalem-sms.md).
|
||||
|
||||
### Expert signature before final Fanavaran submission
|
||||
|
||||
Set `FANAVARAN_REQUIRE_EXPERT_SIGNATURE=true` in the API service environment and restart the API for the deployment that requires it. The expert app reads the setting from the API. The default is `false`.
|
||||
|
||||
With the setting enabled, the submitting expert signs the saved assessment in the Fanavaran tab, then clicks final submission. Changes to the signed assessment require a fresh signature. Automatic final expertise submission waits for this action, and manual final submissions use the saved fields without JSON overrides. Initial Fanavaran stages can still run at their usual points. The insurer PDF includes available party and expert signatures.
|
||||
|
||||
Binary file not shown.
Binary file not shown.
+1
-1
@@ -6,7 +6,7 @@ services:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
container_name: yara724-main-api-dev
|
||||
image: yara724-main-api:dev
|
||||
image: ${YARA_IMAGE:-yara724-main-api:dev}
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
- yara724-main-api-dev-files:/app/files/:rw
|
||||
|
||||
Binary file not shown.
@@ -0,0 +1,74 @@
|
||||
# MIC / Moalem SMS adapter
|
||||
|
||||
The deployment selects `moalem` as its SMS provider. This is independent of the Fanavaran tenant selection. Existing OTP, invitation, signature, document and case-notification callers continue using `SmsGatewayService`. Moalem sends the same plain-text template bodies as Parsian, including the existing user-panel links. Kavenegar and Parsian remain available.
|
||||
|
||||
## Production environment
|
||||
|
||||
```dotenv
|
||||
SMS_PROVIDER=moalem
|
||||
SMS_BRAND_NAME="سامانه خسارت اپکس"
|
||||
MIC_SMS_TOKEN_URL=https://auth.mic.co.ir/connect/token
|
||||
MIC_SMS_SEND_URL=https://api.mic.co.ir/sms/send
|
||||
MIC_SMS_CLIENT_ID=<provided privately by MIC>
|
||||
MIC_SMS_CLIENT_SECRET=<provided privately by MIC>
|
||||
MIC_SMS_TOKEN_TTL=86399
|
||||
MIC_SMS_ATTEMPTS=2
|
||||
MIC_SMS_TIMEOUT_MS=15000
|
||||
FAKE_OTP=false
|
||||
```
|
||||
|
||||
- If the legacy `SMS` setting is nonempty, it overrides `SMS_PROVIDER`. Set it to `moalem` as well, or remove it. `moallem` is accepted as an alias; logs use `moalem`.
|
||||
- Keep the existing `AUTH_SMS_TEMPLATE` and `AUTH_SMS_MESSAGE` settings for OTP text. Existing URL and `USER_BASE_PATH` settings continue controlling message links.
|
||||
- `SMS_BRAND_NAME` controls the name in every SMS; unset or blank defaults to `یارا۷۲۴`. Custom OTP/database patterns can use `{brandName}`. See [SMS deployment branding](../sms-deployment-branding.md).
|
||||
- Supply credentials privately through the server environment or secret store. The repository example contains no credentials. Restart API instances after changing configuration.
|
||||
- Active Moalem deployments fail startup when required MIC credentials, HTTPS URLs or numeric settings are invalid. MIC settings do not block other SMS providers.
|
||||
- Allow outbound HTTPS to `auth.mic.co.ir` and `api.mic.co.ir`. Redirects are disabled. The existing HTTP proxy configuration is reused.
|
||||
- Existing MongoDB is used for the shared token cache, so no Redis or new infrastructure is required. All API instances must share that database. Cache reads explicitly reject expired entries.
|
||||
|
||||
Production disables automatic Mongoose indexes. Have the database deployment create these indexes in the application database:
|
||||
|
||||
```javascript
|
||||
db.micSmsTokens.createIndex({key: 1}, {unique: true});
|
||||
db.micSmsTokens.createIndex({expiresAt: 1}, {expireAfterSeconds: 0});
|
||||
```
|
||||
|
||||
`micSmsTokens` contains server-only bearer tokens, hidden from normal model selection. Restrict database/backup access as for other credentials. Cache identity includes a SHA-256 fingerprint of endpoints and client credentials; credential changes select a new cache entry. Old entries expire. Token lifetime is the smaller of configured TTL and a positive provider `expires_in`, with an early-expiry safety margin. Requests within one process share an in-flight token fetch; simultaneous cold starts across replicas may each fetch a token.
|
||||
|
||||
## Transport and failure contract
|
||||
|
||||
`MicSmsService.sendSms(mobile, message)` is an awaited operation returning:
|
||||
|
||||
```json
|
||||
{"success": true, "data": {"isSuccessful": true, "id": "delivery-id"}, "error": null}
|
||||
```
|
||||
|
||||
```json
|
||||
{"success": false, "data": null, "error": "ارسال پیامک معلم انجام نشد. دوباره تلاش کنید."}
|
||||
```
|
||||
|
||||
`data` contains only documented delivery-response fields, never the authentication response or raw HTTP error. `error` is a safe Persian explanation. Provider response `isSuccessful` must be exactly `true`: HTTP 2xx with `false`, a missing flag, or a malformed response is treated as failure. This deliberately tightens the old PHP behavior.
|
||||
|
||||
The gateway unwraps successful delivery data and throws the existing `SmsProviderException` on failure. This preserves existing caller behavior, including failure auditing and OTP delivery errors. SMS audit records use provider `moalem`.
|
||||
|
||||
- Token request: form-encoded `grant_type=client_credentials`, `client_id`, `client_secret`, `scope=sms_sender`.
|
||||
- Send request: bearer authorization and exactly `RecipientPhoneNumber` / `Body` in JSON.
|
||||
- Mobile numbers `0912…`, `912…`, `98912…`, `+98912…` normalize to `+98912…`. Persian/Arabic numerals are also accepted; invalid mobile numbers fail before any HTTP call.
|
||||
- A send HTTP 401 evicts the rejected cached token conditionally, obtains a token and resends once. A second 401 fails. This recovery is allowed even when the normal attempt count is one.
|
||||
- Other send HTTP 4xx responses, including 429, fail immediately. Negative/malformed HTTP 2xx delivery responses also fail immediately.
|
||||
- Transport errors, token/cache failures and other non-success send statuses retry up to `MIC_SMS_ATTEMPTS` normal attempts, default 2. Delays are `500 * attempt` milliseconds. A single 401 refresh/resend can add one send request to that limit.
|
||||
- Retryable timeouts can be ambiguous: MIC's document specifies no idempotency key, so a retry may duplicate a message that the provider already accepted.
|
||||
- Logs include only fixed failure categories, HTTP status and attempt number. They exclude credentials, tokens, recipient/body and raw Axios errors.
|
||||
|
||||
No asynchronous delivery path was introduced. Callers must await `sendSms()` or the existing gateway. If queued delivery is added later, use a durable queue/worker with separately awaited enqueue calls; do not use an untracked background promise.
|
||||
|
||||
## Send a real test
|
||||
|
||||
From the API repository with `.env` and MongoDB available:
|
||||
|
||||
```bash
|
||||
npm run sms:test:mic -- 09120000000 'پیام آزمایشی سامانه'
|
||||
```
|
||||
|
||||
Use an authorized test recipient: this sends a real SMS. The helper starts only the configuration/database/SMS modules, prints the safe `{success,data,error}` result, closes connections and exits nonzero on failure. It does not start HTTP routes or application workers. Run it twice to exercise shared token reuse. No public test endpoint was added.
|
||||
|
||||
Automated verification uses mocked HTTP and cache operations; no live MIC SMS is sent by tests. Coverage includes normalization, form/payload contracts, shared cache reuse, expiry, one-time 401 recovery, terminal 4xx, backoff, safe failures/logs, templates and audit integration.
|
||||
@@ -0,0 +1,150 @@
|
||||
# AI damage companion
|
||||
|
||||
This opt-in integration supplements the expert's claim review. It never changes workflow status, damage selection/history, prices, severity entered by experts, or compensation decisions. The pipeline returns structured detections and optional advisory market prices, but no rendered image. The expert UI draws boxes on the captured photo.
|
||||
|
||||
## Enable in development
|
||||
|
||||
Set these **API environment variables** and restart the API:
|
||||
|
||||
```dotenv
|
||||
AI_DAMAGE_ENABLED=true
|
||||
AI_DAMAGE_URL=http://79.132.207.77:30531
|
||||
AI_DAMAGE_TIMEOUT_MS=600000
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY=severe
|
||||
```
|
||||
|
||||
The integration is off when `AI_DAMAGE_ENABLED` is missing or false. Enabling it requires a valid URL. Keep it off in production during this development rollout. No frontend environment variable or credential is needed. The supplied pipeline has no authentication header.
|
||||
|
||||
Each API instance must have access to the same persistent `files` storage as the capture API. Jobs are stored in the existing MongoDB database's new `ai-damage-jobs` collection. Development creates the schema indexes automatically. If enabling in an environment with `autoIndex=false`, create both indexes first:
|
||||
|
||||
```javascript
|
||||
db.getCollection('ai-damage-jobs').createIndex({ claimId: 1, imageKey: 1 }, { unique: true });
|
||||
db.getCollection('ai-damage-jobs').createIndex({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });
|
||||
```
|
||||
|
||||
No existing claim documents are migrated or rewritten. The old login/profile/downloadLink adapter and in-memory queue have been removed. Historical legacy `aiImage`/`aiReport` values remain intact but are not used by the new companion.
|
||||
|
||||
## Capture and processing
|
||||
|
||||
- All current user, field expert, registrar, FileMaker and FileReviewer capture routes delegate to `capturePartV2`. Once a damaged-part photo is saved, it queues the exact local file. Car-angle captures, invoices, identity documents and signatures are excluded.
|
||||
- Legacy part uploads also enqueue analysis separately from their existing image records.
|
||||
- Enqueueing waits only for a Mongo upsert, never for inference; a persistence error is logged without failing upload. Viewing the tab re-schedules a missed current photo.
|
||||
- One worker per instance polls every five seconds and claims one job atomically. A lease token guards completion writes across replicas. Expired leases recover after restart; leases last the configured HTTP timeout plus 60 seconds. Storage must be shared across replicas.
|
||||
- Each claim/photo has one job. Repeated reads/uploads do not reset successful or failed analysis. Transient network/server/invalid-response failures retry up to three claims, with 30/60-second delays. Terminal 4xx image errors require explicit retry. A retry exhausted by process crashes is also marked failed.
|
||||
- The worker sends one multipart `images` file to `POST /api/v1/assessments`, with `include_polygons=false` and `include_prices=false` for automatic capture analysis. Explicit expert pricing requests use `include_prices=true`, the configured `price_min_severity`, and a multipart `car` field. The provider also accepts batches of up to 12 images; this adapter intentionally keeps one photo per durable job, using the supported single-image request so results and retries stay tied to their source capture. Managed local files only; no URL fetching, redirects or arbitrary file paths. Maximum file size 15 MiB (enforced before upload), multipart body 16 MiB and response size 2 MiB.
|
||||
- The provider's OpenAPI describes JPEG inputs. Current camera/compression flows emit JPEG; a rejected older format stays visible with a recoverable analysis error.
|
||||
- Current media determines the displayed photos. Replaced and removed photos' job results are retained separately, but never attached to a newer photo or inserted into the live carousel. Existing parts revision history is untouched.
|
||||
|
||||
## JSON and coordinates
|
||||
|
||||
The assessment response contains `request_id`, pipeline provenance, vehicle color/body type, `damaged_parts`, `internal_damages`, and `case_report`. Each damaged part has `part`, `side`, `severity`, `damage_types`, `descriptions`, `localized`, and image-specific `evidence`. Bounding boxes now come from `evidence[].part.box`; confidence and instance IDs also come from the evidence part.
|
||||
|
||||
The adapter retains one normalized part per damaged-part entry with all evidence for the uploaded photo (`image_index: 0`). Only localized parts with `link_status: linked` can produce overlays. Each part can have multiple evidence boxes; all share its numbered label in the UI. Missing/unlinked/invalid coordinates never produce guessed boxes. Evidence belonging to a different image index is excluded. Part descriptions, damage types, possible internal damages, vehicle details, request ID and pipeline versions/hashes are retained. Existing saved results from the retired pipeline remain readable, and the response normalizer retains legacy envelope compatibility.
|
||||
|
||||
Both HTTP error responses and HTTP-success responses containing `{error: {code, message, request_id}}` are failures. HTTP status controls automatic retries; unknown failures use the existing bounded retry policy. Code and request ID are saved for troubleshooting, while experts see Persian error feedback and the request ID. A generic HTTP 400 is no longer assumed to mean no car was found.
|
||||
|
||||
The drawing contract is **pixel coordinates in the uploaded image's displayed intrinsic orientation/dimensions**: `x1,y1,x2,y2`, origin top-left. The UI uses the original image's natural dimensions as the SVG viewBox, scales image and boxes together without letterboxing, and clips boxes to the image. If the provider instead emits resized-image coordinates or uses a different EXIF orientation, its contract must provide those dimensions/orientation before conversion; the UI does not infer them from the largest detection. Validate alignment using a known annotated photo supplied by the AI team before rollout.
|
||||
|
||||
Valid evidence polygons are retained, with invalid placeholder points such as `[null, null]` discarded. The current UI draws bounding boxes; it does not fabricate polygons or masks.
|
||||
|
||||
## Expert UI and access
|
||||
|
||||
Open **گزارش خسارت → تحلیل هوش مصنوعی**. Select a photo, inspect numbered boxes, toggle overlays or select a detected part to highlight its box. Severity, confidence, side, damage types and descriptions are shown next to the detection. Vehicle color/body type and possible internal damage with likelihood/reasons are shown when available; the full report remains available below. Unknown provider labels remain readable rather than being mapped to a guessed catalog ID.
|
||||
|
||||
Pending images poll every five seconds while the tab is mounted and inference is enabled. Failed images offer **تحلیل دوباره تصاویر ناموفق**. Empty, disabled, image-load failure, fetch failure and retry failure states have separate feedback. Existing successful results remain visible when inference is disabled.
|
||||
|
||||
Endpoints:
|
||||
|
||||
- `GET /v2/expert-claim/request/:claimRequestId/ai-analysis`
|
||||
- `POST /v2/expert-claim/request/:claimRequestId/ai-analysis/retry`
|
||||
- `GET /expert-insurer/files/:publicId/ai-analysis`
|
||||
- `POST /expert-insurer/files/:publicId/ai-analysis/retry`
|
||||
- Admin equivalents: `GET /super-admin/insurer/files/:publicId/ai-analysis?clientId=...` and `POST /super-admin/insurer/files/:publicId/ai-analysis/retry?clientId=...`
|
||||
|
||||
Expert endpoints reuse the exact existing claim-detail gate (role, organization, branch, ownership/reviewer assignment and workflow visibility). Insurer endpoints first resolve the existing tenant-scoped public file detail; callers cannot supply a different underlying claim ID. Admin equivalents retain `SuperAdminGuard` and resolve the file inside the explicitly selected client. No public or user endpoint exposes AI results. Responses expose image URLs, status, localized errors and completed compact results; no local paths, raw upstream response or credentials.
|
||||
|
||||
## Development acceptance checks
|
||||
|
||||
1. Enable the environment above; capture two damaged-part JPEGs through any current creation flow. Confirm immediate capture responses and queued/processing jobs.
|
||||
2. Open claim review and its AI tab. Confirm each response belongs to its source photo, repeated detections remain distinct, and boxes line up on desktop/mobile. Confirm JSON severity/confidence and Persian reports match the provider.
|
||||
3. Replace one photo via an allowed resend. Confirm the old result is not shown on the replacement. Remove a part through existing expert editing; confirm its image/result disappears from current analysis while selection history stays intact.
|
||||
4. Stop/restart an API worker during analysis: after lease expiry, a worker must reclaim it. Repeat with two replicas sharing storage; completion must be guarded by the lease token.
|
||||
5. Make the provider unavailable: capture and pricing must still work; retries should stop and the tab should offer retry. Try another tenant/unauthorized claim ID: analysis read/retry must be denied by existing file access controls.
|
||||
|
||||
## Implementation verification
|
||||
|
||||
The historical live probe below used the retired pipeline. The assessment API migration is covered by mocked response, multipart transport, error-envelope and image-size checks; it has not been verified against the live new provider.
|
||||
|
||||
On 2026-10-03 the real multipart adapter successfully called the development pipeline with [Front bumper broken.jpg](https://commons.wikimedia.org/wiki/File:Front_bumper_broken.jpg), a public photograph by Tiia Monto (CC BY-SA 3.0). It returned HTTP 200 and six detections, with Persian reports, severity, confidence and bounding boxes. Rendering was checked against the source JPEG's actual 2121×1188 dimensions. No customer photo was used for this probe. A separate synthetic blank JPEG returned HTTP 500; that failure is handled by the existing bounded retry/error path.
|
||||
|
||||
Backend checks cover upload-to-queue integration, immutable per-photo association, atomic job leases/recovery, retry limits, real multipart bytes/options, response validation, and expert/insurer/admin file-access gates. Frontend checks cover clipping/scaling, readable 24px number badges, report toggles, pending polling, retry, disabled cached results, empty images, fetch recovery and desktop/mobile overflow.
|
||||
|
||||
|
||||
## Unified advisory pricing
|
||||
|
||||
The OpenAI prompt/module, its routes under `/v2/price-estimation`, and the separate
|
||||
expert price tab have been removed. No OpenAI key is needed in this API. Remove
|
||||
`OPENAI_PRICE_ESTIMATION_*` from deployment settings. Existing price-estimate
|
||||
collections are left intact; there is no database deletion or migration.
|
||||
|
||||
The existing AI tab now shows detection and market evidence together. Automatic
|
||||
uploads continue to request detection only. An authorized reviewing expert confirms
|
||||
or enters the damaged vehicle's Persian make/model, selects a current photo, then
|
||||
requests **تحلیل و برآورد قیمت همین تصویر**. The input is prefilled from the panel's
|
||||
resolved damaged-car identity when that name is Persian; missing or English-only
|
||||
names require manual entry. The expert can correct an inquiry name before sending.
|
||||
|
||||
`POST /v2/expert-claim/request/:claimRequestId/ai-analysis/estimate` accepts:
|
||||
|
||||
```json
|
||||
{"imageKey":"<64-character imageKey from the GET response>","carName":"پژو ۲۰۶ تیپ ۲"}
|
||||
```
|
||||
|
||||
It uses the existing claim-detail authorization gate and accepts only a photo from
|
||||
the current case's damage media. It queues work immediately rather than waiting on
|
||||
the upstream model. Failed pricing can use the existing retry endpoint. A running
|
||||
analysis or an already-queued pricing request returns 409 instead of queuing another
|
||||
chargeable request. An explicit request after completion starts a fresh estimate.
|
||||
The submitted car name and severity are stored with that image's job; polling
|
||||
exposes these values while work is pending. Company/super-admin viewers may read
|
||||
saved results and retry detection-only jobs but cannot submit or retry priced analyses.
|
||||
|
||||
The existing backend remains the authorized image transport, durable queue and
|
||||
response adapter. Detection and pricing both come from the same assessment service;
|
||||
there is no separate price-model prompt or market-research orchestration here.
|
||||
|
||||
### Deployment threshold
|
||||
|
||||
`AI_DAMAGE_PRICE_MIN_SEVERITY` accepts `minor`, `moderate`, `severe` (default) or
|
||||
literal `null`. `minor` prices all damaged parts; `moderate` includes moderate and
|
||||
severe parts; `severe` includes only severe parts. The provider's live OpenAPI
|
||||
accepts only the three non-null enum strings, so the `null` setting is adapted to
|
||||
`minor`, meaning all severities. Restart the API after changing configuration.
|
||||
The threshold is recorded per requested job, including on retries.
|
||||
|
||||
### Units, completeness and interpretation
|
||||
|
||||
Provider monetary fields in tomans are converted to rials **once** by the response
|
||||
normalizer: overall/genuine/aftermarket totals, component min/median/max, repair
|
||||
estimates and individual listing prices. Missing/invalid/unsafe numbers remain null,
|
||||
not zero. Unsupported currencies do not acquire a guessed conversion. Provider
|
||||
processing cost and duration remain server-side diagnostics. They are excluded from
|
||||
expert-facing API results, together with request IDs, pipeline versions, model names
|
||||
and hashes, including when reading previously stored jobs. The UI explicitly
|
||||
labels monetary values as rials and identifies an LLM repair guess separately.
|
||||
|
||||
Each job uses one photo, so the provider's `pricing` summary is **that photo's**
|
||||
summary, never a whole-claim total. The UI warns against summing photos: the same
|
||||
physical part may appear in multiple photos. Incomplete results keep their partial
|
||||
warning, priced/unpriced counts and available evidence. No algorithm maps the AI's
|
||||
names to Fanavaran parts or writes prices/repair choices/price drop into the claim.
|
||||
The expert selects the matching catalogue part and enters the final valuation.
|
||||
|
||||
Sources show used/unused status; only absolute HTTP(S) links without credentials
|
||||
are clickable. Price ranges, sample count, spread warning, original/aftermarket
|
||||
alternatives, notes and the result date remain available. Model identity, billing,
|
||||
processing timings and cache diagnostics are not displayed.
|
||||
Legacy detection-only results still render normally. Opening the AI tab does not
|
||||
start paid pricing. No real claim images were sent during implementation tests;
|
||||
transport and UI tests use local fixtures. Validate actual market quality with the
|
||||
AI team before relying on the estimates.
|
||||
@@ -290,7 +290,7 @@
|
||||
<div class="max-wrap">
|
||||
<h1>Blame & Claim Flow Architecture</h1>
|
||||
<p class="subtitle">
|
||||
All active flows — V1 (legacy) · V2 · V3 · V4 · V5 · V6 — with roles,
|
||||
All active UI flows — V1 · V2 · V3 · V4 · V5 · V6 — with roles,
|
||||
route prefixes, and step sequences.
|
||||
</p>
|
||||
|
||||
@@ -394,9 +394,9 @@
|
||||
<th>Claim / Review prefix</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>V1 (legacy)</td>
|
||||
<td><code>blame-request-management/</code></td>
|
||||
<td><code>claim-request-management/</code></td>
|
||||
<td>V1 user screens</td>
|
||||
<td><code>v2/blame-request-management/</code></td>
|
||||
<td><code>v2/claim-request-management/</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>V2 user</td>
|
||||
@@ -478,8 +478,9 @@
|
||||
First party fills blame info and invites the second party via SMS link.
|
||||
An expert blame review is optional. After blame completes the damaged
|
||||
party opens a claim which a damage expert prices.
|
||||
V1 = legacy routes (deprecated, <code>@ApiExcludeController</code>) ·
|
||||
V2 = same logic, <code>v2/</code> prefix, GlobalGuard + RolesGuard (USER).
|
||||
Both current V1 and V2 user screens use the <code>v2/</code> APIs with GlobalGuard + RolesGuard (USER).
|
||||
Retired unversioned V1 mutations are removed; active V1 business rules and the blame-expert APIs remain.
|
||||
See <a href="legacy-api-cleanup.md">the route retirement audit</a> for retained compatibility routes.
|
||||
</p>
|
||||
<div class="grid grid-2">
|
||||
<div class="card">
|
||||
@@ -1142,7 +1143,7 @@
|
||||
<p class="section-intro">
|
||||
Two actors handle the same V3 work split across two controllers.
|
||||
<strong>FileMaker</strong> (<code>v4/file-maker/blame-request-management/</code>)
|
||||
handles the party narrative (OTPs, inquiries, details, signatures) and
|
||||
handles the party narrative (OTPs, inquiries, written details, signatures) and
|
||||
uploads the initial claim documents. <strong>FileReviewer</strong>
|
||||
(<code>v4/file-reviewer/blame-request-management/</code>) handles the
|
||||
damage assessment pass. The final blame video (upload-video) is a no-op
|
||||
@@ -1203,11 +1204,11 @@
|
||||
<div class="step-num purple">5</div>
|
||||
<div class="step-body">
|
||||
<div class="step-label">
|
||||
Location · description · voice (guilty)
|
||||
Written description (guilty; voice optional)
|
||||
</div>
|
||||
<div class="step-route">
|
||||
POST /add-detail-location, /add-detail-description,
|
||||
/upload-voice
|
||||
POST /add-detail-description
|
||||
(location skipped; voice not required)
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
+3680
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,17 @@
|
||||
# Claim beneficiary authorization
|
||||
|
||||
The shared user claim API supports the regular third-party and body-insurance flows. A third-party claim can be created only by the party opposite the recorded `expert.decision.guiltyPartyId`, after the blame case is `COMPLETED` and both parties have accepted and supplied signature files. Both identities must be present and distinct, and the guilty ID must match one of them. An unresolved decision does not grant either party claim creation. Body-insurance claims belong to the first party of the completed blame case.
|
||||
|
||||
`helpers/blame-claim-eligibility.ts` supplies the same eligibility rule to claim creation and the viewer's blame-list/detail guidance. An existing claim remains viewable by both parties, but only the beneficiary receives `CONTINUE_CLAIM`. Claim details include `canAct`; read-only viewers receive no owner action guidance. The user UI sends those viewers to the evaluation screen and hides signing, objections, and invoice-upload controls. An unrelated actor cannot create or mutate the claim.
|
||||
|
||||
New regular claims store the beneficiary in both `owner.userId` and `damagedPartyUserId`, as the in-person flows already do. `owner.clientId` and `owner.userClientKey` still identify the paying insurer (the guilty party's insurer for third-party claims). No existing database rows are rewritten.
|
||||
|
||||
For historical regular claims whose owner is the guilty party, mutation authorization resolves the beneficiary from the linked blame decision rather than granting owner access. Phone-linked user identities remain supported. When the source is unavailable, an explicit `damagedPartyUserId` is authoritative. Snapshot membership alone cannot establish liability because historical and in-person claims have different owner conventions; an ambiguous linked claim is rejected. Standalone legacy claims with neither a linked blame nor snapshot parties retain owner access.
|
||||
|
||||
The specialized expert/registrar creation and capture workflows retain their existing role and initiator checks, including the reorganized flows that create a claim before blame completion. The user creation rule is not imposed on those specialized endpoints.
|
||||
|
||||
For V4/V5 FileMaker files, the FileReviewer must retrieve the precreated claim with `GET /v4|v5/file-reviewer/blame-request-management/claim-id/:requestId`. This lookup verifies organization, branch/location, configured Fanavaran expertise code, sealed-file status, and reviewer assignment. `WAITING_FOR_FILE_REVIEWER` is a valid blame status during this handoff and part selection; blame becomes `COMPLETED` later in the capture workflow. The reviewer acts for the beneficiary through the specialized claim endpoints and must never use ordinary-user claim creation. Manually marking blame complete does not make the reviewer a user beneficiary.
|
||||
|
||||
The user UI stores one active identity. Successful OTP or expert login clears the previous party's token, active case IDs, per-case claim caches, Redux case state, and query data. A legacy browser containing both token keys must log in again. Creation requests are deduplicated per identity and blame case, and a rejected request cannot enable the claim-entry button or borrow an unrelated claim ID. Responses arriving after an account switch cannot overwrite the new account's active claim.
|
||||
|
||||
Regression coverage: `claim-beneficiary-access.spec.ts`, `request-management.user-progress.spec.ts`, `file-reviewer-claim-handoff.spec.ts`, and `ui-user/scripts/test-claim-session.cjs` / `test-claim-entry.cjs`. The handoff tests exercise both V4/V5 controllers, third-party/body files, linked claim lookup, part selection while blame is waiting, and lookup authorization failures. The entry tests execute the shared UI's effect with the actual FileReviewer API adapter, checking role/version routing, errors, and stale responses after account/case changes. Run `npm test -- --runInBand` in `api` and `npm run test:ui` in each UI repository.
|
||||
@@ -0,0 +1,27 @@
|
||||
# Claim resend and invoice workflow regressions — 2026-11-23
|
||||
|
||||
## Reported failures and causes
|
||||
|
||||
- **Resend PUT returned a generic 422.** The exact reported body (part ID 15, no documents and a non-empty description) is accepted for a first resend cycle. The service explicitly returns `DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED` after an earlier resend was fulfilled. The expert proxy discarded that code, and the English explanation fell through to a generic Persian form-validation message. The one-completed-resend policy remains unchanged. The API now gives a specific Persian explanation; the expert proxy retains the code; the sidebar explains and disables a completed resend when its case detail is available, and displays server errors inline.
|
||||
- **Invoice approval shared the assessment submission UI.** Its decisions lived under user opinions and depended on globally initialized factor drafts. It could reach assessment selection/pricing validation and demand damaged parts. Review now belongs to each saved assessment part, beside its invoice viewer. The independent action calls `PATCH /v2/expert-claim/validate-factors/:id` with one decision; it does not update selected damaged parts or resubmit the assessment.
|
||||
- **Mixed replies required a refresh after signing.** The owner page delayed dispatching the pre-signature step by three seconds, the upload callback captured old case state, and the part list also read a stale Redux step. The mutation response now immediately updates the case query, the current API step drives upload permissions, and signature/upload operations invalidate the case query. Pending invoice work also stays visible in in-person flows rather than being hidden by a completion summary.
|
||||
- **Invoice validation could persist changes before rejecting a total.** The service now validates the proposed decisions and the completed-batch V1 total before persistence. The update checks the original case phase and update timestamp (or the parts snapshot for legacy fixtures) to reject a stale write. Invalid/duplicate/unrelated decisions cause no writes. A rejected invoice needs a reason and an expert amount.
|
||||
|
||||
## UI behavior
|
||||
|
||||
- Review actions appear only on `/requests/check`, for claim, field and file-reviewer experts, in the invoice review phase and after all required invoices are uploaded. Insurers and file makers retain viewing access.
|
||||
- Each pending invoice can be approved or repriced/rejected in its own dialog. Enter the **whole line total including labor, in rials**. This is not an additional amount to add to the existing line.
|
||||
- Local validation and server failures keep the dialog/draft available for correction and retry. Cancelling does not save a decision. Saved decisions disappear from the pending controls; case queries refresh. Completing the batch uses `caseStatus` to return to the list, including V5 FileMaker approval.
|
||||
- Signing a mixed reply enables invoice upload on the current page. Every upload refreshes the case. Once all invoices arrive, upload controls and the signature action are replaced by the expert-review waiting state.
|
||||
- The live claim query and in-person query take precedence over the original detail snapshot so refreshed decisions are visible.
|
||||
- The previous invoice controls under user opinions and their unused validation component were removed.
|
||||
|
||||
## Verification
|
||||
|
||||
`test/claim-invoice-resend.e2e-spec.ts` exercises the real Nest controllers, JWT/role guards, DTO validation and workflow services with in-memory persistence. It covers v1–v6 × THIRD_PARTY/CAR_BODY × mixed/all-factor/priced assessments, mixed signing before upload, sequential uploads, duplicate upload rejection, per-invoice partial batches, completion/V5 handoff, malformed/duplicate/unknown decisions, Persian amounts, rejected invoice reasons, cap failure with no writes followed by a corrected retry, stale writes, and the exact resend payload followed by the documented 422 rule.
|
||||
|
||||
The full HTTP suite passes 72 tests with four pre-existing skips. The general API suite retains the ten previously documented failures in `fanavaran-submit-overrides.spec.ts`; they fail at its vehicle-review prerequisite and are unrelated to these changes.
|
||||
|
||||
Both UI suites include invoice regressions. Browser checks at 1440×1100 and 390×844 exercise the rendered expert invoice viewer/review action, required amount validation, an HTTP error with retry, and the actual user result page with canvas signing and two successive invoice uploads without a reload. Browser API replies are intercepted synthetic fixtures; no production case, SMS, Fanavaran or object storage is used. Test artifacts live under `/tmp/invoice-review-*`, and temporary preview routes are removed.
|
||||
|
||||
These are targeted workflow tests, not a claim that every production integration or every application route was manually exercised. Deploy **API, expert UI and user UI together**; there is no environment or database migration requirement.
|
||||
@@ -0,0 +1,38 @@
|
||||
# Driver licence issue dates
|
||||
|
||||
Updated: 2026-11-14.
|
||||
|
||||
The inquiry field is the **issue date**, `driver.driverLicenseDate`, labelled
|
||||
«تاریخ صدور گواهینامه». It is not an expiry date. Both UIs keep the existing
|
||||
structured inquiry contract and send the actual selected date. No replacement
|
||||
checkbox or client-generated Fanavaran status is added.
|
||||
|
||||
For a licensed driver, the date is still required and must be valid and not in
|
||||
the future. The ten-year lower bound has been removed from both UI schemas and
|
||||
the shared API inquiry validator; otherwise an older date would pass the form
|
||||
and still fail at submission. Drivers without a licence retain their existing
|
||||
payload behavior, which omits the licence date.
|
||||
|
||||
The API derives the Fanavaran flag against the **accident date**, preserving the
|
||||
mapping introduced by the pulled changes:
|
||||
|
||||
| Age at accident | Outbound value |
|
||||
|---|---|
|
||||
| Through the third issue-date anniversary | `0` |
|
||||
| After the third anniversary through the tenth anniversary | `null` |
|
||||
| After the tenth anniversary | `1` |
|
||||
|
||||
Hull uses `IsLicenseReplaced`; third-party uses `IsLicenseReplacement`. Recent
|
||||
licences still receive explicit `0` because the current Fanavaran rule requires
|
||||
an answer. Users do not enter this flag themselves. Anniversary comparison uses
|
||||
the actual Jalali year/month/day, so ten years plus one day no longer waits until
|
||||
eleven completed years to become `1`.
|
||||
|
||||
The UIs validate against Iran's current date and reject invalid month/day
|
||||
combinations rather than accepting a date-picker library's rollover. The
|
||||
existing missing-date fallback for legacy records remains unchanged.
|
||||
|
||||
Validation covers old/current/future dates, invalid Jalali dates, Persian input,
|
||||
both insurance products, licensed/unlicensed drivers, inquiry payloads, and
|
||||
three-/ten-year anniversary boundaries. Run `npm run test:ui` in each UI and
|
||||
`npm test -- --runInBand` in the API.
|
||||
@@ -0,0 +1,13 @@
|
||||
# Driving licence selection and display
|
||||
|
||||
`GET /lookups/driving-licence-types` is the source of licence type IDs and captions. It uses the existing tenant-specific Fanavaran disk/DB cache and remote lookup chain. The response is a normalized array of `{ Id, Caption, IsActive }`; unusable or contradictory lookups fail instead of supplying guessed options.
|
||||
|
||||
Both creation interfaces select the actual lookup ID. They disable selection and provide retry when the list is unavailable. They never assume numeric IDs `1`, `2`, or `3` correspond to licence grades, and never substitute free text for a provider ID.
|
||||
|
||||
All ten inquiry entry points in `RequestManagementService` validate licensed drivers against this lookup before saving their inquiry attributes or running the participant inquiries. Unknown/inactive IDs are rejected. Drivers without a licence do not need the lookup.
|
||||
|
||||
`licenseType` remains the selected provider ID. The API adds `licenseTypeLabel`, a caption resolved by the server from that ID, to the normalized driver participant and legacy person data. The existing schemas persist this optional display snapshot; claim party snapshots reuse the same schema. Downstream Fanavaran submissions continue using the original ID.
|
||||
|
||||
Expert views keep IDs unchanged during normalization and resolve them at render time. A saved caption takes priority; older records use the current canonical lookup. Without either source, an unresolved numeric code is explicitly marked as missing its title. Reports no longer apply guessed numeric grade mappings, and licence numbers are not passed through licence type label resolution.
|
||||
|
||||
Deploy API, expert UI, and user UI together. Existing records created with an invented fallback ID cannot be distinguished from valid provider IDs using the stored number alone. Do not automatically remap those records: review the original selection or licence evidence and correct only confirmed cases. No bulk data migration is part of this fix.
|
||||
@@ -0,0 +1,45 @@
|
||||
# Expert access, multiple roles and optional voice
|
||||
|
||||
## Account activation
|
||||
|
||||
In the expert panel, a super-admin selects an insurer, opens **اعضا و کارشناسان → مدیریت**, and uses **غیرفعال کردن / فعال کردن** beside the relevant role account. Insurers can see the status but cannot change it.
|
||||
|
||||
The endpoint is:
|
||||
|
||||
```http
|
||||
PATCH /super-admin/management/staff/:role/:id/status?clientId=<insurer-id>
|
||||
Authorization: Bearer <super-admin-token>
|
||||
Content-Type: application/json
|
||||
|
||||
{"isActive": false}
|
||||
```
|
||||
|
||||
Only a boolean is accepted. The selected account must belong to the supplied insurer. The response excludes passwords and OTPs. The general staff-edit endpoints, including insurer endpoints, do not accept `isActive`.
|
||||
|
||||
Supported roles: `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, `call_center`. Disabling one role account does not disable another role account belonging to the same person. Login and protected expert requests check the saved flag; previously issued tokens cannot be used while that account is disabled. Existing documents without `isActive` are treated as active.
|
||||
|
||||
No existing account, password, case owner or assignment is migrated. Deploy the API before the updated expert UI. No database backfill or index deletion is needed.
|
||||
|
||||
## Same person in several flows
|
||||
|
||||
Create an account for each required role using the same national code, email and password. Continue using the existing login URLs and role selectors. For example, one person can log into `/v4/expert-login` as either a file maker or a file reviewer with the same credentials, provided both assignments have been created. The expert panel likewise uses its existing role selector.
|
||||
|
||||
The creation and edit checks now reject duplicate identifiers **within the selected role**, rather than across all roles. Role collections already have separate indexes, so cross-role reuse requires no production index changes. Within-role uniqueness remains important because login has no insurer selector. This change does not grant another role automatically or merge existing records.
|
||||
|
||||
Credentials remain attached to their existing role records. Administrators should enter the same password when adding another role; changing one role's password does not silently overwrite credentials on another production account. National codes on existing accounts should only be corrected after verifying the person's identity.
|
||||
|
||||
## Voice in v4/v5
|
||||
|
||||
FileMaker flows v4 and v5 no longer display or require the blame voice recorder. Following each party's inquiry, the workflow goes to written details, then signature. Written accident information, car-body description validation, signatures, required documents and reviewer handoff remain in place.
|
||||
|
||||
Older v4/v5 files waiting at `FIRST_VOICE` or `SECOND_VOICE` resume at the corresponding description step. The details page fetches the FileMaker's case through its own `my-files/:requestId` endpoint, with loading/retry states, so reopening does not depend on a previously cached party or case type. The voice-permission notice is also hidden in these flows. Existing recordings, completed-step history and events are retained. The optional upload endpoints are retained for older clients. Other flows keep their voice requirements. The separate claim walk-around video requirement is unchanged.
|
||||
|
||||
## Verification
|
||||
|
||||
- Management tests exercise real Mongoose schemas, cross-role creation/editing, same-role duplicate rejection, activation/reactivation, legacy defaults and tenant boundaries.
|
||||
- HTTP tests use the real management/auth controllers and JWT guards with isolated repositories to verify login, status permissions, rejection of an old token, and the other role remaining usable.
|
||||
- Auth tests cover all staff roles and JWT guard entry points.
|
||||
- Workflow tests cover v4/v5, car-body/third-party, both parties, signatures without voice and older resume states.
|
||||
- Frontend regression scripts cover the status proxy allowlist and v4/v5 submission without voice while retaining the other flows' requirements.
|
||||
|
||||
Run the API suite with `npm test -- --runInBand`, and each frontend suite with `npm run test:ui`. These checks do not use production data or send SMS messages.
|
||||
@@ -19,7 +19,7 @@ Content-Type: application/json
|
||||
|
||||
## بدنه درخواست
|
||||
|
||||
تمام مبلغها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته میشوند؛ برای نمونه هر دو مقدار `"100000"` و `"۱۰۰,۰۰۰"` معتبرند.
|
||||
تمام مبلغها باید **string** باشند. ارقام فارسی/انگلیسی و جداکننده هزارگان پذیرفته میشوند؛ برای نمونه هر دو مقدار `"1000000"` و `"۱۰۰,۰۰۰"` معتبرند.
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -29,12 +29,12 @@ Content-Type: application/json
|
||||
"partId": 201,
|
||||
"typeOfDamage": "تعویض",
|
||||
"price": "2500000",
|
||||
"salary": "400000",
|
||||
"totalPayment": "2900000",
|
||||
"salary": "1000000",
|
||||
"totalPayment": "3500000",
|
||||
"factorNeeded": false,
|
||||
"daghi": {
|
||||
"option": "ارزش لوازم بازیافتی",
|
||||
"price": "300000"
|
||||
"price": "1000000"
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -54,21 +54,29 @@ Content-Type: application/json
|
||||
| --- | --- | --- |
|
||||
| `partId` | بله | عدد صحیح؛ باید متعلق به قطعات آسیبدیده همان پرونده باشد. |
|
||||
| `typeOfDamage` | بله | دقیقاً یکی از `"تعمیر"` یا `"تعویض"`. |
|
||||
| `price` | برای `"تعویض"` بله؛ برای `"تعمیر"` اختیاری | در صورت ارسال، مبلغ بین 100,000 تا 10,000,000,000 تومان. |
|
||||
| `salary` | بله | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
|
||||
| `price` | فقط تعویض با قیمت قطعی | برای ردیف `factorNeeded=true` قیمت قطعه ارسال نشود؛ متن `factor` یا `فاکتور` مبلغ نیست. در صورت ارسال مبلغ، بازه 1,000,000 تا 100,000,000,000 ریال معتبر است. |
|
||||
| `salary` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
|
||||
| `totalPayment` | بله | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. فقط در جریان V1، مجموع این فیلدها در کل پرونده نباید از 530,000,000 ریال بیشتر شود. |
|
||||
| `factorNeeded` | بله | مقدار Boolean واقعی (`true` یا `false`)؛ رشته ارسال نکنید. |
|
||||
| `factorNeeded` | بله | مقدار Boolean واقعی؛ فقط ردیف تعویض میتواند `true` باشد. در تعمیر باید `false` باشد. |
|
||||
| `daghi` | برای `"تعویض"` بله | برای `"تعمیر"` لازم نیست و در ثبت نهایی حذف میشود. |
|
||||
| `daghi.option` | در صورت وجود `daghi` بله | یکی از `"ارزش لوازم بازیافتی"`، `"تحویل داغی"`، `"فاقد ارزش"` یا `"با احتساب داغی"`. |
|
||||
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 100,000 تا 10,000,000,000 تومان. |
|
||||
| `daghi.price` | فقط وقتی `option` برابر `"ارزش لوازم بازیافتی"` است | مبلغ بین 1,000,000 تا 100,000,000,000 ریال. |
|
||||
| `daghi.branchId` | فقط وقتی `option` برابر `"تحویل داغی"` است | Mongo ObjectId معتبرِ شعبه. |
|
||||
|
||||
نکتهها:
|
||||
|
||||
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 100,000 تومان است.
|
||||
- مقدار `0` برای هیچ مبلغ ارسالی این endpoint معتبر نیست؛ حداقل مبلغ 1,000,000 ریال است.
|
||||
- محدودیت هر فیلد مبلغ مستقل است؛ سقف 530 میلیون ریال فقط برای **مجموع `totalPayment` تمام ردیفهای پرونده V1** اعمال میشود. جریانهای V2 تا V6 سقف مجموع ندارند.
|
||||
- فیلدهای ناشناخته در body حذف میشوند. فرانتاند نباید برای انتقال داده به آنها تکیه کند.
|
||||
|
||||
### تغییر روش قیمتگذاری و خطاها
|
||||
|
||||
- انتخاب فاکتور، قیمت قطعی قطعه را پاک میکند؛ `salary` و `totalPayment` همچنان مبلغ عددی معتبر لازم دارند.
|
||||
- تبدیل تعویض به تعمیر، روش فاکتور، قیمت قطعه و اطلاعات داغی را یکجا پاک میکند و مجموع شناختهشده را از اجرت محاسبه میکند.
|
||||
- تبدیل فاکتور به قیمت، `factorNeeded` را خاموش و انتخاب قیمت جدید را الزامی میکند؛ قیمت قدیمی بهطور پنهان استفاده نمیشود.
|
||||
- خطای اعتبارسنجی، پرچم فاکتور یا وضعیت ذخیرهشده پرونده را تغییر نمیدهد. UI پیش از ذخیره تغییرات انتخاب قطعات، پیشاعتبارسنجی میکند و ارسال تکراری همزمان را مسدود میکند.
|
||||
- پیامهای خطای این مسیر با واحد ریال نمایش داده میشوند.
|
||||
|
||||
## پاسخ موفق
|
||||
|
||||
پاسخ `200` شامل مسیر بعدی workflow است. نمونه:
|
||||
@@ -106,7 +114,7 @@ Content-Type: application/json
|
||||
"validationErrors": [
|
||||
{
|
||||
"field": "parts[0].salary",
|
||||
"message": "باید مبلغ صحیح و غیرمنفی به تومان باشد."
|
||||
"message": "باید مبلغ صحیح و غیرمنفی به ریال باشد."
|
||||
},
|
||||
{
|
||||
"field": "parts[0].factorNeeded",
|
||||
@@ -125,14 +133,14 @@ Content-Type: application/json
|
||||
```json
|
||||
{
|
||||
"statusCode": 400,
|
||||
"message": "قیمت قطعه 201 باید حداقل ۱۰۰٬۰۰۰ و حداکثر ۱۰٬۰۰۰٬۰۰۰٬۰۰۰ تومان باشد.",
|
||||
"message": "قیمت قطعه 201 باید حداقل ۱٬۰۰۰٬۰۰۰ و حداکثر ۱۰۰٬۰۰۰٬۰۰۰٬۰۰۰ ریال باشد.",
|
||||
"error": "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
"code": "EXPERT_REPLY_VALIDATION_ERROR",
|
||||
"field": "parts[0].price",
|
||||
"partId": "201",
|
||||
"rule": "amount_out_of_range",
|
||||
"minAmount": 100000,
|
||||
"maxAmount": 10000000000
|
||||
"minAmount": 1000000,
|
||||
"maxAmount": 100000000000
|
||||
}
|
||||
```
|
||||
|
||||
@@ -142,7 +150,7 @@ Content-Type: application/json
|
||||
| --- | --- |
|
||||
| `required` | فیلد لازم ارسال نشده است. |
|
||||
| `invalid_value` | مقدار enum یا شناسه معتبر نیست. |
|
||||
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به تومان نیست. |
|
||||
| `invalid_amount` | مبلغ، عدد صحیح غیرمنفی به ریال نیست. |
|
||||
| `amount_out_of_range` | مبلغ خارج از بازه `minAmount` و `maxAmount` است. |
|
||||
|
||||
در صورت `amount_out_of_range`، برای نمایش محدوده از اعداد `minAmount` و `maxAmount` استفاده کنید، نه از parse کردن متن `message`.
|
||||
|
||||
+18
-120
@@ -319,81 +319,21 @@ curl -X POST "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims" \
|
||||
--data @fanavaran-claim-submit.json
|
||||
```
|
||||
|
||||
## Tejarat Inquiry Provider
|
||||
|
||||
Default base URL:
|
||||
|
||||
```sh
|
||||
TEJARAT_INQUIRY_BASE_URL="${TEJARAT_INQUIRY_BASE_URL:-http://82.99.202.245:3027}"
|
||||
TEJARAT_INQUIRY_EMAIL='xxx@example.com'
|
||||
TEJARAT_INQUIRY_PASSWORD='123321'
|
||||
```
|
||||
|
||||
Used by `src/sand-hub/sand-hub.service.ts` for third-party plate and car-body plate inquiries when ESG is not selected.
|
||||
|
||||
### Sequence
|
||||
|
||||
1. Login to `/user/login`.
|
||||
2. Use returned `accessToken` as `Authorization: Bearer ...`.
|
||||
3. Call inquiry endpoint.
|
||||
|
||||
### Login
|
||||
|
||||
```sh
|
||||
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/user/login" \
|
||||
-H "Accept: */*" \
|
||||
-H "Content-Type: application/json" \
|
||||
--data '{
|
||||
"email": "'"$TEJARAT_INQUIRY_EMAIL"'",
|
||||
"password": "'"$TEJARAT_INQUIRY_PASSWORD"'"
|
||||
}'
|
||||
```
|
||||
|
||||
```sh
|
||||
TEJARAT_ACCESS_TOKEN="<response accessToken>"
|
||||
```
|
||||
|
||||
### Third-Party Plate / Policy Block Inquiry
|
||||
|
||||
```sh
|
||||
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat" \
|
||||
-H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json" \
|
||||
--data '{
|
||||
"leftTwoDigits": "12",
|
||||
"serialLetter": "ب",
|
||||
"threeDigits": "345",
|
||||
"rightTwoDigits": "67",
|
||||
"nationalCode": "0012345678"
|
||||
}'
|
||||
```
|
||||
|
||||
### Car-Body Plate Inquiry
|
||||
|
||||
```sh
|
||||
curl -X POST "$TEJARAT_INQUIRY_BASE_URL/block-inquiry-tejarat/badane" \
|
||||
-H "Authorization: Bearer $TEJARAT_ACCESS_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json" \
|
||||
--data '{
|
||||
"part1": 12,
|
||||
"part2": "ب",
|
||||
"part3": 345,
|
||||
"part4": 67,
|
||||
"nationalCode": "0012345678"
|
||||
}'
|
||||
```
|
||||
|
||||
## ESG Inquiry Provider
|
||||
|
||||
Default/fallback base URL in some call sites:
|
||||
Used by `src/sand-hub/sand-hub.service.ts` for third-party plate/VIN, identity
|
||||
and Sheba inquiries in **every tenant**, including Moalem (`CLIENT_ID=7`).
|
||||
|
||||
```sh
|
||||
ESG_URL="${ESG_URL:-http://192.168.20.22:8085}"
|
||||
ESG_URL="https://<gateway-host>/<optional-prefix>"
|
||||
ESG_USERNAME="<gateway-username>"
|
||||
ESG_PASSWORD="<gateway-password>"
|
||||
```
|
||||
|
||||
Used by `src/sand-hub/sand-hub.service.ts` for selected tenants, for example when `CLIENT_ID=8`.
|
||||
There is no fallback URL or fallback to the deprecated Tejarat provider.
|
||||
Car-body plate and VIN inquiries use the tenant’s Fanavaran profile through
|
||||
`LookupsService.findLastProcessedCarPolicy("car-body", query)`, not ESG.
|
||||
See [inquiry provider routing](inquiry-provider-routing.md) for deployment notes.
|
||||
|
||||
### Sequence
|
||||
|
||||
@@ -417,7 +357,7 @@ curl -X POST "$ESG_URL/auth/login" \
|
||||
ESG_ACCESS_TOKEN="<response accessToken>"
|
||||
```
|
||||
|
||||
### Car By Plate (canonical Parsian third-party plate inquiry)
|
||||
### Car By Plate (third-party inquiry for all tenants)
|
||||
|
||||
```sh
|
||||
curl -X POST "$ESG_URL/inquiry/carByPlate" \
|
||||
@@ -483,15 +423,18 @@ curl -X POST "$ESG_URL/inquiry/sheba" \
|
||||
|
||||
## SandHub Provider
|
||||
|
||||
Used by `src/sand-hub/sand-hub.service.ts` for legacy inquiry flows.
|
||||
Used only for the optional driving-licence and legal vehicle-ownership checks.
|
||||
The current ESG API has no equivalent contract for these checks. Plate/VIN,
|
||||
personal identity and Sheba inquiries do not use this adapter. Configure these
|
||||
settings only when the optional checks are enabled.
|
||||
|
||||
Environment:
|
||||
|
||||
```sh
|
||||
SANHUB_BASE_URL='http://82.99.202.245:3027'
|
||||
SANHUB_URL_LOGIN='http://82.99.202.245:3027/user/login'
|
||||
SANHUB_USERNAME='default@admin.com'
|
||||
SANHUB_PASSWORD='123321'
|
||||
SANHUB_BASE_URL='https://<optional-check-provider>'
|
||||
SANHUB_URL_LOGIN='https://<optional-check-provider>/<login-path>'
|
||||
SANHUB_USERNAME='<optional-check-username>'
|
||||
SANHUB_PASSWORD='<optional-check-password>'
|
||||
```
|
||||
|
||||
### Sequence
|
||||
@@ -515,37 +458,6 @@ curl -X POST "$SANHUB_URL_LOGIN" \
|
||||
SANHUB_ACCESS_TOKEN="<response accessToken>"
|
||||
```
|
||||
|
||||
### Third-Party Plate / Policy Block Inquiry
|
||||
|
||||
```sh
|
||||
curl -X POST "$SANHUB_BASE_URL/block-inquiry-tejarat" \
|
||||
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json" \
|
||||
--data '{
|
||||
"leftTwoDigits": "12",
|
||||
"serialLetter": "ب",
|
||||
"threeDigits": "345",
|
||||
"rightTwoDigits": "67",
|
||||
"nationalCode": "0012345678"
|
||||
}'
|
||||
```
|
||||
|
||||
### Personal Inquiry
|
||||
|
||||
The app converts Jalali birth dates to Gregorian before sending to SandHub.
|
||||
|
||||
```sh
|
||||
curl -X POST "$SANHUB_BASE_URL/personal-inquiry/tejarat-no" \
|
||||
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json" \
|
||||
--data '{
|
||||
"nationalCode": "0012345678",
|
||||
"birthdate": "1999-02-13"
|
||||
}'
|
||||
```
|
||||
|
||||
### Driving License Check
|
||||
|
||||
```sh
|
||||
@@ -575,20 +487,6 @@ curl -X POST "$SANHUB_BASE_URL/ownership" \
|
||||
}'
|
||||
```
|
||||
|
||||
### Sheba Validation
|
||||
|
||||
```sh
|
||||
curl -X POST "$SANHUB_BASE_URL/sheba/sheba-tejaratno" \
|
||||
-H "Authorization: Bearer $SANHUB_ACCESS_TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Accept: application/json" \
|
||||
--data '{
|
||||
"AccountOwnerType": "1",
|
||||
"NationalId": "0012345678",
|
||||
"ShebaId": "IR000000000000000000000000"
|
||||
}'
|
||||
```
|
||||
|
||||
## Map.ir Reverse Geocoding
|
||||
|
||||
Used by `src/claim-request-management/claim-request-management.service.ts`.
|
||||
|
||||
@@ -422,28 +422,21 @@
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════════════════════════════════════════════════ -->
|
||||
<h2 id="ai">7 — AI Service <span class="status-badge status-disabled">disabled (code present)</span></h2>
|
||||
<h2 id="ai">7 — AI Damage Companion <span class="status-badge status-partial">opt-in development rollout</span></h2>
|
||||
<p class="section-intro">
|
||||
An image-based car damage detection service is integrated in the
|
||||
codebase but its HTTP calls are <strong>fully commented out</strong>.
|
||||
The module initialises on startup, attempts a login (silently swallowed
|
||||
if it fails), and exposes an <code>aiRequestImage</code> method — but
|
||||
the underlying axios calls are disabled. The service does not affect
|
||||
any production flow.
|
||||
Damaged-part uploads schedule persisted background analysis in <code>ai-damage-jobs</code>.
|
||||
Expert review shows the original photo with client-drawn bounding boxes, per-detection severity,
|
||||
confidence, side and Persian reports. The AI does not set prices, change selected parts,
|
||||
advance workflow steps, or replace the expert decision.
|
||||
</p>
|
||||
|
||||
<div class="card card-yellow">
|
||||
<h3>Intended interface (when re-enabled)</h3>
|
||||
<h3>Development pipeline</h3>
|
||||
<table>
|
||||
<tr><th style="width:70px">Method</th><th>Path</th><th>What it does</th></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>{AI_URL_V2}/auth/login</code></td><td>Authenticate with username + password. Returns <code>accessToken</code>.</td></tr>
|
||||
<tr><td><span class="method get">GET</span></td><td><code>{AI_URL_V2}/auth/profile</code></td><td>Fetch <code>apiKey.key</code> needed as the <code>gateway-api-key</code> request header.</td></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>{AI_URL_V2}/services/car-damage/detector?version=ai-v7</code></td><td>Submit a car part image (multipart). Returns <code>downloadLink</code> with annotated result.</td></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>{AI_DAMAGE_URL}/pipeline/detect_parts_with_damages?side=true&segments=true&bounding_box=true&severity=true&confidence=true</code></td><td>One JPEG per multipart <code>images</code> request. Returns JSON detections and reports; no image URL or pricing.</td></tr>
|
||||
</table>
|
||||
<p class="warn" style="margin-top:8px;">
|
||||
Status: all three calls are wrapped in commented-out <code>axios.request(…)</code> blocks.
|
||||
<code>CW_URL</code> is not in <code>.env.example</code>. To re-enable, uncomment the login, getApiKey, and aiRequestImage axios calls, and configure <code>AI_URL_V2</code>, <code>AI_USERNAME</code>, <code>AI_PASSWORD</code>.
|
||||
</p>
|
||||
<p class="note">Disabled unless <code>AI_DAMAGE_ENABLED=true</code>. Atomic leases recover jobs after restart; transient errors receive bounded retries. Uploads and expert review continue when AI is unavailable. Replaced or removed photos are excluded from the live AI tab. Older current captures are scheduled when an authorized reviewer opens the tab.</p>
|
||||
<p><a href="ai-damage-companion.md">Configuration, result contract, access controls and rollout checks</a></p>
|
||||
</div>
|
||||
|
||||
<!-- ═══════════════════════════════════════════════════════════ -->
|
||||
@@ -563,9 +556,9 @@
|
||||
<h3>AI service</h3>
|
||||
<table class="env-table">
|
||||
<tr><th>Variable</th><th>Description</th></tr>
|
||||
<tr><td><code>AI_URL_V2</code></td><td>AI gateway base URL. Default: <code>https://ai-gw.ittalie.ir</code> (unused — service is disabled)</td></tr>
|
||||
<tr><td><code>AI_USERNAME</code></td><td>AI service login username (unused)</td></tr>
|
||||
<tr><td><code>AI_PASSWORD</code></td><td>AI service login password (unused)</td></tr>
|
||||
<tr><td><code>AI_DAMAGE_ENABLED</code></td><td>Explicit opt-in (<code>true</code>); defaults to disabled.</td></tr>
|
||||
<tr><td><code>AI_DAMAGE_URL</code></td><td>Development base URL: <code>http://79.132.207.77:30527</code>. Required when enabled.</td></tr>
|
||||
<tr><td><code>AI_DAMAGE_TIMEOUT_MS</code></td><td>Request timeout; default 180000 ms (1000–600000).</td></tr>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
# Expert editing of Fanavaran stage fields
|
||||
|
||||
The expert panel's existing Fanavaran review tab now includes accident and assessment fields, alongside the four vehicle classification fields. All supported expert-panel roles use the existing claim-detail authorization and tenant/assignment/branch checks.
|
||||
|
||||
## Supported fields and lookups
|
||||
|
||||
| Field | Case type | Sending stage | Input / lookup |
|
||||
| --- | --- | --- | --- |
|
||||
| AccidentLocationAddress | Both | Base claim | Non-empty address, up to 1,000 characters |
|
||||
| AccidentCityId | Both | Base claim | `cities` |
|
||||
| AccidentReportTypeId | Both | Base claim | `accident-report-type` |
|
||||
| NotifierTypeId | Both, **TejaratNo only** | Base claim | Supplied `notifier-type` IDs **5516 / 5517**; 5518 is excluded |
|
||||
| NotifierRelationId | Both, **TejaratNo only** | Base claim | Supplied `notifier-relation` IDs **5519–5526** |
|
||||
| DmgHistoryStatus | Third-party | Damage case | `dmg-history-status` (`dmg-case-history-status` upstream) |
|
||||
| InspectionPlaceId | Third-party | Expertise | `inspection-place` |
|
||||
| AccidentTypeId | Car-body | Base claim | `vehicle-hull-accident-types` |
|
||||
| CulpritTypeId | Car-body | Base claim | `vehicle-hull-accident-culprit-type`; never the third-party culprit codebook |
|
||||
| AuthorityCulpritId | Car-body | Base claim | `detection-accident-culprits` |
|
||||
| CustomerFaultPercent | Car-body | Base claim | Integer 0–100, including zero |
|
||||
| RepairDuration | Car-body | Expertise | Positive integer days |
|
||||
| VehicleCurrentValue | Car-body | Expertise | Positive integer **rials**, forwarded unchanged |
|
||||
|
||||
The seven original remote lookup definitions already existed. Options use the deployment's active Fanavaran client and its existing live/cache lookup service. Only active canonical `Id` values are accepted; captions are resolved server-side. Array and nested `data` lookup envelopes are supported. Missing/empty lookups are shown as unavailable and cannot be replaced with guessed IDs.
|
||||
|
||||
### TejaratNo notifier review
|
||||
|
||||
For the configured deployment tenant `tejaratno` (`FANAVARAN_CLIENT`, case-insensitive), the same tab shows **نوع اعلامکننده** and **نسبت اعلامکننده**. The API supplies and validates the tenant-provided IDs/captions directly; these two lists do not depend on a remote fetch or a guessed Fanavaran lookup URL. They are also available through the existing `GET /lookups/fanavaran/notifier-type` and `GET /lookups/fanavaran/notifier-relation` routes for this tenant. Other tenants cannot edit or request these tenant-specific fields.
|
||||
|
||||
Neither selection has a guessed default. Both must be saved before initial vehicle approval/initial Fanavaran submission. Initial combined approval saves the IDs, captions and history atomically. Missing or excluded values cannot bypass the rule through old clients or manual submission: manual initial submission returns `409` with `FANAVARAN_NOTIFIER_REVIEW_REQUIRED`; automatic submission skips until the fields are reviewed. Already approved, unsent claims can save them with the existing versioned field PATCH endpoint. Saving fields alone does not send a remote request.
|
||||
|
||||
The selections are sent as `NotifierTypeId` / `NotifierRelationId` on GEN.03 for both third-party and car-body claims. Hull filtering preserves them only for TejaratNo. They lock once the base stage is sent. Existing submitted claims remain usable without a migration; submitted notifier values are preserved on subsequent hull synchronization, and unknown legacy values are not overwritten with null.
|
||||
|
||||
The notifier payload property names follow the proposed contract; the tenant did not provide an upstream schema. Live Fanavaran acceptance must be verified in tenant QA. No remote writes are performed by regression tests.
|
||||
|
||||
`VehicleCurrentValue` can remain unset when no expert override exists, preserving the existing case-value/policy-value fallback. A stored override cannot be cleared with null or an empty string. This review does not change the application's other valuation fields or calculate price drop.
|
||||
|
||||
## Sending and editing
|
||||
|
||||
- The initial vehicle approval accepts the applicable stage fields in the same database update. Only after that update does the existing automatic base/damage submission resume. The new panel requires valid fields and explicit consent before initial approval.
|
||||
- For already approved cases, experts save changes independently, before the relevant stage is sent. Saving fields does not itself perform a remote write.
|
||||
- Base fields lock when the base claim exists; `DmgHistoryStatus` locks when the damage case exists; assessment fields lock when expertise exists. Stage IDs and successful sync states are checked in both validation and the conditional database update.
|
||||
- Car-body still skips damage-case creation, sends only its base/expertise whitelist, and retains required null values. Third-party payloads retain their existing explicit null keys.
|
||||
- No attempt is made to edit already sent base fields through the unreliable hull PUT route.
|
||||
|
||||
## Endpoints and persistence
|
||||
|
||||
- `GET /v2/expert-claim/request/:id/fanavaran-stage-fields`: applicable field definitions, current/default/submitted values, captions, compact lookup rows and per-field editability. This read does not submit a claim or persist a preview.
|
||||
- `PATCH /v2/expert-claim/request/:id/fanavaran-stage-fields`: `{ values: { ...changedFields }, expectedVersion: 0, confirmed: true }`. Values must apply to the product and belong to an unsent stage. Stale versions or stages sent during validation return `409`.
|
||||
- Existing `PUT .../fanavaran-vehicle-review` additionally accepts optional `stageFields` and `stageFieldsVersion` for the initial combined approval. Older clients retain their existing behavior for other tenants; TejaratNo requires the two notifier selections before initial approval.
|
||||
|
||||
Validated overrides and captions are stored in optional `claimCases.fanavaranFieldReview`, with version, reviewer and review timestamp. History events record before/after values and verified captions. Existing claims keep their existing defaults/fallbacks until reviewed; no migration or bulk data rewrite is required.
|
||||
|
||||
The review covers the eleven original requested fields, the two TejaratNo-only notifier fields and the existing vehicle classification. It does not expose derived totals, provider identifiers, staff-role identifiers or every remaining field in the stage documents for arbitrary editing.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Fanavaran vehicle review gate
|
||||
|
||||
Fanavaran vehicle values returned by external inquiries are advisory only. No outbound Fanavaran stage may create or upload data until an authorized claim-panel actor has approved all four vehicle values.
|
||||
|
||||
## Reviewed values
|
||||
|
||||
| UI field | Fanavaran source | Stored value |
|
||||
| ----------- | ------------------------------ | --------------------------------------- |
|
||||
| نوع خودرو | `vehicle-groups` | `fanavaranVehicleReview.vehicleGroup` |
|
||||
| نوع استفاده | `vehicle-use-types` | `fanavaranVehicleReview.vehicleUseType` |
|
||||
| سیستم خودرو | `vehicle-systems` | `fanavaranVehicleReview.vehicleSystem` |
|
||||
| نام خودرو | filtered `vehicle-kinds` cache | `fanavaranVehicleReview.vehicleKind` |
|
||||
|
||||
The persisted review is an authoritative snapshot containing IDs, captions, relationship IDs, reviewer identity/role, approval time, and a monotonically increasing version. `vehicleUseType.id` is used as GEN.03/GEN.12 `AccidentVehicleUsedId`; `vehicleKind.id` is used as GEN.12 `VehicleKindId`.
|
||||
|
||||
## Inquiry prefill and trust boundary
|
||||
|
||||
The options response also includes an unapproved `suggestion`. It is built from the damaged party's role-specific inquiry snapshot and never writes to `fanavaranVehicleReview` by itself.
|
||||
|
||||
Matching order:
|
||||
|
||||
1. A direct Fanavaran `VehicleKindId`/`vehicle.vehicleKind.Id` is validated against the active `vehicle-kinds` cache. Its `VehicleGroupId` and `VehicleSystemId` relationships provide the group and system.
|
||||
2. A direct Fanavaran `UsedId`/`vehicle.used.Id` is accepted only when it is active and belongs to the matched vehicle group.
|
||||
3. Otherwise semantic inquiry captions are normalized (Persian/Arabic yeh and kaf, digits, whitespace) and exactly matched: `vehicleKind`/`MapTypNam`, `vehicleSystemTitle`/`SystemField`, `UsageField`/`usage`, and `vehicleGroupTitle`.
|
||||
4. Ambiguous or relationship-incompatible results remain empty and produce a warning for manual expert selection.
|
||||
|
||||
Legacy provider codes `UsgCod`, `VehSysCod`, and `CarGrpCod` are returned only under `suggestion.legacyCodes` for audit. They are deliberately **not** used as Fanavaran IDs because their numeric domains differ; for example, inquiry `UsgCod=8` can mean personal use while Fanavaran's personal-use lookup ID is `1`.
|
||||
|
||||
The panel applies the suggestion once, displays its matched-field count and raw legacy codes, leaves consent unchecked, and lets the expert replace any value before approval.
|
||||
|
||||
## Panel endpoints
|
||||
|
||||
- `GET /v2/expert-claim/request/:claimRequestId/fanavaran-vehicle-options?vehicleGroupId=1` returns active groups and only the compatible use types/systems for the selected group.
|
||||
- `GET /lookups/vehicle-list?q=پراید&limit=30&vehicleGroupId=1&vehicleSystemId=14` performs the bounded async vehicle-kind search.
|
||||
- `PUT /v2/expert-claim/request/:claimRequestId/fanavaran-vehicle-review` accepts the four IDs plus `confirmed: true`.
|
||||
|
||||
The approval endpoint re-resolves every caption server-side and rejects inactive values or a group/use/system/kind relationship mismatch. Client-supplied captions are never trusted. A successful approval resumes base-claim submission and, when selected damage parts already exist, the damage-case stage.
|
||||
|
||||
The same tab also supports [expert editing of accident and assessment fields](fanavaran-stage-field-review.md). Initial approval can save `stageFields` with `stageFieldsVersion` atomically alongside vehicle classification, before automatic submission resumes. Fields for subsequent unsent stages remain editable independently after the vehicle classification locks.
|
||||
|
||||
## Outbound enforcement
|
||||
|
||||
Base claim, damage case, attachments, and expertise writes enforce the persisted approval. Automatic stages are deferred with a skip reason; manual stages return `409` with code `FANAVARAN_VEHICLE_REVIEW_REQUIRED`. Read-only previews remain available for diagnosis.
|
||||
|
||||
Once Fanavaran has created the base claim, the review is immutable in the panel because changing it would make the local snapshot disagree with data already written remotely.
|
||||
|
||||
|
||||
## Recovery for previously submitted base claims
|
||||
|
||||
New base submissions (automatic and manual) require vehicle approval. Existing base claims are reused without another POST.
|
||||
|
||||
A case whose base was already submitted without vehicle approval may receive its first approval while `dmgCaseId` and `expertiseId` are absent. This uses the normal authorized review endpoint and active lookup/relationship validation. Approval preserves the existing base IDs and resumes damage submission when selected parts exist. The update compares the current review and stage IDs atomically so a competing approval or submission requires refresh.
|
||||
|
||||
An approved classification stays locked after base submission. Recovery does not rewrite the remote base payload. Base and damage use-type derivation can refer to different parties, so recovery does not impose equality between their use-type fields.
|
||||
@@ -20,7 +20,7 @@ Common business headers (after Login):
|
||||
| `authenticationToken` | Login response |
|
||||
| `CorpId` | Tenant auth |
|
||||
| `ContractId` | Tenant auth |
|
||||
| `Location` | Tenant auth |
|
||||
| `Location` | Assigned staff `locations[].id` (all expert roles); tenant auth only as fallback |
|
||||
| `Content-Type` | `application/json` (except GEN.07 multipart) |
|
||||
|
||||
Template values below are **Parsian-proven** unless noted.
|
||||
@@ -156,7 +156,7 @@ History: `FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED`.
|
||||
"EstimateAmount": 1000,
|
||||
"PolicyId": 13764408,
|
||||
"CulpritLicenceNo": "1124242",
|
||||
"CulpritLicenceIssuDate": "1394/10/13",
|
||||
"CulpritLicenceIssuDate": "1404/08/20",
|
||||
"DamagedCount": 1,
|
||||
"IsLicenseMatchWithVehicleKind": 1,
|
||||
"HasOtherCulprit": 0,
|
||||
|
||||
@@ -23,14 +23,44 @@ Secrets are **not** printed here — read from Mongo `fanavaranClientConfigs` or
|
||||
| `password` | *(config)* | Login | Password | ✅ |
|
||||
| `corpId` | `543` | All business calls | Corp scope | ✅ |
|
||||
| `contractId` | `28` | All business calls | Contract | ✅ |
|
||||
| `location` | `210050` | All business calls / OpBUId | Branch/location | ✅ |
|
||||
| `location` | `210050` | General calls without claim context | Tenant default OpBUId | ✅ (claim submissions require a staff location or branch code) |
|
||||
|
||||
Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(key)`.
|
||||
|
||||
Claim submissions resolve `Location` from staff profiles in the `file-maker`,
|
||||
`file-reviewer`, `expert`, `damage-expert`, and `field-expert` collections. Each
|
||||
profile stores `locations: [{ id, name }]`; the first non-empty `id` is its primary
|
||||
Fanavaran OpBUId. When staff locations are missing, null, or empty, resolve that
|
||||
staff member's `branchId` in the `branches` collection and use the branch's `code`
|
||||
as the OpBUId. This branch fallback is checked before moving to another staff
|
||||
candidate. The branch document's `_id` is never sent as the HTTP Location.
|
||||
|
||||
Resolution priority: claim initiator → blame initiator → active damage reply actor
|
||||
→ assigned damage reviewer → assigned FileReviewer → assigned blame expert → blame
|
||||
decision actor. The first candidate with a location wins. A missing blame record
|
||||
does not discard the claim's own staff. When none has a location, claim submission
|
||||
fails with `FANAVARAN_STAFF_LOCATION_MISSING` instead of sending the tenant default.
|
||||
Base claim, damage, attachment, expertise, hull update, and GEN.44 create calls use
|
||||
the same claim header resolver. Authentication requests do not send Location;
|
||||
the cached login token can be reused across staff locations.
|
||||
|
||||
---
|
||||
|
||||
## Payload defaults (tenant profile.defaults)
|
||||
|
||||
Hull submissions validate selected codebook IDs against fresh Fanavaran API
|
||||
responses before every create, base update, attachment upload, and expertise write.
|
||||
These checks bypass lookup-file and database caches. Missing or inactive IDs block
|
||||
the remote write with `FANAVARAN_HULL_LOOKUP_INVALID`; they are never accepted merely
|
||||
because they appear in the defaults below. Hull collision type, culprit type,
|
||||
authority, damage kind, and cost kind select matching captions from API responses
|
||||
without numeric fallbacks. Policy accessories are read for the current PolicyId;
|
||||
ActualPremium is refreshed from that policy's TotalPremium. Expert-entered amounts
|
||||
and durations remain expert data. Licence issue dates have no 10-year intake
|
||||
cutoff. The server derives `IsLicenseReplaced`: `0` through the third anniversary,
|
||||
`null` after three years through the tenth anniversary, and `1` after ten years,
|
||||
measured against the accident date. Third-party uses `IsLicenseReplacement`.
|
||||
|
||||
| Name | Shared seed | Parsian override | Tejaratno | Moallem | Varies? |
|
||||
|------|-------------|------------------|-----------|---------|---------|
|
||||
| `AccidentCityId` | 701 | same | same | same | usually ❌ |
|
||||
@@ -47,7 +77,7 @@ Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(ke
|
||||
| `PlaqueSampleId` | 10 | same | same | same | may ✅ |
|
||||
| `DriverIsOwner` | 0 | same | same | same | ❌ |
|
||||
| `FaultPercent` | 100 | same | same | same | ❌ |
|
||||
| `ClaimFileTypeId` (GEN.07) | 23 | **63** | 23 | 23 TBD | ✅ |
|
||||
| `ClaimFileTypeId` (GEN.07) | 23 | **63** | 23 | **17** | ✅ |
|
||||
|
||||
**Never swap** GEN.03 `ClaimExpertId` with GEN.08 `ExpertiseClaimExpertId` — different Fanavaran roles.
|
||||
|
||||
|
||||
@@ -113,7 +113,7 @@ flowchart TD
|
||||
|
||||
| Stage | Auto trigger | Function |
|
||||
|-------|--------------|----------|
|
||||
| Base | Claim create (early) | `autoSubmitToFanavaranV2OnClaimCreated` |
|
||||
| Base | Claim create (early; V1/V2/V3/file-maker creates; not deferred to expertise) | `autoSubmitToFanavaranV2OnClaimCreated` |
|
||||
| Base | Claim completed (legacy/fallback; skips if already submitted) | `autoSubmitToFanavaranV2OnClaimCompleted` |
|
||||
| Damage | After outer parts selection | `autoSubmitFanavaranDamageCaseOnOuterPartsSelected` |
|
||||
| Attachments | After successful local image/doc upload | `autoSubmitFanavaranAttachment` |
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
---
|
||||
last_updated: 2026-08-08
|
||||
last_updated: 2026-11-09
|
||||
tags: [fanavaran, yara, integration]
|
||||
source: fanavaran-module-docs
|
||||
---
|
||||
@@ -45,12 +45,44 @@ source: fanavaran-module-docs
|
||||
| Controller | `FanavaranController.preview` / `submit` |
|
||||
| Service | `ClaimRequestManagementService` |
|
||||
| Functions | `previewFanavaranSubmitV2`, `submitFanavaranV2`, `executeFanavaranV2Submit`, `buildFanavaranSubmitPayload`, `getPolicyIdFromNationalCode` |
|
||||
| When | Auto on claim create; manual preview/submit |
|
||||
| When | Auto on claim create (all create paths including V3); soft-ensure before later stages; manual preview/submit. Vehicle review is **not** required for GEN.03 — only for damage/attachments/expertise. |
|
||||
| Send | GEN.03 JSON + business headers |
|
||||
| Receive | `Id`, `ClaimNo` |
|
||||
| Store | `claimId`, `claimNo`, `fanavaranSync.baseClaim.*`, history |
|
||||
| Consumers | Damage/expertise soft-ensure; UI claim detail |
|
||||
|
||||
Hull base claims always GET the selected hull policy, then GET its `VehicleId`
|
||||
at `VehicleVersionNo`. `AccidentVehicleUsedId` is that vehicle response's
|
||||
`UsedId`. This path does not substitute a guilty-party VIN, cached use id,
|
||||
expert override, tenant default, or a generic lookup row. Missing `UsedId`
|
||||
produces `FANAVARAN_HULL_VEHICLE_USE_UNRESOLVED` in preview and blocks submit.
|
||||
Debug preview exposes `accidentVehicleUsedId` and `accidentVehicleUsedSource`.
|
||||
|
||||
#### Staff source for ClaimExpertId across request flows
|
||||
|
||||
The flows in `docs/Yara724 flows.pdf` share the same base-claim resolver.
|
||||
Base claims use `ThirdPartyClaimExpertId` / `CarBodyClaimExpertId`; expertise
|
||||
uses `ThirdPartyExpertiseClaim` / `CarBodyExpertiseClaim` from staff profiles.
|
||||
|
||||
| Local flow | Base-claim staff source | Expertise staff source |
|
||||
|------------|------------------------|------------------------|
|
||||
| V1/V2 user, including expert-panel review | Blame expert when present; otherwise claim damage-review actor or persistent reviewer assignment | Claim damage-review actor |
|
||||
| V2 expert-initiated / V3 | Initiating field expert, then blame expert; claim damage reviewer is a fallback | Claim damage-review actor |
|
||||
| V4 / V5 | Initiating FileMaker | Assigned FileReviewer |
|
||||
|
||||
Outside V4/V5, base resolution checks blame initiator, blame assigned expert,
|
||||
blame deciding expert, claim initiator, claim reply actor, then
|
||||
`workflow.assignedForReviewBy.actorId`, in that order. Reply actor selection
|
||||
matches expertise: the active submitted reply, then final/initial reply actor.
|
||||
Temporary workflow locks are not reviewer assignments.
|
||||
|
||||
An unassigned user-created claim can still have no expert early in its lifecycle:
|
||||
preview returns a missing-expert warning, and submit requires a resolvable code.
|
||||
Tenant defaults and unrelated staff profiles do not supply expert ids.
|
||||
For example, a claim review actor with `ThirdPartyClaimExpertId="5507"` and
|
||||
`ThirdPartyExpertiseClaim="5510"` supplies base `ClaimExpertId=5507` and
|
||||
expertise `ClaimExpertId=5510`.
|
||||
|
||||
### C. Damage case
|
||||
|
||||
| | |
|
||||
|
||||
@@ -90,7 +90,7 @@ Create only on GEN.12 submit when inquiry missed. Cache `otherPersonId` + `drive
|
||||
|-------------------|------------------|
|
||||
| `corpId` | `CorpId` |
|
||||
| `contractId` | `ContractId` |
|
||||
| `location` | `Location` |
|
||||
| staff `locations[].id` (else tenant `auth.location`) | `Location` |
|
||||
| token from Login | `authenticationToken` |
|
||||
|
||||
## Not mapped / out of scope
|
||||
|
||||
@@ -24,6 +24,7 @@ source: fanavaran-module-docs
|
||||
| Missing PolicyId | No/expired policies messages | Block submit; preview may leave null | Manual after data fix | Stage fail history | Admin |
|
||||
| Duplicate create | Local `claimId`/`claimNo` exists | Skip create; use follow-ups | N/A | skipReason | — |
|
||||
| Invalid FileTypeId | `نوع فايل با منبع لوکاپ مطابقت ندارد` | Set `ClaimFileTypeId` from tenant `file-types` (Parsian **63**) | After config fix | Attachment stage | Ops |
|
||||
| Invalid file bytes | `فرمت فایل معتبر نیست` | File is not a real JPEG/PNG/PDF (wrong magic bytes / empty / WEBP-as-jpg). YARA now sniffs magic + sets multipart `contentType` before upload | After replacing the file | Attachment stage | Ops / user re-upload |
|
||||
| Expertise not ready | `Fanavaran expertise payload is not ready` + warnings | Wait for priced parts / factor | Auto when ready | — | Expert UI |
|
||||
| Network / 5xx | Axios / gateway errors | Stage failed + schedule retry | Up to `maxRetries` (2) | Audit | Ops |
|
||||
| Max retries exhausted | Logged warn | Manual submit only | Stop auto | Stage status | Ops |
|
||||
|
||||
@@ -11,7 +11,7 @@ source: fanavaran-module-docs
|
||||
1. `FANAVARAN_CLIENT=parsian` (or target tenant)
|
||||
2. Valid tenant credentials in Mongo / seed
|
||||
3. `INSURANCE_CORP_ID` matching that tenant’s insurance-corp Caption
|
||||
4. Network access to `apimanager.iraneit.com`
|
||||
4. Network access to the tenant host (`api.inssw.ir` for Moallem; `apimanager.iraneit.com` for Parsian / Tejaratno)
|
||||
5. Optional: warm lookups via first `GET /lookups/fanavaran/{name}` or auth script
|
||||
|
||||
## Auth smoke test
|
||||
@@ -52,6 +52,16 @@ Fill **section A** before the first run:
|
||||
|
||||
Lookup ids from Tejaratno/Parsian files are invalid for Moallem (Fanavaran returns `نوع خودرو یافت نشد` and similar). Fetch Moallem lookups first (`GET /lookups/vehicle-kinds` with `FANAVARAN_CLIENT=moallem`, or curl Fanavaran with that tenant’s token).
|
||||
|
||||
For Moallem V14, keep `FANAVARAN_API_VERSION=v14`. The script retains the V14 `AnnouncementDate` field and embeds a `DmgNotifications` item in the GEN.03 request. Fill `CLAIM_NOTIFICATION_DATE`, `NOTIFIER_TYPE_ID`, `NOTIFIER_RELATION_ID`, and `NOTIFIER_PARTY_ID` with Moallem values; the type and relation IDs must come from Moallem's own lookups. This is a live contract probe for Moallem's V14 endpoint. It does not call the V15-only GEN.30 endpoint.
|
||||
|
||||
### Browser UI for Moallem V14
|
||||
|
||||
Use the prepared Moallem env file as the UI server's working file:
|
||||
|
||||
FANAVARAN_FLOW_ENV=scripts/data/fanavaran-flow.moallem.env node scripts/fanavaran-flow-ui-server.js
|
||||
|
||||
Open http://127.0.0.1:17824, confirm the client is moallem and API version is v14, then refresh Moallem's tenant lookups. The notifier form is available for Moallem V14; enter the reporting party's national code and birth date, inquire the party, and select Moallem's notifier type and relation. Submitting GEN.03 sends the V14 body plus the embedded notifier.
|
||||
|
||||
### 2. Network / IP whitelist
|
||||
|
||||
Fanavaran Login is IP-restricted. From a **whitelisted server**, run with no proxy. From **localhost**, Termius dynamic port forwarding does **not** apply automatically — set:
|
||||
|
||||
@@ -21,9 +21,11 @@ source: fanavaran-module-docs
|
||||
|
||||
## Document index
|
||||
|
||||
Depreciation coefficients, age codes and expert entry: [Fanavaran price drop](price-drop.md).
|
||||
|
||||
| # | Document | Covers |
|
||||
|---|----------|--------|
|
||||
| 1 | [01-write-apis.md](./01-write-apis.md) | Auth + GEN.03 / GEN.12 / GEN.07 / GEN.08 write APIs |
|
||||
| 1 | [01-write-apis.md](./01-write-apis.md) | Auth + GEN.03 / GEN.12 / GEN.44 / GEN.07 / GEN.08 write APIs |
|
||||
| 2 | [02-read-apis-lookups.md](./02-read-apis-lookups.md) | Policy inquiry, driver inquiry, lookups |
|
||||
| 3 | [03-constants.md](./03-constants.md) | Shared vs tenant constants |
|
||||
| 4 | [04-tenant-matrix.md](./04-tenant-matrix.md) | Shared ✅ / tenant-specific ✅ matrix |
|
||||
@@ -34,6 +36,11 @@ source: fanavaran-module-docs
|
||||
| 9 | [09-error-handling.md](./09-error-handling.md) | Errors, retry, backoff, logging |
|
||||
| 10 | [10-testing.md](./10-testing.md) | Test scenarios, **manual flow-test script**, proven case |
|
||||
| 11 | [11-onboard-new-client.md](./11-onboard-new-client.md) | Checklist to add a new insurer |
|
||||
| — | [car-body-curl-flow.md](./car-body-curl-flow.md) | **Car-body (بدنه)** manual curl: auth + stages 1, 3, 4 (no dmg-cases) |
|
||||
| — | [third-party-stage-fields.md](./third-party-stage-fields.md) | ثالث: each stage body, null vs required, lookup/inquiry vs user |
|
||||
| — | [car-body-stage-fields.md](./car-body-stage-fields.md) | بدنه: each stage body, null vs required, lookup/inquiry vs user |
|
||||
| — | [flow-design-user-vs-inquiry.md](./flow-design-user-vs-inquiry.md) | Proposed intake: user vs inquiry, Persian titles + types |
|
||||
| — | [hardcoded-payload-audit.md](./hardcoded-payload-audit.md) | Current hardcoded outbound values, removed fallbacks, standalone-tool differences, and remediation priorities (2026-11-11) |
|
||||
|
||||
## Related sources (code)
|
||||
|
||||
@@ -75,8 +82,9 @@ Fanavaran API Manager
|
||||
|-------|---------------|------------------|
|
||||
| Auth | EITAuthentication | token cache (`fanavaranAuthTokens`) |
|
||||
| Policy inquiry | inquiry-my-policies | `fanavaranSync.baseClaim.policyId` |
|
||||
| Other people | GEN.44 | `driverId` / `otherPersonId` when inquiry misses |
|
||||
| Base claim | GEN.03 | `claimId`, `claimNo` |
|
||||
| Damage case | GEN.12 | `dmgCaseId`, `driverId`, … |
|
||||
| Damage case | GEN.12 | `dmgCaseId`, `driverId`, `otherPersonId`, … |
|
||||
| Attachments | GEN.07 | `fanavaranSync.attachments.files[]` |
|
||||
| Expertise | GEN.08 | `expertiseId` |
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
# Fanavaran image receipts and upload failures
|
||||
|
||||
The image ID is the external `Id` returned by Fanavaran's attachment upload, not
|
||||
the MongoDB ID of the local image. Both batch and single-image uploads persist it
|
||||
in `claimCases.fanavaranSync.attachments.files[].fileId`, together with `fileName`,
|
||||
`source`, `submittedAt`, and the response. Per-image success, failure, and skip
|
||||
events are saved in `fanavaranSync.attachments.attempts`. Failures include an error
|
||||
and, when an audited HTTP upload started, a tracking code.
|
||||
|
||||
## Read the IDs beside the claim references
|
||||
|
||||
Claim detail responses that expose `fanavaran` now include:
|
||||
|
||||
```json
|
||||
{
|
||||
"fanavaran": {
|
||||
"claimId": 5190845,
|
||||
"fileIds": [700001],
|
||||
"attachments": {
|
||||
"status": "success",
|
||||
"uploadedCount": 1,
|
||||
"lastError": null,
|
||||
"files": [
|
||||
{
|
||||
"fileId": 700001,
|
||||
"fileName": "image.jpg",
|
||||
"source": "capture:angle:front"
|
||||
}
|
||||
],
|
||||
"attempts": []
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Existing claim-reference codes remain gated on COMPLETED. Image receipts and
|
||||
status can appear earlier. The expertise preview also returns `fileIds` and
|
||||
`attachments` beside `claimId`, `dmgCaseId`, and `expertiseId`.
|
||||
|
||||
## Check every planned image and why it is pending
|
||||
|
||||
`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/attachments/preview`
|
||||
|
||||
This returns `totalLocalImages`, `alreadySubmitted`, `pendingSubmit`, `fileIds`,
|
||||
`uploadStatus`, and one `attachments` row per local upload candidate. Each row
|
||||
includes `fileId`, `alreadySubmitted`, `localFileExists`, `status`, and `lastError`.
|
||||
Use `pendingSubmit` to check whether all current local candidates have saved
|
||||
receipts. Summary status describes recorded outcomes, not unattempted images.
|
||||
|
||||
- `success`: confirmed external file IDs are recorded.
|
||||
- `partial`: receipts exist, but another recorded image failed or was skipped.
|
||||
- `failed` / `skipped`: inspect the per-image error and `nextRetryAt` if present.
|
||||
- `not_recorded`: no upload outcome is stored; this is not proof of remote absence.
|
||||
- `unconfirmed`: legacy upload records have no valid external file ID.
|
||||
|
||||
`POST /v2/fanavaran/parsian/claim-cases/{claimCaseId}/attachments/submit` submits
|
||||
pending candidates and returns each upload's `fileId` or failure/skip reason.
|
||||
Already-recorded successful uploads are skipped. Missing local files are reported
|
||||
instead of silently excluded. A response with no external file ID is unconfirmed
|
||||
and is not automatically retried, to avoid duplicating a possibly accepted upload.
|
||||
|
||||
Older batch uploads did not persist their returned IDs. This change cannot
|
||||
reconstruct those historical receipts from the local database; verify them with
|
||||
Fanavaran before deciding to re-upload. New uploads use the shared persistence
|
||||
path and record their outcomes.
|
||||
|
||||
To verify remote receipts directly, use
|
||||
`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/hull/files`.
|
||||
Retrieve one image and its Base64 content using `/hull/files/{fileId}`.
|
||||
See [hull retrieval](hull-retrieval.md) for all supported read routes.
|
||||
|
||||
## Expertise submit completes missing prerequisites
|
||||
|
||||
The frontend can call
|
||||
`POST /v2/fanavaran/{client}/claim-cases/{claimCaseId}/expertise/submit`
|
||||
without separately retrying earlier stages. The backend completes them in order:
|
||||
|
||||
- Third-party: base claim → damage case → pending attachments → expertise.
|
||||
- Hull: base claim → pending attachments → expertise. Hull has no damage-case stage.
|
||||
|
||||
Existing claim/damage IDs and successful image receipts are reused. A previously
|
||||
skipped attachment stage is retried. Completion is checked against a fresh read
|
||||
of the saved receipts for all current local image candidates, not just the
|
||||
attachment stage's status or an upload response saying success. Missing local
|
||||
files, non-format rejected uploads, and unconfirmed receipts stop expertise
|
||||
submission. If there are no local attachment candidates, there is nothing to
|
||||
upload.
|
||||
|
||||
Invalid file format (`فرمت فایل معتبر نیست` / local magic-byte rejection) is
|
||||
retried once in the same submit. If the second attempt still fails, the file is
|
||||
permanently waived (`FANAVARAN_ATTACHMENT_FORMAT_WAIVED` on the skipped attempt).
|
||||
Waived files count as handled: they are not re-uploaded and do not block
|
||||
expertise or later stages.
|
||||
|
||||
Errors identify `stage` (`baseClaim`, `damageCase`, or `attachments`) and preserve
|
||||
vendor details. An attachment failure includes:
|
||||
|
||||
```json
|
||||
{
|
||||
"statusCode": 400,
|
||||
"code": "FANAVARAN_ATTACHMENTS_INCOMPLETE",
|
||||
"stage": "attachments",
|
||||
"pendingFiles": [
|
||||
{ "fileName": "image.jpg", "error": "Upload failure reason", "skipped": false }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Retrying resumes pending work. Even when expertise already exists, this API first
|
||||
repairs missing prerequisites, then returns the existing expertise response/Id
|
||||
without posting another expertise. Automatic final writes also check attachments.
|
||||
@@ -156,7 +156,7 @@ Example hull-only GEN.03 body (proven Parsian case): [`stage1-hull-body.json`](.
|
||||
| Field | Source |
|
||||
|-------|--------|
|
||||
| `ActualPremium` | `GET /lookups/body-policy/{PolicyId}` → `TotalPremium` |
|
||||
| `AccidentCulpritId` | `GET /lookups/inquiry-by-unique-identifier?nationalCode=…&birthday=…` → `driverId` (fallback: policy `CustomerId`) |
|
||||
| `AccidentCulpritId` | `GET /lookups/inquiry-by-unique-identifier?nationalCode=…&birthday=…` → inspect `parties` for RoleId **166**. Hull submit registers GEN.44 when missing and re-inquires to verify; preview stays read-only. The wrapper `driverId` may fall back to role 161 and is insufficient for this check. |
|
||||
| `CustomerFaultPercent` | **100** (required; درصد تقصير بيمه گذار) |
|
||||
| `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` → بیمهگذار (required; مرجع تعيين مقصر) |
|
||||
|
||||
@@ -190,7 +190,7 @@ curl -sS -X POST \
|
||||
| `AccidentTypeId` | `GET /lookups/vehicle-hull-accident-types` | **2** = تصادف(حادثه) |
|
||||
| `CostSeparationToDmgSections` | `GET /lookups/ans` | **0** = خیر |
|
||||
| `IsOwnerChanged` | `GET /lookups/ans` | **0** = خیر |
|
||||
| `IsLicenseReplaced` | — | **`null`** (must be empty; do not send `0` or ثالث `IsLicenseReplacement`) |
|
||||
| `IsLicenseReplaced` | `GET /lookups/ans` | **0** = خیر (use the hull field name, not ثالث `IsLicenseReplacement`) |
|
||||
| `CulpritTypeId` | `GET /lookups/vehicle-hull-accident-culprit-type` | **301** = حادثه مقصر شناخته شده دارد (not ثالث `337`) |
|
||||
| `CustomerFaultPercent` | — | **100** |
|
||||
| `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` | بیمهگذار (`Id` from lookup, fallback **1**) |
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
Snapshot of **what hull submit actually sends** after `toFanavaranHullBaseClaimPayload` / `toFanavaranHullExpertisePayload`.
|
||||
|
||||
TejaratNo additionally sends expert-reviewed `NotifierTypeId` and `NotifierRelationId` on the base claim, using the tenant-supplied codebooks. Both are required before initial submission; see [expert field review](../fanavaran-stage-field-review.md#tejaratno-notifier-review). Other tenants' bodies are unchanged.
|
||||
|
||||
|
||||
Experts can now review address, city, report type, accident/culprit/authority IDs, fault percentage, repair duration and vehicle value before their sending stage. See [expert field review](../fanavaran-stage-field-review.md); defaults below remain fallbacks for unreviewed records.
|
||||
|
||||
Staged flow (VHUD):
|
||||
|
||||
1. Base: `POST /car/vehicle-hull-claims` (GEN.03)
|
||||
@@ -15,6 +20,15 @@ A PUT to `/vehicle-hull-claims/{Id}` may run before files/expertise; Parsian oft
|
||||
|
||||
**Send rule:** send the **hull whitelist only**. Do not send ثالث-only keys (`DamagedCount`, `HasOtherCulprit`, `CompensationReferenceId`, `DocReceivedDate`, `IsLicenseReplacement`, plaque block on base, …).
|
||||
|
||||
**Manual submit body:** every supplied top-level field overrides its generated
|
||||
value, including IDs, arrays, nested objects, `false`, `0` and JSON `null`.
|
||||
Omitted fields retain generated defaults. Arrays and nested objects replace the
|
||||
corresponding value; they are not merged element by element. Lookup validation
|
||||
checks a copy of manual payloads and does not refresh their supplied premium or
|
||||
rewrite their values. Automatic submission without overrides keeps its existing
|
||||
inquiry, normalization and validation behavior. This also applies to third-party
|
||||
base/damage submits and both products' expertise submits.
|
||||
|
||||
**Source tags:** same as `third-party-stage-fields.md` (`system` / `lookup` / `inquiry` / `user` / `staff` / `derived`).
|
||||
|
||||
---
|
||||
@@ -26,7 +40,12 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
|
||||
**Fanavaran has rejected as required (must not be null):**
|
||||
`CustomerFaultPercent`, `AuthorityCulpritId`, `AccidentTypeId`, `CostSeparationToDmgSections`, `IsOwnerChanged`, `PolicyId`, `ClaimExpertId`, dates/time, `CulpritTypeId`.
|
||||
|
||||
**Must be null:** `IsLicenseReplaced` (error if `0` / mapped from ثالث `IsLicenseReplacement`).
|
||||
**IsLicenseReplaced:** derived on the server from `CulpritLicenceIssuDate` and
|
||||
`AccidentDate`: default `0` through the third anniversary and `null` afterward.
|
||||
Do not infer replacement from licence age exceeding ten years: Parsian rejects
|
||||
that `1` with «باید خالی باشد». The hull base-claim submit body may explicitly
|
||||
override `IsLicenseReplaced` with `0`, `1`, or JSON `null`; omitted fields keep
|
||||
the derived default. Intake accepts valid past issue dates older than ten years. The existing missing-date fallback is `1400/01/01`.
|
||||
|
||||
| Field | Persian | Type | Null? | Current value / source |
|
||||
|-------|---------|------|-------|------------------------|
|
||||
@@ -35,25 +54,25 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
|
||||
| AccidentDate | تاریخ حادثه | string Jalali | **no** | **user** first-party `statement.accidentDate`, else createdAt |
|
||||
| AccidentTime | ساعت حادثه | string `HH:mm` | **no** | **user** `statement.accidentTime` if set |
|
||||
| AnnouncementDate | تاریخ اعلام | string Jalali | **no** | **derived** = AccidentDate |
|
||||
| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **system** `"استان تهران شهر تهران"` |
|
||||
| AccidentCauseId | علت حادثه | number | **no** | **system** `6` · lookup `accident-causes` |
|
||||
| AccidentCityId | شهر حادثه | number | **no** | **system** `701` · lookup `cities` |
|
||||
| AccidentReportTypeId | نحوه اعلام | number | **no** | **system** `155` · lookup `accident-report-type` |
|
||||
| AccidentTypeId | نوع حادثه بدنه | number | **no** | **system** `2` تصادف(حادثه) · **lookup** `GET /lookups/vehicle-hull-accident-types` |
|
||||
| CulpritTypeId | نوع مقصر بدنه | number | **no** | **system** `300` (ثالث `337` remapped) · **lookup** `GET /lookups/vehicle-hull-accident-culprit-type` |
|
||||
| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | **lookup** `GET /lookups/detection-accident-culprits` (caption بیمهگذار, fallback `1`) |
|
||||
| AccidentCulpritId | شناسه مقصر فناوران | number | preferred | **inquiry** parties `inquiry-by-unique-identifier`, fallback hull policy `CustomerId` |
|
||||
| CustomerFaultPercent | درصد تقصیر بیمهگذار | number | **no** | **system** `100` |
|
||||
| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **user** expert review, else **system** `"استان تهران شهر تهران"` |
|
||||
| AccidentCauseId | علت حادثه | number | **no** | **user/expert** `accidentReason.fanavaran` from blame/claim; fallback **system** `6` · lookup `accident-causes` |
|
||||
| AccidentCityId | شهر حادثه | number | **no** | **user** expert review, else **system** `701` · lookup `cities` |
|
||||
| AccidentReportTypeId | نحوه اعلام | number | **no** | **user** expert review, else **system** `155` · lookup `accident-report-type` |
|
||||
| AccidentTypeId | نوع حادثه بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-types` row caption تصادف(حادثه); no numeric fallback |
|
||||
| CulpritTypeId | نوع مقصر بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-culprit-type` row caption بیمهگذار; never reuse third-party `337` |
|
||||
| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | Reviewed choice, else current `detection-accident-culprits` row caption بیمهگذار; no numeric fallback |
|
||||
| AccidentCulpritId | شناسه مقصر فناوران | number | **no** | Actual driver from parties inquiry with RoleId **166**; submit registers GEN.44 if missing, then verifies the role. Preview warns without creating a person. |
|
||||
| CustomerFaultPercent | درصد تقصیر بیمهگذار | number | **no** | **user** expert review, else **system** `100` |
|
||||
| CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` |
|
||||
| IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` |
|
||||
| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | **must be null** | never copy ثالث `IsLicenseReplacement` |
|
||||
| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | often null | **derived** `0` through three years, otherwise `null`; explicit hull submit answer is preserved (ثالث uses `IsLicenseReplacement`) |
|
||||
| ActualPremium | حق بیمه واقعی | number | preferred | **inquiry** hull policy `TotalPremium` via `GET /lookups/body-policy/{PolicyId}` |
|
||||
| EstimateAmount | برآورد | number | **no** | **user** expert prices / provisional |
|
||||
| CulpritLicenceNo | شماره گواهینامه | string | **no** | dummy / **user** |
|
||||
| CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **system** `"1394/10/13"` |
|
||||
| CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **user** `parties.person.driverLicenseDate`; fallback **system** `"1404/08/20"` |
|
||||
| CulpritLicenceTypeId | نوع گواهینامه | number | sent | tenant `2` · lookup `driving-licence-types` |
|
||||
| AccidentVehicleUsedId | کاربری خودرو | number | **no** | **inquiry** VIN/policy, else tenant |
|
||||
| PoliceOfficerId | افسر | number | sent | **system** `1` |
|
||||
| AccidentVehicleUsedId | کاربری خودرو | number | **no** | **inquiry** hull policy `VehicleId` + `VehicleVersionNo` → vehicle GET `UsedId`; no default or expert override. Unresolved inquiry warns in preview and blocks submit. |
|
||||
| PoliceOfficerId | افسر | number | yes | null; do not copy the shared third-party sample `1` |
|
||||
| IsAccidentOutOfBorder | خارج از مرز | number | sent | **system** `0` |
|
||||
| ArchiveNo | بایگانی | string | yes | null |
|
||||
| EntryDate | تاریخ ورود | string | yes | null |
|
||||
@@ -119,8 +138,8 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
|
||||
| Wage | اجرت کل | number | **no** | **user** sum `salary` |
|
||||
| ComponentReplacementCost | قطعه کل | number | **no** | **user** sum `price` |
|
||||
| WasteValue | داغی کل | number | **no** | **user** daghi |
|
||||
| RepairDuration | مدت تعمیر (روز) | number | **no** | **system** `3` |
|
||||
| VehicleCurrentValue | ارزش روز خودرو | number | preferred | **user** `vehicle.carPrice` / `vehicle.price`, else **inquiry** policy `VehicleValue` |
|
||||
| RepairDuration | مدت تعمیر (روز) | number | **no** | **user** expert review, else **system** `3` |
|
||||
| VehicleCurrentValue | ارزش روز خودرو | number | preferred | **user** expert field review (rials), else `vehicle.carPrice` / `vehicle.price`, else **inquiry** policy `VehicleValue` |
|
||||
| DropAmount | افت قیمت | number | **no** | **user** price-drop total or `0` |
|
||||
| CarryAndRescueCost | حمل و نجات | number | yes | null |
|
||||
| WreckHighestValue | بالاترین ارزش لاشه | number | yes | null |
|
||||
@@ -133,14 +152,14 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
|
||||
| AccidentPercent | درصد حادثه | number | yes | null |
|
||||
| TheftCases | موارد سرقت | array | empty `[]` | system |
|
||||
| DmgSections[].Count | تعداد | number | **no** | **system** `1` |
|
||||
| DmgSections[].Desc | شرح قطعه | string | **no** | **user** part label |
|
||||
| DmgSections[].Desc | شرح قطعه | string | **no** | Saved expert-reply part label (`carPartDamage.label_fa`) |
|
||||
| DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** |
|
||||
| DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` |
|
||||
| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | **lookup** `vehicle-hull-dmg-kind` caption تخریب, fallback `5485` |
|
||||
| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | **no** | **system** `3043330` (فابریک) for **every** row |
|
||||
| DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | Saved `evaluation.damageExpertReply.parts[].partId`, passed through directly; policy matching and factory bundles must never replace it |
|
||||
| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | Current `vehicle-hull-dmg-kind` API row caption تخریب; no numeric fallback |
|
||||
| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | preferred | Current policy `dmg-accessories`: exact `AccessoryKindId` or caption match; else the «کليه قطعات فابريک» factory-bundle row `Id`. Keep selected car-components `AccessoryKindId` + part `Desc` |
|
||||
| DmgSections[].DmgSectionCosts[].Caption | عنوان هزینه | string | **no** | **user** label |
|
||||
| DmgSections[].DmgSectionCosts[].Amount | مبلغ (قطعه+اجرت) | number | **no** | **user** |
|
||||
| DmgSections[].DmgSectionCosts[].DmgCostKindId | نوع هزینه | number | **no** | **lookup** `vehicle-hull-dmg-cost-kinds` caption مجموع لوازم, fallback `1` |
|
||||
| DmgSections[].DmgSectionCosts[].DmgCostKindId | نوع هزینه | number | **no** | Current `vehicle-hull-dmg-cost-kinds` API row caption مجموع لوازم; no numeric fallback |
|
||||
|
||||
**Lookups used:** `vehicle-hull-dmg-kind`, `vehicle-hull-dmg-cost-kinds`, `detection-accident-culprits`, `vehicle-hull-accident-types`, `vehicle-hull-accident-culprit-type`, `ans`, optional `vehicle-hull-policies/{id}/dmg-accessories` (no longer used for AccessoryId).
|
||||
|
||||
@@ -152,3 +171,16 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
|
||||
|
||||
Same routes as ثالث (`/base-claim`, `/attachments`, `/expertise`).
|
||||
`/damage-case` preview/submit **skips** for `CAR_BODY`.
|
||||
|
||||
### Hull driver registration
|
||||
|
||||
A policyholder-only (`RoleId=161`) inquiry does not satisfy the hull driver role.
|
||||
Before base-claim submission or hull synchronization, YARA checks the actual driver
|
||||
for `RoleId=166` (سایر) and registers `common/other-people` when missing, using
|
||||
national code, birthday and person details. The policyholder role is preserved.
|
||||
The returned create ID is used only after a subsequent inquiry verifies role 166.
|
||||
A successful registration is cached with national code and birthday so retries
|
||||
wait for verification rather than creating the same role again. Missing identity,
|
||||
lookup failures or unverified registration block the external hull write with
|
||||
`FANAVARAN_HULL_DRIVER_ROLE_REQUIRED`; local claim creation remains best-effort.
|
||||
Third-party driver/owner resolution continues to accept roles 161 or 166.
|
||||
|
||||
@@ -115,7 +115,7 @@ Hull is **first party**. One vehicle, one policy.
|
||||
| درصد تقصیر بیمهگذار | CustomerFaultPercent | number 0–100 | **user** if not 100%; today always 100 |
|
||||
| تفکیک هزینه به نقاط | CostSeparationToDmgSections | ans | **user** default خیر |
|
||||
| مالک تغییر یافته؟ | IsOwnerChanged | ans | **user** default خیر |
|
||||
| گواهینامه تعویضی؟ | IsLicenseReplaced | ans or empty | **must stay empty/null** unless Fanavaran later requires a value |
|
||||
| گواهینامه تعویضی؟ | IsLicenseReplaced | ans | `1` if issue >10y before accident, else `null` |
|
||||
| قطعات آسیبدیده | selectedParts | catalog ids | **user** |
|
||||
|
||||
### Expert pricing (بدنه)
|
||||
|
||||
@@ -0,0 +1,278 @@
|
||||
# Fanavaran hardcoded outbound values — current audit
|
||||
|
||||
Date: **2026-11-11**. Remote baseline: API `90bdc51` on `origin/main`, with the
|
||||
existing local branch-routing work restored. This is a source audit of possible
|
||||
outbound values, not a capture of production requests. Mongo configuration can
|
||||
override seed defaults, so the numbers below are code defaults, not a claim about
|
||||
what is configured on a particular production server.
|
||||
|
||||
**The requirement “never send guessed/default business codes” is not satisfied.**
|
||||
The staff-location fix is present, and recent hull changes removed several
|
||||
numeric fallbacks, but other defaults can still reach Fanavaran. Merely checking
|
||||
that a default ID exists in a lookup does not establish that it describes this
|
||||
accident, driver, vehicle, or assessment.
|
||||
|
||||
This document updates the outbound-default findings in
|
||||
[lookup-coding-audit.md](./lookup-coding-audit.md), which predates the latest hull
|
||||
and location changes. This audit changes documentation only.
|
||||
|
||||
## Audited paths
|
||||
|
||||
| Area | Sources and responsibility |
|
||||
|---|---|
|
||||
| Application write entry points | `src/fanavaran/fanavaran.controller.ts`: base claim, damage case, attachments, expertise preview/submit; automatic and soft-ensure stage calls in `ClaimRequestManagementService` use the same builders |
|
||||
| Payloads and HTTP writes | `src/claim-request-management/claim-request-management.service.ts`: GEN.03, GEN.12, GEN.44, GEN.07, third-party GEN.08, hull base PUT and GEN.06 |
|
||||
| Product-specific helpers | `src/claim-request-management/fanavaran-{hull-base-claim,hull-expertise,hull-expertise-lookups,hull-lookup-validation,party-roles,other-people,accident-vehicle-used,v15-third-party-base}.ts` |
|
||||
| Configuration and headers | `src/core/config/fanavaran-client.config.ts`, `src/fanavaran/fanavaran-{client-config,auth,location}.service.ts`, config schema, system settings |
|
||||
| Lookup/inquiry and local catalogues | `src/fanavaran/fanavaran-lookup.service.ts`, `fanavaran-lookup.config.ts`, `src/lookups/`, `src/static/outer-car-parts-catalog.ts`, part helpers, vehicle/stage review code |
|
||||
| Expert and user UI | Expert Fanavaran API route, vehicle review, stage-field defaults, damage reply fields; user inquiry/part-selection consumers. No matching numeric payload defaults were found in the current UI source search; the expert UI does accept backend-prefilled defaults. |
|
||||
| Standalone tools | `scripts/fanavaran-flow-ui-server.js`, `scripts/data/fanavaran-flow-ui.html`, `scripts/fanavaran-flow-test.sh`, `scripts/fanavaran-auth.sh`, `scripts/get-fanavaran-car-parts.sh`; report-seeding fixtures were distinguished from application writes |
|
||||
|
||||
The runtime tenant type supports `parsian`, `tejaratno`, and `moallem`.
|
||||
`esg/src` had no direct Fanavaran references in the search. `rewrite` was excluded.
|
||||
|
||||
## 1. Business IDs that can still be sent from defaults
|
||||
|
||||
Line references are against the restored worktree at audit time. `service` means
|
||||
`src/claim-request-management/claim-request-management.service.ts`.
|
||||
|
||||
| Field / stage | Hardcoded or seeded value | When it reaches the payload | Evidence / required source |
|
||||
|---|---|---|---|
|
||||
| `AccidentCauseId` — base, both products | **6** | Always initialized to 6. `accidentReason` is passed into the builder but its selected ID / `fanavaran` code is not applied. Hull checks membership, which can accept the wrong but active cause. | `service:405`, `1894`; use the actual selected cause mapped to this tenant. |
|
||||
| `AccidentCityId` — base, both products | **701** | Profile default unless an expert stage review changes it. The shared builder does not resolve the supplied coordinates into a city. | Config `:100`; `service:1893`, `5691`; use accident-city selection/inquiry. |
|
||||
| `AccidentReportTypeId` — base, both products | **155** | Profile default unless reviewed. | Config `:101`; `service:5692`; explicit report-type selection. |
|
||||
| `CompensationReferenceId` — third-party base | **167** | Included from the profile; not among the current editable stage fields or manual-ID overrides. Hull's key whitelist removes it. | Config `:106`; `service:1893`; confirm the required contract/codebook and source. |
|
||||
| `CulpritLicenceTypeId` — base, both products | **2** | Included from the profile. The resolved driver identity includes `licenseType`, but the payload does not use it. Hull checks whether 2 is active, not whether it is the driver's licence category. | Config `:107`; `service:4679` vicinity; map the actual stored driver's selection. |
|
||||
| `LicenceTypeId` — third-party damage | **2** | Always assigned from `defaults.CulpritLicenceTypeId`, ignoring the damaged driver's stored licence type. | `service:3253`. |
|
||||
| `CulpritTypeId` — third-party base | **337 / 338** | Final value comes from a static map: policyholder/driver same national code → 337, different → 338. Missing role information can default to 337. It is no longer simply the profile's 337. | `fanavaran-party-roles.ts:205–226`; `service:4687`; resolve current tenant IDs by confirmed role meaning and reject unknown roles. |
|
||||
| `AccidentVehicleUsedId` — third-party base and damage | **1** | Fallback when inquiry/group resolution is unresolved; an expert's approved use type can override it. Hull base has removed this numeric fallback. | `service:4771`, `3208`; preserve the actual vehicle use or require a selection. |
|
||||
| `DmgCaseTypeId` — third-party damage | **175** | Unconditionally taken from the profile. No current expert stage field for it. | `service:3235`; determine the actual damage-case classification. |
|
||||
| `DmgHistoryStatus` — third-party damage | **5214** | Profile default unless reviewed. | `service:3231–3233`; actual history/explicit selection. |
|
||||
| `PlaqueKindId` / `PlaqueSampleId` — third-party damage | **8 / 10** | National-plate fallback when matched Fanavaran vehicle has no kind. Even with a real kind, a missing sample still falls back to 10 and is labelled `vehicle-inquiry`. | `src/lookups/fanavaran-last-car-policy.ts:391–392`, `450–470`; require sourced plate IDs with compatible kind/sample. |
|
||||
| `PlaqueMiddleCodeId` — third-party damage | Static **1–24** letter map | Used when the matched vehicle does not provide a middle code. These are explicit fixed mappings rather than a default letter, but are still tenant-unverified numeric codes. | `service:424–449`, `3266`; map through the tenant's plate-letter catalogue. |
|
||||
| `PoliceOfficerId` — third-party base | **1** | Assigned directly; hull explicitly replaces it with null. | `service:1857`; `fanavaran-hull-base-claim.ts:164`; real officer selection or null if permitted. |
|
||||
| `InspectionPlaceId` — third-party expertise | **282** | Default unless reviewed. Fetching the inspection-place list does not select or validate this fallback at the write boundary. | `service:6014–6020`; explicit inspection place. |
|
||||
| `DropAmountStatus` — third-party expertise | **5458** | Always assigned directly, even though `drop-amount-status` is fetched. Not a current editable stage field. | `service:6015–6020`; derive from confirmed depreciation outcome or require selection. |
|
||||
| `DmgSections[].AccidentLevel` — third-party expertise | **5456** | Any nonnumeric `typeOfDamage` falls back to 5456. **The ordinary expert UI sends `تعمیر` / `تعویض`, so normal UI replies take this fallback.** Those values express repair/replacement, not damage severity. | `service:5888–5899`; expert `damagePartTable.tsx:2292–2305`, `claimReplySubmit.tsx:183–192`; add a separate severity field rather than treating repair method as severity. |
|
||||
| `FileTypeId`, including `Files[].FileTypeId` — attachments | **Parsian 63 / Tejaratno 23 / Moallem 17** | One configured type is assigned across collected document/photo categories. Hull checks that the ID is active, not that its meaning matches each document. | Config `:155`, `181`, `201` vicinity; `service:5126`, `5329`, `5495–5497`; per-document semantic mapping to current tenant catalogue. |
|
||||
| `CityId` — GEN.44 person creation | **9131** | Fallback if a person's explicit city and caption lookup cannot resolve it; shared helper has no tenant argument. This remains despite the **HTTP Location** fix. | `fanavaran-other-people.ts:95`, `251–254`; actual person city, never a Parsian city ID for another tenant. |
|
||||
| `PersonKindId` — GEN.44 | **46** | Natural-person caption lookup fallback; shared across all clients. | `fanavaran-other-people.ts:96`, `265–268`; resolve correct person kind for the tenant/person. |
|
||||
| `IsIranian` — GEN.44 | **1 / 0** | Fallback when `ans` lookup is unavailable. The helper assumes Iranian unless explicitly false or a naturalized code is present. | `fanavaran-other-people.ts:214–215`, `259–261`; encode confirmed nationality using the proper contract. |
|
||||
|
||||
`ClaimFileTypeId` also has a startup migration: Moallem's stored **23 → 17**
|
||||
(`fanavaran-client-config.service.ts:40–45`). Editing a stored value back to 23
|
||||
does not survive that startup migration.
|
||||
|
||||
The static plate-letter map is:
|
||||
`الف=1، ب=2، پ=3، ج=4، د=5، س=6، ص=7، ط=8، ع=9، ق=10، ل=11، م=12، ن=13، و=14، ه=15، ی=16، ک=17، ژ=18، ت=19، ث=20، ز=21، ش=22، ف=23، گ=24`.
|
||||
|
||||
## 2. Default values that are not lookup IDs but still assert case facts
|
||||
|
||||
| Field | Current assumption | Source / consequence |
|
||||
|---|---|---|
|
||||
| `AccidentLocationAddress` | **`استان تهران شهر تهران`** | `service:404`, `1910`, `5690`. Location coordinates are accepted by the builder but not used here. Expert review/manual text can replace it. **This address default is separate from the fixed HTTP `Location` header.** |
|
||||
| `CulpritLicenceNo`, damage `LicenceNo` | Environment dummy, else **`9705463515`** | `service:412–413`, `1812`, `1818`, `3250`, `7570`. Real licence preferred, but missing/empty values and even empty manual overrides are replaced by a fabricated number. |
|
||||
| `CulpritLicenceIssuDate`, damage `LicenceIssuDate` | **`1394/10/13`** | `fanavaran-party-roles.ts:11`, `237–242`; shared builder also initializes it at `service:1835`. Real stored date wins if available. |
|
||||
| `EstimateAmount` | **1000 rials** | `service:407`, `1770`, `3238`. Base uses it when no positive calculated estimate exists; damage builder always initializes to it, with manual amount override available. |
|
||||
| `FaultPercent` — damage | **100** | Profile default, `service:3239`; does not derive an actual percentage. |
|
||||
| `CustomerFaultPercent` — hull | **100** | `service:2642`, `fanavaran-hull-base-claim.ts:59`, `154–157`; expert stage review can replace it. |
|
||||
| `RepairDuration` — hull expertise | **3 days** | `service:2844–2846`, `fanavaran-hull-expertise.ts:80`, `121–122`; review can replace it. Optional `HullExpertiseRepairDuration` exists in the profile interface but this builder does not use it. |
|
||||
| `DamagedCount` — third-party base | **1** | `service:1838`. Current two-party flow has one beneficiary, but this is a fixed scenario assumption. |
|
||||
| `IsLicenseMatchWithVehicleKind` | **1** | `service:1842`; no actual licence/category compatibility calculation here. |
|
||||
| `HasOtherCulprit`, `IsAccidentOutOfBorder`, `IsFatalAccident`, `IsPlaqueChanged`, `IsLicenseReplacement` — third-party base | **0** | `service:1843–1848`, `1865`; assertions of “no”, not inferred accident facts. |
|
||||
| `IsLicenseReplaced` — hull | **Always 0** | `fanavaran-hull-base-claim.ts:126–129`; forced even if the incoming builder value differs. Current code intentionally implements the previous contract decision. |
|
||||
| `IsOwnerChanged`, `CostSeparationToDmgSections` — hull | **0 when absent** | `fanavaran-hull-base-claim.ts:135–142`. Encoded through `ans`, validated for membership on hull writes. |
|
||||
| `Count` — hull damage section | **1** | `fanavaran-hull-expertise.ts:156`; one item per selected part row. Must be explicit if quantities can differ. |
|
||||
| `ComponentReplacementTaxAndToll` — third-party expertise | **0** | `service:6051`; not computed from an expert-entered tax value. |
|
||||
| `PoliceReportDesc` | **`شرح گزارش`** | `service:1858`; arbitrary placeholder, manual text override possible. |
|
||||
|
||||
Calculated sums starting at zero, optional nulls, empty collections, retry counts,
|
||||
timeouts and pagination limits are not themselves guessed business IDs. They
|
||||
must be distinguished from asserting “zero tax”, “100% fault”, or “no fatality”.
|
||||
|
||||
## 3. Implicit guesses that still violate the intention
|
||||
|
||||
These no longer necessarily use a numeric fallback, but still choose a business
|
||||
meaning without evidence from the case:
|
||||
|
||||
1. **Vehicle use:** `fanavaran-accident-vehicle-used.ts:37–80` preserves a valid
|
||||
preferred use, otherwise chooses a caption containing `شخص`, otherwise the
|
||||
first active row in the vehicle group. A live row is not proof of actual use.
|
||||
Used by third-party base/damage; hull base now bypasses this substitution.
|
||||
2. **Vehicle model:** `service:2029–2065` can select the first caption matching a
|
||||
broad body type such as sedan/SUV. This is a fallback in the damage builder;
|
||||
an approved exact vehicle kind has priority. A broad type is not a model.
|
||||
3. **Hull accident/culprit/authority:** `service:2642–2653` selects
|
||||
`تصادف(حادثه)`, `بیمهگذار`, and an authority caption containing `بیمهگذار`
|
||||
unless review supplies alternatives. IDs come from current lookup responses,
|
||||
but the scenario is still assumed.
|
||||
4. **Hull damage kind/cost kind:** `service:2746–2752` chooses `تخریب` and
|
||||
`مجموع لوازم` for the sections. The removed 5485/1 numeric fallbacks are gone,
|
||||
but the same two meanings are still automatically applied to all parts.
|
||||
5. **Hull accessory:** `fanavaran-hull-expertise-lookups.ts:77–102` first matches
|
||||
the part's accessory kind; otherwise picks the policy's factory-parts bundle.
|
||||
This is a policy-sourced fallback, not a fixed record ID, but bundle
|
||||
applicability still requires a business rule.
|
||||
6. **Hull culprit identity/value:** policy `CustomerId` can substitute for the
|
||||
driver when person inquiry misses (`service:2625` vicinity), and insured
|
||||
`VehicleValue` can substitute for market/current value. Neither is a fixed
|
||||
number, but policyholder is not necessarily driver and insured value is not
|
||||
necessarily current market value.
|
||||
|
||||
## 4. Cross-stage default leakage in the base payload
|
||||
|
||||
`fanavaranPayloadDefaultsWithoutExpertIds` (`service:3426–3437`) removes only
|
||||
`ClaimExpertId` and `ExpertiseClaimExpertId`. The base builder spreads **all
|
||||
remaining profile defaults** (`service:1892–1894`).
|
||||
|
||||
For **Parsian/Moallem third-party** payloads, unlike the hull and Tejarat V15
|
||||
whitelists, this can leave these extra defaults on the outgoing base object:
|
||||
|
||||
- `DmgCaseTypeId=175`
|
||||
- `DmgHistoryStatus=5214`
|
||||
- `DriverIsOwner=0`
|
||||
- `FaultPercent=100`
|
||||
- `ClaimFileTypeId=63` (Parsian) / `17` (Moallem)
|
||||
- Optional `HullExpertiseRepairDuration`, if present in stored defaults.
|
||||
|
||||
The numbers reflect seeds and may differ in Mongo. The defect is the unrestricted
|
||||
spread, regardless of values. These fields belong to other stages; approval of
|
||||
the base accident fields does not fix their leakage. Each product/stage needs an
|
||||
explicit outbound key whitelist.
|
||||
|
||||
## 5. What the recent fixes actually solved
|
||||
|
||||
- **Claim HTTP `Location`: fixed for application claim writes.**
|
||||
`service:3375–3423` requests `requireStaffLocation: true`; the location service
|
||||
uses assigned staff `locations[].id` or that staff member's branch **code**,
|
||||
and throws `FANAVARAN_STAFF_LOCATION_MISSING` when none exists. This is used
|
||||
by claim base, damage, attachment, expertise, hull update, and claim-linked
|
||||
GEN.44 writes. The branch Mongo `_id` is not sent as the OpBUId.
|
||||
- **General lookup/read headers still have a tenant Location fallback.**
|
||||
`fanavaran-auth.service.ts:281` uses `auth.location` when no explicit override
|
||||
exists. Generic `FanavaranLookupService.postToFanavaran` also uses those
|
||||
headers, although its `createOtherPerson` wrapper currently has no production
|
||||
caller in `src`. This does not undo the strict claim-write resolver.
|
||||
- **Hull base `UsedId`: fixed.** Exact policy vehicle/version is used; a missing
|
||||
value blocks the write rather than falling back to 1.
|
||||
- **Hull `VehicleHullAccessoryId=3043330`: removed.** It now comes from the
|
||||
current policy's accessories, with exact-part/factory-bundle resolution.
|
||||
- **Hull numeric accident/culprit/authority/damage/cost fallbacks:** the old
|
||||
2/300/first-row-or-1/5485/1 substitutions have been removed. Caption-derived
|
||||
defaults and other fields listed above remain.
|
||||
- **`PoliceOfficerId=1`: removed for hull**, still present for third-party.
|
||||
- **Assessor/case-owner expert IDs: fixed in application payloads.** Assigned
|
||||
staff's product-specific codes are required; profile `ClaimExpertId` and
|
||||
`ExpertiseClaimExpertId` seeds are stripped rather than used as write fallbacks.
|
||||
Their numeric presence in config alone must not be reported as an active
|
||||
application expert-ID fallback.
|
||||
|
||||
## 6. Standalone Fanavaran flow UI has separate defaults
|
||||
|
||||
The file currently open in the IDE, `scripts/fanavaran-flow-ui-server.js`, launches
|
||||
`scripts/fanavaran-flow-test.sh` (`:962–970`). It does **not** call the Nest claim
|
||||
builder. Fixing one implementation does not automatically fix the other.
|
||||
|
||||
| Tool / location | Defaults or fixed choices |
|
||||
|---|---|
|
||||
| Flow shell `:409–448` | City701, report155, third-party use1, compensation167, licence2, culprit337, cause6, damage type175, history5214, plate8/10, fault100, estimate1000, inspection282, drop5458, severity5456, Tehran address, dummy licence/date, hull repair3. Environment values override these; absent ones silently use the defaults. |
|
||||
| Flow shell `:352–380` | Fixed tenant CorpId/ContractId and Location: Tejaratno **3539/263/100**, Parsian **543/28/210050**, Moallem **5650/304/30900**. Shell hull contract falls back to the configured third-party contract if a hull contract is not supplied. |
|
||||
| Flow HTML `:1052–1092`, `:1316–1399` | Static expert/branch lists. Tejaratno auto-selects case-owner2721 and assessor2709 at location100; Moallem defaults to first case-owner5347 and assessor5350 at location30900; Parsian chooses branch210110 and the first listed maker32/reviewer3989 when no preference exists. Other static choices remain in these tables. |
|
||||
| Flow HTML `:789–790`, `:1611–1619` | Static culprit337/338 mapping by role scenario. |
|
||||
| Flow HTML `:851–853`, `:879–900` | Prefilled GEN.44 city9131/person-kind46/Iranian1, example amounts, repair3, fault100, example vehicle current value0. Also contains sample identity/plate/licence values; do not treat these as real inquiry evidence. |
|
||||
| Flow server `:1168` | Party inquiry falls back to Location **100** if neither environment nor query supplies it. |
|
||||
| Auth shell `scripts/fanavaran-auth.sh:26–55` | Independent hardcoded tenant auth scope/location defaults. |
|
||||
| Car-parts GET shell | Prompts for business credentials/scope; defaults the connection URL. It does not build claim/damage/expertise payloads. |
|
||||
|
||||
The flow UI now requires live active hull lookup selections for relevant stages;
|
||||
that does not remove the shell's underlying defaults, nor static staff/branch
|
||||
choices. It can still write real records when its submission actions are run.
|
||||
|
||||
## 7. Fixed identifiers that need a different treatment
|
||||
|
||||
- `InsuranceLineId=5` (third-party) / **4** (car-body): explicit product routing
|
||||
constants in `src/lookups/fanavaran-last-car-policy.ts:5–6`. These encode the
|
||||
selected product; they are not a fallback to a random policy/person record.
|
||||
- Role IDs161/166 (and the defined owner role163) identify accepted response
|
||||
roles. `fanavaran-driver-inquiry.ts` selects actual returned person IDs rather
|
||||
than sending 161/166 as `DriverId` or falling back to the first arbitrary row.
|
||||
- Tejarat notifier lists in `src/fanavaran/tejarat-notifier.ts` contain the
|
||||
tenant-supplied IDs5516/5517 and5519–5526. They are allowed choices, **not an
|
||||
automatic notifier selection**; review is required. The shared DB lookup's
|
||||
tenant provenance still needs attention.
|
||||
- Tenant CorpId/ContractId, authentication identities and API URL roots are
|
||||
deployment configuration. They must be configured for the deployment rather
|
||||
than deleted as though they were guessed accident data. Auth material also
|
||||
exists in seed/tool source; no secret values are reproduced in this report.
|
||||
- Seed expert IDs still exist (Parsian154/29, Tejaratno2721/2709,
|
||||
Moallem5347/5350; shared4543092/2709). As noted above, the application excludes
|
||||
them from outbound expert-ID resolution; the standalone HTML does not.
|
||||
- Runtime auth-location seeds are Parsian110011 / Tejaratno100 / Moallem1;
|
||||
standalone auth/flow tools have different Parsian/Moallem defaults. Scope them
|
||||
explicitly when using those tools.
|
||||
|
||||
## 8. Catalogue/cache provenance also needs to be fixed
|
||||
|
||||
Removing numeric `?? default` statements alone is insufficient:
|
||||
|
||||
1. `getLiveFanavaranCatalogItems` (`service:774–784`) falls back to the shared
|
||||
static car-component list when lookup rows are empty. This helper is used for
|
||||
selections, despite the snapshot comment saying it is legacy-only. Stored
|
||||
`partId` is then passed into `DmgSectionId` / `AccessoryKindId`. Hull validates
|
||||
membership against live rows; third-party has no equivalent complete guard.
|
||||
2. Mongo `lookups` is keyed by `name` without tenant/product scope; vehicle-kinds
|
||||
has globally unique `Id` without tenant scope. DB-first/cache fallback can
|
||||
therefore produce a real code from the wrong insurer. Lookup startup sync
|
||||
can also populate a tenant's disk cache from that shared DB.
|
||||
3. `getRemoteLookup` accepts any non-null parsed cache value, including an API
|
||||
error object; callers may turn it into an empty list and then use defaults.
|
||||
4. Vehicle/stage review validation at save time is not comprehensive proof of
|
||||
current-tenant outbound validity. Hull validates many codebook IDs immediately
|
||||
before writing; third-party lacks an equivalent complete validation layer.
|
||||
5. Offline/mock inquiry data is another explicit source of seeded values:
|
||||
`src/offline-inquiry/`, SandHub and global system settings. Offline inquiries
|
||||
default to enabled, and live SandHub requires an explicit true setting.
|
||||
Production configuration must be verified separately; this audit did not read
|
||||
production settings or treat fixture IDs as evidence of live inquiries.
|
||||
|
||||
## 9. Recommended implementation order
|
||||
|
||||
1. Whitelist every stage/product payload. Eliminate cross-stage default leakage.
|
||||
2. Remove invented cause/licence/person/city/plate values and preserve actual
|
||||
stored inquiry selections with tenant/product provenance. Missing required
|
||||
values must produce an actionable Persian preview/submit error before any
|
||||
remote write; optional unresolved values should be null/omitted per contract.
|
||||
3. Add explicit expert fields for genuinely unavailable data: cause, licence
|
||||
type, compensation reference, damage-case type, separate damage severity,
|
||||
depreciation status, relevant flags, and document category as needed. Reuse
|
||||
existing city/report/history/inspection controls, initially unselected.
|
||||
4. Resolve tenant codes by selected meaning and current lookup response. Never
|
||||
fall back to first/personal row, fixed record ID, or another insurer's code.
|
||||
Keep a deliberate, documented distinction for product/role protocol constants.
|
||||
5. Make lookup and vehicle-kind storage tenant-scoped. Reject invalid cache
|
||||
shapes and refetch/review old unsourced IDs rather than migrating by number.
|
||||
6. Apply the same strict rules to both standalone flow tools and application
|
||||
writes. Replace static staff/branch defaults with explicit selections.
|
||||
7. Update tests that currently assert defaults; add tests that missing, stale,
|
||||
inactive, wrong-tenant and semantically unrelated IDs never trigger remote
|
||||
POST/PUT. Test normal `تعمیر`/`تعویض` replies with independent severity data.
|
||||
|
||||
## Verification and limits
|
||||
|
||||
- Stashed tracked/untracked local changes, fast-forwarded API to `90bdc51`, and
|
||||
restored the stash without conflicts. Other checked non-rewrite repositories
|
||||
were already current; earlier stashes were preserved.
|
||||
- The backend Jest run completed successfully: **94 suites, 823 tests** in the
|
||||
restored worktree. Existing tests include intentional fallback expectations
|
||||
(for example GEN.44 city9131/person-kind46); passing does not prove absence of
|
||||
guessed values. External providers are mocked in these tests.
|
||||
- An isolated local probe executed source-extracted builder methods without
|
||||
initializing Nest/Mongo or calling HTTP. A supplied cause999 still produced
|
||||
cause6; Parsian/Moallem shared base objects retained the cross-stage fields
|
||||
listed above; both `تعمیر` and `تعویض` produced accident level5456. This probes
|
||||
the builder before product filtering, not a complete production HTTP exchange.
|
||||
- Source tracing covered the application's Fanavaran write builders and their
|
||||
shared submission paths plus standalone tools. No Fanavaran write, real SMS,
|
||||
production database change, or live tenant lookup was performed for this audit.
|
||||
- Application behavior has not been changed. The table is a remediation worklist,
|
||||
not a statement that the “no default codes” policy is already implemented.
|
||||
@@ -0,0 +1,78 @@
|
||||
# Retrieve submitted hull files and expertise sections
|
||||
|
||||
Implemented from the supplied Fanavaran V2.0 customer documents:
|
||||
|
||||
- `CAR.VHUD.APIH.GEN.05 - سرویس فایل های پیوست خسارت بدنه.docx`
|
||||
- `CAR.VHUD.APIH.GEN.12 - سرویس بازیابی نقاط آسیب دیده کارشناسی خسارت بدنه.docx`
|
||||
|
||||
All routes require the existing actor Bearer token and access to the local claim.
|
||||
The path's `claimCaseId` is a local MongoDB ObjectId. The backend resolves the
|
||||
saved external `claimId` (never `claimNo`), hull ContractId, and the claim staff's
|
||||
Location using the submission header resolver. Non-hull claims are rejected.
|
||||
|
||||
## Routes
|
||||
|
||||
Base: `/v2/fanavaran/{client}/claim-cases/{claimCaseId}/hull`
|
||||
|
||||
| Local GET route | Fanavaran GET resource | Result |
|
||||
|---|---|---|
|
||||
| `/files` | `/car/vehicle-hull-claims/{claimId}/files` | Live file metadata: `Id`, `ClaimId`, `FileName`, `FileTypeId`, `Status` |
|
||||
| `/files/{fileId}` | `/car/vehicle-hull-claims/{claimId}/files/{fileId}` | One file with the same metadata plus Base64 `Data` |
|
||||
| `/expertise/dmg-sections` | `/car/vehicle-hull-claims/{claimId}/expertise/{expertiseId}/dmg-sections` | Damage sections, nested costs, section/cost IDs, and provider tracking codes |
|
||||
|
||||
The sections route defaults to the saved `expertiseId`. To read a historical
|
||||
expertise on this same claim, supply `?expertiseId=44237`. A missing saved
|
||||
expertise ID without an explicit override returns 400. File and expertise IDs
|
||||
must be positive safe integers.
|
||||
|
||||
Local validation errors return a stable `code`, a specific Persian message, and
|
||||
the relevant field/product metadata. They do not collapse to the generic form
|
||||
validation message:
|
||||
|
||||
| Code | Meaning |
|
||||
|---|---|
|
||||
| `FANAVARAN_LOCAL_CLAIM_ID_INVALID` | `claimCaseId` must be a local MongoDB ObjectId, not the numeric external claim ID |
|
||||
| `FANAVARAN_HULL_CLAIM_REQUIRED` | The linked claim resolves to third-party; `actualProduct` and `expectedProduct` identify the mismatch |
|
||||
| `FANAVARAN_HULL_CLAIM_NOT_SUBMITTED` | No external `claimId` is saved for the local claim |
|
||||
| `FANAVARAN_HULL_EXPERTISE_ID_MISSING` | No expertise ID is saved and no override was supplied |
|
||||
| `FANAVARAN_HULL_FILE_ID_INVALID` / `FANAVARAN_HULL_EXPERTISE_ID_INVALID` | The selected external ID is not a positive safe integer |
|
||||
| `FANAVARAN_CLIENT_INVALID` | The requested tenant is unsupported |
|
||||
|
||||
Selecting `parsian` chooses the insurer; it does not change a third-party claim
|
||||
into a hull claim. These VHUD routes intentionally reject third-party claims.
|
||||
|
||||
Every response wraps the unmodified vendor body in `data`, with `clientKey`,
|
||||
`claimCaseId`, `claimId`, and the selected `fileId` or `expertiseId` when relevant:
|
||||
|
||||
```json
|
||||
{
|
||||
"clientKey": "parsian",
|
||||
"claimCaseId": "6af4594a32d485128a55742d",
|
||||
"claimId": 5190845,
|
||||
"data": [
|
||||
{
|
||||
"Id": 2008737,
|
||||
"ClaimId": 5190845,
|
||||
"FileName": "1.jpg",
|
||||
"FileTypeId": 70,
|
||||
"Status": 2003
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The list response does **not** contain image bytes. Retrieve the desired file ID
|
||||
with the single-file route to obtain `data.Data` as Base64. Preserve the numeric
|
||||
`Status` value; its meaning belongs to Fanavaran's
|
||||
`/common/code-list/file-status` lookup and is not inferred by these routes.
|
||||
|
||||
GEN.12 responses preserve `Id`, `ExpertiseId`, `AccessoryKindId`,
|
||||
`VehicleHullAccessoryId`, `DmgKindId`, `Count`, `WasteValue`, `DmgAmount`, `Desc`,
|
||||
`CINumber`, `CITrackingCode`, and `DmgSectionCosts` when returned. Each nested cost
|
||||
can include its own `Id`, `DmgSectionId`, `DmgCostKindId`, `Caption`, and `Amount`.
|
||||
|
||||
These reads call Fanavaran directly without resubmitting claims/files/expertise,
|
||||
using local upload receipt caches, or changing local claim records. In particular,
|
||||
the remote file list can reveal historical uploads whose file IDs were not saved
|
||||
by the old batch uploader. Vendor errors retain their original `Message` and
|
||||
`RuleName`; transient errors participate in the shared tenant backoff.
|
||||
@@ -0,0 +1,150 @@
|
||||
# Fanavaran lookup coding audit
|
||||
|
||||
**Update (2026-11-11):** The latest hull/accessory/location changes supersede
|
||||
several findings below. See [the current hardcoded-payload audit](./hardcoded-payload-audit.md)
|
||||
for what remains, including exact outbound defaults and standalone tool behavior.
|
||||
|
||||
Date: 2026-11-10. Clients: Moallem, Tejaratno, Parsian. Scope: current base,
|
||||
damage-case, attachment, expertise and other-person payload builders shared by
|
||||
app flows V1–V6. This is a code and local-snapshot audit, not a live acceptance
|
||||
test against the three insurers. No runtime mappings were changed by this audit.
|
||||
|
||||
## Finding
|
||||
|
||||
The integration does not yet guarantee correct tenant-specific codes for every
|
||||
outbound field. Tenant-specific URLs and disk folders exist, but several payload
|
||||
builders use unvalidated defaults, and Mongo lookup storage has no tenant key.
|
||||
The recent strict policy-vehicle mapping applies to hull base claims only.
|
||||
|
||||
## Inquiry-derived values
|
||||
|
||||
| Fields | Current source | Remaining limitation |
|
||||
|---|---|---|
|
||||
| `PolicyId` | Product-specific policy inquiry / previously stored policy reference | Stored policy references need client/product provenance when reused across explicit client routes |
|
||||
| Base/expertise `ClaimExpertId` | Assigned staff's product-specific Mongo codes | Staff profile correctness is required; tenant config expert defaults are excluded |
|
||||
| Hull base `AccidentVehicleUsedId` | Hull policy `VehicleId` + `VehicleVersionNo` → vehicle GET `UsedId` | Missing inquiry warns / blocks submit; active lookup/group compatibility is not independently revalidated here |
|
||||
| Third-party base `AccidentVehicleUsedId` | Guilty VIN inquiry, then policy vehicle, with generic lookup selection; cache/expert review can take precedence | Can choose personal/first group row or tenant default rather than preserve the actual inquiry value |
|
||||
| Damage-case `AccidentVehicleUsedId` | Approved expert vehicle use, matched damaged vehicle, group lookup, then tenant default | Still permits guessed/default codes |
|
||||
| Damage-case `VehicleKindId` | Expert selection → matched vehicle GET → caption keyword search from broad local `carType` | Final fallback can select an arbitrary vehicle model from the correct broad category |
|
||||
| `DriverId`, `OwnerId` | Person national code + birthday inquiry, accepted roles 161/166; GEN.44 creation on submit | Reused person references need client provenance; these are person record IDs, not generic lookup values |
|
||||
| Hull `AccidentCulpritId` | Driver/person inquiry; fallback hull policy `CustomerId` | Driver and policy customer may differ; fallback is not proof of driver identity |
|
||||
| Hull `ActualPremium` | Policy GET `TotalPremium` | Already inquiry-derived |
|
||||
| Hull `VehicleCurrentValue` | Local/reviewed value, then hull policy `VehicleValue` | Policy insured value is the fallback, not an independent market valuation |
|
||||
| Damage-case plaque coding | Matched Fanavaran vehicle fields | `PlaqueKindId`/`PlaqueSampleId` still fall back to national-plate 8/10; plate-letter map is static |
|
||||
| Hull `ColorId` | Exact policy vehicle GET | Already inquiry-derived when the API returns it |
|
||||
| VIN, motor/chassis, plate text, model year, policy number/CI/dates | Vehicle/policy inquiries and stored provider-mapped fields | These are identity/data values; provider-local numeric codes must not be treated as Fanavaran lookup IDs |
|
||||
| `InsuranceCorpId` | Environment caption matched against client's `insurance-corp` | Resolved scalar cache is not tied to caption changes; localhost fallback uses deployment's active tenant, which can differ from an explicit client route |
|
||||
|
||||
## Base-claim codebooks
|
||||
|
||||
| Field | Codebook / correct source | Actual current behavior |
|
||||
|---|---|---|
|
||||
| `AccidentCityId` | `cities`, based on accident location / explicit selection | Tenant default 701 unless reviewed |
|
||||
| `AccidentReportTypeId` | `accident-report-type`, explicit accident report selection | Tenant default 155 unless reviewed |
|
||||
| `AccidentCauseId` | `accident-causes`, explicit accident cause | Hardcoded 6; builder receives accident reason but does not apply its code |
|
||||
| `CulpritLicenceTypeId` | `driving-licence-types`, correct licence category | Tenant default 2 |
|
||||
| Third-party `CulpritTypeId` | `accident-culprit-type` | Tenant default 337 |
|
||||
| `CompensationReferenceId` | Confirm the product contract/codebook | Tenant default 167; no dedicated remote lookup definition in current catalogue |
|
||||
| `PoliceOfficerId` | Confirm the product contract/codebook | Hardcoded 1; no dedicated remote lookup definition in current catalogue |
|
||||
| Hull `AccidentTypeId` | `vehicle-hull-accident-types`, actual accident type | Reviewed selection, else numeric 2; inactive in Moallem/Tejaratno snapshots |
|
||||
| Hull `CulpritTypeId` | `vehicle-hull-accident-culprit-type` | Reviewed selection, else 300; third-party 337 is remapped |
|
||||
| Hull `AuthorityCulpritId` | `detection-accident-culprits` | Reviewed selection or caption بیمهگذار; then first row / numeric 1 fallback |
|
||||
| Tejaratno notifier type/relation | `notifier-type`, `notifier-relation` | Required reviewed choices; shared Mongo source remains a tenant-isolation concern |
|
||||
|
||||
Reviewed stage choices are checked against active lookup rows when saved.
|
||||
However, defaults and previously stored choices are not uniformly validated
|
||||
against the outbound request's client immediately before submission.
|
||||
|
||||
## Damage-case, expertise, files and GEN.44 codebooks
|
||||
|
||||
| Field | Codebook / correct source | Actual current behavior |
|
||||
|---|---|---|
|
||||
| Damage `DmgCaseTypeId` | `dmg-case-type` | Tenant default 175 |
|
||||
| Damage `DmgHistoryStatus` | `dmg-history-status` | Reviewed choice, else tenant default 5214 |
|
||||
| Damage `LicenceTypeId` | `driving-licence-types` | Tenant `CulpritLicenceTypeId`, normally 2 |
|
||||
| Third-party expertise `InspectionPlaceId` | `inspection-place` | Reviewed choice, else 282; lookup is fetched but fallback not selected from it |
|
||||
| Third-party expertise `DropAmountStatus` | `drop-amount-status` | Hardcoded 5458 even though lookup is fetched |
|
||||
| Third-party `DmgSections[].DmgSectionId` | Client `car-components` | Saved local `partId`; catalog can fall back to a shared static snapshot; no outbound membership check |
|
||||
| Third-party `DmgSections[].AccidentLevel` | Client `accident-level` | Numeric `typeOfDamage`, else 5456; no outbound codebook validation |
|
||||
| Hull `DmgSections[].AccessoryKindId` | Client `car-components` | Saved local `partId`; same catalogue provenance concern |
|
||||
| Hull `DmgSections[].DmgKindId` | `vehicle-hull-dmg-kind` | Exact caption تخریب search; fallback 5485. Persian ی vs Arabic ي mismatch can trigger fallback |
|
||||
| Hull section cost `DmgCostKindId` | `vehicle-hull-dmg-cost-kinds` | Caption مجموع لوازم, else 1 |
|
||||
| Hull `VehicleHullAccessoryId` | **Policy** `GET car/vehicle-hull-policies/{policyId}/dmg-accessories` | **Hardcoded 3043330 for every section**; existing lookup API/helper is not wired into builder |
|
||||
| Attachment `FileTypeId` | Client `file-types`, confirmed document category | Configured defaults: Moallem 17, Tejaratno 23, Parsian 63; no automatic outbound membership/category validation |
|
||||
| GEN.44 `CityId` | User/person city matched to client `cities` | Explicit/inquiry city, caption match, else Parsian-specific 9131 |
|
||||
| GEN.44 `GenderId` | Inquiry or client `gender` | Inquiry code or caption match |
|
||||
| GEN.44 `PersonKindId` | Client `person-kind` | Explicit code or caption حقیقی, else Parsian-specific 46 |
|
||||
| GEN.44 `IsIranian`, `NationalityId`, `MaritalStatus` | Client `ans`, `countries`, `marital-status` plus actual person data | Yes/no fallbacks 1/0; marital status unset; nationality not inferred reliably for foreign people |
|
||||
|
||||
`PlaqueDesignId`, hull expertise `PlaqueCityId`/`AccidentPercent`, licence city/country
|
||||
and glass-break reason are currently generally null, not resolved code mappings.
|
||||
Boolean flags, fault percentages, amounts, dates, counts and text are not all
|
||||
tenant-specific codebook IDs. In particular, the requested hardcoded
|
||||
`PoliceReportDesc="شرح گزارش"` is text and is unaffected by lookup coding.
|
||||
|
||||
## Confirmed cross-client differences in local snapshots
|
||||
|
||||
| Meaning / ID | Moallem | Tejaratno | Parsian |
|
||||
|---|---|---|---|
|
||||
| File ID 17 | Other documents, active | Driving licence, active | Police/judicial documents, inactive |
|
||||
| File ID 23 | Printed form, active | Other documents, active | Contract/agreement, inactive |
|
||||
| Intended general-document file ID | 17 | 23 | 63 |
|
||||
| Hull accident ID 2 | Collision, **inactive** | Collision, **inactive** | Collision, active |
|
||||
| Vehicle vs vehicle hull accident | 19, active | 18, active | No identical dedicated row in snapshot; general collision 2 is active |
|
||||
| Hull accident ID 21 | Collision with objects/animals | Overturn/fall | Not present in snapshot |
|
||||
|
||||
Some Tejaratno disk files (including accident-causes, accident-report-type and
|
||||
inspection-place) contain authentication-error objects rather than codebook
|
||||
arrays. This does not establish the client's live codes; it establishes that
|
||||
the local cache is unusable and must be refreshed, not accepted as a lookup.
|
||||
|
||||
## Infrastructure gaps
|
||||
|
||||
1. `lookups` Mongo schema and reads/writes identify a codebook by `name` only.
|
||||
Parsian defaults to this unscoped DB source; notifier lookup paths also use it.
|
||||
Tenant-specific disk paths do not protect a cache populated from another tenant's DB row.
|
||||
2. `getRemoteLookup` accepts any non-null cache value, including API error objects.
|
||||
These prevent remote refresh and become empty rows in payload mapping.
|
||||
3. `vehicle-kinds` Mongo collection uses globally unique `Id`, with no client key.
|
||||
Search/approval can therefore validate against another tenant's catalogue.
|
||||
4. Vehicle-kind live sync calls `fetchFromFanavaran` with the generic definition
|
||||
URL directly. Tenant host rewriting occurs in `getRemoteLookup`, not in this
|
||||
direct-fetch path; Moallem can be sent to the generic host.
|
||||
5. Saved vehicle/stage reviews and remote person/policy caches do not uniformly
|
||||
record/verify the client/product before an explicit client-route submission.
|
||||
|
||||
## Required completion order
|
||||
|
||||
1. Scope persistent codebooks and vehicle-kind rows by client (and product or
|
||||
contract where the lookup requires it), with a migration/re-fetch strategy
|
||||
for existing unscoped data. Reject cached API-error objects.
|
||||
2. Preserve inquiry record provenance: exact policy vehicle/version for base
|
||||
claims; identity-matched damaged vehicle for GEN.12; policy-specific accessory
|
||||
IDs for hull expertise. Remove generic first-row guesses from these paths.
|
||||
3. Use current-client codebooks for explicit accident/review selections. The
|
||||
policy cannot supply accident cause, inspection location or damage severity.
|
||||
Resolve equivalent concepts by normalized meaning, never by reusing another
|
||||
client's numeric ID, and leave ambiguous choices for the expert.
|
||||
4. Validate every non-null code and its relationships at outbound time. Required
|
||||
unresolved/invalid codes should warn in preview and prevent the Fanavaran
|
||||
write, while existing best-effort handling preserves the local app workflow.
|
||||
5. Test clients with intentionally different IDs/captions and inactive rows,
|
||||
plus cache errors and wrong-client saved references. Then run read-only live
|
||||
inquiry checks per client before claiming end-to-end compatibility.
|
||||
|
||||
## Source entry points
|
||||
|
||||
- `src/claim-request-management/claim-request-management.service.ts`: base,
|
||||
damage, expertise and attachment builders; catalogue and lookup wrappers.
|
||||
- `src/claim-request-management/fanavaran-accident-vehicle-used.ts`: group-based
|
||||
default vehicle-use selection.
|
||||
- `src/claim-request-management/fanavaran-hull-base-claim.ts`: hull default codes.
|
||||
- `src/claim-request-management/fanavaran-hull-expertise-lookups.ts`: damage-kind
|
||||
defaults and existing accessory resolver.
|
||||
- `src/claim-request-management/fanavaran-other-people.ts`: person code mapping.
|
||||
- `src/claim-request-management/fanavaran-stage-fields.ts`: reviewed lookup fields.
|
||||
- `src/fanavaran/fanavaran-lookup.service.ts`: lookup cache/source resolution.
|
||||
- `src/lookups/lookups.service.ts`: shared Mongo persistence and vehicle-kind sync.
|
||||
- `src/lookups/entities/schema/lookup.schema.ts` and `vehicle-kind.schema.ts`:
|
||||
current unscoped storage models.
|
||||
- `files/fanavaran-lookups/{moallem,tejaratno,parsian}/`: inspected snapshots.
|
||||
@@ -0,0 +1,107 @@
|
||||
# Fanavaran depreciation tables
|
||||
|
||||
The calculation now uses [ضرایب افت قیمت.xlsx](<../ضرایب افت قیمت.xlsx>) and [افت قیمت سن.png](<../افت قیمت سن.png>). Their reference data lives in `src/static/fanavaran-price-drop.ts`; the previous fixed production-year table and part coefficients are retired.
|
||||
|
||||
## Part and severity codes
|
||||
|
||||
These codes identify depreciation categories, **not** tenant car-component IDs. The original component ID remains `partId`. The expert can explicitly choose a category when a tenant's component caption is ambiguous. Clear names receive a suggestion; numeric IDs are never assumed to mean the same thing across insurers.
|
||||
|
||||
The depreciation path preserves saved tenant captions even when their component IDs collide with the legacy global fallback snapshot. It does not replace a tenant's saved roof caption with another tenant's trunk-floor-tray caption merely because both use ID 52.
|
||||
|
||||
| Category code | Caption | Minor / Moderate / Severe codes | Coefficients |
|
||||
| --- | --- | --- | --- |
|
||||
| 1 | سقف | 1 / 2 / 3 | 3 / 5 / 7 |
|
||||
| 2 | کلاف | 4 / 5 / 6 | 2 / 3 / 4 |
|
||||
| 3 | ستون | 7 / 8 / 9 | 2 / 3 / 4 |
|
||||
| 4 | درب موتور | 10 / 11 / 12 | 2 / 3 / 4 |
|
||||
| 5 | سینی جلو | 13 / 14 / 15 | 1 / 2 / 3 |
|
||||
| 6 | شاسی جلو | 16 / 17 / 18 | 3 / 5 / 7 |
|
||||
| 7 | گلگیر جلو | 19 / 20 / 21 | 1 / 2 / 3 |
|
||||
| 8 | درب جلو | 22 / 23 / 24 | 1 / 2 / 3 |
|
||||
| 9 | درب عقب | 25 / 26 / 27 | 1 / 2 / 3 |
|
||||
| 10 | رکاب | 28 / 29 / 30 | 1 / 2 / 3 |
|
||||
| 11 | گلگیر عقب | 31 / 32 / 33 | 2 / 3 / 5 |
|
||||
| 12 | درب صندوق | 34 / 35 / 36 | 1 / 3 / 5 |
|
||||
| 13 | سینی عقب | 37 / 38 / 39 | 1 / 2 / 3 |
|
||||
| 14 | سینی کف صندوق | 40 / 41 / 42 | 2 / 4 / 5 |
|
||||
| 15 | شاسی عقب | 43 / 44 / 45 | 2 / 4 / 6 |
|
||||
| 16 | کف اتاق | 46 / 47 / 48 | 4 / 6 / 8 |
|
||||
| 17 | بلوک سیلندر | Severe only: 49 | Severe only: 3 |
|
||||
|
||||
Front/rear bumpers are absent from the supplied table and no longer receive an automatic coefficient. Rear tray and trunk-floor tray are separate. Glass, pillar trim and roof accessories are not mapped to a door/pillar/roof just because that word occurs in their caption. A submitted part must exist among the case's selected damaged parts, and each part may occur only once per calculation. Non-catalog internal rows without a component ID remain available through the existing manual-total option.
|
||||
|
||||
## Age codes
|
||||
|
||||
| Age at accident | Code | Coefficient |
|
||||
| --- | --- | --- |
|
||||
| 0 | 1 | 3 |
|
||||
| 1 | 2 | 2.9 |
|
||||
| 2 | 3 | 2.8 |
|
||||
| 3 | 4 | 2.7 |
|
||||
| 4 | 5 | 2.6 |
|
||||
| 5 | 6 | 2.5 |
|
||||
| 6 | 7 | 2.4 |
|
||||
| 7 | 8 | 2.3 |
|
||||
| 8 | 9 | 2.2 |
|
||||
| 9 | 10 | 2.1 |
|
||||
| 10 | 11 | 2.05 |
|
||||
|
||||
Suggested age is the Jalali accident year minus the **damaged vehicle's** Jalali model year. It does not use the current year or the guilty party's vehicle, even when an expert or the guilty party owns the claim record. Experts can confirm/correct age directly. A Gregorian model year without month/day is not converted speculatively; use explicit age instead.
|
||||
|
||||
The screenshot marks these age rows effective from `1404/05/28`. Cases with a known earlier accident date cannot use automatic calculation from this table. Cars **older than ten at the accident are not eligible for depreciation**. Their calculated and manual depreciation must be zero, with no invented age/coefficient code. Exactly ten remains eligible. Positive manual totals require a known or explicitly entered eligible age. The UI offers an over-ten option, explains the exclusion and only lets the expert save zero. For pre-table accident dates, the manual-total path remains subject to the same age rule.
|
||||
|
||||
## Formula and currency
|
||||
|
||||
The supplied documents define reference rows, not a replacement formula. The existing formula is retained with the new coefficients:
|
||||
|
||||
```text
|
||||
Depreciation = vehicle market price × age coefficient × sum(part severity coefficients) / 400
|
||||
```
|
||||
|
||||
All amounts are **Rials**. Integer arithmetic in hundredths of the coefficient prevents floating-point rounding drift; the result is rounded to whole Rials. Example: a 400,000,000 Rial car aged 3 with moderate trunk-floor-tray damage produces `400000000 × 2.7 × 4 / 400 = 10800000` Rials.
|
||||
|
||||
## Existing API routes
|
||||
|
||||
```text
|
||||
GET /v2/expert-claim/request/:claimRequestId/price-drop
|
||||
PUT /v2/expert-claim/request/:claimRequestId/price-drop
|
||||
```
|
||||
|
||||
The context includes `priceDropCatalog` with `fanavaranPartId`, `severities` and `severityCodes`; `ageCatalog`; `suggestedVehicleAge`; `accidentYear`; `calculationVersion`; `ageTableEffectiveFrom`; and `calculationUnavailableReason` when the accident predates the table.
|
||||
|
||||
Example calculation, where `9876` is an illustrative component ID actually selected on that case:
|
||||
|
||||
```json
|
||||
{
|
||||
"carPrice": 400000000,
|
||||
"vehicleAge": 3,
|
||||
"partSeverities": [
|
||||
{ "partId": 9876, "fanavaranPartId": 14, "severity": "Moderate" }
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`fanavaranPartId` is optional when a safe name mapping exists. The older `carModelYear` input remains supported when an accident date is available. Clients never choose coefficients directly: the API derives them from the static source.
|
||||
|
||||
`evaluation.priceDrop` stores version `fanavaran-v1`, age, `fanavaranAgeId` and the coefficient. Each saved part line includes the actual component `partId`, category `fanavaranPartId` and `fanavaranSeverityId`. The response and strict Mongoose schema retain these fields.
|
||||
|
||||
For eligible ages, the manual path remains (zero is also allowed without an age):
|
||||
|
||||
```json
|
||||
{ "manualPriceDrop": 0 }
|
||||
```
|
||||
|
||||
Calculated requests must omit `manualPriceDrop`; its presence explicitly chooses the manual path. The expert UI separates these writes so a previously saved total cannot silently override recalculation. Manual entry also has an optional `carPrice` field for Fanavaran's market-value data. Manual writes preserve an existing market price when omitted and clear obsolete calculated rows. `manualOverride` now survives schema casting.
|
||||
|
||||
## Fanavaran writes and rollout
|
||||
|
||||
The existing documented write contracts still receive the final total in third-party `DropAmountAdditionsDeductions` or car-body `DropAmount`. Category/severity/age codes are calculation/audit metadata; they are not inserted into undocumented outgoing fields. GEN.13 is read-only in the currently supplied API contract.
|
||||
|
||||
Saved historical assessments are never automatically recalculated. When a known over-ten vehicle has an old positive total, a new Fanavaran submission uses zero; the stored historical assessment is preserved until explicitly corrected. The UI identifies results without the new calculation version and lets the expert explicitly recalculate them. Deploy the API first, then the expert UI. No new environment variables or database migration are required.
|
||||
|
||||
## Verification
|
||||
|
||||
- All 17 category codes/captions and all 49 severity codes/coefficients were compared directly with the supplied workbook.
|
||||
- API regression tests cover age boundaries, date validity, separate severity codes, tenant-ID collisions, explicit mappings, real schema persistence, manual zero, duplicate/unselected parts, vehicle-party isolation and failed writes preserving previous results.
|
||||
- Expert UI regression tests cover request construction and rendered controls. Browser checks at 1440×1100 and 390×844 cover labels, keyboard, overflow, age zero, severe-only cylinder block, HTTP-error retry and separate calculated/manual requests. Browser API calls used synthetic intercepted responses.
|
||||
- The full API suite additionally reports ten failures in the unchanged `fanavaran-submit-overrides.spec.ts` fixture, reproduced on an archive of the unmodified commit. These fail at the existing vehicle-review prerequisite before reaching their intended assertions; they are unrelated to depreciation.
|
||||
@@ -0,0 +1,237 @@
|
||||
# Lookup-backed fields by Fanavaran submission request
|
||||
|
||||
Code snapshot: 2026-11-11. This describes the current YARA builders and validation,
|
||||
not a live acceptance test. Older stage-field/audit documents contain historical
|
||||
defaults; use the validation implementation as the authority for current checks.
|
||||
|
||||
Ordinary codebook names below can be read through
|
||||
`GET /lookups/fanavaran/{lookup-name}`. These routes use the deployment's active
|
||||
insurer. Use the same insurer/product/contract as the submission being checked.
|
||||
Use each row's `Id`, not its Caption or a different provider's code. A valid ID
|
||||
must also represent the intended meaning, be active when IsActive is supplied,
|
||||
and satisfy policy/vehicle/person relationships.
|
||||
|
||||
Validation labels:
|
||||
|
||||
- **Live checked:** current hull outbound validation checks membership/activity
|
||||
using fresh API responses. A failed lookup or invalid selection blocks the write.
|
||||
- **Gap:** no equivalent comprehensive third-party outbound membership check.
|
||||
Some UI selections/inquiries are validated, but defaults and saved values can
|
||||
still be wrong for the target insurer or current contract.
|
||||
- **Conditional:** currently null/unset; becomes a concern if populated or required
|
||||
by a vendor rule. Do not guess an endpoint/code when the source is unconfirmed.
|
||||
|
||||
## 1. Third-party base claim — GEN.03
|
||||
|
||||
`POST /car/third-party-car-financial-claims`
|
||||
|
||||
| Request field | Lookup/source | Current concern |
|
||||
|---|---|---|
|
||||
| AccidentCityId | cities | Reviewed selection or default 701; gap |
|
||||
| AccidentReportTypeId | accident-report-type | Reviewed selection or default 155; gap |
|
||||
| AccidentCauseId | accident-causes | Builder still starts with fixed 6; supplied accident-reason code is not applied as the outbound ID |
|
||||
| AccidentVehicleUsedId | vehicle-use-types + actual policy/VIN vehicle UsedId | Vehicle group must match; inquiry/group/default fallbacks remain |
|
||||
| CulpritTypeId | accident-culprit-type | Derived insurer-driver distinction, currently 337/338; no universal live membership guard |
|
||||
| CulpritLicenceTypeId | driving-licence-types | Tenant default normally 2; must match the driver's actual licence category |
|
||||
| CulpritLicenceCityId | cities | Conditional; normally null |
|
||||
| CulpritLicenceCountryId | countries | Conditional; normally null |
|
||||
| HasOtherCulprit | ans | Currently 0 |
|
||||
| IsFatalAccident | yes/no flag | Currently 0; no third-party live codebook validation |
|
||||
| IsAccidentOutOfBorder | ans / yes-no flag | Currently 0 |
|
||||
| IsPlaqueChanged | yes/no flag | Currently 0 |
|
||||
| IsLicenseMatchWithVehicleKind | yes/no flag | Currently 1; this does not validate the actual licence/vehicle relationship |
|
||||
| IsLicenseReplacement | yes/no flag | Currently 0; hull uses a different field name |
|
||||
| IsOwnerChanged, CostSeparationToDmgSections, IsSurplusArticleEighthLaw | yes/no flags | Conditional; normally null on third-party |
|
||||
| CompensationReferenceId | Dedicated source not configured in the local lookup catalogue | Default 167; confirm the vendor's codebook/contract rather than inventing a lookup URL |
|
||||
| PoliceOfficerId | Dedicated source not configured | Fixed 1 on third-party; needs contract confirmation |
|
||||
| UnknownCulpritCauseId | No source wired | Conditional; currently null |
|
||||
|
||||
TejaratNo's current third-party branch additionally sends:
|
||||
|
||||
| Request field | Lookup/source | Concern |
|
||||
|---|---|---|
|
||||
| DmgNotifications[].NotifierTypeId | notifier-type | Must be an explicitly reviewed allowed choice |
|
||||
| DmgNotifications[].NotifierRelationId | notifier-relation | Must represent the notifier's actual relationship |
|
||||
| DmgNotifications[].NotifierPartyId | Person inquiry / GEN.44 response | Person record ID, not a generic codebook; must identify the correct notifier |
|
||||
| DmgNotifications[].IsInjuredPartyIdentified | yes/no flag | Conditional; currently null |
|
||||
|
||||
Do not apply the TejaratNo DmgNotifications shape to other insurers automatically.
|
||||
|
||||
## 2. Third-party damage case — GEN.12
|
||||
|
||||
`POST /car/third-party-car-financial-claims/{claimId}/dmg-cases`
|
||||
|
||||
| Request field | Lookup/source | Current concern |
|
||||
|---|---|---|
|
||||
| VehicleKindId | vehicle-kinds / matched vehicle GET | Model and VehicleGroupId must match; expert selection and caption fallbacks need correct catalogue provenance |
|
||||
| AccidentVehicleUsedId | vehicle-use-types / vehicle UsedId | Must belong to the selected vehicle's group; default remains possible |
|
||||
| DmgCaseTypeId | dmg-case-type | Tenant default normally 175; gap |
|
||||
| DmgHistoryStatus | dmg-history-status | Reviewed choice or default 5214; gap |
|
||||
| InsuranceCorpId | insurance-corp | Actual damaged vehicle insurer, selected by caption; cached/default tenant provenance can be wrong |
|
||||
| LicenceTypeId | driving-licence-types | Uses tenant CulpritLicenceTypeId, normally 2; gap |
|
||||
| LicenceCityId | cities | Conditional; currently null |
|
||||
| LicenceCountryId | countries | Conditional; currently null |
|
||||
| DriverIsOwner | yes/no flag | Derived 1/0; must represent the actual driver/owner relationship |
|
||||
| PlaqueKindId | Vehicle inquiry / GET | Must match actual plate kind; national-plate fallback 8 remains |
|
||||
| PlaqueSampleId | Vehicle inquiry / GET | Must match actual plate sample; fallback 10 remains |
|
||||
| PlaqueMiddleCodeId | Vehicle response or static plate-letter mapping | Not the visible plate letter or an unrelated provider code; no configured standalone lookup endpoint |
|
||||
| PlaqueCityId | Vehicle response | Conditional; no independent membership check |
|
||||
|
||||
DriverId and OwnerId are person record IDs. Inquiry acceptance currently requires
|
||||
RoleId 161 or 166; a different role cannot simply be reused as DriverId. Missing
|
||||
acceptable people can trigger GEN.44 registration before damage submission.
|
||||
|
||||
## 3. Third-party attachments — GEN.07
|
||||
|
||||
`POST /car/third-party-car-financial-claims/{claimId}/files`
|
||||
|
||||
| Request field | Lookup | Current concern |
|
||||
|---|---|---|
|
||||
| FileTypeId | file-types | Configured ClaimFileTypeId; must be active and the correct document category for that insurer |
|
||||
| Files[].FileTypeId, when this repeated metadata is present | file-types | Must agree with the same document type |
|
||||
|
||||
The strict hull lookup guard does not cover third-party file uploads. A historical
|
||||
successful file type from another insurer is not proof of acceptance here.
|
||||
|
||||
## 4. Third-party expertise — GEN.08
|
||||
|
||||
`POST /car/third-party-car-financial-claims/{claimId}/expertise`
|
||||
|
||||
| Request field | Lookup | Current concern |
|
||||
|---|---|---|
|
||||
| InspectionPlaceId | inspection-place | Reviewed selection, otherwise 282; gap |
|
||||
| DropAmountStatus | drop-amount-status | Fixed 5458; the fetched lookup is not used to select a replacement ID |
|
||||
| DmgSections[].DmgSectionId | car-components | This is the selected catalogue part ID on submission; a local/shared snapshot can be wrong for the insurer |
|
||||
| DmgSections[].AccidentLevel | accident-level | Numeric typeOfDamage or fallback 5456; must be a severity ID, not a label |
|
||||
|
||||
Readiness checks for these fields primarily check presence. They are not the same
|
||||
as the fresh API membership/activity validation added to hull writes.
|
||||
|
||||
## 5. Hull base claim — GEN.03
|
||||
|
||||
`POST /car/vehicle-hull-claims`, also checked for base PUT updates.
|
||||
|
||||
| Request field | Lookup | Current handling |
|
||||
|---|---|---|
|
||||
| AccidentCityId | cities | Live checked; reviewed/configured selection must exist |
|
||||
| AccidentReportTypeId | accident-report-type | Live checked |
|
||||
| AccidentCauseId | accident-causes | Live checked; candidate still starts at 6, so check that its meaning is the actual accident cause |
|
||||
| AccidentTypeId | vehicle-hull-accident-types | Reviewed choice or response row for تصادف(حادثه); live checked, no numeric fallback |
|
||||
| CulpritTypeId | vehicle-hull-accident-culprit-type | Reviewed choice or response row for بیمهگذار; live checked; third-party 337 is not reused |
|
||||
| AuthorityCulpritId | detection-accident-culprits | Reviewed choice or matching بیمهگذار response row; live checked, no first-row/numeric fallback |
|
||||
| CulpritLicenceTypeId | driving-licence-types | Live checked; membership does not prove it matches the real driver's licence |
|
||||
| AccidentVehicleUsedId | vehicle-use-types + exact policy vehicle/version UsedId | Inquiry-derived and live checked; vehicle/group relationship still matters |
|
||||
| IsLicenseReplaced | ans | `1` if licence issue >10y before accident, else `null` |
|
||||
| IsOwnerChanged | ans | Currently 0; live checked |
|
||||
| CostSeparationToDmgSections | ans | Currently 0; live checked |
|
||||
| IsAccidentOutOfBorder | ans | Currently 0; live checked when non-null |
|
||||
| IsSurplusArticleEighthLaw | ans | Conditional; live checked when non-null |
|
||||
| CulpritLicenceCityId | cities | Conditional; live checked when non-null |
|
||||
| CulpritLicenceCountryId | countries | Conditional; live checked when non-null |
|
||||
| NotifierTypeId, TejaratNo only | notifier-type | Root field for hull, unlike third-party DmgNotifications; live checked when present |
|
||||
| NotifierRelationId, TejaratNo only | notifier-relation | Root field; live checked when present |
|
||||
| GlassBreakReasonId | No lookup source currently wired | Conditional; currently null; verify the provider contract if using a glass-break scenario |
|
||||
|
||||
PoliceOfficerId is currently null on hull. CompensationReferenceId and the
|
||||
third-party-only IsLicenseReplacement are stripped from the hull payload.
|
||||
ActualPremium comes from the policy response, not a lookup list.
|
||||
|
||||
## 6. Hull attachments — GEN.05
|
||||
|
||||
`POST /car/vehicle-hull-claims/{claimId}/files`
|
||||
|
||||
| Request field | Lookup | Current handling |
|
||||
|---|---|---|
|
||||
| FileTypeId | file-types | Configured choice, live checked before upload |
|
||||
| Files[].FileTypeId, when present | file-types | Live checked as well |
|
||||
|
||||
A file type being active does not prove the document belongs in that category.
|
||||
The returned attachment Id is saved as fileId; it is not FileTypeId.
|
||||
|
||||
## 7. Hull expertise — GEN.06
|
||||
|
||||
`POST /car/vehicle-hull-claims/{claimId}/expertise`
|
||||
|
||||
| Request field | Lookup/source | Current handling |
|
||||
|---|---|---|
|
||||
| DmgSections[].AccessoryKindId | car-components | Selected part ID, live checked |
|
||||
| DmgSections[].VehicleHullAccessoryId | Current hull policy dmg-accessories | Exact `AccessoryKindId` (or caption) match on one policy row. If missing, use the policy «کليه قطعات فابريک» row `Id` (factory bundle) while keeping the selected car-components `AccessoryKindId` and part `Desc` |
|
||||
| DmgSections[].DmgKindId | vehicle-hull-dmg-kind | Response row caption تخریب; live checked, no numeric fallback |
|
||||
| DmgSections[].DmgSectionCosts[].DmgCostKindId | vehicle-hull-dmg-cost-kinds | Response row caption مجموع لوازم; live checked, no numeric fallback |
|
||||
| ColorId | Policy vehicle GET ColorId | Inquiry-derived; not independently checked against a colour lookup |
|
||||
| PlaqueDesignId | No source wired | Conditional; currently null |
|
||||
| PlaqueCityId | No source wired on hull expertise | Conditional; currently null |
|
||||
| IsDestruction | Optional flag | Currently null; no live yes/no membership check in the expertise validator |
|
||||
|
||||
Get the policy accessory rows using:
|
||||
|
||||
`GET /lookups/vehicle-hull-dmg-accessories/{policyId}`
|
||||
|
||||
Upstream source:
|
||||
`GET /car/vehicle-hull-policies/{policyId}/dmg-accessories`
|
||||
|
||||
Use the row's Id for VehicleHullAccessoryId and that same row's AccessoryKindId.
|
||||
Fanavaran rule `CarDamageBdAsibdideSectionLookupFilterRule` rejects pairing a
|
||||
local car-components part id with an unrelated policy accessory Id (including
|
||||
factory-bundle rows).
|
||||
|
||||
`car-components` is the full part catalogue (frontend picker). Policy
|
||||
`dmg-accessories` is only what that hull policy registered — often a single
|
||||
«کليه قطعات فابريک» OEM/factory coverage line (AccessoryKindId e.g. 112), not
|
||||
every tyre/cap/electrical part. Unlisted parts map to that factory row's `Id`
|
||||
as `VehicleHullAccessoryId`, keep the selected car-components `AccessoryKindId`,
|
||||
and keep `Desc` from the car-components Caption when available.
|
||||
|
||||
Hull has no damage-case POST. DmgCaseId, InspectionPlaceId and DropAmountStatus
|
||||
are not hull expertise fields. AccidentPercent is a percentage, not a lookup ID.
|
||||
|
||||
## 8. Person registration — GEN.44, when triggered by either product
|
||||
|
||||
`POST /common/other-people`
|
||||
|
||||
| Request field | Lookup | Current concern |
|
||||
|---|---|---|
|
||||
| CityId | cities | Explicit/inquiry/caption selection, else default 9131 remains |
|
||||
| GenderId | gender | Inquiry/explicit/caption selection; may remain null |
|
||||
| MaritalStatus | marital-status | Currently normally null |
|
||||
| IsIranian | ans | Actual person status, with 1/0 fallbacks |
|
||||
| NationalityId | countries | Normally null for Iranian people; foreign-nationality mapping needs explicit review |
|
||||
| PersonKindId | person-kind | Explicit/caption selection, else default 46 remains |
|
||||
|
||||
GEN.44 is not covered by the hull base/files/expertise lookup validator. It also
|
||||
has identity, birthday and mobile validation which can fail without a lookup error.
|
||||
|
||||
## Record IDs and headers: related failures, but not ordinary codebooks
|
||||
|
||||
| Value | Correct source / relationship |
|
||||
|---|---|
|
||||
| Base PolicyId | Correct guilty-party third-party policy, or first-party hull policy; never mix the products |
|
||||
| Base ClaimExpertId | Staff ThirdPartyClaimExpertId or CarBodyClaimExpertId |
|
||||
| Expertise ClaimExpertId | Staff ThirdPartyExpertiseClaim or CarBodyExpertiseClaim; different role from base ClaimExpertId |
|
||||
| Third-party DriverId / OwnerId | Appropriate person inquiry / GEN.44 Id; required accepted roles |
|
||||
| Hull AccidentCulpritId | Driver inquiry; policy CustomerId is a fallback and may identify a different person |
|
||||
| NotifierPartyId | Correct notifier person record |
|
||||
| Nested claimId | Base-create response Id, not ClaimNo |
|
||||
| Third-party DmgCaseId | That claim's damage-case response Id |
|
||||
| expertiseId | That claim's expertise response Id |
|
||||
| fileId | That claim's upload response Id; use file-types only for FileTypeId |
|
||||
| Location header | Responsible staff locations[].id, else their branch's code |
|
||||
| ContractId header | Correct product contract; hullContractId where configured |
|
||||
| CorpId header / authenticationToken | Credentials/scoping for the same insurer as all selected codes |
|
||||
|
||||
Amounts, wages, premiums, dates, times, counts, descriptions, licence numbers,
|
||||
VIN/chassis/motor text, and plain plate digits are not generic lookup IDs. They
|
||||
can still fail required-field, format, range, identity or cross-field rules.
|
||||
|
||||
## Highest-priority remaining checks
|
||||
|
||||
Third-party still needs the most attention: base accident/driver codes, damage
|
||||
vehicle/use/plate codes, DmgCaseTypeId/DmgHistoryStatus, expertise inspection/drop/
|
||||
severity/part codes, attachment FileTypeId, and GEN.44 defaults. Hull's live checks
|
||||
prevent missing/inactive IDs but cannot prove that a valid selected code has the
|
||||
correct business meaning or satisfies every provider rule.
|
||||
|
||||
Use stage previews before submission. Hull failures identify lookup fields through
|
||||
FANAVARAN_HULL_LOOKUP_INVALID; prerequisite failures identify stage and pendingFiles.
|
||||
Do not confuse a local guard rejecting invalid data with Fanavaran accepting the
|
||||
whole claim: downstream conditional rules remain authoritative.
|
||||
@@ -43,7 +43,7 @@ Parsian tenant defaults used below: `ClaimExpertId=154`, `ExpertiseClaimExpertId
|
||||
| AccidentCityId | شهر محل حادثه | number | **no** | **system** `701` تهران | Lookup: `GET /lookups/cities` |
|
||||
| AccidentReportTypeId | نحوه اعلام حادثه | number | **no** | **system** `155` | Lookup: `GET /lookups/accident-report-type` |
|
||||
| AccidentVehicleUsedId | نوع کاربری خودرو | number | **no** | **inquiry** VIN / policy vehicle `UsedId`, else tenant `1` | Lookup: `GET /lookups/vehicle-use-types` |
|
||||
| CulpritTypeId | نوع مقصر | number | **no** | **system** `337` | Lookup: `GET /lookups/accident-culprit-type` (ثالث, not hull) |
|
||||
| CulpritTypeId | نوع مقصر | number | **no** | **derived** from guilty party: driver = insurer → `337` (بیمهگذار), else `338` (راننده غير از بيمه گذار). Never `728` | Lookup: `GET /lookups/accident-culprit-type` (ثالث, not hull) |
|
||||
| CulpritLicenceTypeId | نوع گواهینامه مقصر | number | **no** | **system** `2` | Lookup: `GET /lookups/driving-licence-types` |
|
||||
| CulpritLicenceNo | شماره گواهینامه مقصر | string | **no** | **user** party licence if stored, else dummy `9705463515` | Must never be empty |
|
||||
| CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **system** `"1394/10/13"` | Should later be **user** |
|
||||
@@ -104,8 +104,8 @@ If `DriverId` is missing, **submit** (not preview) registers GEN.44 `POST /commo
|
||||
|
||||
| Field | Persian | Type | Null? | Current source |
|
||||
|-------|---------|------|-------|----------------|
|
||||
| DriverId | شناسه راننده زیاندیده در فناوران | number | **no** on submit | **inquiry** `GET /lookups/inquiry-by-unique-identifier` (national code + Jalali birthday). Fallback **GEN.44** create |
|
||||
| OwnerId | شناسه مالک | number | yes | currently `null` |
|
||||
| DriverId | شناسه راننده زیاندیده در فناوران | number | **no** on submit | **inquiry** `GET /lookups/inquiry-by-unique-identifier` — only RoleId **161** or **166**. If missing / only e.g. 162 → **GEN.44** create on submit |
|
||||
| OwnerId | شناسه مالک | number | preferred | **inquiry** same RoleId **161**/**166** rule as DriverId; else **GEN.44** on submit (reuse DriverId when same national code) |
|
||||
| VehicleKindId | نوع خودرو | number | **no** | **inquiry** VIN vehicle `VehicleKindId`, else **lookup** `GET /lookups/vehicle-kinds` matched to `claim.vehicle.carType` |
|
||||
| AccidentVehicleUsedId | کاربری | number | **no** | **inquiry** vehicle `UsedId` / use-types, else tenant |
|
||||
| VIN | شماره شاسی ۱۷ رقمی | string | preferred | **inquiry** plate/VIN inquiry |
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# V14 (Parsian / Moallem) vs Fanavaran V15.00 (Tejaratno)
|
||||
|
||||
V15.00 is the product package. HTTP paths stay `/Api/BimeApi/v2.0/car/...`. There is no `/v15` URL. Auth headers are unchanged (`authenticationToken`, `CorpId`, `ContractId`, `Location`).
|
||||
|
||||
**Tejaratno third-party GEN.03 uses V15.** Parsian and Moallem stay on the V14 body in [third-party-stage-fields.md](./third-party-stage-fields.md). Tejaratno car-body (hull) is not this contract.
|
||||
|
||||
Field tables live in the `fanavaran-api-v15` skill. The live transformer is `src/claim-request-management/fanavaran-v15-third-party-base.ts`.
|
||||
|
||||
## Who sends which GEN.03
|
||||
|
||||
| Tenant | Product | Body |
|
||||
|--------|---------|------|
|
||||
| Tejaratno | ثالث | V15 allowlist, no `AnnouncementDate`, one nested `DmgNotifications[]` item |
|
||||
| Tejaratno | بدنه | Existing hull whitelist. Notifier type/relation are copied onto the hull root only |
|
||||
| Parsian, Moallem | ثالث and بدنه | V14, including `AnnouncementDate = AccidentDate` |
|
||||
|
||||
GEN.12, GEN.07, and GEN.08 are the same URLs and JSON for every tenant. Do not switch Tejaratno attachments to GEN.02.
|
||||
|
||||
## Tejaratno third-party create
|
||||
|
||||
Same staged path as Parsian: GEN.03 base → GEN.12 damage → GEN.07 files (`FileName` / `FileTypeId`) → GEN.08 expertise.
|
||||
|
||||
GEN.03 omits `AnnouncementDate` (still an output). It also omits the V14 keys that are not in the V15 input table: `ActualPremium`, `ArchiveNo`, `AuthorityCulpritId`, `ClaimCompletionDate`, `CostSeparationToDmgSections`, `CustomerFaultPercent`, `GlassBreakReasonId`, `IsOwnerChanged`, `IsSurplusArticleEighthLaw`, `StatusChangeDate`. Do not send `ComplementClaimId`.
|
||||
|
||||
One `DmgNotifications` item is always nested on create. Fanavaran rejects a financial claim with no approved announcer (`PrvMustHaveAnyElamKhesaratWithTaeedStateRuleBL`). Do not POST GEN.30 before the claim exists. GEN.30 (`.../{ClaimId}/dmg-notifications`) is only an extra announcement after `claimId` exists.
|
||||
|
||||
| Notification field | Value on Tejaratno ثالث |
|
||||
|--|--|
|
||||
| `LetterNo`, `Desc`, `IsInjuredPartyIdentified`, `InjuredPartyId` | `null` |
|
||||
| `ClaimNotificationDate`, `LetterDate` | accident date |
|
||||
| `InjuredCount`, `DeathCount` | JSON `null`, never `0` (`FotCountAndMasdumCountMustBeReadOnlyWhenPrvIsSMPrvRuleBL`; counts are only for bodily / driver-accident files) |
|
||||
| `NotifierTypeId`, `NotifierRelationId` | expert review, ids from the `lookups` collection |
|
||||
| `NotifierPartyId` | guilty insurer |
|
||||
|
||||
`NotifierPartyId` is resolved at preview/submit, not chosen on the review form. Parties inquiry prefers RoleId **161** (بیمهگذار), then **166** (سایر). If neither exists, YARA registers the person with GEN.44 `common/other-people`. Mobile is required (`MobileIsRequiredRule`). Submit throws `FANAVARAN_NOTIFIER_PARTY_REQUIRED` when that id cannot be resolved. Preview still returns the body with a null party id.
|
||||
|
||||
Expert review must pick both notifier ids before the first submit (`FANAVARAN_NOTIFIER_REVIEW_REQUIRED`). Options come from Mongo `lookups` documents `notifier-type` and `notifier-relation` (`response` is `{Id, Caption, IsActive}[]`). Those two names are not fetched from Fanavaran. `common/code-list/notifier-type` 404s; the published paths are `car/code-list/notifier-type` (VHUP GEN.45) and `car/code-list/notifier-relation` (VHUP GEN.44). The stored Tejaratno type list includes **5518** (مرجع و یا نهاد رسمی) as well as 5516 and 5517. If either document is missing, the review options are empty and submit stays blocked.
|
||||
|
||||
After a successful create, `fanavaranSync.baseClaim.lastPayload` is the V15 body, so later review reads `NotifierTypeId` / `NotifierRelationId` from `DmgNotifications[0]` as well as the claim root.
|
||||
|
||||
## Unchanged stages
|
||||
|
||||
| Stage | URL | What YARA sends |
|
||||
|-------|-----|-----------------|
|
||||
| GEN.12 damage case | `.../third-party-car-financial-claims/{claimId}/dmg-cases` | Same input as V14 (driver, owner, plaque, policy, licence, `Desc`, `EstimateAmount`, `PolicyCINumber`, `BuiltYear`, `AccidentVehicleUsedId`). Output may include `Status` (`car/code-list/dmg-case-status`) |
|
||||
| GEN.07 files | `.../{claimId}/files` | `FileName`, `FileTypeId`. This is the staged upload |
|
||||
| GEN.08 expertise | `.../{claimId}/expertise` | Same create body (`DmgCaseId`, wages, `DmgSections[]`, `DropAmountStatus`, `ComponentReplacementTaxAndToll`, `DamagedVehicleCurrentPrice`) |
|
||||
| GEN.09 / GEN.13 | damaged points / price drop | GET-only. YARA does not call them |
|
||||
|
||||
GEN.02 is the import-claim file service (`third-party-car-import-claims/{PrvId}/files`, `Title` + `FileType`). It is not the attachment API.
|
||||
|
||||
`DriverId` / `OwnerId` still come from parties inquiry (161 then 166) and GEN.44 when the person is missing. V15 documents those ids against `common/other-people`; the inquiry rule stays.
|
||||
|
||||
On expertise read, `HasDropAmount` is an ans lookup, and the output may include `DropAmounts[]`. GEN.13 returns `AccidentLevel`, `DropAmountRates`, and `AccidentRate`. None of that changes the create body.
|
||||
@@ -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,98 @@
|
||||
# Insurer, staff and branch management
|
||||
|
||||
The expert panel now supports setting up a fresh deployment without creating insurer/staff accounts through Swagger. No existing case, assignment, Fanavaran or reporting routes were removed.
|
||||
|
||||
## Starting with only a super-admin
|
||||
|
||||
1. Sign in through the existing super-admin login.
|
||||
2. Open **شرکتهای بیمه** (`/insurers`), and add the Persian/English insurer names, numeric client code and expert collaboration mode.
|
||||
3. Add a **حساب بیمه** with name, email and password. This creates an existing `company` actor attached to that insurer; its login identifier is its email.
|
||||
4. Use the insurer's **شعبهها** and **اعضا** actions to select the insurer and create branches and staff.
|
||||
5. The insurer's own account can manage its branches and all six staff roles. It cannot create or edit insurers or insurer login accounts.
|
||||
|
||||
The **مدیریت** tabs in `/branches` and `/expert-list` provide creation and editing. Existing date/search filters and performance tables remain under **آمار عملکرد**. The super-admin's existing insurer selector remains available.
|
||||
|
||||
## API surface
|
||||
|
||||
All endpoints require bearer authentication and strictly validate their DTOs. Swagger groups are `super-admin-management` and `insurer-management`.
|
||||
|
||||
| Operation | Super-admin | Insurer |
|
||||
| --- | --- | --- |
|
||||
| List/create insurers | `GET/POST /super-admin/management/clients` | Unavailable |
|
||||
| Edit insurer metadata | `PATCH /super-admin/management/clients/:id` | Unavailable |
|
||||
| Read or update case working hours | `GET/PATCH /super-admin/management/working-hours?clientId=...` | `GET/PATCH /expert-insurer/management/working-hours` |
|
||||
| List/create insurer login accounts | `GET/POST /super-admin/management/clients/:clientId/accounts` | Unavailable |
|
||||
| Edit insurer login account | `PATCH /super-admin/management/clients/:clientId/accounts/:id` | Unavailable |
|
||||
| List/create staff | `GET/POST /super-admin/management/staff?clientId=...` | `GET/POST /expert-insurer/management/staff` |
|
||||
| Edit staff | `PATCH /super-admin/management/staff/:role/:id?clientId=...` | `PATCH /expert-insurer/management/staff/:role/:id` |
|
||||
| Activate/deactivate a staff role account | `PATCH /super-admin/management/staff/:role/:id/status?clientId=...` | Unavailable |
|
||||
| List/create branches | `GET/POST /super-admin/management/branches?clientId=...` | `GET/POST /expert-insurer/management/branches` |
|
||||
| Edit branch | `PATCH /super-admin/management/branches/:id?clientId=...` | `PATCH /expert-insurer/management/branches/:id` |
|
||||
|
||||
Staff list queries accept `search`, `role`, `page` and `limit` (default 20, capped at 100). Responses contain `list`, `total`, `page` and `limit`. Branch responses contain `list`; clients contain `clients`. Account lists share the staff pagination contract.
|
||||
|
||||
## Case working hours
|
||||
|
||||
Insurers edit their own hours in **تنظیمات شرکت بیمه** (`/settings`). Super-admins use **ساعات کاری** on the relevant company in `/insurers`. Existing companies default to 24/7. Saving a change applies it immediately to new case submissions, including submissions for existing cases.
|
||||
|
||||
Schedules use Tehran time and allow one opening window per weekday. Omitted days are closed. For an overnight shift, enter an end time earlier than the start. The API numbers weekdays from Sunday (`0`) through Saturday (`6`) and accepts `24:00` as the end of a day. For example, `{"alwaysOpen":false,"windows":[{"weekday":6,"opensAt":"08:00","closesAt":"16:00"}]}` opens Saturday from 08:00 inclusive to 16:00 exclusive. Enable `alwaysOpen` to allow access around the clock.
|
||||
|
||||
Case creation and updates use the liable insurer's hours once it is identified. At intake, staff use their own insurer's hours. For public intake before the case insurer is known, set the API's existing `CLIENT_ID` to the deployment insurer's numeric client code. If an intake has no known insurer and the deployment has no configured insurer, the schedule applies once the insurer is identified. Case reads, login and schedule settings are available outside those hours. Blocked case updates return HTTP 403 with `OUTSIDE_WORKING_HOURS` and the next opening.
|
||||
|
||||
## Refer a case for damage assessment
|
||||
|
||||
In the insurer case details, use **ارجاع پرونده** to choose an active expert in an active branch of the same company. The destination role follows the original workflow: damage expert for V1/V6, field expert for V2/V3, and file reviewer for V4/V5.
|
||||
|
||||
Referral becomes available once intake and evidence capture are complete and the claim is ready for damage assessment or factor validation. V4/V5 files still in the FileMaker or capture steps stay in those workflows. Any successful Fanavaran stage, including automatic base-claim registration, closes referral eligibility.
|
||||
|
||||
The referral updates the claim's review branch and clears the previous review lock. The new expert opens the case from the expert review list. The intake owner and branch remain in the linked blame case, and V5 approval stays with the original FileMaker. The case timeline records the insurer account and the previous and new experts and branches.
|
||||
|
||||
The insurer routes are `GET /expert-insurer/files/:publicId/review-referral` for eligible experts and the current revision, and `PATCH /expert-insurer/files/:publicId/review-referral` with `expertId` and `revision`. A concurrent write or submission can require refreshing the referral options.
|
||||
|
||||
## Fields
|
||||
|
||||
`role` is one of `expert`, `damage_expert`, `field_expert`, `file_maker`, `file_reviewer`, or `call_center`, and is selected only during creation. These use the existing collections and actor login mechanism.
|
||||
|
||||
Staff creation requires `firstName`, `lastName`, a ten-digit `nationalCode` and a password of at least six characters. Email and mobile are optional for claim experts, field experts, file makers, file reviewers and call-center agents, matching the seed format. Blame experts still require email and mobile. Seed-style accounts without email log in using their national code. National-code and email aliases can be reused across different roles; they remain unique within a role because login has no tenant selector. Create each required role with the same credentials to let one person use several flows. Existing records and passwords are preserved. The remaining-experts seed prepares sparse email indexes for older claim-expert databases before inserting email-less accounts.
|
||||
|
||||
Staff lists include `isActive`, treating older records with no flag as active. Only super-admins can change this flag using the status endpoint and a boolean body, e.g. `{"isActive": false}`. Disabled accounts cannot log in or reuse existing JWTs. Status belongs to the selected role account; the same person's other assignments are unaffected. See [expert access and optional voice](expert-access-and-optional-voice.md).
|
||||
|
||||
Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `state`, `address` and `expertCode`. A branch, when supplied, must belong to the account's insurer. `expertCode` and the role-specific Fanavaran IDs are positive integer strings, matching existing persistence and mapping contracts.
|
||||
|
||||
| Role | Additional optional fields |
|
||||
| --- | --- |
|
||||
| Blame, claim and field expert | All four Fanavaran codes below, plus `locations` |
|
||||
| FileMaker | `ThirdPartyClaimExpertId`, `CarBodyClaimExpertId`, `locations` |
|
||||
| FileReviewer | `ThirdPartyExpertiseClaim`, `CarBodyExpertiseClaim`, `locations` |
|
||||
| Call-center agent | None of the four product/stage codes |
|
||||
|
||||
| Field | Persian label in the panel |
|
||||
| --- | --- |
|
||||
| `ThirdPartyClaimExpertId` | کارشناس مسئول پرونده مالی |
|
||||
| `CarBodyClaimExpertId` | کارشناس مسئول پرونده بدنه |
|
||||
| `ThirdPartyExpertiseClaim` | کارشناس ارزیاب خسارت ثالث مالی |
|
||||
| `CarBodyExpertiseClaim` | کارشناس ارزیاب خسارت بدنه |
|
||||
|
||||
All four codes are optional, editable and clearable for blame, claim and field experts. FileMaker accounts accept only the first two, FileReviewer accounts accept only the last two, and call-center accounts reject all four through the API. The panel presents these four named fields rather than the legacy generic `expertCode` input; existing `expertCode` values are preserved.
|
||||
|
||||
`locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran OpBUId / HTTP `Location` values. Claim submissions prefer the responsible staff member's primary `locations[].id` (file-maker, file-reviewer, field, blame, or damage expert) for all tenants. When that array is missing, null, or empty, the integration loads the staff member's branch using `branchId` and uses `branches.code`. It checks this branch fallback before moving to another staff candidate. If no candidate supplies a staff location or branch code, submission reports `FANAVARAN_STAFF_LOCATION_MISSING` instead of sending the tenant default. Shared staff locations still participate in Parsian FileMaker/FileReviewer matching; management does not alter that matching logic.
|
||||
|
||||
Branches require `code`, `name`, `city`, `state`, and `address`. `fullName`, `phoneNumber`, `isActive` (default true) and `activityStartDate` are optional and editable. Branch codes remain unique within an insurer. Insurer login accounts support name, email, password and optional contact/address fields; their role and tenant are assigned by the server.
|
||||
|
||||
PATCH sends only changed fields. Omit `password` to preserve it; supply a replacement to change it. Nullable optional staff properties can be cleared with `null`; send `locations: []` to clear locations. Required identity and branch properties cannot be cleared. The form preserves the full stored activity timestamp when its date is unchanged.
|
||||
|
||||
## Access and compatibility
|
||||
|
||||
- An insurer's scope is taken from the authenticated actor's `clientKey`. A supplied tenant identifier never overrides it.
|
||||
- Super-admin changes require an existing selected insurer. Foreign branch IDs and cross-tenant account/branch edits are rejected. The tenant predicate is retained on the final atomic update.
|
||||
- Staff roles, client association, arbitrary fields and MongoDB update operators cannot be edited through these endpoints.
|
||||
- Passwords are hashed through the existing `HashService`; passwords, OTPs, tokens and insurer SMS credentials are excluded from management responses.
|
||||
- Existing client settings and integrations are preserved when editing client metadata. This UI does not replace the existing system/settings or inquiry configuration screens.
|
||||
- Existing insurer-create DTOs also accept `expertCode` and the four Fanavaran codes, restricted to the applicable fields for FileMaker/FileReviewer DTOs. The branch schema and existing create DTO accept `fullName`.
|
||||
- No migration, deletion, mass reassignment or change to case workflow is required.
|
||||
|
||||
## Verification
|
||||
|
||||
`npm test -- --runInBand` includes schema-backed management tests for all six roles, optional seed fields, role-specific IDs, locations, tenant isolation, branch updates, account passwords, protected fields and strict DTO validation. The route contract retains the existing routes and records the additional super-admin status endpoint. HTTP tests cover cross-role login, activation, status permissions, and rejection of existing sessions after deactivation.
|
||||
|
||||
The expert UI's `npm run test:ui` includes management proxy and payload regression checks. Desktop/mobile browser checks use mocked local API responses, rather than modifying a real insurer. Live credential login, database indexes under concurrent writes and outbound Fanavaran submission remain integration QA responsibilities.
|
||||
@@ -0,0 +1,216 @@
|
||||
# API legacy retirement and signature status
|
||||
|
||||
Reviewed the API controller surface, both frontend source trees (including expert-panel server proxies), runtime service references, API scripts, and workflow/role documentation. This cleanup starts from the working tree containing the claim-beneficiary authorization fixes; it preserves those fixes.
|
||||
|
||||
## Signature follow-up
|
||||
|
||||
Ordinary users now get the same fresh case status on both the final page and the older waiting-for-signature URL. While waiting, the case is refreshed every 10 seconds and on window focus. The page explicitly says that their signature is recorded and the other party is still required. After the other signature arrives, server-provided nextAction and claimCreation determine the new message and allowed action. Only the beneficiary sees claim creation. Existing expert declaration behavior is retained.
|
||||
|
||||
The silent refresh button was removed. A background refresh failure retains the last successful case, explains that it is the last known status, and offers a retry with a loading state. Initial failures still show the full retry screen. Long declarations can scroll on small screens.
|
||||
|
||||
## Removed code
|
||||
|
||||
- 77 retired routes: obsolete unversioned blame/claim mutations and reads, obsolete expert-claim review/price-drop workflows, hidden registrar V1 aliases, legacy genuine/legal registrations, and deprecated workflow-step helper routes.
|
||||
- 215 unreachable service methods, including their private helper chains and unused database wrappers. Reachability includes controllers, other services, lifecycle hooks, decorated methods, scripts, callbacks, and conservative handling of dynamic property references.
|
||||
- 35 orphaned TypeScript files: old DTOs, response types, unused PDF helpers, examples, barrels, and an obsolete JSON pipe.
|
||||
- Three empty database providers, their unused injections, unused private configuration/price-drop fields, and three retired controllers. Persistent collection registrations and schemas still used by active or blame-expert paths remain.
|
||||
- The unused frontend claim-picker component, its sort helper, and its unversioned claimable-list client method; the unused legacy Fanavaran client method was also removed.
|
||||
|
||||
No database migration, document rewrite, or collection deletion is performed.
|
||||
|
||||
## Deliberately retained
|
||||
|
||||
- Every V1–V6 screen flow. The current V1 user screens call V2 APIs; UI flow versions and API prefixes are different concepts. V1-specific limits and historical workflow repair remain.
|
||||
- Both unversioned and V2 blame-expert controllers, the entire blame-expert service, and its reachable legacy helpers, media and historical models.
|
||||
- The unversioned GET /claim-request-management/car-other-part catalog, GET /expert-claim/imageRequired/:id, GET /expert-claim/stream/:id/voice, and POST /expert-initiated-blame/add-accident-fields/:requestId, because frontend clients/server proxies still reference them. Their guards, roles and responses are unchanged.
|
||||
- Versioned expert-initiated and registrar APIs, all V3/V4/V5/V6 creation/review/approval/link workflows, role onboarding, inquiries, lookup caching, AI, current Fanavaran stages, uploads, reports, and background retry/maintenance jobs.
|
||||
- Deprecated report routes that still have frontend callers, and Fanavaran preview query parameters retained for compatibility. A deprecation label by itself was not treated as proof of disuse.
|
||||
- Historical data/status fallbacks reachable from current endpoints. “Legacy data” is not the same as an unused endpoint.
|
||||
|
||||
The remaining large services implement active workflows and Fanavaran mappings; they were not split or rewritten during this cleanup.
|
||||
|
||||
## Verification
|
||||
|
||||
A structural comparison against the pre-cleanup working tree found identical executable method structure for all 1,336 retained controller/service methods. Formatting, imports and unused constructor dependencies changed; retained method logic did not.
|
||||
|
||||
The public route/access contract in test/contracts/api-routes.json was captured from the pre-cleanup controllers after excluding the explicitly retired routes. src/core/api-route-contract.spec.ts checks all 381 remaining routes against live Nest metadata, including controller and method guards and role restrictions. Update this contract deliberately when changing the public API.
|
||||
|
||||
Regression coverage includes active claim eligibility, cross-tenant/reviewer authorization, V4/V5 transitions, optional documents, captures/AI, licensing inquiries, Fanavaran stage fields, and pricing. Tests solely exercising removed legacy endpoints were retired; equivalent active V2 safeguards remain tested. Constructor mocks use named dependencies where removals changed argument positions.
|
||||
|
||||
The UI status tests cover polling, completion, beneficiary-only actions, initial/background errors and retries. Local browser checks use mocked case responses on the real pages at 320px, 390px and 1366px; they exercise automatic completion and refresh error recovery.
|
||||
|
||||
Final checks: 77 API suites / 486 tests passed; API production build passed; both frontend regression suites passed; user UI production build passed. The UI detector reported no findings. Blame-expert source files were not modified.
|
||||
|
||||
## Controller audit
|
||||
|
||||
Every controller was included. Counts are HTTP routes, including hidden routes.
|
||||
|
||||
| Controller | Before | Retained | Retired |
|
||||
| --- | ---: | ---: | ---: |
|
||||
| `auth/auth-controllers/actor/actor.auth.controller.ts` | 14 | 12 | 2 |
|
||||
| `auth/auth-controllers/user/user.auth.controller.ts` | 2 | 2 | 0 |
|
||||
| `case-expert-report/case-expert-report.controller.ts` | 1 | 1 | 0 |
|
||||
| `claim-request-management/claim-request-management.controller.ts` | 19 | 1 | 18 |
|
||||
| `claim-request-management/claim-request-management.v2.controller.ts` | 17 | 17 | 0 |
|
||||
| `claim-request-management/expert-initiated-claim.mirror.controller.ts` | 11 | 11 | 0 |
|
||||
| `claim-request-management/registrar-claim.mirror.controller.ts` | 10 | 10 | 0 |
|
||||
| `claim-request-management/registrar-claim.v1.controller.ts` | 7 | 0 | 7 |
|
||||
| `client/client-external-inquiries.controller.ts` | 5 | 5 | 0 |
|
||||
| `client/client-panel.controller.ts` | 2 | 2 | 0 |
|
||||
| `client/client.controller.ts` | 4 | 4 | 0 |
|
||||
| `expert-blame/expert-blame.controller.ts` | 10 | 10 | 0 |
|
||||
| `expert-blame/expert-blame.v2.controller.ts` | 9 | 9 | 0 |
|
||||
| `expert-claim/expert-claim.controller.ts` | 13 | 2 | 11 |
|
||||
| `expert-claim/expert-claim.v2.controller.ts` | 23 | 23 | 0 |
|
||||
| `expert-insurer/expert-insurer.controller.ts` | 23 | 23 | 0 |
|
||||
| `fanavaran/fanavaran.controller.ts` | 9 | 9 | 0 |
|
||||
| `lookups/lookups.controller.ts` | 48 | 48 | 0 |
|
||||
| `profile/profile.controller.ts` | 4 | 4 | 0 |
|
||||
| `reports/reports.controller.ts` | 5 | 5 | 0 |
|
||||
| `request-management/call-center-blame-v6.controller.ts` | 6 | 6 | 0 |
|
||||
| `request-management/expert-initiated-blame-v3.mirror.controller.ts` | 19 | 19 | 0 |
|
||||
| `request-management/expert-initiated-blame.mirror.controller.ts` | 14 | 14 | 0 |
|
||||
| `request-management/expert-initiated.controller.ts` | 8 | 1 | 7 |
|
||||
| `request-management/expert-initiated.v2.controller.ts` | 14 | 14 | 0 |
|
||||
| `request-management/file-maker-blame-v4.controller.ts` | 15 | 15 | 0 |
|
||||
| `request-management/file-maker-blame-v5.controller.ts` | 15 | 15 | 0 |
|
||||
| `request-management/file-maker-claim-approval-v5.controller.ts` | 2 | 2 | 0 |
|
||||
| `request-management/file-reviewer-blame-v4.controller.ts` | 12 | 12 | 0 |
|
||||
| `request-management/file-reviewer-blame-v5.controller.ts` | 12 | 12 | 0 |
|
||||
| `request-management/inquiry-refresh.controller.ts` | 1 | 1 | 0 |
|
||||
| `request-management/registrar-blame.mirror.controller.ts` | 13 | 13 | 0 |
|
||||
| `request-management/registrar-initiated.controller.ts` | 10 | 0 | 10 |
|
||||
| `request-management/request-management.controller.ts` | 14 | 0 | 14 |
|
||||
| `request-management/request-management.v2.controller.ts` | 15 | 15 | 0 |
|
||||
| `super-admin/super-admin.controller.ts` | 33 | 31 | 2 |
|
||||
| `system-settings/system-settings.controller.ts` | 5 | 5 | 0 |
|
||||
| `workflow-step-management/workflow-step-management.controller.ts` | 14 | 8 | 6 |
|
||||
|
||||
## Removed service methods
|
||||
|
||||
Line counts below exclude surrounding comments/imports and deleted orphan files.
|
||||
|
||||
| Service | Methods | Implementation lines |
|
||||
| --- | ---: | ---: |
|
||||
| `users/entities/db-service/damage-expert.db.service.ts` | 1 | 5 |
|
||||
| `users/entities/db-service/registrar.db.service.ts` | 1 | 3 |
|
||||
| `users/entities/db-service/file-maker.db.service.ts` | 2 | 8 |
|
||||
| `users/entities/db-service/file-reviewer.db.service.ts` | 2 | 8 |
|
||||
| `users/entities/db-service/call-center-agent.db.service.ts` | 1 | 7 |
|
||||
| `auth/auth-services/actor.auth.service.ts` | 3 | 12 |
|
||||
| `users/entities/db-service/user.db.service.ts` | 1 | 3 |
|
||||
| `users/entities/db-service/expert-file-activity.db.service.ts` | 1 | 24 |
|
||||
| `fanavaran/fanavaran-audit.service.ts` | 1 | 7 |
|
||||
| `fanavaran/fanavaran-auth.service.ts` | 1 | 3 |
|
||||
| `fanavaran/fanavaran-location.service.ts` | 1 | 3 |
|
||||
| `client/external-inquiry-settings.service.ts` | 1 | 11 |
|
||||
| `client/client.service.ts` | 2 | 6 |
|
||||
| `client/entities/db-service/branch.db.service.ts` | 1 | 6 |
|
||||
| `lookups/entities/db-service/lookup.db.service.ts` | 2 | 6 |
|
||||
| `sand-hub/entity/db-service/sand-hub.db.service.ts` | 4 | 21 |
|
||||
| `sand-hub/sand-hub.service.ts` | 2 | 23 |
|
||||
| `plates/plates.service.ts` | 1 | 21 |
|
||||
| `request-management/entities/db-service/blame-video.db.service.ts` | 1 | 3 |
|
||||
| `request-management/entities/db-service/request-management.db.service.ts` | 5 | 24 |
|
||||
| `request-management/entities/db-service/blame-request.db.service.ts` | 1 | 5 |
|
||||
| `workflow-step-management/entities/db-service/workflow-step.db.service.ts` | 2 | 15 |
|
||||
| `workflow-step-management/workflow-step-management.service.ts` | 5 | 68 |
|
||||
| `media-policy/media-policy.service.ts` | 1 | 11 |
|
||||
| `request-management/entities/db-service/blame-document.db.service.ts` | 3 | 12 |
|
||||
| `request-management/entities/db-service/sign.db.service.ts` | 1 | 3 |
|
||||
| `claim-request-management/entites/db-service/claim-case.db.service.ts` | 1 | 3 |
|
||||
| `claim-request-management/entites/db-service/claim-request-management.db.service.ts` | 11 | 63 |
|
||||
| `request-management/request-management.service.ts` | 44 | 3222 |
|
||||
| `claim-request-management/entites/db-service/car-green-card.db.service.ts` | 2 | 8 |
|
||||
| `claim-request-management/entites/db-service/damage-image.db.service.ts` | 2 | 6 |
|
||||
| `claim-request-management/entites/db-service/factor-image.db.service.ts` | 1 | 5 |
|
||||
| `claim-request-management/entites/db-service/video-capture.db.service.ts` | 1 | 5 |
|
||||
| `claim-request-management/entites/db-service/claim-required-document.db.service.ts` | 4 | 16 |
|
||||
| `claim-request-management/claim-request-management.service.ts` | 66 | 2123 |
|
||||
| `expert-claim/expert-claim.service.ts` | 31 | 1334 |
|
||||
| `expert-insurer/expert-insurer.service.ts` | 3 | 86 |
|
||||
| `super-admin/super-admin.service.ts` | 2 | 6 |
|
||||
|
||||
## Retired route list
|
||||
|
||||
These URLs now have no controller handler. Current frontend workflows use their versioned replacements or no longer expose the obsolete operation.
|
||||
|
||||
| Method | Retired route |
|
||||
| --- | --- |
|
||||
| POST | `/actor/register/genuine` |
|
||||
| POST | `/actor/register/legal` |
|
||||
| POST | `/claim-request-management/:blameId` |
|
||||
| PATCH | `/claim-request-management/car-part-damage/:claimRequestID` |
|
||||
| PATCH | `/claim-request-management/car-other-part-damage/:claimRequestID` |
|
||||
| GET | `/claim-request-management/required-documents-status/:claimRequestID` |
|
||||
| GET | `/claim-request-management/car-part-image-required/:claimRequestID` |
|
||||
| PATCH | `/claim-request-management/upload-required-document/:claimRequestID` |
|
||||
| PATCH | `/claim-request-management/capture-car-part-damage/:claimRequestID/:partId` |
|
||||
| PATCH | `/claim-request-management/car-capture/:claimRequestID` |
|
||||
| GET | `/claim-request-management/requests` |
|
||||
| GET | `/claim-request-management/request/:claimRequestId` |
|
||||
| PUT | `/claim-request-management/request/reply/:claimRequestId` |
|
||||
| PUT | `/claim-request-management/request/resend/:claimRequestId/objection` |
|
||||
| PATCH | `/claim-request-management/request/resend/:claimRequestId` |
|
||||
| PUT | `/claim-request-management/request/:claimRequestId/user-rating` |
|
||||
| PATCH | `/claim-request-management/request/reply/:claimRequestId/:partId/upload-factor` |
|
||||
| PATCH | `/claim-request-management/:id/visit` |
|
||||
| GET | `/claim-request-management/fanavaran-submit/:claimRequestId` |
|
||||
| POST | `/claim-request-management/fanavaran-submit/:claimRequestId` |
|
||||
| POST | `/registrar-claim/create-from-blame/:blameRequestId` |
|
||||
| GET | `/registrar-claim/request/:claimRequestId` |
|
||||
| PATCH | `/registrar-claim/select-outer-parts/:claimRequestId` |
|
||||
| PATCH | `/registrar-claim/select-other-parts/:claimRequestId` |
|
||||
| GET | `/registrar-claim/capture-requirements/:claimRequestId` |
|
||||
| POST | `/registrar-claim/upload-document/:claimRequestId` |
|
||||
| POST | `/registrar-claim/capture-part/:claimRequestId` |
|
||||
| GET | `/expert-claim` |
|
||||
| GET | `/expert-claim/:id` |
|
||||
| GET | `/expert-claim/required-documents/:id` |
|
||||
| PUT | `/expert-claim/lock/:id` |
|
||||
| PUT | `/expert-claim/reply/submit/:id` |
|
||||
| PUT | `/expert-claim/resend/submit/:id` |
|
||||
| GET | `/expert-claim/stream/:id/video` |
|
||||
| GET | `/expert-claim/link/:id/video` |
|
||||
| PATCH | `/expert-claim/validate-factors/:claimId` |
|
||||
| PATCH | `/expert-claim/:id/visit` |
|
||||
| GET | `/expert-claim/branches/:insuranceId` |
|
||||
| GET | `/expert-initiated-blame/my-files` |
|
||||
| POST | `/expert-initiated-blame/complete-blame-data/:requestId` |
|
||||
| POST | `/expert-initiated-blame/complete-claim-data/:claimRequestId` |
|
||||
| POST | `/expert-initiated-blame/complete-form-third-party/:requestId` |
|
||||
| POST | `/expert-initiated-blame/complete-form-car-body/:requestId` |
|
||||
| POST | `/expert-initiated-blame/upload-video/:requestId` |
|
||||
| POST | `/expert-initiated-blame/upload-voice/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/create` |
|
||||
| GET | `/registrar-initiated-blame/my-files` |
|
||||
| GET | `/registrar-initiated-blame/blame/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/send-party-otps/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/verify-party-otps/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/complete-blame-data/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/upload-video/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/upload-voice/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/add-accident-fields/:requestId` |
|
||||
| POST | `/registrar-initiated-blame/upload-party-signature/:requestId` |
|
||||
| POST | `/blame-request-management/initial-form/:requestId` |
|
||||
| POST | `/blame-request-management/upload-video/:requestId` |
|
||||
| POST | `/blame-request-management/add-plate/:requestId` |
|
||||
| POST | `/blame-request-management/carbody-form/:requestId` |
|
||||
| POST | `/blame-request-management/carbody-secondform/:requestId` |
|
||||
| POST | `/blame-request-management/add-detail-location/:requestId` |
|
||||
| POST | `/blame-request-management/upload-voice/:requestId` |
|
||||
| POST | `/blame-request-management/add-detail-description/:requestId` |
|
||||
| POST | `/blame-request-management/add-second-party-details/:phoneNumber/:requestId/:frontendRoutes` |
|
||||
| GET | `/blame-request-management/requests` |
|
||||
| GET | `/blame-request-management/creatable-claims` |
|
||||
| GET | `/blame-request-management/request/:requestId` |
|
||||
| PUT | `/blame-request-management/request/reply/:requestId` |
|
||||
| PUT | `/blame-request-management/request/resend/:requestId` |
|
||||
| POST | `/super-admin/register/genuine` |
|
||||
| POST | `/super-admin/register/legal` |
|
||||
| POST | `/workflow-step-management/bulk-upsert` |
|
||||
| POST | `/workflow-step-management/validate-access` |
|
||||
| GET | `/workflow-step-management/category/:category` |
|
||||
| GET | `/workflow-step-management/next-steps/:stepKey` |
|
||||
| GET | `/workflow-step-management/fields/:stepKey` |
|
||||
| GET | `/workflow-step-management/step/:stepKey` |
|
||||
@@ -0,0 +1,42 @@
|
||||
# Accident location without GPS
|
||||
|
||||
Location steps accept either a real latitude/longitude pair or a written accident
|
||||
address. Existing coordinate clients remain supported. No migration is needed.
|
||||
|
||||
```json
|
||||
{ "address": "تهران، خیابان آزادی، روبهروی دانشگاه" }
|
||||
```
|
||||
|
||||
```json
|
||||
{ "lat": 35.6892, "lon": 51.389 }
|
||||
```
|
||||
|
||||
An address is trimmed and must contain 10–1000 characters. Both coordinates must
|
||||
be finite numbers within valid ranges if supplied. Empty input, incomplete
|
||||
coordinates and invalid addresses produce Persian errors. Unknown properties
|
||||
are discarded. The existing party ownership, role and workflow checks still run.
|
||||
|
||||
The same contract covers the normal user/v6 location endpoint, the expert
|
||||
mirror endpoints (v2/v3) and optional v4/v5 location submissions. The expert panel
|
||||
IN_PERSON endpoint wraps the value as `{ "location": { "address": "..." } }`.
|
||||
V4/v5 still skip location and do not gain a new mandatory step.
|
||||
|
||||
The user form always offers a written-address field, including while GPS is
|
||||
pending or denied and when map tiles fail. Typed addresses take precedence over
|
||||
GPS, since the current device position may differ from the accident scene.
|
||||
The initial map centre is only a viewport and is never automatically submitted.
|
||||
Dragging or clicking the map is an explicit selection. Pending location data is
|
||||
reset when switching cases or parties; saved addresses count as completed
|
||||
location evidence on resume.
|
||||
|
||||
`parties[].location.address` persists through the shared location schema, claim
|
||||
snapshots and detail responses. The expert panel and exported case report show
|
||||
the address even without coordinates. The Fanavaran address review is populated
|
||||
from the recorded address when available; previously reviewed/sent values keep
|
||||
precedence. Existing GPS-only Fanavaran behavior is unchanged.
|
||||
|
||||
Checks: `accident-location.spec.ts`, `call-center-v6-workflow.spec.ts`,
|
||||
`file-maker-blame-v4-workflow.spec.ts`, `case-expert-report.builder.spec.ts`,
|
||||
`fanavaran-stage-fields.spec.ts`; UI `test-location-fallback.cjs` and
|
||||
`test-accident-detail.cjs` cover GPS errors, late GPS, saved addresses and user/
|
||||
expert location orchestration across v1/v2/v3/v6.
|
||||
@@ -536,8 +536,9 @@
|
||||
</p>
|
||||
|
||||
<div class="card card-gray">
|
||||
<h3>ثبت تقصیر — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">توجه: <code>@ApiExcludeController</code> — مسیرها وجود دارند اما در مستندات Swagger نمایش داده نمیشوند.</p>
|
||||
<h3>مرجع تاریخی ثبت تقصیر — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">مسیرهای بدون نسخه زیر حذف شدهاند. مسیر فعال ثبت تقصیر <code>v2/registrar/blame-request-management/</code> است. <a href="legacy-api-cleanup.md">گزارش حذف مسیرهای قدیمی</a></p>
|
||||
<p class="note">این جدول فقط مرجع تاریخی است؛ هندلرهای زیر دیگر ثبت نشدهاند.</p>
|
||||
<table>
|
||||
<tr><th style="width:70px">متد</th><th>مسیر</th><th>توضیح</th></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>registrar-initiated-blame/create</code></td><td>ایجاد فایل تقصیر IN_PERSON.</td></tr>
|
||||
|
||||
@@ -528,8 +528,9 @@
|
||||
</p>
|
||||
|
||||
<div class="card card-gray">
|
||||
<h3>Blame filing — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">Note: <code>@ApiExcludeController</code> — routes exist but not surfaced in Swagger docs.</p>
|
||||
<h3>Historical blame filing — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">The unversioned routes below have been retired. Current filing uses <code>v2/registrar/blame-request-management/</code>. See <a href="legacy-api-cleanup.md">the retirement audit</a>.</p>
|
||||
<p class="note">Historical reference only — these handlers are no longer registered.</p>
|
||||
<table>
|
||||
<tr><th style="width:70px">Method</th><th>Route</th><th>What it does</th></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>registrar-initiated-blame/create</code></td><td>Create IN_PERSON blame file.</td></tr>
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# پیامهای خطای فارسی
|
||||
|
||||
خطاهای قابل نمایش به کاربر در API و دو رابط `ui-user` و `ui-expert` در مرز پاسخ یا نمایش فارسی میشوند. پیامهای استعلام، اعتبارسنجی، ورود، امضا، دسترسی و مراحل پرونده، خطاهای شبکه و دسترسی دوربین/میکروفون پوشش داده شدهاند.
|
||||
|
||||
## رفتار و توسعه
|
||||
|
||||
- `PersianErrorFilter` خطاهای HTTP را فارسی میکند؛ وضعیت HTTP، کد خطا، شناسهها و مسیر فیلدها حفظ میشوند. پیامهای آرایهای اعتبارسنجی همچنان آرایه هستند.
|
||||
- `PersianErrorInterceptor` فقط گرههایی را که صریحاً شکست را مشخص میکنند، در پاسخهای موفق پردازش میکند. گزارشها، دادههای پرونده، پاسخهای موفق و فایلها ترجمه نمیشوند.
|
||||
- برای خطای انگلیسی ناشناخته، پیام فارسی متناسب با وضعیت HTTP نمایش داده میشود. پیامهای شناختهشده راهنمای عملی دقیقتری دارند. خطاهای غیرمنتظره سرور در لاگ ثبت میشوند.
|
||||
- رشتههای داخلی سرویسها که بعضی مسیرها برای تصمیمگیری بررسی میکنند تغییر نکردهاند. برای تصمیمگیری جدید از `code` یا وضعیت HTTP استفاده کنید، نه متن پیام.
|
||||
- `getPersianErrorMessage` در رابطها آرایه پیامها و پاسخهای تودرتو را میخواند. تنظیمات Yup پیش از تعریف schema بارگذاری میشوند و پیامهای پیشفرض فارسی هستند. محدودیتهای بومی مرورگر نیز با حفظ اعتبارسنجی فارسی نمایش داده میشوند و با ویرایش فیلد پاک میشوند.
|
||||
- جدول پیامها و عنوان فیلدها در `src/common/errors/persian-errors.ts` است؛ کپی یکسان آن در `src/utils/persianErrors.ts` دو مخزن رابط نگهداری میشود. تغییرات مشترک باید در هر سه کپی اعمال شوند.
|
||||
- برای خطای کسبوکاری جدید، پیام مشخص فارسی و `code` پایدار تعریف کنید؛ اطلاعات حساس یا پاسخ خام سرویس بیرونی را در پیام کاربر نگذارید.
|
||||
|
||||
## بررسیها
|
||||
|
||||
- تست API: `src/common/errors/persian-errors.spec.ts`، `src/common/utils/inquiry-error.spec.ts` و `src/core/api-route-contract.spec.ts`.
|
||||
- تست رابطها: `npm run test:ui`؛ شامل `scripts/test-error-localization.cjs` برای پیامهای استعلام، Yup، مرورگر، آرایه خطا و حفظ کدها.
|
||||
- بررسی نوعها در هر سه مخزن؛ بررسی واقعی Firefox برای پیامهای اجباری، ایمیل، حداقل عدد و رفع خطا پس از ویرایش.
|
||||
|
||||
API و هر دو رابط را برای پوشش کامل با هم منتشر کنید. این تغییر، اعتبارسنجی سراسری جدیدی فعال نمیکند و قرارداد مسیرها یا مجوز نقشها را تغییر نمیدهد.
|
||||
@@ -0,0 +1,28 @@
|
||||
# Persian panel and report presentation
|
||||
|
||||
The expert/user panels and insurer file report use Persian interface labels and system values. The report builder translates persisted lifecycle statuses and known inquiry fields. Unmapped provider field names are omitted instead of being printed as raw English keys. Cached report fields receive the same protection in the PDF renderer.
|
||||
|
||||
Actual identifiers and user-entered facts are preserved: VINs, policy numbers, phone numbers, email addresses and saved vehicle names are not translated or rewritten. National codes remain available in explicitly labelled identity fields; they are never used as a person's display name. No stored case, inquiry or Fanavaran payload is changed by report formatting.
|
||||
|
||||
## Person labels
|
||||
|
||||
The presentation helper prefers a saved full name or first/last name, then an explicitly recorded phone number. Numeric placeholders, database IDs, national codes, email addresses and generic English placeholder names are rejected as names. If neither name nor phone exists, the interface uses a Persian unavailable label. Insurer detail/report views resolve current user profiles by the case's user ID, with a per-request lookup cache. Timeline names resolve the actual event actor rather than the other party or the claim owner by default.
|
||||
|
||||
Driver and owner names are resolved separately. A licence number is never substituted for its issue date. Monetary amounts already stored in rials are labelled ریال without changing their numeric value.
|
||||
|
||||
## Shared damaged-parts catalogue
|
||||
|
||||
The user application no longer asks for a vehicle body type or side before selecting parts, including the objection/additional-parts picker. It searches the shared catalogue by name or code and submits the selected numeric IDs. It does not invent a vehicle type. Existing vehicle identity data used by inquiries and pricing is retained.
|
||||
|
||||
Selections persisted under the old side buckets are merged into the shared selection, deduplicated by ID and preserved. Search does not clear selections. The picker displays loading/failure/retry states, and its catalogue cache is scoped to the current account. Existing document, bank-information and photo steps remain in their flow-specific order.
|
||||
|
||||
## Verification
|
||||
|
||||
- API report/presentation tests: 52 passing tests, plus 21 insurer summary/timeline regression tests.
|
||||
- Both frontend `npm run test:ui` suites, including new Persian presentation and flat-catalogue scenarios covering all six flows.
|
||||
- Type checking and production builds for both frontends; API build.
|
||||
- Real local browser pages at desktop (1440 × 1100, v1) and mobile (390 × 844, v6), using synthetic cases and intercepted API responses: catalogue failure/retry, thin catalogue rows, search by code, selections across searches, no vehicle-type/side prompt, correct IDs-only submission and document-step navigation.
|
||||
- A report was rendered using the actual report builder and PDF component. Persian layout and extracted text were checked; Latin content in the fixture was limited to actual identifiers. Local existing fonts were used for this offline rendering check; production font configuration was unchanged.
|
||||
- The full API suite still has ten previously identified failures in `fanavaran-submit-overrides.spec.ts`, whose fixtures lack reviewed vehicle data. Those unrelated fixtures were not changed.
|
||||
|
||||
No production database or external provider was used for the browser/PDF checks. These checks do not claim every production record or every page was manually exercised.
|
||||
@@ -0,0 +1,37 @@
|
||||
# Recovering already-saved photos during capture
|
||||
|
||||
The capture-requirements endpoint now reads `requiredDocuments` from both
|
||||
Mongoose Maps and ordinary objects. The object case previously returned
|
||||
`uploaded: false` even for a saved chassis/engine photo, causing the UI to
|
||||
request it again and encounter the duplicate-document conflict.
|
||||
|
||||
Initial `upload-document` retries now acknowledge an existing uploaded document
|
||||
when a saved file path/URL is present. The response contains the existing
|
||||
`fileUrl`, the current persisted workflow step and `alreadyUploaded: true`.
|
||||
Ownership/tenant checks still run first. This does not replace the saved image,
|
||||
create a second document reference, append duplicate history, or resend the
|
||||
attachment to Fanavaran. A flag without file evidence is not acknowledged.
|
||||
Expert resends and active in-person replacement uploads keep their existing
|
||||
validation paths. Expert capture-document retries after the capture phase
|
||||
advanced can reuse confirmed evidence after the same ownership checks.
|
||||
|
||||
The user camera and gallery pages read saved part/angle/document flags, offer
|
||||
Continue for those slots without requiring another photo, and keep locally
|
||||
successful photo uploads separate from video completion. If the last photo
|
||||
saves but video upload fails, retrying completion only retries the video; it
|
||||
cannot re-upload the chassis image and encounter a duplicate error. Local photo
|
||||
receipts are scoped to the claim, and field-expert uploads await the selected
|
||||
API promise before recording success or advancing. The version was previously
|
||||
awaited instead of the upload promise in several conditional API calls.
|
||||
|
||||
The camera still records and submits the required walk-around video. Missing
|
||||
images and actual API failures remain blocking; error text or HTTP 409 alone is
|
||||
never treated as evidence of a successful upload.
|
||||
|
||||
Verification:
|
||||
|
||||
- API: `upload-document-idempotency.spec.ts`, `capture-part-concurrency.spec.ts`,
|
||||
`claim-capture-phase.spec.ts`, `ai-capture-integration.spec.ts`.
|
||||
- UI: `scripts/test-capture-upload-recovery.cjs`, included in `npm run test:ui`;
|
||||
covers saved chassis/parts, failed-video retry, awaited/rejected expert
|
||||
requests, case isolation and camera/gallery implementations.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Profile panel review — 2026-11-04
|
||||
|
||||
Scope: the regular user account pages, the actor profiles reachable through user flows V2–V6, and the expert panel's account page/editor. This is a profile functionality and accessibility review, not an audit of every application workflow.
|
||||
|
||||
## Plate management
|
||||
|
||||
Profile plate management remains retired. Neither panel exposes saved-plate management. `POST /user/profile/plate` and `DELETE /user/profile/plate/:id` remain absent from the API. Existing historical data is retained; accident inquiry plate entry is a separate capability and remains available.
|
||||
|
||||
## Confirmed problems and fixes
|
||||
|
||||
| Problem | Fix |
|
||||
| --- | --- |
|
||||
| User GET responses omitted saved province/address. | Return `state` and `address` in the public user profile. |
|
||||
| User PATCH returned the pre-update document. | Read and return the saved public profile after updating. |
|
||||
| Birthday format differed between the picker, legacy stored data and documented API. | Read legacy Jalali and Gregorian dates in the UI; submit Gregorian date-only strings. The API accepts legacy packed/separated Jalali input and validates before saving. |
|
||||
| Gender labels were submitted in Persian despite the stored `male`/`female` contract. | Normalize gender while preserving Persian UI labels. |
|
||||
| User-panel experts were offered birthday/gender fields unsupported by their profile storage. | Show supported actor name/contact/location fields instead. |
|
||||
| File makers, file reviewers and call-center agents could read profiles but not save their personal details. Field experts could not save their location. | Support personal profile updates for all corresponding actor roles. |
|
||||
| Insurer profile lookup depended on the token username being an email. | Resolve the authenticated insurer account by JWT subject when available. |
|
||||
| Expert editor split names on spaces, discarded later surname words and initialized the landline as empty. | Return explicit first/last names and phone; preserve all existing values. |
|
||||
| Expert location selects did not initialize from the profile and could submit undefined location values. | Bind saved names to form state and load cities for the selected province. Submit only changed fields. |
|
||||
| Province/city lookup failures were silent; stale requests could replace a newer city's options. | Provide recoverable errors and associate requests with the selected province; keep saved values. |
|
||||
| Profile fetch failures looked like empty accounts, and save failures were only logged. | Add loading/error/retry states, retain failed edits, and expose logout even when user profile loading fails. |
|
||||
| The expert edit modal nested buttons around its form and lacked proper dialog focus behavior. | Use the existing Radix dialog, associated input labels and error messages; restore focus to the edit button on close. |
|
||||
| Updating the header name replaced other Redux login properties. | Preserve the existing login state when updating the displayed name. |
|
||||
| Actor PATCH returned the authentication document. | Return the same public profile representation as GET, excluding passwords, OTPs, tokens and internal assignment fields. |
|
||||
|
||||
## Profile API contract
|
||||
|
||||
- `GET/PATCH /user/profile`: authenticated user's personal details only; partial updates supported. Birth dates are Gregorian `YYYY-MM-DD` for new writes. User responses continue to omit saved plates.
|
||||
- `GET/PATCH /actor/profile`: public profile includes explicit `firstName`, `lastName`, `phone`, and `editableFields`. The UI uses `editableFields` to offer only supported controls.
|
||||
- Blame expert, damage expert, field expert, insurer, file maker, file reviewer and call center: name, mobile, landline, province, city and address.
|
||||
- Super admin: first and last names, matching its existing schema.
|
||||
- Legacy registrar: email, matching its existing schema.
|
||||
- Self-profile updates cannot alter role, tenant/branch assignments, national code, password or Fanavaran expert codes. Those management operations retain their separate existing APIs.
|
||||
- Validation is performed in profile services because the application does not enable a global validation pipe. Invalid types, invalid phone numbers/dates and unsupported fields are rejected before writing.
|
||||
|
||||
## Verification
|
||||
|
||||
- Backend regression checks cover each supported actor role, insurer lookup by subject, partial updates, missing accounts, malformed/privileged fields, public responses and user birthday/gender compatibility. Existing authentication-guard and API-route-contract tests are included.
|
||||
- User utility checks cover Gregorian/legacy Jalali dates, Persian digits, multiword names and distinct actor/user PATCH payloads. Existing user UI utility/workflow checks are retained.
|
||||
- Expert profile utility checks cover multiword names, landline preservation, partial changes and role-supported fields.
|
||||
- Local Firefox checks use mocked API data only: regular user save/reopen and failed-save recovery; V2/V3 field expert, V4 file maker, V5 file reviewer and V6 call center profile navigation/save; expert dialog save/reopen/error recovery, mobile overflow, Escape and focus restoration. Desktop and mobile viewport screenshots were inspected.
|
||||
- These checks do not modify production accounts and do not establish that every application page is free of bugs. Physical-device and screen-reader testing remain outside this review.
|
||||
@@ -0,0 +1,12 @@
|
||||
# Retirement of profile plate management
|
||||
|
||||
The saved-vehicle feature has been removed from user profiles in every flow (unversioned and V1–V6).
|
||||
|
||||
- `POST /user/profile/plate` and `DELETE /user/profile/plate/:id` are removed from routing and Swagger.
|
||||
- Profile GET/PATCH responses contain personal profile fields, without saved plates.
|
||||
- Profile PATCH accepts only `birthDay`, `gender`, `city`, `state`, and `address`. Plate arrays and MongoDB update operators are rejected before a database write.
|
||||
- The unused profile plate service, model registration, and saved-car detail pages have been removed.
|
||||
- Existing stored records are preserved. No migration or collection deletion is performed.
|
||||
- Case inquiry plate entry and the shared `AddPlateDto`/`PlatesDto` contracts remain available to the active case workflows.
|
||||
|
||||
Verification: the route contract excludes exactly the two retired profile routes. Profile regression tests cover omitted historical plates, blocked direct/operator updates, and preserved personal updates. The full API suite also covers inquiry and expert handoff workflows.
|
||||
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"date": "2026-11-22",
|
||||
"environment": "isolated local MongoDB, synthetic accounts and generated media; external providers mocked",
|
||||
"httpFlowMatrix": {
|
||||
"v1-CAR_BODY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v1-THIRD_PARTY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v2-CAR_BODY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v2-THIRD_PARTY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v3-CAR_BODY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v3-THIRD_PARTY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v4-CAR_BODY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v4-THIRD_PARTY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v5-CAR_BODY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v5-THIRD_PARTY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v6-CAR_BODY": {
|
||||
"status": "COMPLETED"
|
||||
},
|
||||
"v6-THIRD_PARTY": {
|
||||
"status": "COMPLETED"
|
||||
}
|
||||
},
|
||||
"negativeControls": {
|
||||
"malformedId": 400,
|
||||
"createRace": {
|
||||
"success": 1,
|
||||
"conflict": 5
|
||||
},
|
||||
"invalidMedia": 400,
|
||||
"invalidEnums": 400,
|
||||
"foreignFieldMutation": 403
|
||||
},
|
||||
"signedMedia": {
|
||||
"expertCapture": 200,
|
||||
"ownerDocument": true,
|
||||
"blameEvidence": true,
|
||||
"bareFile": 401,
|
||||
"duplicateSignature": 401
|
||||
},
|
||||
"browserChecks": [
|
||||
"v6 login retains blame context",
|
||||
"five formerly denied versioned routes render",
|
||||
"repair-only objection form renders",
|
||||
"Persian-locale expert assessment renders",
|
||||
"written blame resend submits without an image",
|
||||
"instruction-only claim resend acknowledgment reaches expert queue"
|
||||
],
|
||||
"historicalRepair": {
|
||||
"dryRunMatched": 2,
|
||||
"applied": 2,
|
||||
"signedControlUnchanged": true,
|
||||
"pricedControlUnchanged": true
|
||||
},
|
||||
"automatedChecks": {
|
||||
"apiSuites": 111,
|
||||
"apiTestsPassed": 1070,
|
||||
"httpE2ePassed": 26,
|
||||
"httpE2eSkipped": 4,
|
||||
"userUiSuite": "passed",
|
||||
"expertUiSuite": "passed",
|
||||
"apiBuild": "passed",
|
||||
"userUiBuild": "passed",
|
||||
"expertUiBuild": "passed",
|
||||
"uiHardeningDetectorFindings": 0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
# QA remediation — 22 November 2026
|
||||
|
||||
Scope: the 28 distinct findings in `QA_REPORT_2026-11-22.txt`,
|
||||
`QA_REPORT_2026-11-22_CONTINUED.txt`, `QA_REPORT_2026-11-22_EXTENDED.txt`, and
|
||||
`qa-reports/`. The extended report repeats several continued findings; its
|
||||
reconciliation supplies IDs 25–28. Changes cover `api`, `ui-user`, and
|
||||
`ui-expert`. No production database changes or external provider writes were
|
||||
performed. `rewrite` and `esg` are outside this change.
|
||||
|
||||
## Findings and changes
|
||||
|
||||
| ID | Resolution | Verification |
|
||||
| --- | --- | --- |
|
||||
| 1 | All V3 claim evidence/selection entry points authorize the actor against the case before changing it. | Authorization regression; real foreign-field-expert 403 and positive V3 HTTP filing/capture. |
|
||||
| 2 | Reviewer assignment distinguishes initial capture from subsequent assessment after maker rejection. An assigned reviewer can acquire an assessment lock again. | HTTP V5: two reject/review cycles, rejection limit, final maker approval. |
|
||||
| 3 | Both UIs spell rial amounts using locale-independent integer grouping instead of the library recursion triggered by Persian grouping. | Both UI suites; real Persian-locale expert assessment browser. |
|
||||
| 4 | Added the ordinary-user V6 login page; the incoming blame token survives login redirection. | Real mobile browser link and URL assertion. |
|
||||
| 5 | Labor-only lines tolerate absent prices; objection payloads omit absent optional monetary values and submission failures remain visible. | Real mobile browser protest form; UI regression suite. |
|
||||
| 6 | Expired V6 ordinary-user sessions return to `/v6/login`; call-center sessions retain their expert login route. | Role-aware redirect regression. |
|
||||
| 7 | Multipart nested objection rows become DTO instances and are validated explicitly at the service boundary, including deployments without a global validation pipe. | DTO tests and a real multipart objection through HTTP/MongoDB. |
|
||||
| 8 | Vehicle subdocuments are serialized before merging resolved identity fields, exposing saved vehicle prices without Mongoose internals or parent documents. | HTTP detail assertions for price and absence of `_doc`/`$__parent`. |
|
||||
| 9 | Unique-index conflicts during concurrent claim creation become HTTP 409 rather than 500. The database uniqueness constraint remains intact. | Real six-way creation race: one success, five HTTP 409 responses. |
|
||||
| 10 | Owner claim-detail rejects malformed ObjectIds before querying MongoDB. | Real malformed-ID HTTP 400 control and explicit ID guard. |
|
||||
| 11 | Upload policy verifies readable media streams and decodes content; text disguised as MP4, wrong media kinds and unreadable content cannot satisfy evidence steps. | Generated image/video/audio controls and corrupt/wrong-kind regression tests. |
|
||||
| 12 | Shared description handlers enforce the declared weather, road and light enums, including expert form variants. | HTTP invalid-enum rejection without advancement, then valid filing; full API suite. |
|
||||
| 13 | Expert cards recognize rejected cases and treat rejected/cancelled/stopped cases as view-only. | Expert UI status regressions. |
|
||||
| 14 | Sheba masking preserves the existing prefix rather than prepending another `IR`. | Response mapping review and full API suite. |
|
||||
| 15 | Car-body video instructions describe the vehicle and accident scene without requiring two vehicles. | User production build and UI source check. |
|
||||
| 16 | Evidence is served through a signed, expiring read route, replacing anonymous static serving. Authorized case responses supply links usable by image/video/PDF elements. Arbitrary description text does not mint links. | Bare link 401; signed link 200; altered/expired/cross-path capability tests. See proxy requirements below. |
|
||||
| 17 | Owner acceptance/rejection uses one conditional atomic update; only its winner records the decision and invokes integrations. Concurrent losing signature records are removed. Signature upload names use UUIDs. | Six-way unit and real MongoDB/HTTP race. |
|
||||
| 18 | Registrar signatures accept registrar-created cases and follow the same signatures-before-accident-fields order as the shared V2 contract. | HTTP registrar CAR_BODY and THIRD_PARTY through signatures and accident fields. |
|
||||
| 19 | Instruction-only claim resends display the instruction and offer acknowledgment through the existing endpoint. | Actual mobile browser acknowledgment and persisted queue transition. |
|
||||
| 20 | Part resends send a stable catalog key/ID, independent of an optional English label. | Client key mapping and HTTP catalog-ID capture. |
|
||||
| 21 | In-person visits have a pending status, owner instructions and a resumable expert review lock. They no longer imply completion/acceptance. Historical repair is provided separately. | HTTP visit → owner guidance → reassignment → assessment; V4/V5 visit controls; repair dry-run/apply controls. |
|
||||
| 22 | Expert portfolio queries retain linked blame product type for product filters. | HTTP product counts: both products nonzero and their sum equals the total. |
|
||||
| 23 | Insurer expert reports use linked blame product types. Missing types for roster-owned claims are resolved in one batch after claim scoping. | Reporting regression, including a linked blame outside the party-insurer list. |
|
||||
| 24 | Satisfaction rating is written only if no rating exists, in one conditional atomic update. | Six-way concurrent rating regression and real HTTP/MongoDB race: one successful rating. |
|
||||
| 25 | Versioned user route allowlists use real end anchors instead of requiring a literal `$`. | Browser assertions on five formerly denied routes. |
|
||||
| 26 | Written blame resends use the text field; voice and document requests render their respective controls. The old duplicate page reuses the shared implementation. | Real browser text-only resend and successful navigation after submission. |
|
||||
| 27 | Every requested replacement must have a timestamp at or after the current resend request. A partial upload cannot reuse old evidence to finish the request. | Real three-item replacement replay plus timestamp regression; original evidence stays intact. |
|
||||
| 28 | Legacy top-rated-file normalization preserves root `userRating`, with a fallback for old nested records. | Reporting regression. |
|
||||
|
||||
## Verification
|
||||
|
||||
Sanitized results: [verification JSON](qa-remediation-2026-11-22-verification.json).
|
||||
|
||||
- API: **111 suites, 1,070 tests passed** (`npm test -- --runInBand`).
|
||||
- API HTTP E2E suite: **26 passed, 4 skipped** (`npm run test:e2e -- --runInBand`).
|
||||
The four opt-in browser scenarios were not enabled in that runner; independent
|
||||
browser replays were run separately as described above.
|
||||
- Both UI regression suites passed (`npm run test:ui`).
|
||||
- All three production builds passed (`npm run build` in each repository).
|
||||
- Browser checks used Chromium/Brave, Persian locale, a 390×844 user viewport
|
||||
and a desktop expert viewport. The UI hardening detector reported no findings
|
||||
on the changed user-facing views.
|
||||
- **All 12 flow/product combinations** (v1–v6 × CAR_BODY/THIRD_PARTY) reached
|
||||
completed claims through filing, capture and assessment. V1/V6 included owner
|
||||
acceptance; V5 included maker approval. V4/V5 also resumed after a visit.
|
||||
- Additional HTTP replays used the actual updated Nest process and a disposable
|
||||
local MongoDB database, synthetic users and generated media. External inquiry,
|
||||
SMS, AI and Fanavaran requests were intercepted with offline provider fixtures.
|
||||
These checks do not verify customer WAF/proxy configuration or real provider
|
||||
acceptance.
|
||||
|
||||
## Deployment requirements
|
||||
|
||||
Deploy the API and both UIs together, because the pending-visit status and signed
|
||||
evidence links span their contracts.
|
||||
|
||||
1. **Media tools:** the API Dockerfile now installs `ffmpeg`, which includes
|
||||
`ffprobe`. For deployments outside that Dockerfile, install both binaries in
|
||||
the API runtime and verify that its service account can execute them. Missing
|
||||
binaries will correctly reject uploads as unreadable; do not bypass validation.
|
||||
2. **Evidence proxy:** remove any public Nginx `alias`/`root`/static/CDN rule that
|
||||
directly exposes the API's `files` directory. Proxy `/files/*` (including its
|
||||
deployed `/car-damage/api/` prefix, if applicable) to Nest, preserving the
|
||||
query string and Range headers. A reverse-proxy static bypass would leave the
|
||||
original anonymous-access issue unresolved. Purge previously cached public
|
||||
evidence responses. Keep the existing API prefix/rewrite conventions; do not
|
||||
copy a new `proxy_pass` prefix blindly.
|
||||
3. **Signing secret:** all API instances serving the same files must share the
|
||||
existing `JWT_SECRET`. File URLs expire after one hour; reopening/refetching
|
||||
the authorized case returns fresh URLs. No additional signing secret or
|
||||
public access switch is introduced. Old cached bare links require a refresh.
|
||||
4. **Historical visits:** back up the database and preview the narrow repair
|
||||
from the `api` directory with the intended deployment's environment:
|
||||
|
||||
```bash
|
||||
node scripts/repair-premature-visit-completions.js
|
||||
# After checking the matched count:
|
||||
node scripts/repair-premature-visit-completions.js --apply
|
||||
```
|
||||
|
||||
Dry-run is the default. The script only changes `COMPLETED` +
|
||||
`NEEDS_REVISION` records with an in-person-visit history event and no
|
||||
submitted assessment, priced parts or recorded owner approvals. It unlocks
|
||||
review and writes a repair history event. It does not invent an address or
|
||||
change evidence, payment amounts, signatures or other completed cases.
|
||||
Dry-run and apply were exercised on synthetic records, with signed/priced
|
||||
controls left closed. More ambiguous old records need individual review.
|
||||
5. **Historical races:** overwritten satisfaction ratings or contradictory
|
||||
owner decisions already recorded before this change cannot be reliably
|
||||
reconstructed automatically. Review their history and provider submission
|
||||
records; the code prevents new overlapping writes but does not guess which
|
||||
old decision was intended.
|
||||
|
||||
No commits or pushes are included in this remediation task.
|
||||
@@ -0,0 +1,51 @@
|
||||
# Sheba is entered once per claim
|
||||
|
||||
| UI flow | Bank information is collected at |
|
||||
| --- | --- |
|
||||
| v1, user-created, third-party or car-body | Claim other-parts/bank-information step |
|
||||
| v2, field expert | Claim other-parts/bank-information step |
|
||||
| v3, field expert | Damaged party's inquiry: first party for car-body, second party for third-party |
|
||||
| v4/v5, file maker and reviewer | File maker's damaged-party inquiry; reviewer reuses the claim's bank information |
|
||||
| v6, call centre and user | User's claim other-parts/bank-information step; call centre never collects Sheba |
|
||||
|
||||
The v1/v6 initial-form endpoints do not persist a Sheba. The shared inquiry UI
|
||||
previously requested it for v1, and then requested it again during the claim.
|
||||
It now asks only on inquiry endpoints that actually validate and save it.
|
||||
|
||||
At the claim step, the UI fetches the current claim before showing bank inputs.
|
||||
It requests only missing fields, reuses an already uploaded green card, and
|
||||
shows a Persian confirmation when Sheba is already available. A failed or
|
||||
pending fetch does not display empty bank fields. Values are not copied between
|
||||
cases or kept in browser storage. User-facing bank values remain masked.
|
||||
|
||||
The claim snapshot adds `bankInformation.shebaProvided` and
|
||||
`bankInformation.ownerNationalCodeProvided`. These booleans let the UI reuse
|
||||
saved data without receiving unmasked account numbers. The owner national code
|
||||
can come from the linked blame's vehicle-owner participant.
|
||||
|
||||
`selectOtherPartsV2` accepts omitted bank fields when the claim already has
|
||||
them. It normalizes IR-prefixed and digits-only Sheba consistently and validates
|
||||
new or changed bank details. It retains beneficiary authorization and rejects
|
||||
another owner's saved account. Unchanged saved bank details do not trigger a
|
||||
second inquiry. Explicit replacement remains available during expert resend;
|
||||
an ordinary parts submission cannot silently replace an existing account.
|
||||
|
||||
The expert panel renders one claim-entry form for the damaged vehicle rather
|
||||
than independent forms for both vehicles. It passes saved bank details into
|
||||
that form. The expert claim-completion service also recognizes an IR-prefixed
|
||||
saved Sheba when advancing the workflow.
|
||||
|
||||
No database migration is required. A Sheba entered into an old initial form and
|
||||
discarded by the old endpoint cannot be recovered; those cases still need it
|
||||
once at the claim step.
|
||||
|
||||
## Regression checks
|
||||
|
||||
- API: `npm test -- --runInBand claim-bank-information.spec.ts claim-beneficiary-access.spec.ts`
|
||||
- User UI: `node scripts/test-claim-bank-information.cjs` (also run by `npm run test:ui`)
|
||||
- Expert UI: `node scripts/test-claim-bank-information.cjs` (also run by `npm run test:ui`)
|
||||
|
||||
Tests cover every flow/role/party/case-type collection combination, saved and
|
||||
missing values, stale/loading/error states, legacy aliases and formats,
|
||||
resends, vehicle-owner mismatches, masked responses and the single expert
|
||||
claim-entry form. HTTP and database dependencies are mocked.
|
||||
@@ -0,0 +1,47 @@
|
||||
# Deployment-specific SMS names
|
||||
|
||||
Set the public display name in the API deployment environment and restart the API:
|
||||
|
||||
```env
|
||||
SMS_BRAND_NAME="سامانه خسارت اپکس"
|
||||
```
|
||||
|
||||
The default for an absent, empty or whitespace-only value is `یارا۷۲۴`.
|
||||
This name is independent of the Fanavaran tenant and SMS provider settings.
|
||||
No database migration or frontend deployment is required.
|
||||
|
||||
Every locally rendered SMS carries this name: OTPs, invitations, field-expert
|
||||
links, signature notices, document requests, case-review updates, Fanavaran
|
||||
registration confirmations and plain messages loaded from `sms-texts`.
|
||||
Messages without an embedded name receive the name on a final line. Existing
|
||||
Persian/English Yara724 name spellings in message patterns are replaced when
|
||||
rendered; stored patterns are not changed. URLs and inserted token values are
|
||||
preserved.
|
||||
|
||||
Custom OTP and database message patterns can place the name explicitly:
|
||||
|
||||
```env
|
||||
AUTH_SMS_MESSAGE="رمز ورود شما در {brandName}: {token}"
|
||||
```
|
||||
|
||||
`{brandName}` is resolved from `SMS_BRAND_NAME`. The existing `{token}`,
|
||||
`{token2}`, `{token3}` and `{token10}` placeholders retain their purposes.
|
||||
Locally rendered deliveries and skipped test OTPs record the same rendered text
|
||||
in the SMS audit. Kavenegar hosted lookups record a locally reconstructed text;
|
||||
their actual body is controlled by the provider's approved template. Previously
|
||||
stored SMS logs are historical records and are not modified.
|
||||
|
||||
## Provider behavior
|
||||
|
||||
- **Parsian and Moalem:** all templates are rendered locally; no provider-side
|
||||
template changes are needed.
|
||||
- **Kavenegar:** with the default name, existing hosted lookup templates continue
|
||||
to work. With a custom name, application templates and OTPs are rendered locally
|
||||
and sent through `sms/send.json` using the existing sender. The Kavenegar
|
||||
account/sender must support plain-text delivery, including the intended
|
||||
recipients. Hosted templates cannot have their fixed text changed by this
|
||||
environment variable. Unknown external template identifiers continue to use
|
||||
hosted lookup; all current application notifications have local templates.
|
||||
|
||||
Changing the display name does not change provider credentials, sender numbers,
|
||||
template identifiers, user-panel links or the SMS destination numbers.
|
||||
@@ -0,0 +1,52 @@
|
||||
# User signing and claim-start guidance
|
||||
|
||||
The user UI v1 calls `/v2/blame-request-management`. Both its list and detail
|
||||
responses now include a viewer-specific `nextAction`. This is computed from the
|
||||
existing case, the viewer's party confirmation, and the existing claim. It does
|
||||
not change persisted statuses, signatures, ownership, or workflow transitions.
|
||||
|
||||
| nextAction | User interface behavior |
|
||||
| --- | --- |
|
||||
| `SIGN` | Open the signing screen. |
|
||||
| `WAIT_FOR_OTHER_SIGNATURE` | Confirm that the viewer signed, explain the remaining signature, and refresh the case while waiting. |
|
||||
| `CREATE_CLAIM` | Show “آماده ثبت درخواست خسارت” and a “ثبت درخواست خسارت” action. |
|
||||
| `CONTINUE_CLAIM` | Open the claim list for the existing claim. |
|
||||
| `VIEW_RESULT` | Show the completed or stopped result; do not offer unauthorized claim creation. |
|
||||
| `null` | Continue the existing information-collection/review routing. |
|
||||
|
||||
The detail response also includes `userSide`. `claimCreation` retains `hasClaim`
|
||||
and `shouldGuideToCreateClaim`, with `claimRequestId` when a claim exists.
|
||||
Third-party creation still requires completed blame, both accepted confirmations,
|
||||
and the damaged party as viewer. Body-insurance creation retains its single-party
|
||||
eligibility rule. A completed blame case means the user can start loss assessment;
|
||||
it does not mean compensation has already been approved for payment.
|
||||
|
||||
User details expose only the viewer's party. The frontend must use this guidance
|
||||
rather than count signatures from that partial array. Signing acknowledgements
|
||||
use `requestId`, not `_id`. After a successful signature, the frontend refreshes
|
||||
the detail and invalidates case lists before presenting the next action.
|
||||
|
||||
When the second-party description returns `workflow.currentStep =
|
||||
WAITING_FOR_SIGNATURES`, route directly to signing. Cases waiting for an expert
|
||||
continue to use the review-waiting screen. Reopening the waiting screen also
|
||||
checks the current case and redirects to signing or completion when appropriate.
|
||||
|
||||
## List response size
|
||||
|
||||
`partyIdentities` is server-side filter material. It is removed after identity
|
||||
filtering, sorting, and pagination from these response boundaries:
|
||||
|
||||
- User/initiator blame list: `GET /v2/blame-request-management`.
|
||||
- User/initiator claim list: `GET /v2/claim-request-management/requests`.
|
||||
- Expert claim queues, including field experts, file makers, and file reviewers,
|
||||
through `ExpertClaimService.paginateClaimListV2`.
|
||||
|
||||
The blame list uses an explicit response field list instead of spreading Mongo
|
||||
documents, so internal revision values and initiator IDs are not returned.
|
||||
Claim lists retain the IDs, status, workflow, lock, vehicle, and role-specific
|
||||
fields consumed by the two frontends. Detail, reporting, and integration payloads
|
||||
retain the evidence and inquiry data needed by their callers. Identity filtering
|
||||
continues to run on internal rows before the public response is constructed.
|
||||
|
||||
Regression coverage is in `request-management.user-progress.spec.ts`,
|
||||
`public-list-response.spec.ts`, and the user UI's `test-blame-progress.cjs`.
|
||||
@@ -0,0 +1,106 @@
|
||||
# User-selected claim branch (flows 1 and 6)
|
||||
|
||||
Before accepting the blame report/signature, the damaged party selects a city and an active branch of the insurer **paying** the claim. In third-party cases the payer is the guilty party's insurer, even if the damaged vehicle has another insurer. In car-body cases it is the first/only party's insurer. Both guilty-party positions and call-center cases are supported.
|
||||
|
||||
Expert/registrar/FileMaker-created flows retain their existing branch/ownership rules. The server determines applicability from the stored case flags, not a browser version parameter. Administrative insurer/super-admin oversight is unchanged.
|
||||
|
||||
## API
|
||||
|
||||
All routes below use existing user authentication and the user-role guard:
|
||||
|
||||
- `GET /v2/blame-request-management/:requestId/claim-branches`: authorize case access, resolve the beneficiary/payer, and return `{required, branchId, locked, branches, claimRequestId?}`. `claimRequestId` is included when a claim already exists for the beneficiary so reloading claim entry can resume it. Locked claims do not fetch branch options. Only the beneficiary receives branch options. Each option contains `id`, `name`, `code`, `city`, `state`, `address`, and optional `phoneNumber`. Options are active branches from the payer only; the client cannot supply an insurer ID.
|
||||
- `PUT /v2/blame-request-management/:requestId/claim-branch`: `{branchId}` saves a validated branch while waiting for signatures or after signing, before any claim exists. This supports historical cases that were already signed when the feature deployed. Other parties cannot select a branch. Existing claims freeze routing; this endpoint cannot move them to another branch.
|
||||
- Existing `PUT /v2/blame-request-management/sign/:requestId` accepts an additional multipart `branchId`. When the damaged user accepts in a user-led flow, a valid branch is mandatory (either supplied now or previously saved). Branch validation occurs before creating the signature record. Confirmation and branch ID are saved in the same blame update. The guilty party signs normally without choosing a branch. Rejection does not require a branch.
|
||||
|
||||
Invalid IDs, inactive branches and branches from another insurer are rejected with Persian errors. The API checks the insurer relationship; UI filtering alone is insufficient. If there are no active branches, the user sees a support message and cannot confirm acceptance/create a new claim until the insurer provisions its branches.
|
||||
|
||||
`GET /v2/blame-request-management/:requestId` includes `claimBranch: {required, branchId}` for the current viewer.
|
||||
|
||||
## Claim creation and expert access
|
||||
|
||||
`createClaimFromBlameV2` revalidates the active branch and copies `blame.branchId` to `claim.branchId`. Missing/invalid selection prevents creation and automatic Fanavaran submission. Changing browser state or calling the creation endpoint directly cannot omit branch validation. This adds no Fanavaran lookup ID or payload field.
|
||||
|
||||
Flow 1 skips automatic Fanavaran submission during local claim creation. Later staged submission hooks remain enabled and can create the base Fanavaran claim when needed. Flow 6 and expert/registrar/FileMaker-created flows retain their existing submission timing.
|
||||
|
||||
The existing expert claim list filter and detail/assignment/action authorization compare the claim branch with the expert's stored branch, in addition to insurer/tenant isolation. Thus a new routed claim appears in that branch's queue and is rejected for damage experts from another branch, including direct access by case ID. Missing expert branch assignments are already denied. Insurer administrators should assign claim experts to the appropriate branches before rollout.
|
||||
|
||||
Existing claims are not migrated or reassigned. Their current access/ownership rules remain in effect. Already-signed blame cases without a claim select their branch on the final screen before entering claim creation. Direct entry into `/claim` also checks selection and returns to that screen if necessary. Deactivation between signing and creation requires choosing another active branch.
|
||||
|
||||
## User interface
|
||||
|
||||
The city and branch selectors appear above the signature canvas, only for the damaged user. A city change clears the branch selection. Same-named cities in different provinces have separate choices. The selected branch's address and phone are displayed. Loading, fetch failure/retry, empty lists and locked routing have explicit Persian states. Confirmation is disabled until the selection is valid. The signature dialog scrolls vertically on small screens.
|
||||
|
||||
The final screen displays the saved branch by name. It only shows the selector for signed cases without a valid active selection (including historical cases); the backend selection rule also protects direct claim entry. Later v6 claim-result signing no longer asks for another branch, avoiding a competing choice. Existing expert-created flows retain their existing result-signing UI.
|
||||
|
||||
## Deployment and verification
|
||||
|
||||
Deploy API and `ui-user` together. No environment variables or database migration are required: the existing `branchId` fields and branch indexes are reused. Configure active branches, city/state/address and expert branch membership in the management panels. `ui-expert` already implements the required branch checks; no UI change there is needed.
|
||||
|
||||
Backend tests cover beneficiary/payer resolution, car-body and both third-party guilty positions, active insurer-scoped options, rejected foreign/inactive IDs, signature enforcement/persistence, culprit restrictions, legacy pre-claim selection, immutable existing claims, claim inheritance and branch access. Existing v6 workflow and authorization tests remain in place. Frontend tests cover city grouping, actor/case partitioning, loading/error/empty states, signature navigation and claim-entry compatibility.
|
||||
|
||||
Production QA should exercise each product in v1 and v6, both signature orders, a signed historical case, no active branches, deactivation before creation, and experts from two branches in the same insurer. Verify the selected branch sees the submitted claim and the other branch cannot list/open/assign it. Repeat expert-created flows 2–5 to confirm their creator ownership is preserved.
|
||||
|
||||
## Combined verification — 2026-11-11
|
||||
|
||||
| Check | Result |
|
||||
| --- | --- |
|
||||
| Complete API unit/regression suite | 90 suites, 774 tests passed |
|
||||
| HTTP branch/signature/claim integration | 16 scenarios passed (`npm run test:e2e`) |
|
||||
| User and expert frontend regression suites | Both passed |
|
||||
| Browser scenarios | 14 passed on real v1/v6 pages: desktop/mobile positive paths, legacy entry and guilty-party signing |
|
||||
| TypeScript | API, user UI and expert UI checked |
|
||||
|
||||
The integration test is `test/claim-branch-flows.e2e-spec.ts`. It uses the production controllers, JWT verification, role guards, Persian error filter, branch service, signature service and claim creation method. Repository operations are isolated in-memory implementations that return fresh documents and apply persisted updates; media policy and external SMS/Fanavaran delivery are mocked. Generated test signature files are removed afterward. The resulting claim is passed through the actual expert tenant/branch authorization and queue-filter methods.
|
||||
|
||||
The matrix covers v1 car-body, v6 car-body, both possible v1 third-party damaged parties, v6's second/damaged party, and both valid third-party signature orders. It asserts the insurer comes from the paying party, validates branch inheritance, prevents guilty-party claim creation, rejects foreign/inactive branches, requires both signatures, preserves existing expert-created LINK branches, handles signed legacy cases, rechecks deactivation, blocks missing authentication/wrong roles/non-participants, freezes existing claim routing, and prevents duplicate sequential creation.
|
||||
|
||||
Browser tests draw a signature, verify its multipart request includes the selected branch, continue to claim creation once, and verify the claim can proceed. Changing city clears the previous branch. Existing signed cases entering `/claim` without a branch return to the branch picker. Separate v1/v6 guilty-party checks confirm no branch selection is requested and no claim-creation button appears. Existing suites cover the flow 2–5 ownership and file-maker/reviewer handoff rules.
|
||||
|
||||
No new application defect was found in this verification pass; the additional HTTP integration tests/configuration were retained as regression coverage. External-provider availability, production branch/staff configuration, real database connectivity/indexes and live SMS delivery were not exercised. Those still require deployment QA; these results do not claim an exhaustive proof of every possible application state.
|
||||
|
||||
## Reliability corrections — 2026-11-16
|
||||
|
||||
The original implementation hydrated the complete case (voice/video URLs, expert profile and claim hints) just to authorize branch loading, then loaded that case again. The branch endpoint now reuses the exact authorization, user binding and workflow recovery logic directly, with no media/profile hydration. Legacy branch city/state values are normalized before sorting.
|
||||
|
||||
The frontend branch query has a 15-second timeout and explicit retry. A disabled query no longer renders a loader; an unparseable local JWT no longer silently disables the query forever. Options are cached for 30 seconds by actor and case; every save/signature and claim creation still validates the selected branch on the server. Empty active-branch lists remain a real setup error, with an explicit Persian explanation. They cannot be bypassed by accepting an arbitrary branch.
|
||||
|
||||
Accepting a signature now returns the persisted status, the viewer's `nextAction`, their confirmation, `claimBranch`, and `claimCreation`. The frontend applies that acknowledgement to both the case and branch caches immediately. It does not wait for an additional case GET before navigating. That cache update is essential: without it the next screen still has the pre-signature `branchId: null` and asks for the same branch again. A normal signed case therefore has one city/branch selection, on the blame-signature screen. Later acceptance of the financial assessment remains a separate legal decision and does not ask v1/v6 users for another branch.
|
||||
|
||||
User-led signatures use conditional writes: the case must still be waiting and the viewer must not already have a confirmation. A repeated identical acceptance returns the stored confirmation and branch without replacing them. A conflicting decision cannot overwrite an existing signature. Signature upload filenames use UUIDs so two users uploading `signature.png` in the same millisecond cannot overwrite each other's image. Completing the case is conditional on the persisted required signatures and waiting status; it uses `$addToSet` for workflow history. The same completion logic recovers interrupted records where all required accepted signatures exist but status remains waiting, on detail/list/branch reads or a safe retry. Stopped files and expert-created flows are excluded from this recovery. A notification failure after saving cannot turn a persisted signature into a failed submission.
|
||||
|
||||
Case status polling continues while waiting for the other party, and the next action switches to claim creation only for the beneficiary. The culprit can sign without a branch and cannot create the claim. Case-detail requests are cancellable and bounded; intentional cancellation does not show a false error toast. Failed signing shows the actual Persian error and preserves the canvas while rechecking the saved state. Closing the signature dialog returns to a page with a signing link. Claim entry offers retry, and an existing claim returned by the branch preflight is resumed instead of creating a second claim.
|
||||
|
||||
### Regression commands
|
||||
|
||||
```bash
|
||||
# API unit/regression suite, plus authenticated HTTP scenarios (mock repositories/providers).
|
||||
npm test -- --runInBand
|
||||
npm run test:e2e -- --runInBand
|
||||
|
||||
# In ui-user:
|
||||
npm run test:ui
|
||||
npx tsc --noEmit
|
||||
```
|
||||
|
||||
The HTTP suite also has an optional combined browser tier. Start the user UI with a temporary test-only API URL, then run the test with Playwright installed. The browser forwards only that mock API prefix to the actual test HTTP controllers; JWT/role guards, case/branch/signature services and claim creation run normally. Database operations and SMS/Fanavaran remain isolated fixtures.
|
||||
|
||||
```bash
|
||||
# ui-user terminal (use a separate dev build if another dev server is running):
|
||||
NEXT_PUBLIC_BASE_URL=http://127.0.0.1:3217/mock-api NEXT_PUBLIC_BASE_PATH='' npm run dev -- --hostname 127.0.0.1 --port 3217
|
||||
|
||||
# api terminal; PLAYWRIGHT_MODULE may point to a locally installed Playwright package.
|
||||
CLAIM_BRANCH_UI_URL=http://127.0.0.1:3217 PLAYWRIGHT_MODULE=/path/to/playwright npm run test:e2e -- --runInBand
|
||||
# Optional: CLAIM_BRANCH_BROWSER_EXECUTABLE=/path/to/chrome-or-brave
|
||||
```
|
||||
|
||||
Deploy API and ui-user together. No environment/schema migration is needed. Existing active branches and expert branch assignments are still required. No production data, real provider availability or live SMS delivery is exercised by these isolated tests.
|
||||
|
||||
### Verification of the corrections
|
||||
|
||||
- API: **97 suites / 874 tests passed**.
|
||||
- Authenticated HTTP + combined mobile browser tier: **30 scenarios passed**, including four real UI → controller → persistence scenarios for v1/v6 × car-body/third-party. Database repositories and providers are mocked.
|
||||
- Additional isolated browser matrix: **13 normal/legacy/error scenarios and 6 recovery scenarios passed**, covering desktop/mobile layouts, delayed GETs after signing, guilty-party access, historic signed cases, branch errors/timeouts, empty options, waiting for the other signature, failed signing, double-clicks and cancellation. These use Chromium/Brave with emulated desktop/mobile viewports and drawn canvas signatures.
|
||||
- Complete user UI regression script, API/user TypeScript checks and whitespace checks passed.
|
||||
- The default Next.js production build (`npm run build`) passed with normal build-worker permissions. The initial sandboxed compilation was stopped after stalling; no deployment configuration was changed.
|
||||
|
||||
The tests do not change production data or contact SMS/Fanavaran. The browser tier is intentionally opt-in so a developer without Playwright can still run all HTTP tests; use the command above to include it.
|
||||
@@ -0,0 +1,45 @@
|
||||
# V6 call-center workflow and inquiry recovery
|
||||
|
||||
The call-center operator performs the caller's inquiry once, for both `CAR_BODY` and `THIRD_PARTY`. Plate and VIN use the same subsequent workflow. These are API workflow rules; `skipInitialFormStep` by itself is not proof of successful inquiry.
|
||||
|
||||
## Root cause and correction
|
||||
|
||||
The backend previously skipped `FIRST_INITIAL_FORM` after video **only for third-party** cases. Car-body cases therefore returned to inquiry even with fully stored operator results. The operator endpoints also stored a success-history event without marking the inquiry workflow step complete. The earlier frontend video fix followed the response correctly, but could not correct the car-body response.
|
||||
|
||||
After a successful operator inquiry, the API records `FIRST_INITIAL_FORM` as complete without advancing past the caller's required introduction/video. Failed or partially populated inquiries do not enable link sending. After video both case types advance to `FIRST_LOCATION`. The second party's independent inquiry is never skipped.
|
||||
|
||||
Authorized user reads and operator detail reads repair older cases stuck at `FIRST_INITIAL_FORM` when the stored operator success event and insurer/client association establish completion. Video evidence or completed video is required to advance to location; otherwise recovery returns to video. Stopped, cancelled, completed and locked cases are not repaired. Later narrative, second-party and signature steps are not rewound. No inquiry is rerun as part of recovery.
|
||||
|
||||
The user UI also rechecks a bookmarked V6 first-party inquiry page and replaces it with the remaining accident-type, video or narrative page when the API confirms the first inquiry is complete. Operator and second-party inquiry forms retain their normal behavior.
|
||||
|
||||
V6 SMS links retain `/v6/` for the initial caller link, second-party invitation, signature notices and claim-ready notice. Other flows retain their existing URL version.
|
||||
|
||||
## Expected paths
|
||||
|
||||
| Stage | Car-body | Third-party |
|
||||
| --- | --- | --- |
|
||||
| Operator | Create → plate/VIN inquiry → review → send link | Same |
|
||||
| Caller login | Accident-type form | Video (confession already established) |
|
||||
| First-party collection | Video → location → voice → description/accident fields | Video → location → voice → description |
|
||||
| Next | Single-party signature | Invite second party → their inquiry → their location/voice/description |
|
||||
| Completion | Accept signature → blame completed | Both accept signatures → blame completed |
|
||||
| Rejection | Stop case | Stop case |
|
||||
| Claim | Existing claim-creation authorization and required payment data | Existing claim-creation authorization; damaged party only |
|
||||
|
||||
Skipping repeat blame inquiry does not waive claim-stage IBAN, payment details, documents or insurer eligibility. Existing claim-stage validation remains in place.
|
||||
|
||||
## Verification and production QA
|
||||
|
||||
Backend regressions exercise both products and both inquiry entry points, first login/resume, accident-type/video, narrative, second-party invitation/required inquiry boundary, signatures/completion/rejection, recovery, authorization, failed inquiry, repeated links, operator detail and preserved SMS versions. External inquiry calls and SMS delivery are mocked. In the third-party scenario the external second-party inquiry itself is represented by its completed workflow boundary; existing inquiry-specific tests cover its provider contracts.
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
npm test -- --runInBand call-center-v6-workflow.spec file-maker-blame-v4-workflow.spec
|
||||
```
|
||||
|
||||
Frontend navigation regressions are included in `ui-user`'s `npm run test:ui`.
|
||||
|
||||
For production QA, use separate test users for caller and damaged party. Run one case of each type with plate inquiry, and VIN if enabled. Reload at video, location, voice, description, waiting/signing and completed states; reopen from the case list; revisit an old inquiry URL; resend the operator link. Confirm no repeated caller inquiry and no skipped video. For third-party, verify the second party still provides their inquiry, only the damaged party can proceed to claim, and both signatures are required. Confirm SMS links stay on v6. Test inquiry failure before sending a link and a rejected signature. Provider availability, actual SMS delivery and browser/device media capture still require environment QA.
|
||||
|
||||
Deploy both the API correction and the user UI recovery. No environment changes, bulk database migration or manual status edits are required; eligible old records recover on authorized reads.
|
||||
Binary file not shown.
Generated
+1
@@ -30,6 +30,7 @@
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.1",
|
||||
"socks-proxy-agent": "^8.0.4",
|
||||
"socks-proxy-agent": "^8.0.4",
|
||||
"svg-captcha": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
"start:dev": "nest start --watch",
|
||||
"start:debug": "nest start --debug --watch",
|
||||
"start:prod": "node dist/main",
|
||||
"sms:test:mic": "ts-node -r tsconfig-paths/register scripts/test-mic-sms.ts",
|
||||
"seed:parsian-tehran": "ts-node scripts/seed-parsian-tehran.ts",
|
||||
"seed:parsian-remaining": "node scripts/data/parsian-tehran/seed-remaining-experts.js",
|
||||
"seed:parsian-all": "node scripts/data/parsian-tehran/seed-remaining-experts.js",
|
||||
"seed:reports-fixtures": "ts-node scripts/seed-insurer-reports-fixtures.ts",
|
||||
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
|
||||
"test": "jest",
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
{
|
||||
"claimId": "12280969",
|
||||
"savedAt": "2026-10-27T12:23:58.684Z",
|
||||
"env": {
|
||||
"FANAVARAN_CLIENT": "moallem",
|
||||
"FANAVARAN_API_VERSION": "v15",
|
||||
"APP_NAME": "ItTalie",
|
||||
"APP_SECRET": "itT@l!3@api",
|
||||
"FANAVARAN_USERNAME": "itTalieUser",
|
||||
"FANAVARAN_PASSWORD": "itT@l!3@user",
|
||||
"CORP_ID": "5650",
|
||||
"CONTRACT_ID": "304",
|
||||
"CURL_PROXY": "socks5h://127.0.0.1:4030",
|
||||
"LOCATION": "1",
|
||||
"CLAIM_EXPERT_ID": "5507",
|
||||
"EXPERTISE_CLAIM_EXPERT_ID": "5507",
|
||||
"ACCIDENT_CULPRIT_ID": "",
|
||||
"CLAIM_FILE_TYPE_ID": "17",
|
||||
"VEHICLE_KIND_ID": "15694",
|
||||
"DMG_SECTION_ID": "1",
|
||||
"INSURANCE_CORP_ID": "343",
|
||||
"CULPRIT_TYPE_ID": "337",
|
||||
"GUILTY_NATIONAL_CODE": "0410543195",
|
||||
"ACCIDENT_DATE": "1405/08/04",
|
||||
"ACCIDENT_TIME": "10:30",
|
||||
"CULPRIT_LICENCE_NO": "9705463515",
|
||||
"CULPRIT_LICENCE_ISSU_DATE": "1400/06/15",
|
||||
"DRIVER_NATIONAL_CODE": "5560568341",
|
||||
"DRIVER_BIRTH_YEAR": "1373",
|
||||
"DRIVER_BIRTH_MONTH": "12",
|
||||
"DRIVER_BIRTH_DAY": "28",
|
||||
"DRIVER_IS_INSURER": "0",
|
||||
"DRIVER_IS_OWNER": "1",
|
||||
"DRIVER_MOBILE": "",
|
||||
"DRIVER_TEL": "",
|
||||
"DRIVER_ADDRESS": "",
|
||||
"DRIVER_POSTAL_CODE": "",
|
||||
"DRIVER_EMAIL": "",
|
||||
"DRIVER_JOB_ADDRESS": "",
|
||||
"DRIVER_CITY_ID": "9131",
|
||||
"DRIVER_PERSON_KIND_ID": "46",
|
||||
"IS_IRANIAN": "1",
|
||||
"DRIVER_IDENTITY_ISSU_PLACE": "",
|
||||
"DRIVER_MARITAL_STATUS": "",
|
||||
"DRIVER_NATIONALITY_ID": "",
|
||||
"DRIVER_PASSPORT_NO": "",
|
||||
"DRIVER_NATURALIZED_CODE": "",
|
||||
"DRIVER_ECONOMIC_CODE": "",
|
||||
"DRIVER_AD_BIRTH_YEAR": "",
|
||||
"DRIVER_AD_BIRTH_MONTH": "",
|
||||
"DRIVER_AD_BIRTH_DAY": "",
|
||||
"LICENCE_NO": "9705463515",
|
||||
"LICENCE_ISSU_DATE": "1400/06/15",
|
||||
"DESC": "سپر عقب",
|
||||
"PLAQUE_LEFT_NO": "59",
|
||||
"PLAQUE_RIGHT_NO": "419",
|
||||
"PLAQUE_SERIAL": "78",
|
||||
"PLAQUE_MIDDLE_CODE_ID": "16",
|
||||
"PLAQUE_NO": "59ی41978",
|
||||
"BUILT_YEAR": "1394",
|
||||
"VIN": "IRPC941V2BD798656",
|
||||
"CHASSIS_NO": "NAS431100E5798656",
|
||||
"MOTOR_NO": "5215907",
|
||||
"POLICY_NO": "1405/1143-1143/200/29",
|
||||
"POLICY_CI_NUMBER": "16040446424",
|
||||
"BEGIN_DATE": "1405/04/06",
|
||||
"END_DATE": "1406/04/06",
|
||||
"ATTACHMENT_FILE": "/home/sepehr/Pictures/tasaodfiiii.jpg",
|
||||
"DMG_ASSESSMENT_DATE": "1405/08/04",
|
||||
"INSPECTION_TIME": "11:00",
|
||||
"ESTIMATE_AMOUNT": "1000",
|
||||
"REPAIR_WAGE": "100000",
|
||||
"COMPONENT_REPLACEMENT_COST": "500000",
|
||||
"WASTE_VALUE": "0",
|
||||
"POLICY_ID": "23466457",
|
||||
"CLAIM_ID": "12280969",
|
||||
"CLAIM_NO": "3993",
|
||||
"DRIVER_ID": "36473146",
|
||||
"INSURANCE_CORP_ID_NUM": "343",
|
||||
"DMG_CASE_ID": "478527",
|
||||
"EXPERTISE_ID": "",
|
||||
"DMG_NOTIFICATION_ID": "",
|
||||
"CLAIM_NOTIFICATION_DATE": "1405/08/04",
|
||||
"NOTIFY_LETTER_NO": "",
|
||||
"NOTIFY_LETTER_DATE": "1405/08/04",
|
||||
"INJURED_COUNT": "",
|
||||
"DEATH_COUNT": "",
|
||||
"NOTIFY_DESC": "",
|
||||
"NOTIFIER_TYPE_ID": "5517",
|
||||
"NOTIFIER_RELATION_ID": "5522",
|
||||
"NOTIFIER_PARTY_ID": "35825103",
|
||||
"IS_INJURED_PARTY_IDENTIFIED": "",
|
||||
"INJURED_PARTY_ID": "",
|
||||
"INCLUDE_DMG_NOTIFICATION_ON_BASE": "1"
|
||||
},
|
||||
"ui": {
|
||||
"guiltyRoleMode": "1",
|
||||
"damagedRoleMode": "2a",
|
||||
"guiltyInsurerNc": "0410543195",
|
||||
"guiltyInsurerBd": "13760405",
|
||||
"guiltyOwnerNc": "0651828562",
|
||||
"guiltyOwnerBd": "13571201",
|
||||
"guiltyDriverNc": "0410543195",
|
||||
"guiltyDriverBd": "13760405",
|
||||
"guiltyPlateLeft": "23",
|
||||
"guiltyPlateLetter": "م",
|
||||
"guiltyPlateRight": "218",
|
||||
"guiltyPlateSerial": "21",
|
||||
"guiltyBuiltYear": "1398",
|
||||
"guiltyMotorNo": "M158828700",
|
||||
"guiltyChassisNo": "NAS821100K1236795",
|
||||
"guiltyInquiryNc": "0410543195",
|
||||
"guiltyInquiryVin": "NAS821100K1236795",
|
||||
"guiltyInquiryMode": "plate",
|
||||
"damagedInquiryNc": "5560568341",
|
||||
"damagedInquiryVin": "IRPC941V2BD798656",
|
||||
"damagedInquiryMode": "plate",
|
||||
"damagedDriverBd": "13731228",
|
||||
"notifierNc": "0410543195",
|
||||
"notifierBd": "13760405",
|
||||
"VEHICLE_KIND_ID_search": "پژو 206 [15694]",
|
||||
"DMG_SECTION_ID_search": "جلو کامل [1]",
|
||||
"ACCIDENT_CULPRIT_ID_search": ""
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
# Fanavaran flow test — copy this file, fill section A, then run:
|
||||
#
|
||||
# cp scripts/data/fanavaran-flow.env.example scripts/data/fanavaran-flow.moallem.env
|
||||
# ./scripts/fanavaran-flow-test.sh --env scripts/data/fanavaran-flow.moallem.env
|
||||
# FANAVARAN_FLOW_ENV=scripts/data/fanavaran-flow.moallem.env node scripts/fanavaran-flow-ui-server.js
|
||||
#
|
||||
# Section A = you fill before (or when the script asks).
|
||||
# Section B = leave empty. The script writes Fanavaran ids here after each stage
|
||||
@@ -16,6 +16,10 @@
|
||||
# --- tenant ---
|
||||
FANAVARAN_CLIENT=moallem
|
||||
|
||||
# Moallem uses the V14 GEN.03 body and requires an embedded claimant notification.
|
||||
FANAVARAN_API_VERSION=v14
|
||||
FANAVARAN_BASE_URL=https://api.inssw.ir/BimeApiManager/api
|
||||
|
||||
# Localhost only: route curl through Termius SOCKS (Dynamic Port Forwarding).
|
||||
# Example: CURL_PROXY=socks5h://127.0.0.1:1080
|
||||
# Or run the script on the Moallem server (no proxy needed).
|
||||
@@ -30,6 +34,11 @@ FANAVARAN_CLIENT=moallem
|
||||
# CONTRACT_ID=
|
||||
# LOCATION=
|
||||
|
||||
# Moallem is always authenticated against api.inssw.ir. The flow script enforces
|
||||
# this endpoint even if an inherited API .env contains another Fanavaran host.
|
||||
# FANAVARAN_BASE_URL=https://api.inssw.ir/BimeApiManager/api
|
||||
# FANAVARAN_BIME_URL=https://api.inssw.ir/BimeApiManager/api/BimeApi/v2.0
|
||||
|
||||
# --- tenant lookup ids (from this insurer's Fanavaran lookups) ---
|
||||
CLAIM_EXPERT_ID=
|
||||
EXPERTISE_CLAIM_EXPERT_ID=
|
||||
@@ -45,6 +54,20 @@ GUILTY_NATIONAL_CODE=
|
||||
ACCIDENT_DATE=1404/05/20
|
||||
ACCIDENT_TIME=12:00
|
||||
|
||||
# --- Moallem V14 GEN.03 embedded claimant notification ---
|
||||
# IDs must come from Moallem's own Fanavaran code lists / party inquiry.
|
||||
CLAIM_NOTIFICATION_DATE=
|
||||
NOTIFY_LETTER_DATE=
|
||||
NOTIFIER_TYPE_ID=
|
||||
NOTIFIER_RELATION_ID=
|
||||
NOTIFIER_PARTY_ID=
|
||||
NOTIFY_LETTER_NO=
|
||||
NOTIFY_DESC=
|
||||
INJURED_COUNT=
|
||||
DEATH_COUNT=
|
||||
IS_INJURED_PARTY_IDENTIFIED=
|
||||
INJURED_PARTY_ID=
|
||||
|
||||
# --- GEN.12 case ---
|
||||
DRIVER_NATIONAL_CODE=
|
||||
DRIVER_BIRTH_YEAR=1370
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
# Combined Parsian expert seed
|
||||
|
||||
The seed merges the original `branches.json`, `file-reviewers.json`, `file-makers.json`, the assessor records in `field-experts.json`, and the fixed `remaining-experts.json`. No Excel reader or generation step is needed.
|
||||
|
||||
Run from `api/`, using that API's `.env`:
|
||||
|
||||
```bash
|
||||
npm run seed:parsian-all -- --dry-run
|
||||
npm run seed:parsian-all
|
||||
```
|
||||
|
||||
`npm run seed:parsian-remaining` runs the same combined seed, so the previous command also works. Use this combined seed instead of rerunning the old Tehran seed.
|
||||
|
||||
Combined source totals: **120 people, 50 branches, 88 claim experts, 88 file reviewers and 39 file makers**. Actual inserts depend on the accounts/branches already in the database.
|
||||
|
||||
Merge rules:
|
||||
|
||||
- A national code identifies a person; role + national code identifies an account. Existing account IDs, passwords, email/username aliases and activation states are retained. New accounts use national-code usernames and the hashed password `123321`.
|
||||
- Existing primary branches stay unchanged. Additional source locations are merged and deduplicated into `locations`; differing branch lists no longer abort the import. This does not grant multiple primary branches in the application's branch-based authorization.
|
||||
- A new claim/reviewer counterpart inherits the existing counterpart's valid primary branch and assessment codes. File makers retain their own role-specific source locations.
|
||||
- Original JSON product codes take precedence over conflicting values in the remaining list. Existing database codes take precedence over imported values. Missing codes are filled; differing existing codes are kept and reported as merge notes, without stopping the batch.
|
||||
- Missing branches are created. Existing branch data is preserved, and missing details can be filled from the original directory. New branches without an address keep it blank. No address, contact or Fanavaran code is invented.
|
||||
- Ambiguous duplicate accounts, identities belonging to another insurer, incorrect stored roles, or unresolved primary branches are skipped with an explicit note. They are not silently moved, deleted or merged across insurers; the rest of the batch can continue.
|
||||
- No cases, case owners, signatures, SMS or Fanavaran requests are changed.
|
||||
|
||||
The reported reviewer ending **8521** remains at their existing primary branch and gains the additional source location. The assessment-code differences for the reviewer ending **8118** preserve existing/original codes rather than choosing the new conflicting values.
|
||||
|
||||
The historical `field-experts.json` contains assessor titles; those become claim experts + file reviewers, not FIELD_EXPERT accounts. Generic assessors are included without guessing product-specific codes. File-responsible / مسئول خسارت / ثبات titles create file makers only.
|
||||
|
||||
Excel row **37** remains excluded because its national code has 11 digits. The remaining source's `skippedRows` records it. National-code checksum warnings for rows 11, 26 and 27 retain the supplied ten-digit values for verification.
|
||||
|
||||
`--dry-run` performs reads only and prints planned creates, updates, skips and merge notes. Applying ensures the role identity indexes and sparse unique email indexes needed for email-less accounts, with a temporary uniqueness guard during legacy email-index replacement (MongoDB 5.0+). Keep the corresponding API changes supporting claim experts without email/mobile.
|
||||
|
||||
The seed is resumable. If an unexpected database/index error occurs, earlier successful writes remain. Conditional updates reject concurrent edits instead of overwriting them. Re-running merges the data again without resetting passwords or duplicating accounts.
|
||||
|
||||
Regression tests: `node scripts/data/parsian-tehran/seed-remaining-experts.test.cjs`.
|
||||
@@ -137,7 +137,8 @@
|
||||
"branchName": "شعبه والفجر",
|
||||
"city": "کاشان",
|
||||
"state": "اصفهان",
|
||||
"title": "كارشناس ارزياب خسارت بدنه"
|
||||
"title": "كارشناس ارزياب خسارت بدنه",
|
||||
"expertCode": "3705"
|
||||
},
|
||||
{
|
||||
"nationalCode": "3781847039",
|
||||
@@ -150,4 +151,4 @@
|
||||
"title": "كارشناس ارزياب خسارت ثالث مالي"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "91",
|
||||
@@ -37,7 +37,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4221",
|
||||
@@ -47,7 +47,7 @@
|
||||
"nationalCode": "0492295557",
|
||||
"mobile": "09125409101",
|
||||
"firstName": "اکبر",
|
||||
"lastName": "بيگ محمدي",
|
||||
"lastName": "بيگ محمدي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "111130",
|
||||
@@ -64,7 +64,7 @@
|
||||
"nationalCode": "3220096573",
|
||||
"mobile": "09104933206",
|
||||
"firstName": "پدرام",
|
||||
"lastName": "حاتمي",
|
||||
"lastName": "حاتمي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210120",
|
||||
@@ -81,7 +81,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "739",
|
||||
@@ -95,7 +95,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "3215",
|
||||
@@ -119,11 +119,11 @@
|
||||
"nationalCode": "0084130938",
|
||||
"mobile": "09392558640",
|
||||
"firstName": "رسول",
|
||||
"lastName": "کرکي",
|
||||
"lastName": "کرکي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4662"
|
||||
@@ -136,7 +136,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4245",
|
||||
@@ -150,7 +150,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "89",
|
||||
@@ -164,7 +164,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4455",
|
||||
@@ -178,7 +178,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "742",
|
||||
@@ -220,7 +220,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4652",
|
||||
@@ -244,11 +244,11 @@
|
||||
"nationalCode": "0066868521",
|
||||
"mobile": "09129344240",
|
||||
"firstName": "عليرضا",
|
||||
"lastName": "گودرزي پور",
|
||||
"lastName": "گودرزي پور ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4663"
|
||||
@@ -261,7 +261,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4220",
|
||||
@@ -275,7 +275,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4452",
|
||||
@@ -299,11 +299,11 @@
|
||||
"nationalCode": "0056888082",
|
||||
"mobile": "09122406750",
|
||||
"firstName": "قاسم",
|
||||
"lastName": "نصراللهي",
|
||||
"lastName": "نصراللهي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4664"
|
||||
@@ -330,7 +330,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "4092",
|
||||
@@ -344,7 +344,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "1010",
|
||||
@@ -354,11 +354,11 @@
|
||||
"nationalCode": "0493217789",
|
||||
"mobile": "09126966943",
|
||||
"firstName": "مصطفي",
|
||||
"lastName": "محمدزاده قورقچي",
|
||||
"lastName": "محمدزاده قورقچي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4665"
|
||||
@@ -371,7 +371,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyClaimExpertId": "745",
|
||||
@@ -381,11 +381,11 @@
|
||||
"nationalCode": "0078209129",
|
||||
"mobile": "09126038117",
|
||||
"firstName": "مهدي",
|
||||
"lastName": "شاملوفرد",
|
||||
"lastName": "شاملوفرد ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4666"
|
||||
@@ -426,7 +426,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "1004",
|
||||
@@ -440,7 +440,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "4646",
|
||||
@@ -454,7 +454,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyClaimExpertId": "228",
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "29",
|
||||
@@ -50,7 +50,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"CarBodyExpertiseClaim": "15",
|
||||
@@ -74,11 +74,11 @@
|
||||
"nationalCode": "0056888082",
|
||||
"mobile": "09122406750",
|
||||
"firstName": "قاسم",
|
||||
"lastName": "نصراللهي",
|
||||
"lastName": "نصراللهي ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "4645"
|
||||
@@ -91,7 +91,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران(210040)"
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "3985",
|
||||
@@ -119,7 +119,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
}
|
||||
],
|
||||
"ThirdPartyExpertiseClaim": "3545",
|
||||
@@ -147,7 +147,7 @@
|
||||
"locations": [
|
||||
{
|
||||
"id": "210050",
|
||||
"name": "شعبه غرب تهران(210050)"
|
||||
"name": "شعبه غرب تهران"
|
||||
},
|
||||
{
|
||||
"id": "210110",
|
||||
@@ -156,6 +156,43 @@
|
||||
],
|
||||
"CarBodyExpertiseClaim": "73",
|
||||
"ThirdPartyExpertiseClaim": "72"
|
||||
},
|
||||
{
|
||||
"nationalCode": "3781847039",
|
||||
"firstName": "اکبر",
|
||||
"lastName": "ديني ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nationalCode": "0759153981",
|
||||
"firstName": "رضا",
|
||||
"lastName": "صالحي زاده ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"nationalCode": "0013480261",
|
||||
"firstName": "عليرضا",
|
||||
"lastName": "خازني ❌",
|
||||
"locations": [
|
||||
{
|
||||
"id": "210040",
|
||||
"name": "شعبه شرق تهران"
|
||||
},
|
||||
{
|
||||
"id": "210110",
|
||||
"name": "شعبه پونک"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,663 @@
|
||||
#!/usr/bin/env node
|
||||
"use strict";
|
||||
|
||||
// Merge the original Parsian JSON directory and the fixed remaining-experts data.
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const crypto = require("node:crypto");
|
||||
const { promisify } = require("node:util");
|
||||
const mongoose = require("mongoose");
|
||||
const scrypt = promisify(crypto.scrypt);
|
||||
const roles = {
|
||||
damage_expert: {
|
||||
collection: "damage-expert",
|
||||
codes: [
|
||||
"ThirdPartyClaimExpertId",
|
||||
"CarBodyClaimExpertId",
|
||||
"ThirdPartyExpertiseClaim",
|
||||
"CarBodyExpertiseClaim",
|
||||
],
|
||||
},
|
||||
file_reviewer: {
|
||||
collection: "file-reviewer",
|
||||
codes: ["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"],
|
||||
},
|
||||
file_maker: {
|
||||
collection: "file-maker",
|
||||
codes: ["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
|
||||
},
|
||||
};
|
||||
const string = (value) => String(value ?? "");
|
||||
const empty = (value) => value == null || value === "";
|
||||
class SeedError extends Error {}
|
||||
|
||||
function mergeLocations(...lists) {
|
||||
const merged = new Map();
|
||||
for (const location of lists.flat()) {
|
||||
const id = string(location?.id).trim();
|
||||
if (id && !merged.has(id))
|
||||
merged.set(id, { id, name: string(location.name).trim() });
|
||||
}
|
||||
return [...merged.values()];
|
||||
}
|
||||
|
||||
function loadMergedData(
|
||||
sources = {
|
||||
branches: require("./branches.json"),
|
||||
reviewers: require("./file-reviewers.json"),
|
||||
makers: require("./file-makers.json"),
|
||||
legacy: require("./field-experts.json"),
|
||||
remaining: require("./remaining-experts.json"),
|
||||
},
|
||||
) {
|
||||
if (Object.values(sources).some((source) => source.clientCode !== 8))
|
||||
throw new SeedError(
|
||||
"All input JSON files must belong to Parsian (clientCode=8).",
|
||||
);
|
||||
const branches = new Map(),
|
||||
experts = new Map(),
|
||||
notes = [];
|
||||
// The established branch directory wins; new data fills missing details only.
|
||||
for (const branch of [
|
||||
...sources.branches.branches,
|
||||
...sources.remaining.branches,
|
||||
]) {
|
||||
const code = string(branch.code),
|
||||
current = branches.get(code);
|
||||
if (!current) branches.set(code, { ...branch, code });
|
||||
else
|
||||
for (const [field, value] of Object.entries(branch))
|
||||
if (empty(current[field]) && !empty(value)) current[field] = value;
|
||||
}
|
||||
const allCodeFields = [
|
||||
...new Set(Object.values(roles).flatMap((role) => role.codes)),
|
||||
];
|
||||
function addExpert(record, assignedRoles, locations, source) {
|
||||
const nationalCode = string(record.nationalCode);
|
||||
let expert = experts.get(nationalCode);
|
||||
if (!expert) {
|
||||
expert = {
|
||||
nationalCode,
|
||||
firstName: record.firstName,
|
||||
lastName: record.lastName,
|
||||
roles: [],
|
||||
locations: [],
|
||||
roleLocations: {},
|
||||
};
|
||||
experts.set(nationalCode, expert);
|
||||
}
|
||||
for (const field of ["firstName", "lastName", "mobile"])
|
||||
if (empty(expert[field]) && !empty(record[field]))
|
||||
expert[field] = record[field];
|
||||
expert.locations = mergeLocations(expert.locations, locations);
|
||||
expert.branchCode = expert.locations[0]?.id;
|
||||
for (const role of assignedRoles) {
|
||||
if (!expert.roles.includes(role)) expert.roles.push(role);
|
||||
expert.roleLocations[role] = mergeLocations(
|
||||
expert.roleLocations[role] ?? [],
|
||||
locations,
|
||||
);
|
||||
}
|
||||
for (const field of allCodeFields)
|
||||
if (!empty(record[field])) {
|
||||
const value = string(record[field]);
|
||||
if (empty(expert[field])) expert[field] = value;
|
||||
else if (expert[field] !== value)
|
||||
notes.push({
|
||||
nationalCode: `******${nationalCode.slice(-4)}`,
|
||||
field,
|
||||
source,
|
||||
action: "kept-original-source-code",
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const record of sources.reviewers.fileReviewers)
|
||||
addExpert(
|
||||
record,
|
||||
["damage_expert", "file_reviewer"],
|
||||
record.locations,
|
||||
"file-reviewers.json",
|
||||
);
|
||||
for (const record of sources.makers.fileMakers)
|
||||
addExpert(record, ["file_maker"], record.locations, "file-makers.json");
|
||||
// This older file contains assessor titles, rather than FIELD_EXPERT accounts.
|
||||
for (const record of sources.legacy.fieldExperts) {
|
||||
const title = string(record.title).replace(/ي/g, "ی").replace(/ك/g, "ک");
|
||||
if (!title.includes("ارزیاب") || !title.includes("خسارت")) continue;
|
||||
const mapped = { ...record };
|
||||
if (record.expertCode) {
|
||||
if (/ثالث|مالی/.test(title))
|
||||
mapped.ThirdPartyExpertiseClaim = string(record.expertCode);
|
||||
if (/بدنه/.test(title))
|
||||
mapped.CarBodyExpertiseClaim = string(record.expertCode);
|
||||
}
|
||||
addExpert(
|
||||
mapped,
|
||||
["damage_expert", "file_reviewer"],
|
||||
[{ id: record.branchCode, name: record.branchName }],
|
||||
"field-experts.json",
|
||||
);
|
||||
}
|
||||
for (const record of sources.remaining.experts)
|
||||
addExpert(
|
||||
record,
|
||||
record.roles,
|
||||
[{ id: record.branchCode, name: branches.get(record.branchCode)?.name }],
|
||||
"remaining-experts.json",
|
||||
);
|
||||
const result = {
|
||||
clientCode: 8,
|
||||
branches: [...branches.values()],
|
||||
experts: [...experts.values()],
|
||||
skippedRows: sources.remaining.skippedRows,
|
||||
notes,
|
||||
};
|
||||
validateData(result);
|
||||
return result;
|
||||
}
|
||||
|
||||
function validateData(seed) {
|
||||
if (seed.clientCode !== 8)
|
||||
throw new SeedError("This seed is for Parsian (clientCode=8) only.");
|
||||
const branches = new Set(seed.branches.map((branch) => branch.code));
|
||||
if (branches.size !== seed.branches.length)
|
||||
throw new SeedError("Duplicate branch codes in JSON.");
|
||||
for (const branch of seed.branches)
|
||||
if (
|
||||
!/^\d+$/.test(branch.code) ||
|
||||
!branch.name ||
|
||||
!branch.city ||
|
||||
!branch.state
|
||||
)
|
||||
throw new SeedError("Invalid branch data in JSON.");
|
||||
const identities = new Set();
|
||||
for (const expert of seed.experts) {
|
||||
if (
|
||||
!/^\d{10}$/.test(expert.nationalCode) ||
|
||||
!expert.firstName ||
|
||||
!expert.lastName ||
|
||||
!branches.has(expert.branchCode)
|
||||
)
|
||||
throw new SeedError("Invalid expert identity or branch in JSON.");
|
||||
if (
|
||||
!expert.roles?.length ||
|
||||
new Set(expert.roles).size !== expert.roles.length ||
|
||||
expert.roles.some((role) => !Object.hasOwn(roles, role))
|
||||
)
|
||||
throw new SeedError("Invalid or repeated expert role in JSON.");
|
||||
if (expert.mobile && !/^09\d{9}$/.test(expert.mobile))
|
||||
throw new SeedError("Invalid mobile in JSON.");
|
||||
for (const location of [
|
||||
...(expert.locations ?? []),
|
||||
...Object.values(expert.roleLocations ?? {}).flat(),
|
||||
])
|
||||
if (!branches.has(location.id))
|
||||
throw new SeedError(
|
||||
"Expert location has no matching branch in the combined JSON data.",
|
||||
);
|
||||
for (const role of expert.roles) {
|
||||
const identity = `${role}:${expert.nationalCode}`;
|
||||
if (identities.has(identity))
|
||||
throw new SeedError("Duplicate role/national code in JSON.");
|
||||
identities.add(identity);
|
||||
for (const field of roles[role].codes)
|
||||
if (
|
||||
expert[field] != null &&
|
||||
(!/^\d+$/.test(expert[field]) ||
|
||||
!Number.isSafeInteger(Number(expert[field])) ||
|
||||
Number(expert[field]) <= 0)
|
||||
)
|
||||
throw new SeedError("Invalid Fanavaran expert code in JSON.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function databaseConfig() {
|
||||
const env = { ...process.env },
|
||||
filename = path.resolve(__dirname, "../../../.env");
|
||||
if (fs.existsSync(filename))
|
||||
for (const line of fs.readFileSync(filename, "utf8").split(/\r?\n/)) {
|
||||
const match = line.match(/^\s*(?:export\s+)?([A-Za-z_]\w*)\s*=\s*(.*)$/);
|
||||
if (!match || Object.hasOwn(env, match[1])) continue;
|
||||
let value = match[2].trim();
|
||||
if (/^["']/.test(value))
|
||||
value = value.slice(1, value.lastIndexOf(value[0]));
|
||||
else value = value.replace(/\s+#.*$/, "").trim();
|
||||
env[match[1]] = value;
|
||||
}
|
||||
let uri = env.MONGO_URI ?? "";
|
||||
for (let pass = 0; pass < 10 && /\$\{/.test(uri); pass++)
|
||||
uri = uri.replace(/\$\{([^}]+)\}/g, (_, key) => env[key] ?? "");
|
||||
if (!/^mongodb(?:\+srv)?:\/\//.test(uri) || /\$\{/.test(uri))
|
||||
throw new SeedError(
|
||||
"MONGO_URI is missing or invalid in the API environment.",
|
||||
);
|
||||
return {
|
||||
uri,
|
||||
options: {
|
||||
tls: env.MONGO_TLS === "true",
|
||||
tlsAllowInvalidCertificates: env.MONGO_TLS_ALLOW_INVALID_CERTS === "true",
|
||||
serverSelectionTimeoutMS: 10000,
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function buildPlan(db, seed = loadMergedData()) {
|
||||
validateData(seed);
|
||||
const clients = await db
|
||||
.collection("clients")
|
||||
.find({ clientCode: 8 }, { projection: { _id: 1 } })
|
||||
.toArray();
|
||||
if (clients.length !== 1)
|
||||
throw new SeedError(
|
||||
"Exactly one existing Parsian insurer (clientCode=8) is required.",
|
||||
);
|
||||
const clientKey = clients[0]._id;
|
||||
const branches = await db
|
||||
.collection("branches")
|
||||
.find({ clientKey: { $in: [clientKey, string(clientKey)] } })
|
||||
.toArray();
|
||||
const branchIds = new Map(),
|
||||
plan = [];
|
||||
plan.notes = [...(seed.notes ?? [])];
|
||||
function conditionalUpdate(record, changes) {
|
||||
const filter = { _id: record._id, clientKey: record.clientKey };
|
||||
for (const field of Object.keys(changes))
|
||||
filter[field] = Object.hasOwn(record, field)
|
||||
? record[field]
|
||||
: { $exists: false };
|
||||
return filter;
|
||||
}
|
||||
for (const branch of seed.branches) {
|
||||
const matches = branches.filter(
|
||||
(record) => string(record.code) === branch.code,
|
||||
);
|
||||
if (matches.length > 1) {
|
||||
plan.notes.push({
|
||||
branchCode: branch.code,
|
||||
action: "skipped-ambiguous-database-branch",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const current = matches[0],
|
||||
_id = current?._id ?? new mongoose.Types.ObjectId();
|
||||
branchIds.set(branch.code, _id);
|
||||
if (!current) {
|
||||
plan.push({
|
||||
kind: "branch",
|
||||
collection: "branches",
|
||||
document: {
|
||||
...branch,
|
||||
_id,
|
||||
clientKey,
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const changes = {};
|
||||
for (const [field, value] of Object.entries(branch))
|
||||
if (field !== "code" && empty(current[field]) && !empty(value))
|
||||
changes[field] = value;
|
||||
if (Object.keys(changes).length)
|
||||
plan.push({
|
||||
kind: "branchUpdate",
|
||||
collection: "branches",
|
||||
filter: conditionalUpdate(current, changes),
|
||||
changes,
|
||||
});
|
||||
}
|
||||
const identifiers = seed.experts.map((expert) => expert.nationalCode);
|
||||
const storedCodes = [
|
||||
...new Set([
|
||||
...identifiers,
|
||||
...identifiers.map((value) => String(Number(value))),
|
||||
...identifiers.map(Number),
|
||||
]),
|
||||
];
|
||||
const existingByRole = {};
|
||||
for (const [role, config] of Object.entries(roles))
|
||||
existingByRole[role] = await db
|
||||
.collection(config.collection)
|
||||
.find(
|
||||
{
|
||||
$or: [
|
||||
{ nationalCode: { $in: storedCodes } },
|
||||
{ username: { $in: identifiers } },
|
||||
{ email: { $in: identifiers } },
|
||||
],
|
||||
},
|
||||
{ projection: { password: 0, otp: 0, personalDocs: 0 } },
|
||||
)
|
||||
.toArray();
|
||||
|
||||
for (const expert of seed.experts) {
|
||||
const matches = {};
|
||||
for (const role of Object.keys(roles))
|
||||
matches[role] = existingByRole[role].filter(
|
||||
(record) =>
|
||||
string(record.nationalCode).padStart(10, "0") ===
|
||||
expert.nationalCode ||
|
||||
record.username === expert.nationalCode ||
|
||||
record.email === expert.nationalCode,
|
||||
);
|
||||
const validExisting = (role) => {
|
||||
const records = matches[role];
|
||||
const record = records.length === 1 ? records[0] : null;
|
||||
return record &&
|
||||
string(record.clientKey) === string(clientKey) &&
|
||||
string(record.nationalCode).padStart(10, "0") === expert.nationalCode &&
|
||||
(!record.role || record.role === role)
|
||||
? record
|
||||
: null;
|
||||
};
|
||||
for (const role of expert.roles) {
|
||||
const config = roles[role],
|
||||
records = matches[role];
|
||||
const note = (action, details = {}) =>
|
||||
plan.notes.push({
|
||||
nationalCode: `******${expert.nationalCode.slice(-4)}`,
|
||||
role,
|
||||
action,
|
||||
...details,
|
||||
});
|
||||
if (
|
||||
records.length > 1 ||
|
||||
records.some((record) => string(record.clientKey) !== string(clientKey))
|
||||
) {
|
||||
note("skipped-ambiguous-or-foreign-insurer-account");
|
||||
continue;
|
||||
}
|
||||
const current = records[0];
|
||||
if (current && !validExisting(role)) {
|
||||
note("skipped-different-identity-or-role");
|
||||
continue;
|
||||
}
|
||||
const sourceLocations = expert.roleLocations?.[role] ??
|
||||
expert.locations ?? [
|
||||
{
|
||||
id: expert.branchCode,
|
||||
name: seed.branches.find(
|
||||
(branch) => branch.code === expert.branchCode,
|
||||
)?.name,
|
||||
},
|
||||
];
|
||||
const counterpart =
|
||||
role === "damage_expert"
|
||||
? validExisting("file_reviewer")
|
||||
: role === "file_reviewer"
|
||||
? validExisting("damage_expert")
|
||||
: null;
|
||||
const inheritedBranch =
|
||||
!current?.branchId &&
|
||||
counterpart?.branchId &&
|
||||
branches.find(
|
||||
(branch) => string(branch._id) === string(counterpart.branchId),
|
||||
);
|
||||
const branchId =
|
||||
current?.branchId ??
|
||||
(inheritedBranch
|
||||
? inheritedBranch._id
|
||||
: branchIds.get(sourceLocations[0]?.id));
|
||||
const primaryBranch =
|
||||
branches.find((branch) => string(branch._id) === string(branchId)) ??
|
||||
seed.branches.find(
|
||||
(branch) => string(branchIds.get(branch.code)) === string(branchId),
|
||||
);
|
||||
if (!branchId || !primaryBranch) {
|
||||
note("skipped-unresolved-primary-branch");
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
current?.branchId &&
|
||||
string(primaryBranch.code) !== sourceLocations[0]?.id
|
||||
)
|
||||
note("kept-existing-primary-branch", {
|
||||
primaryBranchCode: string(primaryBranch.code),
|
||||
addedBranchCodes: sourceLocations.map((location) => location.id),
|
||||
});
|
||||
const locations = mergeLocations(
|
||||
current?.locations ?? [],
|
||||
[{ id: primaryBranch.code, name: primaryBranch.name }],
|
||||
sourceLocations,
|
||||
!current ? (counterpart?.locations ?? []) : [],
|
||||
);
|
||||
const codes = {};
|
||||
for (const field of config.codes) {
|
||||
const candidates = field.endsWith("ExpertiseClaim")
|
||||
? [validExisting("file_reviewer"), validExisting("damage_expert")]
|
||||
: [validExisting("file_maker"), validExisting("damage_expert")];
|
||||
const inherited = candidates
|
||||
.map((record) => record?.[field])
|
||||
.find(
|
||||
(value) =>
|
||||
/^\d+$/.test(string(value)) &&
|
||||
Number(value) > 0 &&
|
||||
Number.isSafeInteger(Number(value)),
|
||||
);
|
||||
if (!empty(inherited) || !empty(expert[field]))
|
||||
codes[field] = string(inherited ?? expert[field]);
|
||||
if (
|
||||
!empty(current?.[field]) &&
|
||||
!empty(expert[field]) &&
|
||||
string(current[field]) !== expert[field]
|
||||
)
|
||||
note("kept-existing-code", { field });
|
||||
}
|
||||
const values = {
|
||||
firstName: expert.firstName,
|
||||
lastName: expert.lastName,
|
||||
username: expert.nationalCode,
|
||||
nationalCode: expert.nationalCode,
|
||||
role,
|
||||
clientKey,
|
||||
branchId,
|
||||
locations,
|
||||
city: primaryBranch.city,
|
||||
state: primaryBranch.state,
|
||||
...(expert.mobile ? { mobile: expert.mobile } : {}),
|
||||
...(role === "damage_expert"
|
||||
? { userType: "legal", insuActivityCo: string(clientKey) }
|
||||
: {}),
|
||||
...codes,
|
||||
};
|
||||
if (!current) {
|
||||
plan.push({
|
||||
kind: "create",
|
||||
collection: config.collection,
|
||||
role,
|
||||
document: {
|
||||
...values,
|
||||
isActive: true,
|
||||
otp: "",
|
||||
createdAt: new Date(),
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const changes = {};
|
||||
for (const [field, value] of Object.entries(values)) {
|
||||
if (field === "clientKey") continue;
|
||||
if (field === "locations") {
|
||||
if (JSON.stringify(current.locations ?? []) !== JSON.stringify(value))
|
||||
changes.locations = value;
|
||||
} else if (
|
||||
(field === "nationalCode" &&
|
||||
current.nationalCode !== expert.nationalCode) ||
|
||||
empty(current[field])
|
||||
)
|
||||
changes[field] = value;
|
||||
}
|
||||
plan.push({
|
||||
kind: Object.keys(changes).length ? "update" : "keep",
|
||||
collection: config.collection,
|
||||
role,
|
||||
filter: conditionalUpdate(current, changes),
|
||||
changes,
|
||||
});
|
||||
}
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
async function indexes(collection) {
|
||||
try {
|
||||
return await collection.indexes();
|
||||
} catch (error) {
|
||||
if (error.code === 26) return [];
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
async function ensureEmailIndex(collection) {
|
||||
const emailKey = (index) =>
|
||||
Object.keys(index.key ?? {}).length === 1 && index.key.email === 1;
|
||||
const legacy = (await indexes(collection)).filter(
|
||||
(index) =>
|
||||
emailKey(index) &&
|
||||
index.unique &&
|
||||
!index.sparse &&
|
||||
!index.partialFilterExpression,
|
||||
);
|
||||
const guard = "remaining_experts_email_guard";
|
||||
if (legacy.length) {
|
||||
// Preserve uniqueness of real emails while allowing multiple email-less logins.
|
||||
await collection.createIndex(
|
||||
{ email: 1 },
|
||||
{
|
||||
name: guard,
|
||||
unique: true,
|
||||
partialFilterExpression: { email: { $type: "string" } },
|
||||
},
|
||||
);
|
||||
for (const index of legacy) await collection.dropIndex(index.name);
|
||||
}
|
||||
if (
|
||||
!(await indexes(collection)).some(
|
||||
(index) => emailKey(index) && index.unique && index.sparse,
|
||||
)
|
||||
)
|
||||
await collection.createIndex(
|
||||
{ email: 1 },
|
||||
{ name: "email_1", unique: true, sparse: true },
|
||||
);
|
||||
if (
|
||||
(await indexes(collection)).some(
|
||||
(index) =>
|
||||
index.name === guard &&
|
||||
emailKey(index) &&
|
||||
index.unique &&
|
||||
JSON.stringify(index.partialFilterExpression) ===
|
||||
JSON.stringify({ email: { $type: "string" } }),
|
||||
)
|
||||
)
|
||||
await collection.dropIndex(guard);
|
||||
}
|
||||
async function hashPassword() {
|
||||
const salt = crypto.randomBytes(16).toString("hex");
|
||||
const derived = await scrypt("123321", salt, 64);
|
||||
return `${salt}:${derived.toString("hex")}`;
|
||||
}
|
||||
async function applyPlan(db, plan, hash = hashPassword) {
|
||||
await db
|
||||
.collection("branches")
|
||||
.createIndex({ clientKey: 1, code: 1 }, { unique: true });
|
||||
for (const role of new Set(
|
||||
plan.filter((action) => action.role).map((action) => action.role),
|
||||
)) {
|
||||
const collection = db.collection(roles[role].collection);
|
||||
await ensureEmailIndex(collection);
|
||||
await collection.createIndex(
|
||||
role === "damage_expert"
|
||||
? { nationalCode: 1 }
|
||||
: { clientKey: 1, nationalCode: 1 },
|
||||
role === "damage_expert"
|
||||
? { unique: true }
|
||||
: { unique: true, sparse: true },
|
||||
);
|
||||
}
|
||||
for (const action of plan) {
|
||||
const collection = db.collection(action.collection);
|
||||
if (action.kind === "branch") await collection.insertOne(action.document);
|
||||
if (action.kind === "create")
|
||||
await collection.insertOne({
|
||||
...action.document,
|
||||
password: await hash(),
|
||||
});
|
||||
if (["update", "branchUpdate"].includes(action.kind)) {
|
||||
const result = await collection.updateOne(action.filter, {
|
||||
$set: { ...action.changes, updatedAt: new Date() },
|
||||
});
|
||||
if (result.matchedCount !== 1)
|
||||
throw new SeedError(
|
||||
"An account changed after preflight. Import stopped instead of overwriting it; rerun after reviewing.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function main(argv = process.argv.slice(2)) {
|
||||
if (argv.some((arg) => arg !== "--dry-run"))
|
||||
throw new SeedError("Usage: npm run seed:parsian-remaining -- [--dry-run]");
|
||||
const dryRun = argv.includes("--dry-run");
|
||||
const data = loadMergedData();
|
||||
const config = databaseConfig(),
|
||||
connection = mongoose.createConnection(config.uri, config.options);
|
||||
try {
|
||||
try {
|
||||
await connection.asPromise();
|
||||
} catch {
|
||||
throw new SeedError(
|
||||
"Could not connect to MongoDB. Check the API environment and TLS settings.",
|
||||
);
|
||||
}
|
||||
const plan = await buildPlan(connection.db);
|
||||
console.log({
|
||||
dryRun,
|
||||
clientCode: data.clientCode,
|
||||
people: data.experts.length,
|
||||
branchesToCreate: plan.filter((action) => action.kind === "branch")
|
||||
.length,
|
||||
branchesToFill: plan.filter((action) => action.kind === "branchUpdate")
|
||||
.length,
|
||||
accountsToCreate: plan.filter((action) => action.kind === "create")
|
||||
.length,
|
||||
accountsToFill: plan.filter((action) => action.kind === "update").length,
|
||||
accountsUnchanged: plan.filter((action) => action.kind === "keep").length,
|
||||
skippedAccounts: plan.notes.filter(
|
||||
(note) => note.role && note.action.startsWith("skipped-"),
|
||||
).length,
|
||||
mergeNotes: plan.notes,
|
||||
skippedSpreadsheetRows: data.skippedRows.flatMap((row) => row.rows),
|
||||
});
|
||||
if (dryRun) return;
|
||||
await applyPlan(connection.db, plan);
|
||||
console.log(
|
||||
"Combined Parsian experts seeded successfully. Existing passwords, primary branches, codes and active states were preserved.",
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
if (require.main === module)
|
||||
main().catch((error) => {
|
||||
console.error(
|
||||
error instanceof SeedError
|
||||
? error.message
|
||||
: "Seed stopped because of a database/index error. Existing passwords were not reset. Review a dry-run before retrying.",
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
module.exports = {
|
||||
validateData,
|
||||
loadMergedData,
|
||||
mergeLocations,
|
||||
buildPlan,
|
||||
applyPlan,
|
||||
hashPassword,
|
||||
ensureEmailIndex,
|
||||
main,
|
||||
};
|
||||
@@ -0,0 +1,390 @@
|
||||
const { test } = require("node:test");
|
||||
const assert = require("node:assert/strict");
|
||||
const { isDeepStrictEqual } = require("node:util");
|
||||
const mongoose = require("mongoose");
|
||||
const {
|
||||
loadMergedData,
|
||||
buildPlan,
|
||||
applyPlan,
|
||||
} = require("./seed-remaining-experts");
|
||||
|
||||
const nationalCode = "0012345678";
|
||||
const branch = (code, name, address = "") => ({
|
||||
code,
|
||||
name,
|
||||
city: "تهران",
|
||||
state: "تهران",
|
||||
address,
|
||||
isActive: true,
|
||||
});
|
||||
const west = branch("210050", "شعبه غرب", "نشانی اصلی");
|
||||
const poonak = branch("210110", "شعبه پونک");
|
||||
function sources() {
|
||||
return {
|
||||
branches: { clientCode: 8, branches: [west] },
|
||||
reviewers: {
|
||||
clientCode: 8,
|
||||
fileReviewers: [
|
||||
{
|
||||
nationalCode,
|
||||
firstName: "نام",
|
||||
lastName: "آزمایشی",
|
||||
locations: [{ id: west.code, name: west.name }],
|
||||
ThirdPartyExpertiseClaim: "11",
|
||||
CarBodyExpertiseClaim: "12",
|
||||
},
|
||||
],
|
||||
},
|
||||
makers: {
|
||||
clientCode: 8,
|
||||
fileMakers: [
|
||||
{
|
||||
nationalCode,
|
||||
firstName: "نام",
|
||||
lastName: "آزمایشی",
|
||||
locations: [{ id: poonak.code, name: poonak.name }],
|
||||
ThirdPartyClaimExpertId: "21",
|
||||
},
|
||||
],
|
||||
},
|
||||
legacy: { clientCode: 8, fieldExperts: [] },
|
||||
remaining: {
|
||||
clientCode: 8,
|
||||
branches: [poonak, { ...west, address: "" }],
|
||||
skippedRows: [],
|
||||
experts: [
|
||||
{
|
||||
nationalCode,
|
||||
firstName: "نام",
|
||||
lastName: "آزمایشی",
|
||||
branchCode: poonak.code,
|
||||
roles: ["damage_expert", "file_reviewer"],
|
||||
ThirdPartyExpertiseClaim: "99",
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
const same = (a, b) =>
|
||||
Array.isArray(a) || Array.isArray(b)
|
||||
? isDeepStrictEqual(a, b)
|
||||
: String(a ?? "") === String(b ?? "");
|
||||
function matches(record, filter) {
|
||||
return Object.entries(filter).every(([key, value]) => {
|
||||
if (key === "$or") return value.some((part) => matches(record, part));
|
||||
if (value?.$in) return value.$in.some((entry) => same(record[key], entry));
|
||||
if (value?.$exists !== undefined)
|
||||
return (record[key] !== undefined) === value.$exists;
|
||||
return same(record[key], value);
|
||||
});
|
||||
}
|
||||
function database() {
|
||||
const clientKey = new mongoose.Types.ObjectId();
|
||||
const store = {
|
||||
clients: [{ _id: clientKey, clientCode: 8 }],
|
||||
branches: [],
|
||||
"damage-expert": [],
|
||||
"file-reviewer": [],
|
||||
"file-maker": [],
|
||||
};
|
||||
const writes = [],
|
||||
indexMap = {};
|
||||
return {
|
||||
clientKey,
|
||||
store,
|
||||
writes,
|
||||
collection(name) {
|
||||
assert.ok(
|
||||
Object.hasOwn(store, name),
|
||||
`The seed must not access case/history collections: ${name}`,
|
||||
);
|
||||
indexMap[name] ??= [{ key: { email: 1 }, name: "email_1", unique: true }];
|
||||
return {
|
||||
find: (filter) => ({
|
||||
toArray: async () =>
|
||||
store[name].filter((record) => matches(record, filter)),
|
||||
}),
|
||||
indexes: async () => indexMap[name],
|
||||
createIndex: async (key, options) => {
|
||||
const label =
|
||||
options.name ??
|
||||
Object.entries(key)
|
||||
.map(([field, order]) => `${field}_${order}`)
|
||||
.join("_");
|
||||
writes.push({ action: "index", name, label });
|
||||
if (!indexMap[name].some((index) => index.name === label))
|
||||
indexMap[name].push({ key, name: label, ...options });
|
||||
},
|
||||
dropIndex: async (label) => {
|
||||
writes.push({ action: "drop", name, label });
|
||||
indexMap[name] = indexMap[name].filter(
|
||||
(index) => index.name !== label,
|
||||
);
|
||||
},
|
||||
insertOne: async (record) => {
|
||||
store[name].push({
|
||||
...record,
|
||||
_id: record._id ?? new mongoose.Types.ObjectId(),
|
||||
});
|
||||
writes.push({ action: "insert", name });
|
||||
},
|
||||
updateOne: async (filter, update) => {
|
||||
const record = store[name].find((row) => matches(row, filter));
|
||||
if (!record) return { matchedCount: 0 };
|
||||
Object.assign(record, update.$set);
|
||||
writes.push({ action: "update", name });
|
||||
return { matchedCount: 1 };
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
function existingReviewer(db) {
|
||||
const existingWest = {
|
||||
...west,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
isActive: false,
|
||||
address: "",
|
||||
};
|
||||
db.store.branches.push(existingWest);
|
||||
const reviewer = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
nationalCode,
|
||||
role: "file_reviewer",
|
||||
clientKey: db.clientKey,
|
||||
branchId: existingWest._id,
|
||||
locations: [{ id: west.code, name: west.name }],
|
||||
password: "kept-password",
|
||||
username: "kept-alias",
|
||||
isActive: false,
|
||||
ThirdPartyExpertiseClaim: "77",
|
||||
};
|
||||
db.store["file-reviewer"].push(reviewer);
|
||||
return { existingWest, reviewer };
|
||||
}
|
||||
|
||||
test("merges all real JSON sources and resolves the reported branch/code disagreements", () => {
|
||||
const merged = loadMergedData();
|
||||
assert.equal(merged.experts.length, 120);
|
||||
assert.equal(merged.branches.length, 50);
|
||||
for (const [role, expected] of [
|
||||
["damage_expert", 88],
|
||||
["file_reviewer", 88],
|
||||
["file_maker", 39],
|
||||
])
|
||||
assert.equal(
|
||||
merged.experts.filter((expert) => expert.roles.includes(role)).length,
|
||||
expected,
|
||||
);
|
||||
const reported = merged.experts.find((expert) =>
|
||||
expert.nationalCode.endsWith("8521"),
|
||||
);
|
||||
assert.deepEqual(
|
||||
reported.roleLocations.file_reviewer.map((location) => location.id),
|
||||
["210050", "210110"],
|
||||
);
|
||||
const codes = merged.experts.find((expert) =>
|
||||
expert.nationalCode.endsWith("8118"),
|
||||
);
|
||||
assert.equal(codes.ThirdPartyExpertiseClaim, "3985");
|
||||
assert.equal(codes.CarBodyExpertiseClaim, "3986");
|
||||
assert.ok(
|
||||
merged.notes.some((note) => note.action === "kept-original-source-code"),
|
||||
);
|
||||
});
|
||||
|
||||
test("retains role-specific source branches and the original address when building a fresh database", async () => {
|
||||
const db = database(),
|
||||
seed = loadMergedData(sources());
|
||||
const plan = await buildPlan(db, seed);
|
||||
assert.equal(
|
||||
db.writes.length,
|
||||
0,
|
||||
"Planning/dry-run must not write indexes or documents",
|
||||
);
|
||||
await applyPlan(db, plan, async () => "new-hash");
|
||||
assert.equal(
|
||||
db.store.branches.find((record) => record.code === west.code).address,
|
||||
west.address,
|
||||
);
|
||||
const claim = db.store["damage-expert"][0],
|
||||
maker = db.store["file-maker"][0];
|
||||
assert.equal(
|
||||
String(claim.branchId),
|
||||
String(db.store.branches.find((record) => record.code === west.code)._id),
|
||||
);
|
||||
assert.equal(
|
||||
String(maker.branchId),
|
||||
String(db.store.branches.find((record) => record.code === poonak.code)._id),
|
||||
);
|
||||
assert.equal(claim.ThirdPartyExpertiseClaim, "11");
|
||||
assert.equal(claim.ThirdPartyClaimExpertId, "21");
|
||||
assert.equal(maker.ThirdPartyExpertiseClaim, undefined);
|
||||
});
|
||||
|
||||
test("reconciles the complete original Tehran seed with the remaining list without aborting", async () => {
|
||||
const db = database();
|
||||
for (const record of require("./branches.json").branches)
|
||||
db.store.branches.push({
|
||||
...record,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
});
|
||||
for (const [file, key, role, collection] of [
|
||||
[
|
||||
"./file-reviewers.json",
|
||||
"fileReviewers",
|
||||
"file_reviewer",
|
||||
"file-reviewer",
|
||||
],
|
||||
["./file-makers.json", "fileMakers", "file_maker", "file-maker"],
|
||||
])
|
||||
for (const record of require(file)[key]) {
|
||||
db.store[collection].push({
|
||||
...record,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
branchId: db.store.branches.find(
|
||||
(branch) => branch.code === record.locations[0].id,
|
||||
)._id,
|
||||
username: record.nationalCode,
|
||||
password: "preserved",
|
||||
role,
|
||||
isActive: true,
|
||||
});
|
||||
}
|
||||
const reviewer = db.store["file-reviewer"].find((record) =>
|
||||
record.nationalCode.endsWith("8521"),
|
||||
);
|
||||
const before = {
|
||||
id: String(reviewer._id),
|
||||
branchId: String(reviewer.branchId),
|
||||
};
|
||||
const plan = await buildPlan(db);
|
||||
assert.equal(plan.filter((action) => action.kind === "branch").length, 44);
|
||||
assert.equal(plan.filter((action) => action.kind === "create").length, 171);
|
||||
assert.ok(!plan.notes.some((note) => note.action.startsWith("skipped-")));
|
||||
await applyPlan(db, plan, async () => "new-hash");
|
||||
assert.equal(db.store.branches.length, 50);
|
||||
assert.equal(db.store["damage-expert"].length, 88);
|
||||
assert.equal(db.store["file-reviewer"].length, 88);
|
||||
assert.equal(db.store["file-maker"].length, 39);
|
||||
assert.equal(String(reviewer._id), before.id);
|
||||
assert.equal(String(reviewer.branchId), before.branchId);
|
||||
assert.equal(reviewer.password, "preserved");
|
||||
assert.deepEqual(
|
||||
reviewer.locations.map((location) => location.id),
|
||||
["210050", "210110"],
|
||||
);
|
||||
const again = await buildPlan(db);
|
||||
assert.ok(again.every((action) => action.kind === "keep"));
|
||||
});
|
||||
|
||||
test("merges existing reviewer locations/codes without moving it or replacing credentials; new claim inherits its branch/codes", async () => {
|
||||
const db = database(),
|
||||
{ existingWest, reviewer } = existingReviewer(db);
|
||||
const previousId = String(reviewer._id);
|
||||
const seed = loadMergedData(sources()),
|
||||
plan = await buildPlan(db, seed);
|
||||
assert.ok(
|
||||
plan.notes.some(
|
||||
(note) => note.action === "kept-existing-primary-branch",
|
||||
) === false,
|
||||
);
|
||||
assert.ok(plan.notes.some((note) => note.action === "kept-existing-code"));
|
||||
await applyPlan(db, plan, async () => "new-hash");
|
||||
assert.equal(String(reviewer._id), previousId);
|
||||
assert.equal(String(reviewer.branchId), String(existingWest._id));
|
||||
assert.equal(reviewer.password, "kept-password");
|
||||
assert.equal(reviewer.username, "kept-alias");
|
||||
assert.equal(reviewer.isActive, false);
|
||||
assert.equal(reviewer.ThirdPartyExpertiseClaim, "77");
|
||||
assert.equal(reviewer.CarBodyExpertiseClaim, "12");
|
||||
assert.deepEqual(
|
||||
reviewer.locations.map((location) => location.id),
|
||||
[west.code, poonak.code],
|
||||
);
|
||||
assert.equal(existingWest.isActive, false);
|
||||
assert.equal(existingWest.address, west.address);
|
||||
const claim = db.store["damage-expert"][0];
|
||||
assert.equal(String(claim.branchId), String(reviewer.branchId));
|
||||
assert.equal(claim.ThirdPartyExpertiseClaim, "77");
|
||||
assert.equal(claim.username, nationalCode);
|
||||
assert.equal(claim.password, "new-hash");
|
||||
const again = await buildPlan(db, seed);
|
||||
assert.ok(again.every((action) => action.kind === "keep"));
|
||||
await applyPlan(db, again, async () => {
|
||||
throw new Error("Rerun must not create/reset passwords");
|
||||
});
|
||||
assert.equal(db.store["file-reviewer"].length, 1);
|
||||
assert.equal(db.store["damage-expert"].length, 1);
|
||||
});
|
||||
|
||||
test("an existing primary branch absent from the imported primary is preserved and reported", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
db.store.branches.push({
|
||||
...poonak,
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
clientKey: db.clientKey,
|
||||
});
|
||||
reviewer.branchId = db.store.branches[1]._id;
|
||||
reviewer.locations = [{ id: poonak.code, name: poonak.name }];
|
||||
const plan = await buildPlan(db, loadMergedData(sources()));
|
||||
assert.ok(
|
||||
plan.notes.some((note) => note.action === "kept-existing-primary-branch"),
|
||||
);
|
||||
await applyPlan(db, plan, async () => "hash");
|
||||
assert.equal(String(reviewer.branchId), String(db.store.branches[1]._id));
|
||||
assert.deepEqual(
|
||||
reviewer.locations.map((location) => location.id),
|
||||
[poonak.code, west.code],
|
||||
);
|
||||
});
|
||||
|
||||
test("skips cross-insurer and ambiguous accounts while importing unrelated roles/accounts", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
reviewer.clientKey = new mongoose.Types.ObjectId();
|
||||
const before = { ...reviewer };
|
||||
const plan = await buildPlan(db, loadMergedData(sources()));
|
||||
assert.ok(
|
||||
plan.notes.some(
|
||||
(note) =>
|
||||
note.role === "file_reviewer" && note.action.startsWith("skipped-"),
|
||||
),
|
||||
);
|
||||
await applyPlan(db, plan, async () => "hash");
|
||||
assert.deepEqual(reviewer, before);
|
||||
assert.equal(db.store["damage-expert"].length, 1);
|
||||
assert.equal(db.store["file-maker"].length, 1);
|
||||
});
|
||||
|
||||
test("normalizes a stored numeric national code without changing its account ID", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
reviewer.nationalCode = Number(nationalCode);
|
||||
const id = reviewer._id;
|
||||
await applyPlan(
|
||||
db,
|
||||
await buildPlan(db, loadMergedData(sources())),
|
||||
async () => "hash",
|
||||
);
|
||||
assert.equal(reviewer.nationalCode, nationalCode);
|
||||
assert.equal(reviewer._id, id);
|
||||
});
|
||||
|
||||
test("concurrent location edits are not overwritten by a stale merge", async () => {
|
||||
const db = database(),
|
||||
{ reviewer } = existingReviewer(db);
|
||||
const plan = await buildPlan(db, loadMergedData(sources()));
|
||||
reviewer.locations = [{ id: "999999", name: "ویرایش همزمان" }];
|
||||
await assert.rejects(
|
||||
applyPlan(db, plan, async () => "hash"),
|
||||
/changed after preflight/,
|
||||
);
|
||||
assert.deepEqual(reviewer.locations, [
|
||||
{ id: "999999", name: "ویرایش همزمان" },
|
||||
]);
|
||||
});
|
||||
@@ -4,7 +4,7 @@ set -euo pipefail
|
||||
usage() {
|
||||
cat <<'USAGE'
|
||||
Usage:
|
||||
scripts/fanavaran-auth.sh <tejaratno|parsian>
|
||||
scripts/fanavaran-auth.sh <tejaratno|parsian|moallem>
|
||||
|
||||
Calls Fanavaran GetAppToken, then Login with the returned appToken.
|
||||
Outputs the appToken and authenticationToken, and writes raw responses to:
|
||||
@@ -40,6 +40,15 @@ case "$client" in
|
||||
contract_id='28'
|
||||
location='210050'
|
||||
;;
|
||||
moallem)
|
||||
app_name='ItTalie'
|
||||
app_secret='itT@l!3@api'
|
||||
fanavaran_username='itTalieUser'
|
||||
fanavaran_password='itT@l!3@user'
|
||||
corp_id='5650'
|
||||
contract_id='304'
|
||||
location='30900'
|
||||
;;
|
||||
*)
|
||||
printf 'Unknown Fanavaran client: %s\n\n' "$client" >&2
|
||||
usage >&2
|
||||
@@ -51,6 +60,13 @@ base_url="${FANAVARAN_BASE_URL:-https://apimanager.iraneit.com/BimeApiManager/ap
|
||||
auth_dir="files/fanavaran-auth/$client"
|
||||
mkdir -p "$auth_dir"
|
||||
|
||||
curl_proxy_args() {
|
||||
local proxy="${CURL_PROXY:-${ALL_PROXY:-}}"
|
||||
if [[ -n "$proxy" ]]; then
|
||||
printf '%s' "--proxy $proxy"
|
||||
fi
|
||||
}
|
||||
|
||||
app_token_headers="$auth_dir/get-app-token.headers"
|
||||
app_token_body="$auth_dir/get-app-token.body.json"
|
||||
login_headers="$auth_dir/login.headers"
|
||||
@@ -88,7 +104,9 @@ printf 'Fanavaran client: %s\n' "$client"
|
||||
printf 'Base URL: %s\n\n' "$base_url"
|
||||
|
||||
printf '1. Calling GetAppToken...\n'
|
||||
# shellcheck disable=SC2046
|
||||
curl -sS -D "$app_token_headers" -o "$app_token_body" \
|
||||
$(curl_proxy_args) \
|
||||
-X POST "$base_url/EITAuthentication/GetAppToken" \
|
||||
-H "appname: $app_name" \
|
||||
-H "secret: $app_secret" \
|
||||
@@ -102,7 +120,9 @@ if [[ -z "$app_token" ]]; then
|
||||
fi
|
||||
|
||||
printf '2. Calling Login...\n'
|
||||
# shellcheck disable=SC2046
|
||||
curl -sS -D "$login_headers" -o "$login_body" \
|
||||
$(curl_proxy_args) \
|
||||
-X POST "$base_url/EITAuthentication/Login" \
|
||||
-H "appToken: $app_token" \
|
||||
-H "userName: $fanavaran_username" \
|
||||
|
||||
+685
-57
File diff suppressed because it is too large
Load Diff
Executable
+1361
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,96 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const { test } = require("node:test");
|
||||
|
||||
// Exercise the inquiry entry point without starting the UI or contacting a provider.
|
||||
function inquiryContext(response) {
|
||||
const source = fs.readFileSync(path.join(__dirname, "fanavaran-flow-ui-server.js"), "utf8")
|
||||
.split("const server = http.createServer")[0];
|
||||
const context = vm.createContext({ require, __dirname, process: { env: {} }, Buffer });
|
||||
vm.runInContext(source, context);
|
||||
context.response = response;
|
||||
vm.runInContext(`
|
||||
findOfflinePlate = () => null;
|
||||
getSandhubToken = async () => "test-token";
|
||||
httpJson = async () => response;
|
||||
`, context);
|
||||
return context;
|
||||
}
|
||||
|
||||
for (const [name, json, status] of [
|
||||
["HTTP error JSON", { statusCode: 401, message: "Unauthorized" }, 401],
|
||||
["provider failure", { success: false, message: "No policy found" }, 200],
|
||||
["nested provider failure", { data: { hasError: true, message: "Not found" } }, 200],
|
||||
["empty result", { data: {} }, 200],
|
||||
]) {
|
||||
test(`${name} must not report success with empty vehicle inputs`, async () => {
|
||||
const context = inquiryContext({ code: 0, status, json });
|
||||
const result = await vm.runInContext('inquireVehicle({ client: "tejaratno" })', context);
|
||||
assert.equal(result.ok, false);
|
||||
assert.ok(result.error);
|
||||
});
|
||||
}
|
||||
|
||||
test("successful Tejarat inquiry fills vehicle and policy fields", async () => {
|
||||
const context = inquiryContext({ code: 0, status: 200, json: { data: {
|
||||
mtrnum: "ENGINE-1", shsNam: "CHASSIS-1", vin: "VIN-1", ModelField: "1400",
|
||||
insuranceNumber: "POLICY-1", PlcyUnqCod: "12345",
|
||||
persianStartDate: "1404/01/01", persianEndDate: "1405/01/01",
|
||||
} } });
|
||||
const result = await vm.runInContext('inquireVehicle({ client: "tejaratno" })', context);
|
||||
assert.equal(result.ok, true);
|
||||
assert.deepEqual(JSON.parse(JSON.stringify(result.vehicle)), {
|
||||
MOTOR_NO: "ENGINE-1", CHASSIS_NO: "CHASSIS-1", VIN: "VIN-1", BUILT_YEAR: "1400",
|
||||
POLICY_NO: "POLICY-1", POLICY_CI_NUMBER: "12345",
|
||||
BEGIN_DATE: "1404/01/01", END_DATE: "1405/01/01",
|
||||
});
|
||||
});
|
||||
|
||||
test("policy aliases used by existing inquiry mappings populate all three fields", async () => {
|
||||
const context = inquiryContext({ code: 0, status: 200, json: {
|
||||
MtrNum: "ENGINE-1", LastCompanyDocumentNumber: "POLICY-2",
|
||||
SatrtDate: "1404/02/01", endDate: "1405/02/01",
|
||||
} });
|
||||
const result = await vm.runInContext('inquireVehicle({ client: "tejaratno" })', context);
|
||||
assert.equal(result.vehicle.POLICY_NO, "POLICY-2");
|
||||
assert.equal(result.vehicle.BEGIN_DATE, "1404/02/01");
|
||||
assert.equal(result.vehicle.END_DATE, "1405/02/01");
|
||||
});
|
||||
|
||||
test("flow UI includes every seed expert in each assigned branch and both Kazemi codes", () => {
|
||||
const context = inquiryContext({});
|
||||
const branches = vm.runInContext("parsianBranchSeeds()", context);
|
||||
for (const [file, key, role] of [
|
||||
["file-makers.json", "fileMakers", "makers"],
|
||||
["file-reviewers.json", "fileReviewers", "reviewers"],
|
||||
]) {
|
||||
const seeds = JSON.parse(fs.readFileSync(path.join(__dirname, "data/parsian-tehran", file)))[key];
|
||||
for (const expert of seeds) {
|
||||
for (const location of expert.locations) {
|
||||
assert.ok(branches[location.id][role].some(r => r.name === `${expert.firstName} ${expert.lastName}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
const kazemi = branches["210120"].reviewers.find(r => r.name.includes("کاظمي دولت سرا"));
|
||||
assert.equal(kazemi.tp, "3992");
|
||||
assert.equal(kazemi.body, "3991");
|
||||
});
|
||||
|
||||
test("hull flow derives all three licence replacement states from dates", () => {
|
||||
const script = fs.readFileSync(path.join(__dirname, "fanavaran-flow-test.sh"), "utf8");
|
||||
const start = script.indexOf('const e=process.env, n=(k)=>Number(e[k]), nullable=');
|
||||
const builder = script.slice(start, script.indexOf('\nNODE', start));
|
||||
for (const [issue, expected] of [
|
||||
["1404/08/24", 0], ["1401/08/24", null], ["1394/08/24", 1],
|
||||
["1402/08/24", 0], ["1395/08/24", null],
|
||||
]) {
|
||||
let output = "";
|
||||
vm.runInNewContext(builder, { process: {
|
||||
env: { POLICE_REPORT_DESC: "شرح حادثه", CULPRIT_LICENCE_ISSU_DATE: issue, ACCIDENT_DATE: "1405/08/24" },
|
||||
stdout: { write: text => { output += text; } },
|
||||
} });
|
||||
assert.equal(JSON.parse(output).IsLicenseReplaced, expected, issue);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
const assert = require("node:assert/strict");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const vm = require("node:vm");
|
||||
const { test } = require("node:test");
|
||||
const { spawnSync } = require("node:child_process");
|
||||
const html = fs.readFileSync(path.join(__dirname, "data/fanavaran-flow-ui.html"), "utf8");
|
||||
const shell = fs.readFileSync(path.join(__dirname, "fanavaran-flow-test.sh"), "utf8");
|
||||
|
||||
test("hull selection keeps the registration tab visible and preserves an open registration panel", () => {
|
||||
const tab = { hidden: true, classList: { contains: () => true } };
|
||||
const panel = { hidden: false };
|
||||
const element = { closest: () => ({ querySelector: () => ({}) }) };
|
||||
const context = vm.createContext({
|
||||
q: (id) => id === "FANAVARAN_PRODUCT" ? "CAR_BODY" : "v14",
|
||||
$: () => element,
|
||||
showFormTab: () => assert.fail("switching product must not eject the person tab"),
|
||||
document: {
|
||||
body: { dataset: {} },
|
||||
querySelector: (selector) => selector.includes('panel="person"') ? panel : tab,
|
||||
},
|
||||
});
|
||||
const start = html.indexOf(" function syncProduct()");
|
||||
const end = html.indexOf(" function missingRequiredNotifier", start);
|
||||
vm.runInContext(html.slice(start, end) + "\nsyncProduct();", context);
|
||||
assert.equal(tab.hidden, false);
|
||||
assert.equal(panel.hidden, false);
|
||||
});
|
||||
|
||||
function selectDriver(product, rows, afterCreate = false, requiredRole = "") {
|
||||
const start = shell.indexOf(' DRIVER_ID="$(node -e \'', shell.indexOf(afterCreate ? "create_other_person() {" : "inquire_driver_id() {"));
|
||||
const bodyStart = shell.indexOf("\n", start) + 1;
|
||||
const end = shell.indexOf("\n' ", bodyStart);
|
||||
let selected = "";
|
||||
const exited = {};
|
||||
const context = vm.createContext({
|
||||
require: () => ({ readFileSync: () => JSON.stringify(rows) }),
|
||||
process: { argv: afterCreate ? ["node", "fixture", product, requiredRole] : ["node", "fixture", "166", product, requiredRole], exit: () => { throw exited; } },
|
||||
console: { log: (value) => { selected = String(value); } },
|
||||
});
|
||||
try { vm.runInContext(shell.slice(bodyStart, end), context); }
|
||||
catch (error) { if (error !== exited) throw error; }
|
||||
return selected;
|
||||
}
|
||||
|
||||
for (const afterCreate of [false, true]) {
|
||||
test(`hull ${afterCreate ? "post-registration verification" : "inquiry"} requires role 166`, () => {
|
||||
assert.equal(selectDriver("CAR_BODY", [{ Id: 41, RoleId: 161 }], afterCreate), "");
|
||||
assert.equal(selectDriver("CAR_BODY", [{ Id: 41, RoleId: 161 }, { Id: 42, RoleId: 166 }], afterCreate), "42");
|
||||
});
|
||||
test(`third-party ${afterCreate ? "verification" : "inquiry"} retains role-161 acceptance`, () => {
|
||||
assert.equal(selectDriver("THIRD_PARTY", [{ Id: 41, RoleId: 161 }], afterCreate), "41");
|
||||
});
|
||||
}
|
||||
|
||||
test("the inline UI script parses", () => {
|
||||
const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
|
||||
new vm.Script(script);
|
||||
});
|
||||
|
||||
for (const [client, version] of [["moallem", "v14"], ["tejaratno", "v15"]]) {
|
||||
test(`${client} ${version}: registering a person does not require claim notifier fields`, () => {
|
||||
const context = vm.createContext({
|
||||
q: (id) => ({ FANAVARAN_PRODUCT: "THIRD_PARTY", FANAVARAN_CLIENT: client,
|
||||
FANAVARAN_API_VERSION: version, CLAIM_NOTIFICATION_DATE: "1405/08/30",
|
||||
NOTIFIER_PARTY_ID: "41" })[id] || "",
|
||||
lookupValue: () => "",
|
||||
stateIds: { CLAIM_ID: "" },
|
||||
});
|
||||
const start = html.indexOf(" function missingRequiredNotifier(stage)");
|
||||
const end = html.indexOf(" function envToText", start);
|
||||
vm.runInContext(html.slice(start, end), context);
|
||||
assert.equal(vm.runInContext('missingRequiredNotifier("person")', context), "");
|
||||
assert.match(vm.runInContext('missingRequiredNotifier("base")', context), /NotifierTypeId/);
|
||||
assert.match(vm.runInContext('missingRequiredNotifier("base")', context), /NotifierRelationId/);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
for (const afterCreate of [false, true]) {
|
||||
test(`manual person ${afterCreate ? "verification" : "inquiry"} enforces the selected role even in third-party mode`, () => {
|
||||
assert.equal(selectDriver("THIRD_PARTY", [{ Id: 41, RoleId: 161 }], afterCreate, "166"), "");
|
||||
assert.equal(selectDriver("THIRD_PARTY", [{ Id: 41, RoleId: 161 }, { Id: 42, RoleId: 166 }], afterCreate, "166"), "42");
|
||||
});
|
||||
}
|
||||
|
||||
test("manual role-166 registration checks live inquiry despite a cached driver ID", () => {
|
||||
const start = shell.indexOf("inquire_driver_id() {");
|
||||
const end = shell.indexOf("create_other_person() {", start);
|
||||
const script = `set -euo pipefail
|
||||
${shell.slice(start, end)}
|
||||
is_car_body() { return 1; }
|
||||
ask_var() { :; }
|
||||
info() { :; }
|
||||
ok() { :; }
|
||||
warn() { :; }
|
||||
persist_env() { :; }
|
||||
save_ids() { :; }
|
||||
fv_curl_json() { echo LIVE_INQUIRY; }
|
||||
node() { printf 42; }
|
||||
create_other_person() { echo UNEXPECTED_CREATE; }
|
||||
DRIVER_ID=41
|
||||
DRIVER_IS_INSURER=1
|
||||
DRIVER_NATIONAL_CODE=0012345678
|
||||
DRIVER_BIRTH_YEAR=1360
|
||||
DRIVER_BIRTH_MONTH=1
|
||||
DRIVER_BIRTH_DAY=2
|
||||
FANAVARAN_PRODUCT=THIRD_PARTY
|
||||
FANAVARAN_BIME_URL=https://example.invalid
|
||||
OUT_DIR=/tmp
|
||||
inquire_driver_id 166
|
||||
printf 'RESULT=%s' "$DRIVER_ID"
|
||||
`;
|
||||
const result = spawnSync("/bin/bash", ["-c", script], { encoding: "utf8", timeout: 5000 });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /LIVE_INQUIRY/);
|
||||
assert.match(result.stdout, /RESULT=42/);
|
||||
assert.doesNotMatch(result.stdout, /UNEXPECTED_CREATE/);
|
||||
});
|
||||
|
||||
test("the registration button requires an explicit supported role before sending a request", async () => {
|
||||
const notices = [];
|
||||
let focused = false;
|
||||
const context = vm.createContext({
|
||||
busy: false,
|
||||
ping: async () => true,
|
||||
q: () => "",
|
||||
setStatus: (message) => notices.push(message),
|
||||
showFormTab: (name) => assert.equal(name, "person"),
|
||||
$: (id) => { assert.equal(id, "PERSON_ROLE_ID"); return { focus: () => { focused = true; } }; },
|
||||
api: () => assert.fail("registration cannot run before role selection"),
|
||||
});
|
||||
const start = html.indexOf(" async function runStage(stage)");
|
||||
const end = html.indexOf(' $("LOCATION").addEventListener', start);
|
||||
vm.runInContext(html.slice(start, end), context);
|
||||
await vm.runInContext('runStage("person")', context);
|
||||
assert.equal(focused, true);
|
||||
assert.match(notices[0], /166/);
|
||||
});
|
||||
Executable
+211
@@ -0,0 +1,211 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/yara724"
|
||||
CONFIG_FILE="$CONFIG_DIR/fanavaran-car-parts.env"
|
||||
|
||||
usage() {
|
||||
cat <<'USAGE'
|
||||
Usage: scripts/get-fanavaran-car-parts.sh [--reset]
|
||||
|
||||
Fetches Fanavaran's complete car-components lookup:
|
||||
GET /BimeApi/v2.0/car/base-info/car-components
|
||||
|
||||
On first run, prompts for the Fanavaran credentials and request header values,
|
||||
then saves them with owner-only permissions under ~/.config/yara724/.
|
||||
Use --reset to enter new values.
|
||||
USAGE
|
||||
}
|
||||
|
||||
die() {
|
||||
printf 'Error: %s\n' "$*" >&2
|
||||
exit 1
|
||||
}
|
||||
|
||||
encode() {
|
||||
printf '%s' "$1" | base64 | tr -d '\n'
|
||||
}
|
||||
|
||||
decode() {
|
||||
printf '%s' "$1" | base64 --decode
|
||||
}
|
||||
|
||||
prompt_value() {
|
||||
local label="$1" variable="$2" secret="${3:-false}" value
|
||||
if [[ "$secret" == true ]]; then
|
||||
read -r -s -p "$label: " value
|
||||
printf '\n' >&2
|
||||
else
|
||||
read -r -p "$label: " value
|
||||
fi
|
||||
[[ -n "$value" ]] || die "$label is required"
|
||||
printf -v "$variable" '%s' "$value"
|
||||
}
|
||||
|
||||
save_config() {
|
||||
mkdir -p "$CONFIG_DIR"
|
||||
chmod 700 "$CONFIG_DIR"
|
||||
local temporary_file
|
||||
temporary_file="$(mktemp "$CONFIG_DIR/.fanavaran-car-parts.XXXXXX")"
|
||||
chmod 600 "$temporary_file"
|
||||
{
|
||||
printf 'BASE_URL=%s\n' "$(encode "$base_url")"
|
||||
printf 'APP_NAME=%s\n' "$(encode "$app_name")"
|
||||
printf 'APP_SECRET=%s\n' "$(encode "$app_secret")"
|
||||
printf 'USERNAME=%s\n' "$(encode "$fanavaran_username")"
|
||||
printf 'PASSWORD=%s\n' "$(encode "$fanavaran_password")"
|
||||
printf 'CORP_ID=%s\n' "$(encode "$corp_id")"
|
||||
printf 'CONTRACT_ID=%s\n' "$(encode "$contract_id")"
|
||||
printf 'LOCATION=%s\n' "$(encode "$location")"
|
||||
} > "$temporary_file"
|
||||
mv -f "$temporary_file" "$CONFIG_FILE"
|
||||
}
|
||||
|
||||
load_config() {
|
||||
[[ -f "$CONFIG_FILE" ]] || return 1
|
||||
# Config values are base64 encoded, so this file is safe to parse as data.
|
||||
while IFS='=' read -r key value; do
|
||||
case "$key" in
|
||||
BASE_URL) base_url="$(decode "$value")" ;;
|
||||
APP_NAME) app_name="$(decode "$value")" ;;
|
||||
APP_SECRET) app_secret="$(decode "$value")" ;;
|
||||
USERNAME) fanavaran_username="$(decode "$value")" ;;
|
||||
PASSWORD) fanavaran_password="$(decode "$value")" ;;
|
||||
CORP_ID) corp_id="$(decode "$value")" ;;
|
||||
CONTRACT_ID) contract_id="$(decode "$value")" ;;
|
||||
LOCATION) location="$(decode "$value")" ;;
|
||||
esac
|
||||
done < "$CONFIG_FILE"
|
||||
[[ -n "${base_url:-}" && -n "${app_name:-}" && -n "${app_secret:-}" && \
|
||||
-n "${fanavaran_username:-}" && -n "${fanavaran_password:-}" && \
|
||||
-n "${corp_id:-}" && -n "${contract_id:-}" && -n "${location:-}" ]] ||
|
||||
die "Saved config is incomplete. Run with --reset to re-enter it."
|
||||
}
|
||||
|
||||
prompt_config() {
|
||||
local client
|
||||
printf 'Choose Fanavaran tenant (parsian, tejaratno, moallem).\n'
|
||||
prompt_value 'Tenant' client
|
||||
case "${client,,}" in
|
||||
parsian|tejaratno) base_url_default='https://apimanager.iraneit.com/BimeApiManager/api' ;;
|
||||
moallem) base_url_default='https://api.inssw.ir/BimeApiManager/api' ;;
|
||||
*) die 'Tenant must be parsian, tejaratno, or moallem' ;;
|
||||
esac
|
||||
|
||||
read -r -p "API manager base URL [$base_url_default]: " base_url
|
||||
base_url="${base_url:-$base_url_default}"
|
||||
base_url="${base_url%/}"
|
||||
[[ "$base_url" == https://* ]] || die 'Base URL must use HTTPS'
|
||||
|
||||
prompt_value 'App name' app_name
|
||||
prompt_value 'App secret' app_secret true
|
||||
prompt_value 'Fanavaran username' fanavaran_username
|
||||
prompt_value 'Fanavaran password' fanavaran_password true
|
||||
prompt_value 'CorpId' corp_id
|
||||
prompt_value 'ContractId' contract_id
|
||||
prompt_value 'Location' location
|
||||
save_config
|
||||
printf 'Credentials saved privately to %s\n' "$CONFIG_FILE" >&2
|
||||
}
|
||||
|
||||
read_response_header() {
|
||||
local wanted="$1" file="$2"
|
||||
awk -F: -v wanted="$wanted" '
|
||||
tolower($1) == tolower(wanted) {
|
||||
sub(/^[^:]*:[[:space:]]*/, "")
|
||||
sub(/\r$/, "")
|
||||
print
|
||||
exit
|
||||
}
|
||||
' "$file"
|
||||
}
|
||||
|
||||
check_http_status() {
|
||||
local status="$1" body_file="$2" label="$3"
|
||||
if [[ ! "$status" =~ ^2[0-9][0-9]$ ]]; then
|
||||
printf '%s failed (HTTP %s). Response:\n' "$label" "$status" >&2
|
||||
cat "$body_file" >&2
|
||||
printf '\n' >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
reset_config=false
|
||||
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
|
||||
usage
|
||||
exit 0
|
||||
elif [[ "${1:-}" == "--reset" ]]; then
|
||||
reset_config=true
|
||||
elif [[ $# -gt 0 ]]; then
|
||||
usage >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
if [[ "$reset_config" == true ]] || ! load_config; then
|
||||
prompt_config
|
||||
fi
|
||||
|
||||
command -v curl >/dev/null || die 'curl is required'
|
||||
command -v base64 >/dev/null || die 'base64 is required'
|
||||
command -v node >/dev/null || die 'node is required to parse the login response'
|
||||
|
||||
temporary_dir="$(mktemp -d)"
|
||||
chmod 700 "$temporary_dir"
|
||||
trap 'rm -rf "$temporary_dir"' EXIT
|
||||
|
||||
printf 'Requesting Fanavaran app token...\n' >&2
|
||||
cat > "$temporary_dir/app-token.headers" <<HEADERS
|
||||
appname: $app_name
|
||||
secret: $app_secret
|
||||
Content-Length: 0
|
||||
HEADERS
|
||||
chmod 600 "$temporary_dir/app-token.headers"
|
||||
app_status="$(curl --silent --show-error --output "$temporary_dir/app-token.body" \
|
||||
--dump-header "$temporary_dir/app-token.response-headers" --write-out '%{http_code}' \
|
||||
--request POST --header "@$temporary_dir/app-token.headers" \
|
||||
"$base_url/EITAuthentication/GetAppToken")"
|
||||
check_http_status "$app_status" "$temporary_dir/app-token.body" 'GetAppToken'
|
||||
app_token="$(read_response_header apptoken "$temporary_dir/app-token.response-headers")"
|
||||
[[ -n "$app_token" ]] || die 'GetAppToken succeeded but no apptoken response header was found'
|
||||
|
||||
printf 'Logging in to Fanavaran...\n' >&2
|
||||
cat > "$temporary_dir/login.headers" <<HEADERS
|
||||
appToken: $app_token
|
||||
userName: $fanavaran_username
|
||||
password: $fanavaran_password
|
||||
Content-Length: 0
|
||||
HEADERS
|
||||
chmod 600 "$temporary_dir/login.headers"
|
||||
login_status="$(curl --silent --show-error --output "$temporary_dir/login.body" \
|
||||
--dump-header "$temporary_dir/login.response-headers" --write-out '%{http_code}' \
|
||||
--request POST --header "@$temporary_dir/login.headers" \
|
||||
"$base_url/EITAuthentication/Login")"
|
||||
check_http_status "$login_status" "$temporary_dir/login.body" 'Login'
|
||||
authentication_token="$(read_response_header authenticationtoken "$temporary_dir/login.response-headers")"
|
||||
if [[ -z "$authentication_token" ]]; then
|
||||
authentication_token="$(node -e '
|
||||
const fs = require("node:fs");
|
||||
try {
|
||||
const body = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
|
||||
process.stdout.write(body.authenticationToken || body.authenticationtoken || body.authentication_token || "");
|
||||
} catch {}
|
||||
' "$temporary_dir/login.body")"
|
||||
fi
|
||||
[[ -n "$authentication_token" ]] || die 'Login succeeded but no authentication token was found'
|
||||
|
||||
cat > "$temporary_dir/lookup.headers" <<HEADERS
|
||||
authenticationToken: $authentication_token
|
||||
CorpId: $corp_id
|
||||
ContractId: $contract_id
|
||||
Location: $location
|
||||
Accept: application/json
|
||||
HEADERS
|
||||
chmod 600 "$temporary_dir/lookup.headers"
|
||||
|
||||
printf 'Fetching complete car-parts lookup...\n' >&2
|
||||
lookup_status="$(curl --silent --show-error --output "$temporary_dir/lookup.body" \
|
||||
--write-out '%{http_code}' --request GET --header "@$temporary_dir/lookup.headers" \
|
||||
"$base_url/BimeApi/v2.0/car/base-info/car-components")"
|
||||
check_http_status "$lookup_status" "$temporary_dir/lookup.body" 'Car-parts lookup'
|
||||
cat "$temporary_dir/lookup.body"
|
||||
printf '\n'
|
||||
@@ -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;
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/** Send one real MIC SMS using .env. Does not start application workers or HTTP routes. */
|
||||
import "reflect-metadata";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { NestFactory } from "@nestjs/core";
|
||||
import { ConfigModule } from "@nestjs/config";
|
||||
import { DatabaseModule } from "../src/core/database/database.module";
|
||||
import { SmsGatewayModule } from "../src/sms-orchestration/provider/sms-gateway.module";
|
||||
import {
|
||||
MicSmsService,
|
||||
normalizeMicMobile,
|
||||
} from "../src/sms-orchestration/provider/mic-sms.service";
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
ConfigModule.forRoot({ isGlobal: true }),
|
||||
DatabaseModule,
|
||||
SmsGatewayModule,
|
||||
],
|
||||
})
|
||||
class MicSmsTestModule {}
|
||||
|
||||
async function main() {
|
||||
const [mobile, message] = process.argv.slice(2);
|
||||
if (!mobile || !normalizeMicMobile(mobile) || !message?.trim()) {
|
||||
console.error('Usage: npm run sms:test:mic -- 09120000000 "پیام آزمایشی"');
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
const app = await NestFactory.createApplicationContext(MicSmsTestModule, {
|
||||
logger: false,
|
||||
abortOnError: false,
|
||||
});
|
||||
try {
|
||||
const result = await app.get(MicSmsService).sendSms(mobile, message);
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
if (!result.success) process.exitCode = 1;
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
main().catch(() => {
|
||||
// Never print configuration, credentials, or raw connection/HTTP errors.
|
||||
console.error(
|
||||
"MIC SMS test could not start. Check database connectivity and MIC SMS environment settings.",
|
||||
);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -1,21 +0,0 @@
|
||||
export enum CarPartEnum {
|
||||
LeftBackFender = "leftBackFender",
|
||||
RightBackFender = "rightBackFender",
|
||||
BackWheel = "backWheel",
|
||||
LeftBackDoor = "leftBackDoor",
|
||||
RightBackDoor = "rightBackDoor",
|
||||
LeftFrontDoor = "leftFrontDoor",
|
||||
RightFrontDoor = "rightFrontDoor",
|
||||
LeftMirror = "leftMirror",
|
||||
RightMirror = "rightMirror",
|
||||
FrontWheel = "frontWheel",
|
||||
LeftFrontFender = "leftFrontFender",
|
||||
RightFrontFender = "RightFrontFender",
|
||||
FrontBumper = "frontBumper",
|
||||
FrontCarWindow = "frontCarWindow",
|
||||
CarHood = "carHood",
|
||||
BackBumper = "backBumper",
|
||||
CarTrunk = "carTrunk",
|
||||
BackCarWindow = "backCarWindow",
|
||||
Roof = "roof",
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
export class PriceDropIF {
|
||||
total: number;
|
||||
carPrice: number;
|
||||
carModel: number;
|
||||
carValue: number[];
|
||||
sumOfSeverity: number;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export enum InPersonDocumentsEnum {
|
||||
NationalCertificate = "nationalCertificate",
|
||||
CarCertificate = "carCertificate",
|
||||
DrivingLicense = "drivingLicense",
|
||||
CarGreenCard = "carGreenCard",
|
||||
Plate = "plate",
|
||||
CarPlate = "carPlate",
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export enum UploaderModeEnum {
|
||||
Sign = "uploadService",
|
||||
Certificate = "certService",
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { SuperAdminController } from "src/super-admin/super-admin.controller";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { ExpertClaimV2Controller } from "src/expert-claim/expert-claim.v2.controller";
|
||||
import { ExpertInsurerController } from "src/expert-insurer/expert-insurer.controller";
|
||||
|
||||
describe("AI analysis file access", () => {
|
||||
const actor = { sub: "actor", clientKey: "tenant" };
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis", "estimateAiAnalysis"])(
|
||||
"expert %s uses the existing file access gate before reading results or scheduling work",
|
||||
async (method) => {
|
||||
const service = {
|
||||
getClaimDetailV2: jest.fn().mockRejectedValue(new ForbiddenException()),
|
||||
};
|
||||
const ai = { list: jest.fn(), retry: jest.fn() },
|
||||
db = { findById: jest.fn() };
|
||||
const controller = new ExpertClaimV2Controller(
|
||||
service as any,
|
||||
ai as any,
|
||||
db as any,
|
||||
{} as any,
|
||||
);
|
||||
await expect(controller[method]("other-tenant", actor)).rejects.toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(db.findById).not.toHaveBeenCalled();
|
||||
expect(ai.list).not.toHaveBeenCalled();
|
||||
expect(ai.retry).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis"])(
|
||||
"insurer %s validates its public file identifier before resolving a claim",
|
||||
async (method) => {
|
||||
const service = {
|
||||
retrieveFileDetailsByPublicId: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new ForbiddenException()),
|
||||
};
|
||||
const ai = { list: jest.fn(), retry: jest.fn() },
|
||||
db = { findById: jest.fn() };
|
||||
const controller = new ExpertInsurerController(
|
||||
service as any,
|
||||
{} as any,
|
||||
ai as any,
|
||||
{} as any,
|
||||
db as any,
|
||||
);
|
||||
await expect(controller[method](actor, "other-tenant")).rejects.toThrow(
|
||||
ForbiddenException,
|
||||
);
|
||||
expect(service.retrieveFileDetailsByPublicId).toHaveBeenCalledWith(
|
||||
"tenant",
|
||||
"other-tenant",
|
||||
);
|
||||
expect(db.findById).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("admin AI tenant selection", () => {
|
||||
it.each(["getAiAnalysis", "retryAiAnalysis"])(
|
||||
"%s resolves the file inside the selected tenant before reading AI results",
|
||||
async (method) => {
|
||||
const insurer = {
|
||||
retrieveFileDetailsByPublicId: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new ForbiddenException()),
|
||||
};
|
||||
const ai = { list: jest.fn(), retry: jest.fn() },
|
||||
db = { findById: jest.fn() };
|
||||
const controller = new SuperAdminController(
|
||||
{} as any,
|
||||
{} as any,
|
||||
insurer as any,
|
||||
ai as any,
|
||||
db as any,
|
||||
);
|
||||
await expect(
|
||||
controller[method]("selected-client", "other-client-file"),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
expect(insurer.retrieveFileDetailsByPublicId).toHaveBeenCalledWith(
|
||||
"selected-client",
|
||||
"other-client-file",
|
||||
);
|
||||
expect(db.findById).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { Types } from "mongoose";
|
||||
import { ForbiddenException } from "@nestjs/common";
|
||||
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||
import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum";
|
||||
|
||||
function setup() {
|
||||
const id = new Types.ObjectId(),
|
||||
userId = new Types.ObjectId().toString();
|
||||
const claim = {
|
||||
_id: id,
|
||||
owner: { fullName: "تست" },
|
||||
workflow: { currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES },
|
||||
damage: {
|
||||
selectedParts: [
|
||||
{ id: 123, name: "Fender", side: "Left", label_fa: "گلگیر" },
|
||||
],
|
||||
},
|
||||
media: {
|
||||
damagedParts: [
|
||||
{
|
||||
id: 123,
|
||||
name: "Fender",
|
||||
path: "files/previous.jpg",
|
||||
url: "/files/previous.jpg",
|
||||
},
|
||||
],
|
||||
carAngles: {},
|
||||
},
|
||||
};
|
||||
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||
const db = {
|
||||
findById: jest.fn().mockResolvedValue(claim),
|
||||
findByIdAndUpdate: jest.fn().mockResolvedValue(claim),
|
||||
};
|
||||
const ai = { enqueue: jest.fn().mockResolvedValue(undefined) };
|
||||
Object.assign(service, {
|
||||
claimCaseDbService: db,
|
||||
aiService: ai,
|
||||
resolveClaimEffectiveUserId: jest.fn().mockResolvedValue(userId),
|
||||
assertEffectiveUserIsDamagedPartyOnClaim: jest
|
||||
.fn()
|
||||
.mockResolvedValue(undefined),
|
||||
autoSubmitFanavaranAttachment: jest.fn().mockResolvedValue({}),
|
||||
logger: { error: jest.fn() },
|
||||
});
|
||||
const file = {
|
||||
path: "files/current.jpg",
|
||||
filename: "current.jpg",
|
||||
} as Express.Multer.File;
|
||||
return { id: id.toString(), userId, service, db, ai, file };
|
||||
}
|
||||
describe("real capture flow AI scheduling", () => {
|
||||
it.each(["user", "field_expert", "file_maker", "file_reviewer"])(
|
||||
"%s capture persists the exact part photo before queueing without waiting for inference",
|
||||
async (role) => {
|
||||
const { id, userId, service, db, ai, file } = setup();
|
||||
const result = await service.capturePartV2(
|
||||
id,
|
||||
{ captureType: "part", captureKey: "123" },
|
||||
file,
|
||||
userId,
|
||||
{ sub: userId, role },
|
||||
);
|
||||
expect(
|
||||
db.findByIdAndUpdate.mock.calls[0][1]["media.damagedParts.0"],
|
||||
).toMatchObject({ path: file.path, fileName: file.filename });
|
||||
expect(ai.enqueue).toHaveBeenCalledWith(
|
||||
id,
|
||||
expect.objectContaining({ path: file.path, fileName: file.filename }),
|
||||
);
|
||||
expect(db.findByIdAndUpdate.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
ai.enqueue.mock.invocationCallOrder[0],
|
||||
);
|
||||
expect(result.captureKey).toBe("123");
|
||||
},
|
||||
);
|
||||
it("does not send car angle photos to the part-analysis queue", async () => {
|
||||
const { id, userId, service, ai, file } = setup();
|
||||
await service.capturePartV2(
|
||||
id,
|
||||
{ captureType: "angle", captureKey: "front" },
|
||||
file,
|
||||
userId,
|
||||
);
|
||||
expect(ai.enqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
it("does not enqueue an unauthorized upload", async () => {
|
||||
const { id, userId, service, ai, file } = setup();
|
||||
service.assertEffectiveUserIsDamagedPartyOnClaim.mockRejectedValue(
|
||||
new ForbiddenException(),
|
||||
);
|
||||
await expect(
|
||||
service.capturePartV2(
|
||||
id,
|
||||
{ captureType: "part", captureKey: "123" },
|
||||
file,
|
||||
userId,
|
||||
),
|
||||
).rejects.toThrow(ForbiddenException);
|
||||
expect(ai.enqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { AiCapture } from "./ai.service";
|
||||
|
||||
/** Use current media only: removed parts and replaced photos belong to history. */
|
||||
export function currentAiCaptures(claim: any): AiCapture[] {
|
||||
const parts = claim?.media?.damagedParts;
|
||||
const rows = Array.isArray(parts)
|
||||
? parts
|
||||
: Object.entries(parts ?? {})
|
||||
.filter(
|
||||
([key]) =>
|
||||
!["front", "back", "left", "right"].includes(key.toLowerCase()),
|
||||
)
|
||||
.map(([, row]) => row);
|
||||
const seen = new Set<string>();
|
||||
return rows.flatMap((row: any) => {
|
||||
if (typeof row?.path !== "string" || !row.path.trim() || seen.has(row.path))
|
||||
return [];
|
||||
seen.add(row.path);
|
||||
return [
|
||||
{
|
||||
path: row.path,
|
||||
fileName: row.fileName,
|
||||
label: row.label_fa || row.name || "تصویر خسارت",
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
|
||||
import { Schema as MongoSchema } from "mongoose";
|
||||
import { AiResult } from "./ai-result";
|
||||
|
||||
@Schema({ collection: "ai-damage-jobs", timestamps: true, versionKey: false })
|
||||
export class AiJob {
|
||||
@Prop({ required: true }) claimId: string;
|
||||
@Prop({ required: true }) imageKey: string;
|
||||
@Prop({ required: true }) path: string;
|
||||
@Prop() fileName?: string;
|
||||
@Prop() carName?: string;
|
||||
@Prop({ default: false }) includePrices?: boolean;
|
||||
@Prop() priceMinSeverity?: string;
|
||||
@Prop({
|
||||
default: "queued",
|
||||
enum: ["queued", "processing", "completed", "failed"],
|
||||
})
|
||||
status: string;
|
||||
@Prop({ default: 0 }) attempts: number;
|
||||
@Prop({ default: () => new Date() }) nextAttemptAt: Date;
|
||||
@Prop() leaseUntil?: Date;
|
||||
@Prop() leaseToken?: string;
|
||||
@Prop() completedAt?: Date;
|
||||
@Prop() error?: string;
|
||||
@Prop() errorCode?: string;
|
||||
@Prop() errorRequestId?: string;
|
||||
@Prop({ type: MongoSchema.Types.Mixed }) result?: AiResult;
|
||||
}
|
||||
export const AiJobSchema = SchemaFactory.createForClass(AiJob);
|
||||
AiJobSchema.index({ claimId: 1, imageKey: 1 }, { unique: true });
|
||||
AiJobSchema.index({ status: 1, nextAttemptAt: 1, leaseUntil: 1 });
|
||||
@@ -0,0 +1,21 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsString, Matches, MaxLength, MinLength } from "class-validator";
|
||||
export class AiPricingRequestDto {
|
||||
@ApiProperty({
|
||||
description: "Current imageKey from the AI analysis response",
|
||||
})
|
||||
@IsString()
|
||||
@Matches(/^[a-f0-9]{64}$/, { message: "شناسه تصویر معتبر نیست." })
|
||||
imageKey: string;
|
||||
|
||||
@ApiProperty({
|
||||
example: "پژو ۲۰۶ تیپ ۲",
|
||||
description:
|
||||
"Expert-confirmed Persian make and model of the damaged vehicle",
|
||||
})
|
||||
@IsString({ message: "نام خودرو را به فارسی وارد کنید." })
|
||||
@MinLength(2, { message: "نام خودرو باید حداقل ۲ کاراکتر باشد." })
|
||||
@MaxLength(100, { message: "نام خودرو باید حداکثر ۱۰۰ کاراکتر باشد." })
|
||||
@Matches(/[آ-ی]/, { message: "نام خودرو را به فارسی وارد کنید." })
|
||||
carName: string;
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import { validateSync } from "class-validator";
|
||||
import { EnvironmentVariables } from "src/core/config/config.schema";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import {
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ServiceUnavailableException,
|
||||
} from "@nestjs/common";
|
||||
import { normalizePartPrice, normalizePricing } from "./ai-pricing";
|
||||
import { normalizeAiResult } from "./ai-result";
|
||||
import { AiService, aiImageKey } from "./ai.service";
|
||||
const raw = {
|
||||
status: "estimated",
|
||||
currency: "toman",
|
||||
totals: { overall: 120000, genuine: 200000, aftermarket: 100000 },
|
||||
components: [
|
||||
{
|
||||
name: "Mirror",
|
||||
overall: {
|
||||
count: 3,
|
||||
min: 100000,
|
||||
median: 120000,
|
||||
max: 200000,
|
||||
wide_spread: true,
|
||||
},
|
||||
},
|
||||
],
|
||||
repair_estimate: { amount: 20000, is_llm_guess: true },
|
||||
confidence: "low",
|
||||
sources: [
|
||||
{ price: 120000, url: "https://shop.example/part", used: true },
|
||||
{ price: 100000, url: "javascript:alert(1)", used: false },
|
||||
],
|
||||
};
|
||||
describe("assessment market pricing", () => {
|
||||
it("converts every monetary field to rials once, including ranges, repair and sources", () => {
|
||||
const price = normalizePartPrice(raw)!;
|
||||
expect(price.currency).toBe("rial");
|
||||
expect(price.originalCurrency).toBe("toman");
|
||||
expect(price.totals).toEqual({
|
||||
overall: 1200000,
|
||||
genuine: 2000000,
|
||||
aftermarket: 1000000,
|
||||
});
|
||||
expect(price.components[0].overall).toEqual({
|
||||
count: 3,
|
||||
min: 1000000,
|
||||
median: 1200000,
|
||||
max: 2000000,
|
||||
wideSpread: true,
|
||||
});
|
||||
expect(price.repairEstimate).toEqual({ amount: 200000, isLlmGuess: true });
|
||||
expect(price.sources[0]).toMatchObject({ price: 1200000, used: true });
|
||||
expect(price.sources[1].url).toBeNull();
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, currency: "rial" })!.totals.overall,
|
||||
).toBe(120000);
|
||||
});
|
||||
it("does not turn missing, unsafe or unsupported amounts into zero", () => {
|
||||
for (const value of [
|
||||
null,
|
||||
undefined,
|
||||
"100",
|
||||
-1,
|
||||
Infinity,
|
||||
Number.MAX_SAFE_INTEGER,
|
||||
])
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, totals: { overall: value } })!.totals
|
||||
.overall,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, currency: "usd" })!.totals.overall,
|
||||
).toBeNull();
|
||||
expect(
|
||||
normalizePartPrice({ ...raw, totals: { overall: 0 } })!.totals.overall,
|
||||
).toBe(0);
|
||||
});
|
||||
it("retains partial summary, detection boxes, pricing metadata and provider cost without converting dollars", () => {
|
||||
const pricing = {
|
||||
car: "پژو ۲۰۶",
|
||||
min_severity: "severe",
|
||||
currency: "toman",
|
||||
totals: { overall: 120000 },
|
||||
complete: false,
|
||||
priced_parts: 1,
|
||||
unpriced_parts: 2,
|
||||
model: "price-model",
|
||||
cost_usd: 0.05,
|
||||
duration_ms: 1200,
|
||||
};
|
||||
expect(normalizePricing(pricing)).toMatchObject({
|
||||
complete: false,
|
||||
pricedParts: 1,
|
||||
unpricedParts: 2,
|
||||
costUsd: 0.05,
|
||||
totals: { overall: 1200000 },
|
||||
});
|
||||
const result = normalizeAiResult({
|
||||
request_id: "r1",
|
||||
pipeline: { price_model: "p1" },
|
||||
damaged_parts: [
|
||||
{
|
||||
part: "Mirror",
|
||||
localized: true,
|
||||
evidence: [
|
||||
{
|
||||
image_index: 0,
|
||||
link_status: "linked",
|
||||
part: { box: { x1: 1, y1: 2, x2: 10, y2: 20 } },
|
||||
},
|
||||
],
|
||||
price: raw,
|
||||
},
|
||||
],
|
||||
case_report: "گزارش",
|
||||
pricing,
|
||||
});
|
||||
expect(result.parts[0].bbox).toEqual({ x1: 1, y1: 2, x2: 10, y2: 20 });
|
||||
expect(result.parts[0].price?.totals.overall).toBe(1200000);
|
||||
expect(result.pipeline?.price_model).toBe("p1");
|
||||
});
|
||||
});
|
||||
function setup(enabled = true, severity = "moderate") {
|
||||
const jobs = {
|
||||
updateMany: jest.fn().mockResolvedValue({}),
|
||||
updateOne: jest.fn().mockResolvedValue({ matchedCount: 1 }),
|
||||
find: jest.fn().mockReturnValue({ lean: async () => [] }),
|
||||
};
|
||||
const service = new AiService(
|
||||
new ConfigService({
|
||||
AI_DAMAGE_ENABLED: String(enabled),
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: severity,
|
||||
}),
|
||||
jobs as any,
|
||||
);
|
||||
return { service, jobs };
|
||||
}
|
||||
const images = [{ path: "files/current.jpg" }];
|
||||
const input = { imageKey: aiImageKey(images[0].path), carName: "پژو ۲۰۶" };
|
||||
describe("explicit assessment pricing requests", () => {
|
||||
it("requires enabled service, a current photo and a usable Persian car name before queuing", async () => {
|
||||
await expect(
|
||||
setup(false).service.requestPricing("c1", images, input),
|
||||
).rejects.toThrow(ServiceUnavailableException);
|
||||
for (const carName of ["", "sedan", "FAW 111", "الف".repeat(50)])
|
||||
await expect(
|
||||
setup().service.requestPricing("c1", images, { ...input, carName }),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
await expect(
|
||||
setup().service.requestPricing("c1", images, {
|
||||
...input,
|
||||
imageKey: aiImageKey("files/removed.jpg"),
|
||||
}),
|
||||
).rejects.toThrow(BadRequestException);
|
||||
});
|
||||
it("stores the input/threshold snapshot and atomically excludes running or already-priced queued jobs", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.requestPricing("c1", images, input);
|
||||
expect(jobs.updateOne.mock.calls[1][0]).toMatchObject({
|
||||
claimId: "c1",
|
||||
imageKey: input.imageKey,
|
||||
status: { $ne: "processing" },
|
||||
$or: [{ status: { $ne: "queued" } }, { includePrices: { $ne: true } }],
|
||||
});
|
||||
expect(jobs.updateOne.mock.calls[1][1].$set).toMatchObject({
|
||||
carName: "پژو ۲۰۶",
|
||||
includePrices: true,
|
||||
priceMinSeverity: "moderate",
|
||||
status: "queued",
|
||||
});
|
||||
jobs.updateOne.mockResolvedValue({ matchedCount: 0 });
|
||||
await expect(service.requestPricing("c1", images, input)).rejects.toThrow(
|
||||
ConflictException,
|
||||
);
|
||||
});
|
||||
it("adapts deployment null to provider-supported minor", () =>
|
||||
expect(setup(true, "null").service.priceMinSeverity).toBe("minor"));
|
||||
});
|
||||
|
||||
describe("viewer pricing retry boundaries", () => {
|
||||
it("excludes price requests when an insurer/admin retries detection", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.retry("c1", images, false);
|
||||
expect(jobs.updateMany).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ includePrices: { $ne: true } }),
|
||||
expect.anything(),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("assessment severity environment", () => {
|
||||
it.each(["minor", "moderate", "severe", "null"])("accepts %s", (value) => {
|
||||
const errors = validateSync(
|
||||
Object.assign(new EnvironmentVariables(), {
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: value,
|
||||
}),
|
||||
{ skipMissingProperties: true },
|
||||
);
|
||||
expect(
|
||||
errors.some((error) => error.property === "AI_DAMAGE_PRICE_MIN_SEVERITY"),
|
||||
).toBe(false);
|
||||
});
|
||||
it("rejects unrecognized severity before deployment starts", () => {
|
||||
const errors = validateSync(
|
||||
Object.assign(new EnvironmentVariables(), {
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: "typo",
|
||||
}),
|
||||
{ skipMissingProperties: true },
|
||||
);
|
||||
expect(
|
||||
errors.some((error) => error.property === "AI_DAMAGE_PRICE_MIN_SEVERITY"),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
/** Market prices are normalized from the provider's tomans to the panel's rials. */
|
||||
export interface AiPriceTotals {
|
||||
overall: number | null;
|
||||
genuine: number | null;
|
||||
aftermarket: number | null;
|
||||
}
|
||||
export interface AiPriceStats {
|
||||
count: number | null;
|
||||
min: number | null;
|
||||
median: number | null;
|
||||
max: number | null;
|
||||
wideSpread: boolean;
|
||||
}
|
||||
export interface AiPartPrice {
|
||||
status: string;
|
||||
message: string | null;
|
||||
query: { car: string | null; part: string | null };
|
||||
currency: "rial";
|
||||
originalCurrency: string | null;
|
||||
totals: AiPriceTotals;
|
||||
components: Array<{
|
||||
name: string | null;
|
||||
overall: AiPriceStats;
|
||||
genuine: AiPriceStats;
|
||||
aftermarket: AiPriceStats;
|
||||
}>;
|
||||
repairEstimate: { amount: number | null; isLlmGuess: boolean } | null;
|
||||
confidence: string | null;
|
||||
notes: string | null;
|
||||
sources: Array<{
|
||||
component: string | null;
|
||||
kind: string | null;
|
||||
price: number | null;
|
||||
title: string | null;
|
||||
url: string | null;
|
||||
used: boolean;
|
||||
unusedReason: string | null;
|
||||
}>;
|
||||
cached: boolean;
|
||||
}
|
||||
export interface AiPricing {
|
||||
car: string | null;
|
||||
minSeverity: string | null;
|
||||
currency: "rial";
|
||||
originalCurrency: string | null;
|
||||
totals: AiPriceTotals;
|
||||
complete: boolean;
|
||||
pricedParts: number | null;
|
||||
unpricedParts: number | null;
|
||||
model: string | null;
|
||||
costUsd: number | null;
|
||||
durationMs: number | null;
|
||||
}
|
||||
const text = (value: unknown) =>
|
||||
typeof value === "string" ? value.trim().slice(0, 2000) : null;
|
||||
const nonnegative = (value: unknown): number | null =>
|
||||
typeof value === "number" && Number.isFinite(value) && value >= 0
|
||||
? value
|
||||
: null;
|
||||
const count = (value: unknown) =>
|
||||
Number.isSafeInteger(value) && (value as number) >= 0
|
||||
? (value as number)
|
||||
: null;
|
||||
const money = (value: unknown, currency: unknown) => {
|
||||
const n = nonnegative(value);
|
||||
if (n === null || !["toman", "rial"].includes(String(currency))) return null;
|
||||
const amount = currency === "toman" ? n * 10 : n;
|
||||
return amount <= Number.MAX_SAFE_INTEGER ? Math.round(amount) : null;
|
||||
};
|
||||
const totals = (value: any, currency: unknown): AiPriceTotals => ({
|
||||
overall: money(value?.overall, currency),
|
||||
genuine: money(value?.genuine, currency),
|
||||
aftermarket: money(value?.aftermarket, currency),
|
||||
});
|
||||
const stats = (value: any, currency: unknown): AiPriceStats => ({
|
||||
count: count(value?.count),
|
||||
min: money(value?.min, currency),
|
||||
median: money(value?.median, currency),
|
||||
max: money(value?.max, currency),
|
||||
wideSpread: value?.wide_spread === true,
|
||||
});
|
||||
const safeUrl = (value: unknown): string | null => {
|
||||
if (typeof value !== "string") return null;
|
||||
try {
|
||||
const u = new URL(value);
|
||||
return ["http:", "https:"].includes(u.protocol) &&
|
||||
!u.username &&
|
||||
!u.password
|
||||
? u.toString()
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
export function normalizePartPrice(raw: any): AiPartPrice | undefined {
|
||||
if (!raw || typeof raw !== "object" || typeof raw.status !== "string")
|
||||
return undefined;
|
||||
const currency = raw.currency;
|
||||
return {
|
||||
status: raw.status.slice(0, 100),
|
||||
message: text(raw.message),
|
||||
query: { car: text(raw.query?.car), part: text(raw.query?.part) },
|
||||
currency: "rial",
|
||||
originalCurrency: text(currency),
|
||||
totals: totals(raw.totals, currency),
|
||||
components: (Array.isArray(raw.components) ? raw.components : [])
|
||||
.slice(0, 100)
|
||||
.map((item: any) => ({
|
||||
name: text(item?.name),
|
||||
overall: stats(item?.overall, currency),
|
||||
genuine: stats(item?.genuine, currency),
|
||||
aftermarket: stats(item?.aftermarket, currency),
|
||||
})),
|
||||
repairEstimate: raw.repair_estimate
|
||||
? {
|
||||
amount: money(raw.repair_estimate.amount, currency),
|
||||
isLlmGuess: raw.repair_estimate.is_llm_guess === true,
|
||||
}
|
||||
: null,
|
||||
confidence: text(raw.confidence),
|
||||
notes: text(raw.notes),
|
||||
cached: raw.cached === true,
|
||||
sources: (Array.isArray(raw.sources) ? raw.sources : [])
|
||||
.slice(0, 200)
|
||||
.map((item: any) => ({
|
||||
component: text(item?.component),
|
||||
kind: text(item?.kind),
|
||||
price: money(item?.price, currency),
|
||||
title: text(item?.title),
|
||||
url: safeUrl(item?.url),
|
||||
used: item?.used === true,
|
||||
unusedReason: text(item?.unused_reason),
|
||||
})),
|
||||
};
|
||||
}
|
||||
export function normalizePricing(raw: any): AiPricing | undefined {
|
||||
if (!raw || typeof raw !== "object") return undefined;
|
||||
return {
|
||||
car: text(raw.car),
|
||||
minSeverity: text(raw.min_severity),
|
||||
currency: "rial",
|
||||
originalCurrency: text(raw.currency),
|
||||
totals: totals(raw.totals, raw.currency),
|
||||
complete: raw.complete === true,
|
||||
pricedParts: count(raw.priced_parts),
|
||||
unpricedParts: count(raw.unpriced_parts),
|
||||
model: text(raw.model),
|
||||
costUsd: nonnegative(raw.cost_usd),
|
||||
durationMs: nonnegative(raw.duration_ms),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { AiAssessmentError, normalizeAiResult } from "./ai-result";
|
||||
import { currentAiCaptures } from "./ai-captures";
|
||||
|
||||
const response = () => ({
|
||||
distinct_damaged_parts_report: {
|
||||
parts: [
|
||||
{
|
||||
part_name: "Headlight",
|
||||
damage_severity: "Severe",
|
||||
part_bbox: { x1: 10.5, y1: 20, x2: 40, y2: 80 },
|
||||
confidence: 0.95,
|
||||
side: "Right",
|
||||
car_side: "front_right",
|
||||
},
|
||||
{
|
||||
part_name: "Headlight",
|
||||
damage_severity: null,
|
||||
part_bbox: null,
|
||||
confidence: null,
|
||||
},
|
||||
],
|
||||
report: "گزارش تصویر",
|
||||
},
|
||||
damaged_part_table: [{ name: "Headlight" }],
|
||||
case_report: "گزارش کامل",
|
||||
});
|
||||
|
||||
describe("AI response contract", () => {
|
||||
const assessment = () => ({
|
||||
request_id: "assessment-123",
|
||||
pipeline: { version: "v1", vlm_model: "model", prompt_version: "p1" },
|
||||
vehicle: { color: "خاکستری", body_type: "sedan" },
|
||||
damaged_parts: [
|
||||
{
|
||||
part: "Mirror",
|
||||
side: "left",
|
||||
severity: "minor",
|
||||
localized: true,
|
||||
damage_types: ["scratch"],
|
||||
descriptions: ["خراش روی آینه"],
|
||||
evidence: [
|
||||
{
|
||||
image_index: 0,
|
||||
filename: "mirror.jpg",
|
||||
view: "front",
|
||||
severity: "minor",
|
||||
link_status: "linked",
|
||||
part: {
|
||||
instance_id: 1,
|
||||
confidence: 0.9,
|
||||
box: { x1: 10, y1: 20, x2: 40, y2: 80 },
|
||||
polygon: [
|
||||
[10, 20],
|
||||
[40, 20],
|
||||
[40, 80],
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
internal_damages: [
|
||||
{
|
||||
category: "radiator",
|
||||
label_fa: "رادیاتور",
|
||||
likelihood: "medium",
|
||||
reason: "نیاز به بررسی",
|
||||
},
|
||||
],
|
||||
case_report: "گزارش ارزیابی",
|
||||
});
|
||||
|
||||
it("normalizes assessments, retaining evidence, damage descriptions and provenance", () => {
|
||||
const result = normalizeAiResult(assessment());
|
||||
expect(result).toMatchObject({
|
||||
requestId: "assessment-123",
|
||||
pipeline: { version: "v1" },
|
||||
vehicle: { color: "خاکستری", bodyType: "sedan" },
|
||||
internalDamages: [
|
||||
{ labelFa: "رادیاتور", likelihood: "medium", reason: "نیاز به بررسی" },
|
||||
],
|
||||
caseReport: "گزارش ارزیابی",
|
||||
parts: [
|
||||
{
|
||||
name: "Mirror",
|
||||
side: "left",
|
||||
severity: "minor",
|
||||
localized: true,
|
||||
damageTypes: ["scratch"],
|
||||
descriptions: ["خراش روی آینه"],
|
||||
confidence: 0.9,
|
||||
bbox: { x1: 10, y1: 20, x2: 40, y2: 80 },
|
||||
evidence: [
|
||||
{
|
||||
imageIndex: 0,
|
||||
instanceId: 1,
|
||||
polygon: [
|
||||
[10, 20],
|
||||
[40, 20],
|
||||
[40, 80],
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps multiple evidence boxes for a part without drawing evidence from another photo", () => {
|
||||
const value = assessment();
|
||||
const evidence = value.damaged_parts[0].evidence;
|
||||
evidence.push({
|
||||
...evidence[0],
|
||||
part: { ...evidence[0].part, instance_id: 2 },
|
||||
});
|
||||
evidence.push({ ...evidence[0], image_index: 1 });
|
||||
const result = normalizeAiResult(value);
|
||||
expect(result.parts).toHaveLength(1);
|
||||
expect(result.parts[0].evidence).toHaveLength(2);
|
||||
expect(
|
||||
result.parts[0].evidence.every((item) => item.imageIndex === 0),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not invent boxes for unlocalized, unlinked or invalid evidence", () => {
|
||||
const value = assessment();
|
||||
value.damaged_parts[0].localized = false;
|
||||
expect(normalizeAiResult(value).parts[0].bbox).toBeNull();
|
||||
value.damaged_parts[0].localized = true;
|
||||
value.damaged_parts[0].evidence[0].link_status = "unlinked";
|
||||
expect(normalizeAiResult(value).parts[0].bbox).toBeNull();
|
||||
value.damaged_parts[0].evidence[0].link_status = "linked";
|
||||
value.damaged_parts[0].evidence[0].part.box.x2 = NaN;
|
||||
value.damaged_parts[0].evidence[0].part.polygon = [[null, null]];
|
||||
expect(normalizeAiResult(value).parts[0].evidence[0]).toMatchObject({
|
||||
bbox: null,
|
||||
polygon: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts zero detections and parts without evidence", () => {
|
||||
const value = assessment();
|
||||
value.damaged_parts[0].evidence = [];
|
||||
expect(normalizeAiResult(value).parts[0]).toMatchObject({
|
||||
bbox: null,
|
||||
evidence: [],
|
||||
});
|
||||
value.damaged_parts = [];
|
||||
expect(normalizeAiResult(value).parts).toEqual([]);
|
||||
});
|
||||
|
||||
it("rejects error envelopes even with an HTTP-success response, preserving code and request id", () => {
|
||||
try {
|
||||
normalizeAiResult({
|
||||
error: {
|
||||
code: "INVALID_IMAGE",
|
||||
message: "Invalid image",
|
||||
request_id: "r-1",
|
||||
},
|
||||
});
|
||||
throw new Error("Expected assessment failure");
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(AiAssessmentError);
|
||||
expect(error).toMatchObject({
|
||||
code: "INVALID_IMAGE",
|
||||
requestId: "r-1",
|
||||
message: "Invalid image",
|
||||
});
|
||||
}
|
||||
expect(() =>
|
||||
normalizeAiResult({ damaged_parts: [], case_report: null }),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
normalizeAiResult({ ...assessment(), internal_damages: {} }),
|
||||
).toThrow();
|
||||
});
|
||||
it("preserves distinct repeated detections, nullable fields and Persian reports without requiring a returned image", () => {
|
||||
const result = normalizeAiResult(response());
|
||||
expect(result.parts).toHaveLength(2);
|
||||
expect(result.parts[0]).toMatchObject({
|
||||
name: "Headlight",
|
||||
severity: "Severe",
|
||||
confidence: 0.95,
|
||||
bbox: { x1: 10.5, y1: 20, x2: 40, y2: 80 },
|
||||
});
|
||||
expect(result.parts[1]).toMatchObject({
|
||||
name: "Headlight",
|
||||
bbox: null,
|
||||
severity: null,
|
||||
confidence: null,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
report: "گزارش تصویر",
|
||||
caseReport: "گزارش کامل",
|
||||
});
|
||||
});
|
||||
it("does not turn corrupt or failed responses into a successful empty analysis", () => {
|
||||
for (const value of [
|
||||
null,
|
||||
{},
|
||||
{ detail: "failure" },
|
||||
{ ...response(), case_report: null },
|
||||
])
|
||||
expect(() => normalizeAiResult(value)).toThrow();
|
||||
});
|
||||
it("accepts a legitimate zero-detection response", () => {
|
||||
const value = response();
|
||||
value.distinct_damaged_parts_report.parts = [];
|
||||
expect(normalizeAiResult(value).parts).toEqual([]);
|
||||
});
|
||||
it("omits corrupt boxes and out-of-range confidence without discarding the part", () => {
|
||||
const value = response();
|
||||
value.distinct_damaged_parts_report.parts[0].part_bbox.x2 = NaN;
|
||||
value.distinct_damaged_parts_report.parts[0].confidence = 1.2;
|
||||
expect(normalizeAiResult(value).parts[0]).toMatchObject({
|
||||
name: "Headlight",
|
||||
bbox: null,
|
||||
confidence: null,
|
||||
});
|
||||
});
|
||||
it("lists current photos only, deduplicates identical files and excludes history and unphotographed additions", () => {
|
||||
const images = currentAiCaptures({
|
||||
media: {
|
||||
damagedParts: [
|
||||
{ path: "files/new.jpg", label_fa: "گلگیر" },
|
||||
{ path: "files/new.jpg" },
|
||||
{ name: "door" },
|
||||
],
|
||||
},
|
||||
damage: {
|
||||
partSelectionHistory: [{ removedParts: [{ path: "files/old.jpg" }] }],
|
||||
},
|
||||
});
|
||||
expect(images).toEqual([
|
||||
{ path: "files/new.jpg", fileName: undefined, label: "گلگیر" },
|
||||
]);
|
||||
expect(
|
||||
currentAiCaptures({
|
||||
media: { damagedParts: { door: { path: "files/door.jpg" } } },
|
||||
}),
|
||||
).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
import {
|
||||
AiPartPrice,
|
||||
AiPricing,
|
||||
normalizePartPrice,
|
||||
normalizePricing,
|
||||
} from "./ai-pricing";
|
||||
export interface AiPart {
|
||||
price?: AiPartPrice;
|
||||
name: string;
|
||||
severity: string | null;
|
||||
confidence: number | null;
|
||||
side: string | null;
|
||||
carSide: string | null;
|
||||
bbox: { x1: number; y1: number; x2: number; y2: number } | null;
|
||||
damageTypes?: string[];
|
||||
descriptions?: string[];
|
||||
localized?: boolean;
|
||||
evidence?: AiEvidence[];
|
||||
}
|
||||
export interface AiEvidence {
|
||||
imageIndex: number;
|
||||
filename: string | null;
|
||||
view: string | null;
|
||||
severity: string | null;
|
||||
linkStatus: string | null;
|
||||
instanceId: number | null;
|
||||
confidence: number | null;
|
||||
bbox: AiPart["bbox"];
|
||||
polygon: [number, number][] | null;
|
||||
}
|
||||
export interface AiResult {
|
||||
pricing?: AiPricing;
|
||||
parts: AiPart[];
|
||||
report: string;
|
||||
caseReport: string;
|
||||
requestId?: string | null;
|
||||
pipeline?: Record<string, string | null>;
|
||||
vehicle?: { color: string | null; bodyType: string | null };
|
||||
internalDamages?: Array<{
|
||||
category: string | null;
|
||||
labelFa: string | null;
|
||||
likelihood: string | null;
|
||||
reason: string | null;
|
||||
}>;
|
||||
}
|
||||
const text = (v: unknown): string | null =>
|
||||
typeof v === "string" ? v.trim().slice(0, 20000) : null;
|
||||
|
||||
export class AiAssessmentError extends Error {
|
||||
constructor(
|
||||
public readonly code: string | null,
|
||||
public readonly requestId: string | null,
|
||||
public readonly httpStatus?: number,
|
||||
message = "AI assessment provider returned an error",
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function boundingBox(value: any): AiPart["bbox"] {
|
||||
return value &&
|
||||
[value.x1, value.y1, value.x2, value.y2].every(
|
||||
(n) => typeof n === "number" && Number.isFinite(n),
|
||||
) &&
|
||||
value.x2 > value.x1 &&
|
||||
value.y2 > value.y1
|
||||
? { x1: value.x1, y1: value.y1, x2: value.x2, y2: value.y2 }
|
||||
: null;
|
||||
}
|
||||
|
||||
const confidence = (value: unknown): number | null =>
|
||||
typeof value === "number" &&
|
||||
Number.isFinite(value) &&
|
||||
value >= 0 &&
|
||||
value <= 1
|
||||
? value
|
||||
: null;
|
||||
|
||||
function strings(value: unknown): string[] {
|
||||
return Array.isArray(value)
|
||||
? value
|
||||
.slice(0, 100)
|
||||
.map(text)
|
||||
.filter((item): item is string => !!item)
|
||||
: [];
|
||||
}
|
||||
|
||||
/** Each durable job uploads exactly one image, whose evidence index is zero. */
|
||||
function normalizeAssessment(raw: any): AiResult {
|
||||
if (!Array.isArray(raw.damaged_parts) || typeof raw.case_report !== "string")
|
||||
throw new Error("Invalid AI assessment response");
|
||||
if (
|
||||
raw.damaged_parts.length > 500 ||
|
||||
(raw.internal_damages != null && !Array.isArray(raw.internal_damages)) ||
|
||||
(raw.internal_damages?.length ?? 0) > 500
|
||||
)
|
||||
throw new Error("Invalid AI assessment collections");
|
||||
let evidenceCount = 0;
|
||||
const parts = raw.damaged_parts.map((part: any): AiPart => {
|
||||
const name = text(part?.part);
|
||||
if (!name || (part.evidence != null && !Array.isArray(part.evidence)))
|
||||
throw new Error("Invalid AI damaged part");
|
||||
evidenceCount += part.evidence?.length ?? 0;
|
||||
if (evidenceCount > 2000) throw new Error("Too many AI evidence records");
|
||||
const evidence: AiEvidence[] = (part.evidence ?? [])
|
||||
.filter((item: any) => item?.image_index === 0)
|
||||
.map((item: any): AiEvidence => {
|
||||
const linked = part.localized === true && item.link_status === "linked";
|
||||
const rawPolygon = item.part?.polygon;
|
||||
const polygon =
|
||||
linked &&
|
||||
Array.isArray(rawPolygon) &&
|
||||
rawPolygon.length >= 3 &&
|
||||
rawPolygon.length <= 10000 &&
|
||||
rawPolygon.every(
|
||||
(point: unknown) =>
|
||||
Array.isArray(point) &&
|
||||
point.length === 2 &&
|
||||
point.every((n) => typeof n === "number" && Number.isFinite(n)),
|
||||
)
|
||||
? rawPolygon.map(
|
||||
(point: number[]) => [point[0], point[1]] as [number, number],
|
||||
)
|
||||
: null;
|
||||
return {
|
||||
imageIndex: 0,
|
||||
filename: text(item.filename),
|
||||
view: text(item.view),
|
||||
severity: text(item.severity),
|
||||
linkStatus: text(item.link_status),
|
||||
instanceId: Number.isInteger(item.part?.instance_id)
|
||||
? item.part.instance_id
|
||||
: null,
|
||||
confidence: confidence(item.part?.confidence),
|
||||
bbox: linked ? boundingBox(item.part?.box) : null,
|
||||
polygon,
|
||||
};
|
||||
});
|
||||
const firstBox = evidence.find((item) => item.bbox);
|
||||
return {
|
||||
name,
|
||||
price: normalizePartPrice(part.price),
|
||||
severity: text(part.severity),
|
||||
confidence: firstBox?.confidence ?? null,
|
||||
side: text(part.side),
|
||||
carSide: firstBox?.view ?? null,
|
||||
bbox: firstBox?.bbox ?? null,
|
||||
damageTypes: strings(part.damage_types),
|
||||
descriptions: strings(part.descriptions),
|
||||
localized: part.localized === true,
|
||||
evidence,
|
||||
};
|
||||
});
|
||||
return {
|
||||
parts,
|
||||
report: "",
|
||||
caseReport: text(raw.case_report) ?? "",
|
||||
requestId: text(raw.request_id),
|
||||
pricing: normalizePricing(raw.pricing),
|
||||
pipeline: Object.fromEntries(
|
||||
[
|
||||
"version",
|
||||
"vlm_model",
|
||||
"price_model",
|
||||
"prompt_version",
|
||||
"part_model_sha256",
|
||||
"car_model_sha256",
|
||||
].map((key) => [key, text(raw.pipeline?.[key])]),
|
||||
),
|
||||
vehicle: {
|
||||
color: text(raw.vehicle?.color),
|
||||
bodyType: text(raw.vehicle?.body_type),
|
||||
},
|
||||
internalDamages: (raw.internal_damages ?? []).map((item: any) => ({
|
||||
category: text(item?.category),
|
||||
labelFa: text(item?.label_fa),
|
||||
likelihood: text(item?.likelihood),
|
||||
reason: text(item?.reason),
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
/** Preserve detections independently: repeated names may describe different boxes. */
|
||||
export function normalizeAiResult(value: unknown): AiResult {
|
||||
const raw = value as any;
|
||||
if (raw?.error)
|
||||
throw new AiAssessmentError(
|
||||
text(raw.error.code),
|
||||
text(raw.error.request_id),
|
||||
undefined,
|
||||
text(raw.error.message) ?? undefined,
|
||||
);
|
||||
if (raw && "damaged_parts" in raw) return normalizeAssessment(raw);
|
||||
const report = raw?.distinct_damaged_parts_report;
|
||||
if (
|
||||
!report ||
|
||||
!Array.isArray(report.parts) ||
|
||||
typeof report.report !== "string" ||
|
||||
typeof raw.case_report !== "string"
|
||||
) {
|
||||
throw new Error("Invalid AI response");
|
||||
}
|
||||
if (report.parts.length > 500) throw new Error("Too many AI detections");
|
||||
const parts = report.parts.map((part: any): AiPart => {
|
||||
const name = text(part?.part_name);
|
||||
if (!name) throw new Error("Invalid AI part");
|
||||
const b = part.part_bbox;
|
||||
const bbox =
|
||||
b &&
|
||||
[b.x1, b.y1, b.x2, b.y2].every(
|
||||
(v) => typeof v === "number" && Number.isFinite(v),
|
||||
) &&
|
||||
b.x2 > b.x1 &&
|
||||
b.y2 > b.y1
|
||||
? { x1: b.x1, y1: b.y1, x2: b.x2, y2: b.y2 }
|
||||
: null;
|
||||
return {
|
||||
name,
|
||||
bbox,
|
||||
severity: text(part.damage_severity),
|
||||
confidence:
|
||||
typeof part.confidence === "number" &&
|
||||
Number.isFinite(part.confidence) &&
|
||||
part.confidence >= 0 &&
|
||||
part.confidence <= 1
|
||||
? part.confidence
|
||||
: null,
|
||||
side: text(part.side),
|
||||
carSide: text(part.car_side),
|
||||
};
|
||||
});
|
||||
return {
|
||||
parts,
|
||||
report: text(report.report) ?? "",
|
||||
caseReport: text(raw.case_report) ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
/** Expert-facing view: keep provider diagnostics and billing metadata server-side. */
|
||||
export function publicAiResult(result: AiResult | null | undefined) {
|
||||
if (!result) return result;
|
||||
return {
|
||||
parts: result.parts,
|
||||
report: result.report,
|
||||
caseReport: result.caseReport,
|
||||
vehicle: result.vehicle,
|
||||
internalDamages: result.internalDamages,
|
||||
...(result.pricing
|
||||
? {
|
||||
pricing: {
|
||||
car: result.pricing.car,
|
||||
minSeverity: result.pricing.minSeverity,
|
||||
currency: result.pricing.currency,
|
||||
originalCurrency: result.pricing.originalCurrency,
|
||||
totals: result.pricing.totals,
|
||||
complete: result.pricing.complete,
|
||||
pricedParts: result.pricing.pricedParts,
|
||||
unpricedParts: result.pricing.unpricedParts,
|
||||
},
|
||||
}
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
+5
-1
@@ -1,8 +1,12 @@
|
||||
import { Module } from "@nestjs/common";
|
||||
import { MongooseModule } from "@nestjs/mongoose";
|
||||
import { AiService } from "./ai.service";
|
||||
import { AiJob, AiJobSchema } from "./ai-job.schema";
|
||||
|
||||
@Module({
|
||||
imports: [],
|
||||
imports: [
|
||||
MongooseModule.forFeature([{ name: AiJob.name, schema: AiJobSchema }]),
|
||||
],
|
||||
providers: [AiService],
|
||||
exports: [AiService],
|
||||
})
|
||||
|
||||
@@ -0,0 +1,358 @@
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { AiService, aiImageKey } from "./ai.service";
|
||||
import { AiJobSchema } from "./ai-job.schema";
|
||||
import { AiAssessmentError } from "./ai-result";
|
||||
|
||||
const image = { path: "files/part.jpg", label: "گلگیر" };
|
||||
const result = { parts: [], report: "گزارش", caseReport: "گزارش کامل" };
|
||||
function setup(enabled = true, severity = "severe") {
|
||||
const jobs = {
|
||||
updateOne: jest.fn().mockResolvedValue({}),
|
||||
updateMany: jest.fn().mockResolvedValue({}),
|
||||
find: jest.fn().mockReturnValue({ lean: jest.fn().mockResolvedValue([]) }),
|
||||
findOneAndUpdate: jest
|
||||
.fn()
|
||||
.mockReturnValue({ lean: jest.fn().mockResolvedValue(null) }),
|
||||
};
|
||||
const config = new ConfigService({
|
||||
AI_DAMAGE_ENABLED: String(enabled),
|
||||
AI_DAMAGE_URL: "http://example.test",
|
||||
AI_DAMAGE_TIMEOUT_MS: 1000,
|
||||
AI_DAMAGE_PRICE_MIN_SEVERITY: severity,
|
||||
});
|
||||
return { service: new AiService(config, jobs as any), jobs };
|
||||
}
|
||||
function claimJob(
|
||||
jobs: ReturnType<typeof setup>["jobs"],
|
||||
fields: Record<string, unknown> = {},
|
||||
) {
|
||||
jobs.findOneAndUpdate.mockImplementation((_q: any, update: any) => ({
|
||||
lean: async () => ({
|
||||
_id: "job1",
|
||||
claimId: "claim1",
|
||||
imageKey: aiImageKey(image.path),
|
||||
...image,
|
||||
status: "processing",
|
||||
attempts: 1,
|
||||
leaseToken: update.$set.leaseToken,
|
||||
...fields,
|
||||
}),
|
||||
}));
|
||||
}
|
||||
describe("durable AI jobs", () => {
|
||||
it("is opt-in and does not send or enqueue photos when disabled", async () => {
|
||||
const { service, jobs } = setup(false);
|
||||
await service.enqueue("claim1", image);
|
||||
await service.work();
|
||||
expect(jobs.updateOne).not.toHaveBeenCalled();
|
||||
expect(jobs.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
it("uniquely queues each claim/photo and never resets a completed job on repeated uploads", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.enqueue("claim1", image);
|
||||
expect(AiJobSchema.indexes()).toContainEqual([
|
||||
{ claimId: 1, imageKey: 1 },
|
||||
{ unique: true, background: true },
|
||||
]);
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
{ claimId: "claim1", imageKey: aiImageKey(image.path) },
|
||||
{
|
||||
$setOnInsert: expect.objectContaining({
|
||||
status: "queued",
|
||||
attempts: 0,
|
||||
}),
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
});
|
||||
it("a persistence failure does not fail the photo upload", async () => {
|
||||
const { service, jobs } = setup();
|
||||
jobs.updateOne.mockRejectedValue(new Error("offline"));
|
||||
await expect(service.enqueue("claim1", image)).resolves.toBeUndefined();
|
||||
});
|
||||
it("leases pending and expired jobs atomically and persists only the owning worker's result", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
jest.spyOn(service, "aiRequestImage").mockResolvedValue(result);
|
||||
await service.work();
|
||||
const [filter, update] = jobs.findOneAndUpdate.mock.calls[0];
|
||||
expect(filter.$or).toEqual([
|
||||
expect.objectContaining({ status: "queued" }),
|
||||
expect.objectContaining({
|
||||
status: "processing",
|
||||
leaseUntil: expect.any(Object),
|
||||
}),
|
||||
]);
|
||||
expect(update.$inc).toEqual({ attempts: 1 });
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
_id: "job1",
|
||||
leaseToken: update.$set.leaseToken,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({ status: "completed", result }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("prevents overlapping processing in one instance", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
let finish!: (v: typeof result) => void;
|
||||
jest.spyOn(service, "aiRequestImage").mockImplementation(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const first = service.work();
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
await service.work();
|
||||
expect(jobs.findOneAndUpdate).toHaveBeenCalledTimes(1);
|
||||
finish(result);
|
||||
await first;
|
||||
});
|
||||
it("retries transient failures with delay, but stops after three attempts", async () => {
|
||||
for (const attempts of [1, 3]) {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs, { attempts });
|
||||
jest
|
||||
.spyOn(service, "aiRequestImage")
|
||||
.mockRejectedValue(new Error("timeout"));
|
||||
await service.work();
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
status: attempts === 1 ? "queued" : "failed",
|
||||
nextAttemptAt: expect.any(Date),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
it("does not retry rejected requests automatically or assume every 400 means no car", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
jest
|
||||
.spyOn(service, "aiRequestImage")
|
||||
.mockRejectedValue({ response: { status: 400 } });
|
||||
await service.work();
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
status: "failed",
|
||||
error: "سرویس هوش مصنوعی درخواست تحلیل این تصویر را نپذیرفت.",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("persists provider error tracking metadata and uses the HTTP status for retry decisions", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs);
|
||||
jest
|
||||
.spyOn(service, "aiRequestImage")
|
||||
.mockRejectedValue(
|
||||
new AiAssessmentError(
|
||||
"INVALID_INPUT",
|
||||
"req-123",
|
||||
422,
|
||||
"Unusable photo",
|
||||
),
|
||||
);
|
||||
await service.work();
|
||||
expect(jobs.updateOne).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({
|
||||
status: "failed",
|
||||
errorCode: "INVALID_INPUT",
|
||||
errorRequestId: "req-123",
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
it("never sends another request after recovering a repeatedly crashed job beyond its limit", async () => {
|
||||
const { service, jobs } = setup();
|
||||
claimJob(jobs, { attempts: 4 });
|
||||
const send = jest.spyOn(service, "aiRequestImage");
|
||||
await service.work();
|
||||
expect(send).not.toHaveBeenCalled();
|
||||
});
|
||||
it("only returns current photo results and never exposes storage paths or provider payloads", async () => {
|
||||
const { service, jobs } = setup();
|
||||
jobs.find.mockReturnValue({
|
||||
lean: jest.fn().mockResolvedValue([
|
||||
{
|
||||
imageKey: aiImageKey(image.path),
|
||||
status: "completed",
|
||||
result: {
|
||||
...result,
|
||||
requestId: "PRIVATE_REQUEST",
|
||||
pipeline: { price_model: "PRIVATE_MODEL" },
|
||||
pricing: {
|
||||
car: "پژو",
|
||||
totals: { overall: 1200000 },
|
||||
costUsd: 0.04,
|
||||
model: "PRIVATE_MODEL",
|
||||
durationMs: 1000,
|
||||
},
|
||||
},
|
||||
errorRequestId: "PRIVATE_ERROR_REQUEST",
|
||||
path: "private",
|
||||
attempts: 1,
|
||||
},
|
||||
]),
|
||||
});
|
||||
const view = await service.list("claim1", [image]);
|
||||
expect(jobs.find).toHaveBeenCalledWith({
|
||||
claimId: "claim1",
|
||||
imageKey: { $in: [aiImageKey(image.path)] },
|
||||
});
|
||||
expect(view.images[0]).toMatchObject({
|
||||
label: "گلگیر",
|
||||
status: "completed",
|
||||
result,
|
||||
});
|
||||
expect(view.images[0]).not.toHaveProperty("path");
|
||||
expect(view.images[0]).not.toHaveProperty("errorRequestId");
|
||||
expect(view.images[0].result).not.toHaveProperty("requestId");
|
||||
expect(view.images[0].result).not.toHaveProperty("pipeline");
|
||||
expect(view.images[0].result.pricing).toMatchObject({
|
||||
car: "پژو",
|
||||
totals: { overall: 1200000 },
|
||||
});
|
||||
for (const key of ["costUsd", "model", "durationMs"])
|
||||
expect(view.images[0].result.pricing).not.toHaveProperty(key);
|
||||
expect(JSON.stringify(view)).not.toContain("PRIVATE_");
|
||||
});
|
||||
it("manual retry affects only failed jobs for current claim/photos", async () => {
|
||||
const { service, jobs } = setup();
|
||||
await service.retry("claim1", [image]);
|
||||
expect(jobs.updateMany).toHaveBeenCalledWith(
|
||||
{
|
||||
claimId: "claim1",
|
||||
imageKey: { $in: [aiImageKey(image.path)] },
|
||||
status: "failed",
|
||||
},
|
||||
expect.objectContaining({
|
||||
$set: expect.objectContaining({ status: "queued", attempts: 0 }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("AI multipart transport", () => {
|
||||
it("posts real image bytes to assessments with no retired pipeline flags", async () => {
|
||||
const fs = await import("node:fs/promises");
|
||||
const { resolve, join } = await import("node:path");
|
||||
const axios = (await import("axios")).default;
|
||||
const root = await fs.mkdtemp("/tmp/yara-ai-jest-");
|
||||
const file = join(root, "test.jpg");
|
||||
const bytes = Buffer.from([0xff, 0xd8, 0xff, 0x00, 0x01, 0xff, 0xd9]);
|
||||
await fs.writeFile(file, bytes);
|
||||
const realpath = fs.realpath;
|
||||
const pathSpy = jest
|
||||
.spyOn(fs, "realpath")
|
||||
.mockImplementation(((path: string) =>
|
||||
path === resolve("files")
|
||||
? Promise.resolve(root)
|
||||
: realpath(path)) as any);
|
||||
let pricedRequest = false;
|
||||
const post = jest
|
||||
.spyOn(axios, "post")
|
||||
.mockImplementation(async (url, form: any, config) => {
|
||||
const parsed = new URL(String(url));
|
||||
expect(parsed.pathname).toBe("/api/v1/assessments");
|
||||
expect(parsed.searchParams.get("include_polygons")).toBe("false");
|
||||
expect(parsed.searchParams.get("include_prices")).toBe(
|
||||
pricedRequest ? "true" : "false",
|
||||
);
|
||||
if (pricedRequest)
|
||||
expect(parsed.searchParams.get("price_min_severity")).toBe(
|
||||
"moderate",
|
||||
);
|
||||
expect(config?.headers?.["content-type"]).toMatch(
|
||||
/^multipart\/form-data; boundary=/,
|
||||
);
|
||||
expect(config?.maxRedirects).toBe(0);
|
||||
const chunks: Buffer[] = [];
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
form.on("data", (chunk: string | Buffer) =>
|
||||
chunks.push(Buffer.from(chunk)),
|
||||
);
|
||||
form.on("end", resolve);
|
||||
form.on("error", reject);
|
||||
form.resume();
|
||||
});
|
||||
const body = Buffer.concat(chunks);
|
||||
expect(
|
||||
body.includes(Buffer.from('name="images"; filename="test.jpg"')),
|
||||
).toBe(true);
|
||||
expect(body.includes(bytes)).toBe(true);
|
||||
if (pricedRequest) {
|
||||
expect(body.includes(Buffer.from('name="car"'))).toBe(true);
|
||||
expect(body.includes(Buffer.from("پژو ۲۰۶"))).toBe(true);
|
||||
}
|
||||
return {
|
||||
data: {
|
||||
request_id: "req-123",
|
||||
damaged_parts: [],
|
||||
internal_damages: [],
|
||||
case_report: "گزارش کامل",
|
||||
},
|
||||
} as any;
|
||||
});
|
||||
try {
|
||||
const { service } = setup();
|
||||
await expect(
|
||||
service.aiRequestImage({ path: file, fileName: "test.jpg" }),
|
||||
).resolves.toMatchObject({ parts: [], requestId: "req-123" });
|
||||
await expect(
|
||||
service.aiRequestImage({ path: "/etc/hosts" }),
|
||||
).rejects.toThrow("outside upload storage");
|
||||
expect(post).toHaveBeenCalledTimes(1);
|
||||
await fs.truncate(file, 15 * 1024 * 1024 + 1);
|
||||
await expect(service.aiRequestImage({ path: file })).rejects.toThrow(
|
||||
"Invalid image size",
|
||||
);
|
||||
expect(post).toHaveBeenCalledTimes(1);
|
||||
|
||||
await fs.writeFile(file, bytes);
|
||||
const { AxiosError } = await import("axios");
|
||||
pricedRequest = true;
|
||||
await service.aiRequestImage({
|
||||
path: file,
|
||||
carName: "پژو ۲۰۶",
|
||||
includePrices: true,
|
||||
priceMinSeverity: "moderate",
|
||||
});
|
||||
pricedRequest = false;
|
||||
post.mockRejectedValueOnce(
|
||||
new AxiosError("Rejected", undefined, undefined, undefined, {
|
||||
status: 422,
|
||||
data: {
|
||||
error: {
|
||||
code: "INVALID_INPUT",
|
||||
message: "Invalid image",
|
||||
request_id: "req-error",
|
||||
},
|
||||
},
|
||||
} as any),
|
||||
);
|
||||
await expect(
|
||||
service.aiRequestImage({ path: file }),
|
||||
).rejects.toMatchObject({
|
||||
code: "INVALID_INPUT",
|
||||
requestId: "req-error",
|
||||
httpStatus: 422,
|
||||
message: "Invalid image",
|
||||
});
|
||||
} finally {
|
||||
pathSpy.mockRestore();
|
||||
post.mockRestore();
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
+349
-173
@@ -1,204 +1,380 @@
|
||||
import { createReadStream, existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { publicAiResult } from "./ai-result";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { realpath, stat } from "node:fs/promises";
|
||||
import { basename, resolve, sep } from "node:path";
|
||||
import {
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
BadRequestException,
|
||||
ConflictException,
|
||||
ServiceUnavailableException,
|
||||
Injectable,
|
||||
Logger,
|
||||
OnModuleDestroy,
|
||||
OnModuleInit,
|
||||
} from "@nestjs/common";
|
||||
import { ConfigService } from "@nestjs/config";
|
||||
import { AxiosRequestConfig } from "axios"; // TODO: Change all axios usages to HttpModule
|
||||
import { InjectModel } from "@nestjs/mongoose";
|
||||
import { Model } from "mongoose";
|
||||
import axios from "axios";
|
||||
import FormData = require("form-data");
|
||||
import { AiJob } from "./ai-job.schema";
|
||||
import { AiAssessmentError, normalizeAiResult } from "./ai-result";
|
||||
import { buildFileLink } from "src/helpers/urlCreator";
|
||||
|
||||
export interface AiCapture {
|
||||
path: string;
|
||||
fileName?: string;
|
||||
label?: string;
|
||||
carName?: string;
|
||||
includePrices?: boolean;
|
||||
priceMinSeverity?: string;
|
||||
}
|
||||
export const aiImageKey = (path: string) =>
|
||||
createHash("sha256").update(resolve(path)).digest("hex");
|
||||
|
||||
@Injectable()
|
||||
export class AiService implements OnModuleInit {
|
||||
private apiKey: string;
|
||||
private accessToken: string = null;
|
||||
export class AiService implements OnModuleInit, OnModuleDestroy {
|
||||
private readonly logger = new Logger(AiService.name);
|
||||
private timer?: NodeJS.Timeout;
|
||||
private busy = false;
|
||||
private stopping = false;
|
||||
private abort?: AbortController;
|
||||
constructor(
|
||||
private readonly config: ConfigService,
|
||||
@InjectModel(AiJob.name) private readonly jobs: Model<AiJob>,
|
||||
) {}
|
||||
|
||||
// These configurations are for authentication and getting the API key.
|
||||
private readonly loginOptions: AxiosRequestConfig = {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
url: `${this.configService.get<string>("AI_URL_V2")}/auth/login`,
|
||||
data: {
|
||||
username: this.configService.get<string>("AI_USERNAME"),
|
||||
password: this.configService.get<string>("AI_PASSWORD"),
|
||||
},
|
||||
timeout: 1000, // TODO: Make this ENV
|
||||
};
|
||||
|
||||
constructor(private readonly configService: ConfigService) {}
|
||||
|
||||
private get profileOptions(): AxiosRequestConfig {
|
||||
return {
|
||||
method: "GET",
|
||||
url: `${this.configService.get<string>("AI_URL_V2")}/auth/profile`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
},
|
||||
};
|
||||
get enabled() {
|
||||
return this.config.get<string>("AI_DAMAGE_ENABLED") === "true";
|
||||
}
|
||||
get priceMinSeverity(): string {
|
||||
const value =
|
||||
this.config.get<string>("AI_DAMAGE_PRICE_MIN_SEVERITY") ?? "severe";
|
||||
return value === "null" ? "minor" : value;
|
||||
}
|
||||
|
||||
// This getter dynamically creates the base options for the image processing request.
|
||||
private get imageProcessOptions(): AxiosRequestConfig {
|
||||
return {
|
||||
method: "POST",
|
||||
url: `${process.env.AI_URL_V2}/services/car-damage/detector?version=ai-v7`,
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.accessToken}`,
|
||||
"gateway-api-key": `${this.apiKey}`,
|
||||
},
|
||||
};
|
||||
private get timeout() {
|
||||
return Math.min(
|
||||
600000,
|
||||
Math.max(1000, Number(this.config.get("AI_DAMAGE_TIMEOUT_MS")) || 180000),
|
||||
);
|
||||
}
|
||||
|
||||
async onModuleInit() {
|
||||
onModuleInit() {
|
||||
if (!this.enabled) return;
|
||||
this.timer = setInterval(() => {
|
||||
void this.work();
|
||||
}, 5000);
|
||||
this.timer.unref();
|
||||
void this.work();
|
||||
}
|
||||
onModuleDestroy() {
|
||||
this.stopping = true;
|
||||
clearInterval(this.timer);
|
||||
this.abort?.abort();
|
||||
}
|
||||
|
||||
/** Only persist the job here; never wait for the AI in an upload request. */
|
||||
async enqueue(claimId: string, image: AiCapture): Promise<void> {
|
||||
if (!this.enabled || !image.path) return;
|
||||
try {
|
||||
const res = await this.login();
|
||||
// if (res?.accessToken) {
|
||||
// this.accessToken = res.accessToken;
|
||||
// await this.getApiKey();
|
||||
// }
|
||||
await this.jobs.updateOne(
|
||||
{ claimId, imageKey: aiImageKey(image.path) },
|
||||
{
|
||||
$setOnInsert: {
|
||||
claimId,
|
||||
imageKey: aiImageKey(image.path),
|
||||
path: image.path,
|
||||
fileName: image.fileName,
|
||||
status: "queued",
|
||||
attempts: 0,
|
||||
nextAttemptAt: new Date(),
|
||||
},
|
||||
},
|
||||
{ upsert: true },
|
||||
);
|
||||
} catch (error) {
|
||||
// Don't prevent app startup if AI service is temporarily unavailable
|
||||
// The service will attempt to re-authenticate when aiRequestImage is called
|
||||
// Reset tokens so re-authentication will be attempted
|
||||
this.accessToken = null;
|
||||
this.apiKey = null;
|
||||
// Concurrent duplicate uploads are already queued. A storage outage must not fail capture.
|
||||
if ((error as any)?.code !== 11000)
|
||||
this.logger.error(
|
||||
"Could not persist AI job; expert review will retry scheduling.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async login() {
|
||||
// const loginResponse = await axios.request(this.loginOptions);
|
||||
// return loginResponse.data;
|
||||
async list(claimId: string, images: AiCapture[]) {
|
||||
// Older captures and jobs missed during a database outage are scheduled on review.
|
||||
for (const image of images) await this.enqueue(claimId, image);
|
||||
const keys = images.map((image) => aiImageKey(image.path));
|
||||
const rows = await this.jobs
|
||||
.find({ claimId, imageKey: { $in: keys } })
|
||||
.lean();
|
||||
const byKey = new Map(rows.map((row) => [row.imageKey, row]));
|
||||
return {
|
||||
enabled: this.enabled,
|
||||
priceMinSeverity: this.priceMinSeverity,
|
||||
images: images.map((image) => {
|
||||
const key = aiImageKey(image.path);
|
||||
const job = byKey.get(key);
|
||||
return {
|
||||
imageKey: key,
|
||||
label: image.label ?? "تصویر خسارت",
|
||||
imageUrl: buildFileLink(image.path),
|
||||
status: job?.status ?? (this.enabled ? "queued" : "disabled"),
|
||||
attempts: job?.attempts ?? 0,
|
||||
pricingRequested: job?.includePrices === true,
|
||||
pricingCarName: job?.carName,
|
||||
pricingMinSeverity: job?.priceMinSeverity,
|
||||
completedAt: job?.completedAt,
|
||||
error: job?.error,
|
||||
errorCode: job?.errorCode,
|
||||
result: job?.status === "completed" ? publicAiResult(job.result) : undefined,
|
||||
};
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private async getApiKey() {
|
||||
// const profileResponse = await axios.request(this.profileOptions);
|
||||
// this.apiKey = profileResponse.data.apiKey.key;
|
||||
// return this.apiKey;
|
||||
async retry(claimId: string, images: AiCapture[], allowPricing = true) {
|
||||
if (this.enabled)
|
||||
await this.jobs.updateMany(
|
||||
{
|
||||
claimId,
|
||||
imageKey: { $in: images.map((image) => aiImageKey(image.path)) },
|
||||
status: "failed",
|
||||
...(!allowPricing ? { includePrices: { $ne: true } } : {}),
|
||||
},
|
||||
{
|
||||
$set: { status: "queued", attempts: 0, nextAttemptAt: new Date() },
|
||||
$unset: {
|
||||
error: 1,
|
||||
errorCode: 1,
|
||||
errorRequestId: 1,
|
||||
leaseToken: 1,
|
||||
leaseUntil: 1,
|
||||
},
|
||||
},
|
||||
);
|
||||
return this.list(claimId, images);
|
||||
}
|
||||
|
||||
public async aiRequestImage(file: {
|
||||
path: string;
|
||||
fileName?: string;
|
||||
}): Promise<any> {
|
||||
// Ensure authentication is set up
|
||||
if (!this.accessToken || !this.apiKey) {
|
||||
try {
|
||||
const res = await this.login();
|
||||
// if (res?.accessToken) {
|
||||
// this.accessToken = res.accessToken;
|
||||
// await this.getApiKey();
|
||||
// } else {
|
||||
// throw new HttpException(
|
||||
// "AI Service authentication failed",
|
||||
// HttpStatus.UNAUTHORIZED,
|
||||
// );
|
||||
// }
|
||||
} catch (error) {
|
||||
throw new HttpException(
|
||||
"AI Service authentication failed",
|
||||
HttpStatus.UNAUTHORIZED,
|
||||
/** Explicit advisory request: never maps AI part names or writes claim valuations. */
|
||||
async requestPricing(
|
||||
claimId: string,
|
||||
images: AiCapture[],
|
||||
input: { imageKey: string; carName: string },
|
||||
) {
|
||||
if (!this.enabled)
|
||||
throw new ServiceUnavailableException(
|
||||
"سرویس تحلیل هوش مصنوعی در این محیط غیرفعال است.",
|
||||
);
|
||||
const carName =
|
||||
typeof input?.carName === "string" ? input.carName.trim() : "";
|
||||
if (
|
||||
carName.length < 2 ||
|
||||
carName.length > 100 ||
|
||||
!/[آ-ی]/.test(carName) ||
|
||||
/[\r\n\x00-\x1f]/.test(carName)
|
||||
)
|
||||
throw new BadRequestException(
|
||||
"نام و مدل خودروی زیاندیده را به فارسی و حداکثر در ۱۰۰ کاراکتر وارد کنید.",
|
||||
);
|
||||
const image = images.find(
|
||||
(item) => aiImageKey(item.path) === input?.imageKey,
|
||||
);
|
||||
if (!image)
|
||||
throw new BadRequestException(
|
||||
"تصویر انتخابشده متعلق به تصاویر فعلی این پرونده نیست. صفحه را تازه کنید.",
|
||||
);
|
||||
await this.enqueue(claimId, image);
|
||||
const change = await this.jobs.updateOne(
|
||||
{
|
||||
claimId,
|
||||
imageKey: input.imageKey,
|
||||
status: { $ne: "processing" },
|
||||
$or: [{ status: { $ne: "queued" } }, { includePrices: { $ne: true } }],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
status: "queued",
|
||||
includePrices: true,
|
||||
carName,
|
||||
priceMinSeverity: this.priceMinSeverity,
|
||||
attempts: 0,
|
||||
nextAttemptAt: new Date(),
|
||||
},
|
||||
$unset: {
|
||||
result: 1,
|
||||
completedAt: 1,
|
||||
error: 1,
|
||||
errorCode: 1,
|
||||
errorRequestId: 1,
|
||||
leaseToken: 1,
|
||||
leaseUntil: 1,
|
||||
},
|
||||
},
|
||||
);
|
||||
if (!change.matchedCount)
|
||||
throw new ConflictException(
|
||||
"تحلیل این تصویر در صف یا در حال اجراست. پس از پایان آن دوباره تلاش کنید.",
|
||||
);
|
||||
return this.list(claimId, images);
|
||||
}
|
||||
|
||||
async aiRequestImage(file: AiCapture, signal?: AbortSignal) {
|
||||
// Only local managed uploads; never fetch a supplied URL or arbitrary server file.
|
||||
const root = await realpath(resolve("files"));
|
||||
const path = await realpath(resolve(file.path));
|
||||
if (!path.startsWith(root + sep))
|
||||
throw new Error("Image outside upload storage");
|
||||
const info = await stat(path);
|
||||
if (!info.isFile() || info.size <= 0)
|
||||
throw new AiAssessmentError(null, null, 422, "Invalid image size");
|
||||
if (info.size > 15 * 1024 * 1024)
|
||||
throw new AiAssessmentError(null, null, 413, "Invalid image size");
|
||||
const base = this.config.get<string>("AI_DAMAGE_URL");
|
||||
if (!base) throw new Error("AI_DAMAGE_URL is required");
|
||||
const url = new URL("/api/v1/assessments", base);
|
||||
url.searchParams.set("include_polygons", "false");
|
||||
url.searchParams.set(
|
||||
"include_prices",
|
||||
file.includePrices ? "true" : "false",
|
||||
);
|
||||
if (file.includePrices) {
|
||||
if (!file.carName)
|
||||
throw new BadRequestException(
|
||||
"نام فارسی خودرو برای برآورد قیمت لازم است.",
|
||||
);
|
||||
url.searchParams.set(
|
||||
"price_min_severity",
|
||||
file.priceMinSeverity || this.priceMinSeverity,
|
||||
);
|
||||
}
|
||||
const form = new FormData();
|
||||
if (file.includePrices) form.append("car", file.carName!);
|
||||
const stream = createReadStream(path);
|
||||
form.append("images", stream, {
|
||||
filename: file.fileName || basename(path),
|
||||
knownLength: info.size,
|
||||
});
|
||||
try {
|
||||
const { data } = await axios.post(url.toString(), form, {
|
||||
headers: form.getHeaders(),
|
||||
timeout: this.timeout,
|
||||
signal,
|
||||
maxBodyLength: 16 * 1024 * 1024,
|
||||
maxContentLength: 2 * 1024 * 1024,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
return normalizeAiResult(data);
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error) && error.response?.data?.error) {
|
||||
const detail = error.response.data.error;
|
||||
const safeText = (value: unknown) =>
|
||||
typeof value === "string" ? value.slice(0, 500) : null;
|
||||
throw new AiAssessmentError(
|
||||
safeText(detail.code),
|
||||
safeText(detail.request_id),
|
||||
error.response.status,
|
||||
safeText(detail.message) ?? undefined,
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
} finally {
|
||||
stream.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve relative paths to absolute paths
|
||||
const filePath = file.path.startsWith("/")
|
||||
? file.path
|
||||
: join(process.cwd(), file.path.replace(/^\.\//, ""));
|
||||
|
||||
// Check if file exists
|
||||
if (!existsSync(filePath)) {
|
||||
throw new HttpException(
|
||||
`File not found: ${file.path}`,
|
||||
HttpStatus.NOT_FOUND,
|
||||
);
|
||||
}
|
||||
|
||||
// const form = new FormData();
|
||||
const fileStream = createReadStream(filePath);
|
||||
|
||||
// Append file with filename if available
|
||||
if (file.fileName) {
|
||||
// form.append("images", fileStream, file.fileName);
|
||||
} else {
|
||||
// Extract filename from path if not provided
|
||||
const pathParts = filePath.split("/");
|
||||
const extractedFileName = pathParts[pathParts.length - 1];
|
||||
// form.append("images", fileStream, extractedFileName);
|
||||
}
|
||||
|
||||
/** Atomic leases make this safe across replicas and recover jobs after a restart. */
|
||||
async work() {
|
||||
if (!this.enabled || this.busy || this.stopping) return;
|
||||
this.busy = true;
|
||||
try {
|
||||
const requestHeaders = {
|
||||
...this.imageProcessOptions.headers,
|
||||
// ...form.getHeaders(),
|
||||
};
|
||||
|
||||
const fs = require("fs");
|
||||
const stats = fs.statSync(filePath);
|
||||
|
||||
// const response = await axios.request({
|
||||
// ...this.imageProcessOptions,
|
||||
// headers: requestHeaders,
|
||||
// // data: form,
|
||||
// maxContentLength: Infinity,
|
||||
// maxBodyLength: Infinity,
|
||||
// });
|
||||
|
||||
// Validate response structure
|
||||
// if (!response.data) {
|
||||
// throw new HttpException(
|
||||
// "AI Service returned empty response",
|
||||
// HttpStatus.BAD_GATEWAY,
|
||||
// );
|
||||
// }
|
||||
|
||||
// // Check for error in response first (AI service returns 201 with error in body)
|
||||
// if (response.data.error) {
|
||||
// throw new HttpException(
|
||||
// `AI Service error: ${response.data.error}`,
|
||||
// HttpStatus.BAD_GATEWAY,
|
||||
// );
|
||||
// }
|
||||
|
||||
// // Check for processed image (downloadLink)
|
||||
// if (!response.data.downloadLink) {
|
||||
// throw new HttpException(
|
||||
// "AI Service did not return processed image (downloadLink missing)",
|
||||
// HttpStatus.BAD_GATEWAY,
|
||||
// );
|
||||
// }
|
||||
|
||||
// return response.data;
|
||||
} catch (er) {
|
||||
// Determine error source
|
||||
let errorSource = "UNKNOWN";
|
||||
let errorMessage = er.message;
|
||||
let errorDetails = "No error details available";
|
||||
|
||||
if (er.response) {
|
||||
errorSource = "AI_SERVICE_RESPONSE";
|
||||
errorMessage =
|
||||
er.response?.data?.message ||
|
||||
er.message ||
|
||||
`HTTP ${er.response.status}`;
|
||||
errorDetails = er.response?.data
|
||||
? JSON.stringify(er.response.data, null, 2)
|
||||
: `Status: ${er.response.status}, StatusText: ${er.response.statusText}`;
|
||||
} else if (er.request) {
|
||||
errorSource = "NETWORK_ERROR";
|
||||
errorMessage = "Network error - AI service did not respond";
|
||||
errorDetails = "Request was made but no response received";
|
||||
} else {
|
||||
errorSource = "REQUEST_SETUP_ERROR";
|
||||
errorMessage = er.message || "Error setting up request";
|
||||
const now = new Date();
|
||||
const token = randomUUID();
|
||||
const job = await this.jobs
|
||||
.findOneAndUpdate(
|
||||
{
|
||||
$or: [
|
||||
{ status: "queued", nextAttemptAt: { $lte: now } },
|
||||
{ status: "processing", leaseUntil: { $lte: now } },
|
||||
],
|
||||
},
|
||||
{
|
||||
$set: {
|
||||
status: "processing",
|
||||
leaseToken: token,
|
||||
leaseUntil: new Date(now.getTime() + this.timeout + 60000),
|
||||
},
|
||||
$inc: { attempts: 1 },
|
||||
},
|
||||
{ new: true, sort: { nextAttemptAt: 1 } },
|
||||
)
|
||||
.lean();
|
||||
if (!job) return;
|
||||
const owned = { _id: job._id, status: "processing", leaseToken: token };
|
||||
try {
|
||||
if (job.attempts > 3) throw new Error("Retry limit reached");
|
||||
this.abort = new AbortController();
|
||||
const result = await this.aiRequestImage(job, this.abort.signal);
|
||||
await this.jobs.updateOne(owned, {
|
||||
$set: { status: "completed", result, completedAt: new Date() },
|
||||
$unset: {
|
||||
error: 1,
|
||||
errorCode: 1,
|
||||
errorRequestId: 1,
|
||||
leaseUntil: 1,
|
||||
leaseToken: 1,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.stopping) return; // Leave lease for another process after shutdown.
|
||||
const providerError =
|
||||
error instanceof AiAssessmentError ? error : undefined;
|
||||
const status =
|
||||
providerError?.httpStatus ?? (error as any)?.response?.status;
|
||||
const terminal =
|
||||
job.attempts >= 3 ||
|
||||
[400, 401, 403, 404, 413, 415, 422].includes(status);
|
||||
await this.jobs.updateOne(owned, {
|
||||
$set: {
|
||||
status: terminal ? "failed" : "queued",
|
||||
error:
|
||||
status === 413
|
||||
? "حجم تصویر برای تحلیل باید حداکثر ۱۵ مگابایت باشد."
|
||||
: status === 400
|
||||
? "سرویس هوش مصنوعی درخواست تحلیل این تصویر را نپذیرفت."
|
||||
: status === 422 || status === 415
|
||||
? "سرویس هوش مصنوعی این تصویر را نپذیرفت؛ یک تصویر JPEG واضح بارگذاری کنید."
|
||||
: "تحلیل تصویر انجام نشد. دوباره تلاش کنید.",
|
||||
...(providerError?.code ? { errorCode: providerError.code } : {}),
|
||||
...(providerError?.requestId
|
||||
? { errorRequestId: providerError.requestId }
|
||||
: {}),
|
||||
nextAttemptAt: new Date(
|
||||
Date.now() + 30000 * 2 ** Math.min(job.attempts - 1, 3),
|
||||
),
|
||||
},
|
||||
$unset: {
|
||||
leaseUntil: 1,
|
||||
leaseToken: 1,
|
||||
...(!providerError?.code ? { errorCode: 1 } : {}),
|
||||
...(!providerError?.requestId ? { errorRequestId: 1 } : {}),
|
||||
},
|
||||
});
|
||||
this.logger.warn(
|
||||
`AI analysis failed (${status ?? "network/response"}); ${terminal ? "manual retry available" : "retry queued"}.` +
|
||||
(providerError
|
||||
? ` ${JSON.stringify({ code: providerError.code, requestId: providerError.requestId })}`
|
||||
: ""),
|
||||
);
|
||||
}
|
||||
|
||||
// Re-throw with detailed error information
|
||||
throw new HttpException(
|
||||
`[${errorSource}] ${errorMessage}`,
|
||||
er.response?.status || HttpStatus.INTERNAL_SERVER_ERROR,
|
||||
} catch {
|
||||
this.logger.error(
|
||||
"AI worker storage unavailable; will retry on the next tick.",
|
||||
);
|
||||
} finally {
|
||||
this.abort = undefined;
|
||||
this.busy = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user