1
0
forked from Yara724/api

Compare commits

..

72 Commits

Author SHA1 Message Date
SepehrYahyaee
45630a33ef YARA-1181 2026-07-29 09:49:01 +03:30
50ea476fa5 Merge pull request 'main' (#228) from s.hajizadeh/yara724api:main into main
Reviewed-on: Yara724/api#228
2026-07-28 16:59:02 +03:30
8609dbc377 merge upstream 2026-07-28 16:58:26 +03:30
0019a22ccd claim things fixed 2026-07-28 16:58:03 +03:30
8aae4b75e1 Merge pull request 'YARA-1135' (#227) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#227
2026-07-28 16:44:09 +03:30
SepehrYahyaee
891b1b2bbc YARA-1135 2026-07-28 16:43:29 +03:30
7ed102c6ef Merge pull request 'YARA-1148: add CALL_CENTER to LocalActorAuthGuard role allowlist' (#226) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#226
2026-07-28 15:44:00 +03:30
SepehrYahyaee
ec0d03fadf YARA-1148: add CALL_CENTER to LocalActorAuthGuard role allowlist 2026-07-28 15:40:11 +03:30
75adb2a3d2 Merge pull request 'main' (#225) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#225
2026-07-28 15:01:31 +03:30
SepehrYahyaee
4cf0461a48 YARA-1147 2026-07-28 15:00:09 +03:30
d7e6784746 Merge pull request 'main' (#1) from Yara724/api:main into main
Reviewed-on: #1
2026-07-28 12:47:43 +03:30
d119cd64aa Merge pull request 'main' (#224) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#224
2026-07-28 12:25:22 +03:30
SepehrYahyaee
021d749962 Added permission for file maker and reviewers to access branches 2026-07-28 12:24:12 +03:30
SepehrYahyaee
61684156c6 YARA-1133 2026-07-27 14:00:54 +03:30
639e6ceebb Merge pull request 'YARA-1165' (#223) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#223
2026-07-27 11:46:36 +03:30
SepehrYahyaee
588a92c4b4 YARA-1165 2026-07-27 11:46:03 +03:30
f2e20b32eb Merge pull request 'YARA-1164' (#222) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#222
2026-07-27 11:39:39 +03:30
SepehrYahyaee
c94dd27a96 YARA-1164 2026-07-27 11:38:54 +03:30
6e1405c309 Merge pull request 'main' (#221) from s.hajizadeh/yara724api:main into main
Reviewed-on: Yara724/api#221
2026-07-27 10:39:57 +03:30
f053ee1348 merge upstream 2026-07-27 10:39:17 +03:30
182db56e15 the serial letter normalization added to the code to normalize the Heh , Ya , Kaf and etc to the correct character 2026-07-27 10:38:35 +03:30
9b348d567d Merge pull request 'YARA-1162' (#220) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#220
2026-07-27 10:16:22 +03:30
SepehrYahyaee
e4c3b7a16a YARA-1162 2026-07-27 10:15:46 +03:30
23fca04705 Merge pull request 'YARA-1154' (#219) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#219
2026-07-27 09:39:08 +03:30
SepehrYahyaee
4b9d946bfd YARA-1154 2026-07-27 09:31:07 +03:30
c85503e598 Merge pull request 'YARA-1136' (#218) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#218
2026-07-26 11:35:59 +03:30
SepehrYahyaee
9828aee8af YARA-1136 2026-07-26 11:35:21 +03:30
778544c321 Merge pull request 'YARA-1147' (#217) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#217
2026-07-25 12:32:22 +03:30
SepehrYahyaee
3afff67336 YARA-1147 2026-07-25 12:31:54 +03:30
793ff639ba Merge pull request 'Added insurer capabilities for super-admin' (#216) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#216
2026-07-25 11:55:42 +03:30
SepehrYahyaee
ec15cff557 Added insurer capabilities for super-admin 2026-07-25 11:55:00 +03:30
fd42adf9d6 Merge pull request 'Added inner parts to APIs for expert claim' (#215) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#215
2026-07-25 11:10:38 +03:30
SepehrYahyaee
4272790fad Added inner parts to APIs for expert claim 2026-07-25 11:10:02 +03:30
ac65cdb77b Merge pull request 'lookups and inquiries in lookups added' (#214) from s.hajizadeh/yara724api:main into main
Reviewed-on: Yara724/api#214
2026-07-25 11:04:42 +03:30
8430c68e3a lookups and inquiries in lookups added 2026-07-25 11:03:58 +03:30
49fe548215 Merge pull request 'Fixed v5 file maker approval field' (#213) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#213
2026-07-25 10:25:10 +03:30
SepehrYahyaee
777eae1028 Fixed v5 file maker approval field 2026-07-25 10:24:34 +03:30
b67dd733cd Merge pull request 'Fixed upload documents counting for v4' (#212) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#212
2026-07-25 09:53:07 +03:30
SepehrYahyaee
4818f73252 Fixed upload documents counting for v4 2026-07-25 09:52:42 +03:30
cc8a5354c7 Merge pull request 'v4 bug fixed' (#211) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#211
2026-07-25 09:29:42 +03:30
SepehrYahyaee
2d5ade33d2 v4 bug fixed 2026-07-25 09:29:12 +03:30
b73c92c21f Merge pull request 'Fixed Bugs: 1) V4 incorrect advancement to file maker approval state, 2) V4 race condition for finishing file maker steps' (#210) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#210
2026-07-23 13:44:05 +03:30
f9f462d47b Fixed Bugs: 1) V4 incorrect advancement to file maker approval state, 2) V4 race condition for finishing file maker steps 2026-07-23 13:43:37 +03:30
c3eb36dc41 Merge pull request 'Fixed v4 sign' (#209) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#209
2026-07-22 17:37:00 +03:30
SepehrYahyaee
f75ecf5c2c Fixed v4 sign 2026-07-22 17:36:29 +03:30
75c4cb6a05 Merge pull request 'Fixed v4/v5 flow' (#208) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#208
2026-07-22 17:22:55 +03:30
SepehrYahyaee
7a4277f8b2 Fixed v4/v5 flow 2026-07-22 17:22:27 +03:30
e50bc78344 Merge pull request 'Fixed sign' (#207) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#207
2026-07-22 15:47:02 +03:30
SepehrYahyaee
2c1cd93dd0 Fixed sign 2026-07-22 15:46:33 +03:30
ffd44df718 Merge pull request 'Fix v2 flow sign of second party' (#206) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#206
2026-07-22 15:35:53 +03:30
SepehrYahyaee
64865b70f2 Fix v2 flow sign of second party 2026-07-22 15:35:14 +03:30
c207c30be9 Merge pull request 'Fixed v2 flow' (#205) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#205
2026-07-22 15:10:00 +03:30
SepehrYahyaee
fcb169e9ac Fixed v2 flow 2026-07-22 15:09:34 +03:30
1867292499 Merge pull request 'Fixed v2 flow' (#204) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#204
2026-07-22 14:53:33 +03:30
SepehrYahyaee
2cc96f6132 Fixed v2 flow 2026-07-22 14:52:51 +03:30
4d5b91d4fe Merge pull request 'update the fanavaran for both tejarat no and parsian clients , dont forget about the env files' (#203) from s.hajizadeh/yara724api:main into main
Reviewed-on: Yara724/api#203
2026-07-20 16:30:15 +03:30
8ba97537a4 update the fanavaran for both tejarat no and parsian clients , dont forget about the env files 2026-07-20 16:28:25 +03:30
70160543a2 Merge pull request 'Fixed v2 mirror' (#202) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#202
2026-07-20 11:45:26 +03:30
61f4181065 Merge pull request 'BUG fix of status' (#201) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#201
2026-07-19 16:51:15 +03:30
b2ad43d050 Merge pull request 'YARA-1020' (#200) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#200
2026-07-19 16:35:15 +03:30
213cdd765b Merge pull request 'YARA-985' (#199) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#199
2026-07-19 11:47:12 +03:30
318a5c74dd Merge pull request 'removed guard' (#198) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#198
2026-07-18 16:14:59 +03:30
1f4a520145 Merge pull request 'Removed the guard of accidentWay' (#197) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#197
2026-07-18 16:03:55 +03:30
0420eda35f Merge pull request 'Edited 2 APIs names' (#196) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#196
2026-07-18 15:28:27 +03:30
b129c1ef9b Merge pull request 'YARA-1061, Fixed v3 mirror flow' (#195) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#195
2026-07-18 15:02:18 +03:30
5e4897f609 Fix empty Rocket.Chat notify (Woodpecker ${} escaping) 2026-07-15 17:06:27 +03:30
a79c3ca05f Fix git pull SSH in pipeline (host keys + known_hosts) 2026-07-15 16:59:46 +03:30
36fa1c552e Allow git in bind-mounted workspace (safe.directory) 2026-07-15 16:43:31 +03:30
9742fecc11 Update .woodpecker.yml 2026-07-15 16:35:40 +03:30
8007c30efd Fix path typo of workspace 2026-07-15 16:26:06 +03:30
144f8f3e2a Update .woodpecker.yml docker repositories 2026-07-15 16:05:01 +03:30
8674dd8762 Merge pull request 'Fixed v4/v5 car capture flow' (#194) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#194
2026-07-15 16:00:01 +03:30
64 changed files with 3852 additions and 589 deletions

View File

@@ -5,6 +5,10 @@ NODE_ENV =
PORT =
CLIENT_ID =
CLIENT_NAME =
FANAVARAN_CLIENT=parsian
INSURANCE_CORP_ID='شرکت بيمه پارسيان(بيمه گر)'
CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED=false
CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN=53000000
# ---------------------------------------------
# 🌐 Application URLs
# ---------------------------------------------
@@ -63,6 +67,23 @@ AUTH_SMS_TEMPLATE =
EXP_OTP_TIME =
FAKE_OTP =
# ---------------------------------------------
# 🌐 Proxy Configuration (Local Development Only)
# ---------------------------------------------
# NOTE: These proxy settings are for local development only.
# When deploying to the server, comment out or remove these lines
# as the server IP is already whitelisted by Fanavaran.
# SOCKS_PROXY_HOST = localhost
# SOCKS_PROXY_PORT = 6565
# ---------------------------------------------
# 🏢 Fanavaran Insurance Corp
# ---------------------------------------------
# Caption from Fanavaran insurance-corp lookup used to resolve InsuranceCorpId
# for damage-case payloads. Must match a Caption in the insurance-corp code-list.
# Example: "شرکت بيمه تجارت نو"
INSURANCE_CORP_ID =
# ---------------------------------------------
# ⚙️ Application Features / Flags
# ---------------------------------------------

View File

@@ -10,8 +10,11 @@ when:
skip_clone: true
variables:
- &host_workspace /data/1-deploy/gitea/yara724/api
- &workspace_volume /data/1-deploy/gitea/yara724/api:/workspace
- &host_ssh /home/talieh/.ssh:/root/.ssh:ro
- &pipeline_env
WORKSPACE: /data/1-delploy/gitea/yara724/api
WORKSPACE: *host_workspace
PROJECT_NAME: Yara724 API
ENVIRONMENT: Development
APPLICATION_URL: https://y724-user.ittalie.ir/api
@@ -23,41 +26,46 @@ variables:
steps:
pull:
image: alpine/git:latest
image: docker.arvancloud.ir/alpine/git:latest
environment:
<<: *pipeline_env
GIT_SSH_COMMAND: ssh -o UserKnownHostsFile=/tmp/known_hosts -o StrictHostKeyChecking=yes
volumes:
- /data/1-delploy/gitea/yara724/api:/workspace
- *workspace_volume
- *host_ssh
commands:
- 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
- date +%s > /workspace/.wp-deploy-start
deploy:
image: docker:24-cli
image: docker.arvancloud.ir/docker:24-cli
environment:
<<: *pipeline_env
volumes:
- /var/run/docker.sock:/var/run/docker.sock
- /data/1-delploy/gitea/yara724/api:/workspace
- *workspace_volume
commands:
- cd /workspace
- docker compose -f docker-compose.yml up -d --build
notify-success:
image: alpine:3.20
image: docker.arvancloud.ir/alpine:3.20
environment:
<<: *pipeline_env
ROCKETCHAT_WEBHOOK:
from_secret: rocketchat_webhook
volumes:
- /data/1-delploy/gitea/yara724/api:/workspace
- *workspace_volume
when:
- status: success
commands:
- apk add --no-cache curl jq git > /dev/null
- |
set -euo pipefail
git config --global --add safe.directory /workspace
cd /workspace
COMMIT_HASH="$(git rev-parse --short HEAD)"
@@ -69,20 +77,20 @@ steps:
COMMIT_2="$(git log -2 --pretty=format:'%s' | tail -n1)"
COMMIT_3="$(git log -3 --pretty=format:'%s' | tail -n1)"
TITLE="✅ ${PROJECT_NAME} - ${ENVIRONMENT} ✅"
TEXT="🌐 **URL**: ${APPLICATION_URL}
TITLE="✅ $PROJECT_NAME - $ENVIRONMENT ✅"
TEXT="🌐 **URL**: $APPLICATION_URL
🔖 **Commit Hash**: [${COMMIT_HASH}](${GIT_COMMIT_URL}${COMMIT_HASH})
🔖 **Commit Hash**: [$COMMIT_HASH]($GIT_COMMIT_URL$COMMIT_HASH)
📝 **Recent Changes**:
• ${COMMIT_1}
• $COMMIT_1
• ${COMMIT_2}
• $COMMIT_2
• ${COMMIT_3}
• $COMMIT_3
⏱️ **Deployment Duration**: ${DEPLOY_DURATION}s"
⏱️ **Deployment Duration**: $${DEPLOY_DURATION}s"
payload="$(jq -n \
--arg title "$TITLE" \
@@ -94,31 +102,32 @@ steps:
rm -f /workspace/.wp-deploy-start
notify-failure:
image: alpine:3.20
image: docker.arvancloud.ir/alpine:3.20
environment:
<<: *pipeline_env
ROCKETCHAT_WEBHOOK:
from_secret: rocketchat_webhook
volumes:
- /data/1-delploy/gitea/yara724/api:/workspace
- *workspace_volume
when:
- status: failure
commands:
- apk add --no-cache curl jq git > /dev/null
- |
set -euo pipefail
git config --global --add safe.directory /workspace
cd /workspace
COMMIT_HASH="$(git rev-parse --short HEAD 2>/dev/null || echo unknown)"
TITLE="💥 ${PROJECT_NAME} - ${ENVIRONMENT} 💥"
TITLE="💥 $PROJECT_NAME - $ENVIRONMENT 💥"
TEXT="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
🌐 **Application URL**
${APPLICATION_URL}
$APPLICATION_URL
🔖 **Commit**
\`${COMMIT_HASH}\`
\`$COMMIT_HASH\`
⚠️ **Pipeline failed** — check Woodpecker for the failing step.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

View File

@@ -274,6 +274,20 @@ curl -X GET "$FANAVARAN_BIME_URL/car/code-list/accident-culprit-type" \
-H "ContractId: $CONTRACT_ID" \
-H "Location: $LOCATION" \
-H "Content-Type: application/json"
curl -X GET "$FANAVARAN_BIME_URL/car/base-info/vehicle-kinds" \
-H "authenticationToken: $AUTHENTICATION_TOKEN" \
-H "CorpId: $CORP_ID" \
-H "ContractId: $CONTRACT_ID" \
-H "Location: $LOCATION" \
-H "Content-Type: application/json"
curl -X GET "$FANAVARAN_BIME_URL/car/vehicles/inquiry-by-vin?vin=IRNKAEK4150012345" \
-H "authenticationToken: $AUTHENTICATION_TOKEN" \
-H "CorpId: $CORP_ID" \
-H "ContractId: $CONTRACT_ID" \
-H "Location: $LOCATION" \
-H "Content-Type: application/json"
```
### 3B. Policy Inquiry By National Code

View File

@@ -45,6 +45,7 @@
"pdfkit": "^0.19.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1",
"socks-proxy-agent": "^8.0.4",
"svg-captcha": "^1.4.0"
},
"devDependencies": {

View File

@@ -0,0 +1,86 @@
#!/usr/bin/env node
/**
* Quick manual verification for plate normalization.
*
* Usage: node scripts/verify-plate-normalization.mjs
*
* Demonstrates that:
* 339ه77 (ه + U+200D) -> 339ه77 -> letter ه -> code 15
* 339ي77 (Arabic ي) -> 339ی77 -> letter ی -> code 16
*/
// ---------- paste the pure function here so no build needed ----------
function normalizePlateText(text) {
if (!text) return text;
let result = String(text);
result = result.normalize("NFKC");
result = result.replace(/[\u200C\u200D\u200E\u200F\uFEFF]/g, "");
result = result.replace(/\u064A/g, "\u06CC"); // Arabic ي → Persian ی
result = result.trim();
return result;
}
// ---------- the canonical plate-letter → code mapping ----------
const PLATE_LETTER_MAP = {
الف: 1, ب: 2, پ: 3, ج: 4, د: 5,
س: 6, ص: 7, ط: 8, ع: 9, ق: 10,
ل: 11, م: 12, ن: 13, و: 14, ه: 15,
ی: 16, ک: 17, ژ: 18, ت: 19, ث: 20,
ز: 21, ش: 22, ف: 23, گ: 24,
};
function extractAndMap(plateString) {
const normalized = normalizePlateText(plateString);
// Simple parser: digits | letter | digits (left+right digits, 1 letter)
const match = normalized.match(/^(\d+)([^\d]+)(\d+)$/);
if (!match) return { input: plateString, normalized, error: "no match" };
const [, leftDigits, letterRaw, rightDigits] = match;
const letter = normalizePlateText(letterRaw);
const code = PLATE_LETTER_MAP[letter];
return {
input: plateString,
normalized,
leftDigits,
letter,
rightDigits,
code,
ok: code !== undefined,
};
}
// ---------- test cases ----------
const cases = [
{ desc: "ه + ZWJ (the original bug)", plate: "339ه\u200D77" },
{ desc: "Arabic ي → Persian ی", plate: "339ي77" },
{ desc: "ه + ZWNJ", plate: "339ه\u200C77" },
{ desc: "RTL mark around letter", plate: "339\u200Fه\u200E77" },
{ desc: "BOM + ZWJ combined", plate: "\uFEFF339ه\u200D77" },
{ desc: "clean letter (no junk)", plate: "339ه77" },
{ desc: "full plate: الف", plate: "11الف22" },
{ desc: "full plate: ی", plate: "55ی99" },
];
console.log("Plate Normalization Verification\n");
console.log("=".repeat(72));
let allPassed = true;
for (const { desc, plate } of cases) {
const r = extractAndMap(plate);
const status = r.ok ? "PASS" : "FAIL";
if (!r.ok) allPassed = false;
console.log(`\n[${status}] ${desc}`);
console.log(` Input: ${JSON.stringify(plate)}`);
console.log(` Normalized: ${JSON.stringify(r.normalized)}`);
if (r.letter) {
console.log(` Letter: ${r.letter} (U+${r.letter.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")})`);
}
console.log(` Code: ${r.code ?? "undefined"}`);
}
console.log("\n" + "=".repeat(72));
console.log(allPassed ? "\n All tests PASSED ✓" : "\n Some tests FAILED ✗");
process.exit(allPassed ? 0 : 1);

View File

@@ -9,4 +9,5 @@ export enum RoleEnum {
FILE_MAKER = "file_maker",
FILE_REVIEWER = "file_reviewer",
SUPER_ADMIN = "super_admin",
CALL_CENTER = "call_center",
}

View File

@@ -1,9 +1,8 @@
import { HttpModule } from "@nestjs/axios";
import { Module } from "@nestjs/common";
import { AiService } from "./ai.service";
@Module({
imports: [HttpModule],
imports: [],
providers: [AiService],
exports: [AiService],
})

View File

@@ -1,7 +1,8 @@
import { join } from "node:path";
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
import { Module } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { HttpModule } from "@nestjs/axios";
import { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor";
import { MongooseModule } from "@nestjs/mongoose";
import { ServeStaticModule } from "@nestjs/serve-static";
@@ -28,9 +29,15 @@ import { WorkflowStepManagementModule } from "./workflow-step-management/workflo
import { DatabaseModule } from "./core/database/database.module";
import { AppConfigModule } from "./core/config/config.module";
import { SuperAdminModule } from "./super-admin/super-admin.module";
import { createHttpModuleOptions } from "./core/config/http-proxy.factory";
@Module({
imports: [
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
AppConfigModule,
DatabaseModule,
CronModule,

View File

@@ -29,6 +29,7 @@ import { FieldExpertDbService } from "src/users/entities/db-service/field-expert
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service";
import { HashService } from "src/utils/hash/hash.service";
import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service";
import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service";
@@ -58,6 +59,7 @@ export class ActorAuthService {
private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService,
private readonly superAdminDbService: SuperAdminDbService,
private readonly callCenterAgentDbService: CallCenterAgentDbService,
) {}
// TODO convrt to class for dynamic controller
@@ -123,6 +125,14 @@ export class ActorAuthService {
});
else res = await this.superAdminDbService.findByLoginIdentifier(username);
break;
case RoleEnum.CALL_CENTER:
if (username == null && userId)
res = await this.callCenterAgentDbService.findOne({
_id: new Types.ObjectId(userId),
});
else
res = await this.callCenterAgentDbService.findByLoginIdentifier(username);
break;
default:
return null;
}

View File

@@ -46,6 +46,7 @@ export class LocalActorAuthGuard implements CanActivate {
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
RoleEnum.SUPER_ADMIN,
RoleEnum.CALL_CENTER,
].includes(payload.role)
) {
throw new UnauthorizedException("User role is not authorized");

View File

@@ -1,5 +1,8 @@
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { AiModule } from "src/ai/ai.module";
import { SandHubModule } from "src/sand-hub/sand-hub.module";
import { RequestManagementModule } from "src/request-management/request-management.module";
@@ -52,15 +55,20 @@ import { ClientModule } from "src/client/client.module";
import { ClaimAccessGuard } from "src/auth/guards/claim-access.guard";
import { JwtModule } from "@nestjs/jwt";
import { MediaPolicyModule } from "src/media-policy/media-policy.module";
import { HttpModule } from "@nestjs/axios";
import { FanavaranAuditModule } from "src/fanavaran/fanavaran-audit.module";
import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module";
import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normalizer.module";
@Module({
imports: [
HttpModule,
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
FanavaranAuditModule,
FanavaranLookupModule,
PlateNormalizerModule,
PublicIdModule,
UsersModule,
RequestManagementModule,

View File

@@ -106,14 +106,16 @@ export class SelectOtherPartsV2ResponseDto {
@ApiProperty({
description: 'Sheba number (masked for security)',
example: 'IR12************1234',
required: false,
})
shebaNumber: string;
shebaNumber?: string;
@ApiProperty({
description: 'National code of owner (masked)',
example: '12******90',
required: false,
})
nationalCodeOfOwner: string;
nationalCodeOfOwner?: string;
@ApiProperty({
description: 'Current workflow step',

View File

@@ -86,6 +86,15 @@ export class FanavaranSyncStage {
@Prop({ type: MongooseSchema.Types.Mixed })
response?: unknown;
@Prop({ type: Number, default: 0 })
retryCount?: number;
@Prop({ type: Number, default: 2 })
maxRetries?: number;
@Prop({ type: Date })
nextRetryAt?: Date;
}
export const FanavaranSyncStageSchema =
SchemaFactory.createForClass(FanavaranSyncStage);
@@ -256,6 +265,21 @@ export class ClaimCase {
@Prop({ type: Types.ObjectId, index: true })
fileMakerApprovalActorId?: Types.ObjectId;
/**
* V5 split flow: number of times the FileMaker has rejected this claim.
* Capped at 2; on the 3rd attempt the reject endpoint returns 422 and
* the FileMaker must approve instead.
*/
@Prop({ type: Number, default: 0 })
fileMakerRejectionCount?: number;
/**
* V5 split flow: reason text from the most recent FileMaker rejection.
* Overwritten on each rejection.
*/
@Prop({ type: String })
fileMakerRejectionReason?: string;
/**
* Legacy fields kept optional to simplify progressive migration.
* If you choose to migrate later, we can remove these.

View File

@@ -4,9 +4,12 @@ import {
Body,
Controller,
Get,
HttpException,
InternalServerErrorException,
Param,
Patch,
Post,
Put,
Query,
UploadedFile,
UseGuards,
@@ -50,6 +53,7 @@ import {
CapturePartV2ResponseDto,
} from "./dto/capture-part-v2.dto";
import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-v2.dto";
import { Role } from "src/common/auth/enums";
/**
* Expert-initiated claim flow that mirrors the normal user claim API
@@ -68,7 +72,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-
@Controller("v2/expert-initiated/claim-request-management")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@Roles(RoleEnum.FIELD_EXPERT)
@Roles(RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER, RoleEnum.FILE_REVIEWER)
export class ExpertInitiatedClaimMirrorController {
constructor(
private readonly claimRequestManagementService: ClaimRequestManagementService,
@@ -78,7 +82,8 @@ export class ExpertInitiatedClaimMirrorController {
@Post("create-from-blame/:blameRequestId")
@ApiParam({ name: "blameRequestId" })
@ApiOperation({
summary: "[Expert mirror] Create claim from expert-initiated IN_PERSON blame",
summary:
"[Expert mirror] Create claim from expert-initiated IN_PERSON blame",
description:
"Blame must be COMPLETED. Creates a ClaimCase owned by the damaged (non-guilty) party.",
})
@@ -170,8 +175,7 @@ export class ExpertInitiatedClaimMirrorController {
})
@ApiBody({
type: SelectOuterPartsV2Dto,
description:
"Selected vehicle type + selected outer part IDs from catalog",
description: "Selected vehicle type + selected outer part IDs from catalog",
examples: {
example1: {
summary: "Sedan - minor front damage",
@@ -208,7 +212,10 @@ export class ExpertInitiatedClaimMirrorController {
description: "Outer parts selected successfully",
type: SelectOuterPartsV2ResponseDto,
})
@ApiResponse({ status: 400, description: "Invalid workflow step or validation failed" })
@ApiResponse({
status: 400,
description: "Invalid workflow step or validation failed",
})
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({ status: 409, description: "Outer parts already selected" })
async selectOuterParts(
@@ -293,9 +300,15 @@ Optional: upload car green card file in the same step.
description: "Other parts and bank information saved successfully",
type: SelectOtherPartsV2ResponseDto,
})
@ApiResponse({ status: 400, description: "Invalid workflow step or validation failed" })
@ApiResponse({
status: 400,
description: "Invalid workflow step or validation failed",
})
@ApiResponse({ status: 404, description: "Claim case not found" })
@ApiResponse({ status: 409, description: "Bank information already submitted" })
@ApiResponse({
status: 409,
description: "Bank information already submitted",
})
async selectOtherParts(
@Param("claimRequestId") claimRequestId: string,
@Body() body: SelectOtherPartsV2Dto,
@@ -516,6 +529,81 @@ Returns status of each item (uploaded/captured or not).
);
}
// ─── Owner signature on expert pricing ───────────────────────────────────────
@Put("claim-sign/:claimRequestId")
@ApiParam({ name: "claimRequestId" })
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "Signature file, agreement, and branch",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
properties: {
sign: {
type: "string",
format: "binary",
description: "Signature image",
},
agree: {
type: "boolean",
description: "true to accept, false to reject",
},
branchId: { type: "string", description: "Insurer branch ID" },
},
},
})
@ApiOperation({
summary:
"Owner signature on expert pricing (Flow 3 — expert acts on behalf of user)",
description:
"Field expert submits the damaged party's signature during the final approval stage. " +
"Delegates to the same service method as the user sign endpoint; the expert's " +
"identity is resolved to the claim owner via `resolveClaimEffectiveUserId`.",
})
@UseInterceptors(
FileInterceptor("sign", {
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
},
}),
}),
)
async submitOwnerSign(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() expert: any,
@UploadedFile() sign: Express.Multer.File,
) {
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
const agreed =
typeof agree === "string"
? agree === "true" || agree === "1"
: Boolean(agree);
try {
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
expert.sub,
expert,
);
} catch (error) {
if (error instanceof HttpException) throw error;
throw new InternalServerErrorException(
error instanceof Error ? error.message : "Failed to submit signature",
);
}
}
@Patch("car-capture/:claimRequestId")
@ApiConsumes("multipart/form-data")
@UseInterceptors(

View File

@@ -20,7 +20,9 @@ export class AuthGuard implements CanActivate {
}
try {
const payload: JwtPayload =
await this.jwtService.verifyAsync<JwtPayload>(token);
await this.jwtService.verifyAsync<JwtPayload>(token, {
secret: `${process.env.JWT_SECRET}`,
});
request["user"] = payload;
} catch {
throw new UnauthorizedException("Invalid or expired token");

View File

@@ -37,6 +37,7 @@ export interface FanavaranPayloadDefaults {
AccidentReportTypeId: number;
AccidentVehicleUsedId: number;
ClaimExpertId: number;
ExpertiseClaimExpertId: number;
CompensationReferenceId: number;
CulpritLicenceTypeId: number;
CulpritTypeId: number;
@@ -74,7 +75,8 @@ const FANAVARAN_CLIENT_PROFILES: Record<
AccidentCityId: 701,
AccidentReportTypeId: 155,
AccidentVehicleUsedId: 1,
ClaimExpertId: 1589,
ClaimExpertId: 4543092,
ExpertiseClaimExpertId: 4543092,
CompensationReferenceId: 167,
CulpritLicenceTypeId: 2,
CulpritTypeId: 337,
@@ -84,7 +86,7 @@ const FANAVARAN_CLIENT_PROFILES: Record<
PlaqueSampleId: 10,
DriverIsOwner: 0,
FaultPercent: 100,
ClaimFileTypeId: 70,
ClaimFileTypeId: 23,
},
},
parsian: {
@@ -103,6 +105,7 @@ const FANAVARAN_CLIENT_PROFILES: Record<
AccidentReportTypeId: 155,
AccidentVehicleUsedId: 1,
ClaimExpertId: 154,
ExpertiseClaimExpertId: 29,
CompensationReferenceId: 167,
CulpritLicenceTypeId: 2,
CulpritTypeId: 337,

View File

@@ -0,0 +1,26 @@
import { ConfigService } from "@nestjs/config";
import { HttpModuleOptions } from "@nestjs/axios";
import { SocksProxyAgent } from "socks-proxy-agent";
/**
* Shared HttpModule.registerAsync factory that applies the SOCKS proxy
* when SOCKS_PROXY_HOST + SOCKS_PROXY_PORT env vars are set.
* Used by every module that imports HttpModule.
*/
export function createHttpModuleOptions(
configService: ConfigService,
): HttpModuleOptions | Promise<HttpModuleOptions> {
const socksHost = configService.get<string>("SOCKS_PROXY_HOST");
const socksPort = configService.get<string>("SOCKS_PROXY_PORT");
if (socksHost && socksPort) {
const proxyUrl = `socks5://${socksHost}:${socksPort}`;
const agent = new SocksProxyAgent(proxyUrl);
return {
httpsAgent: agent,
httpAgent: agent,
proxy: false,
};
}
return {};
}

View File

@@ -1871,6 +1871,7 @@ export class ExpertBlameService {
link: this.smsOrchestrationService.buildBlamePartyLink(
requestIdToken,
role,
"v1",
),
});
}
@@ -2065,6 +2066,7 @@ export class ExpertBlameService {
link: this.smsOrchestrationService.buildBlamePartyLink(
requestIdToken,
linkRole,
"v1",
),
});
}

View File

@@ -77,6 +77,19 @@ export class ClaimListItemV2Dto {
example: true,
})
requiresFileMakerApproval?: boolean;
@ApiPropertyOptional({
description:
"V5 only. Number of times the FileMaker has rejected this claim (02). When this reaches 2 the FileMaker can only approve.",
example: 1,
})
fileMakerRejectionCount?: number;
@ApiPropertyOptional({
description: "V5 only. Reason text supplied with the most recent FileMaker rejection.",
example: "Damage assessment is incorrect — please re-evaluate parts X and Y",
})
fileMakerRejectionReason?: string;
}
export class GetClaimListV2ResponseDto {

View File

@@ -22,4 +22,5 @@ export class BusinessRuleException extends HttpException {
export const BusinessErrorCode = {
DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED: "DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED",
FILE_MAKER_REJECTION_LIMIT_EXCEEDED: "FILE_MAKER_REJECTION_LIMIT_EXCEEDED",
} as const;

View File

@@ -1,5 +1,7 @@
import { HttpModule } from "@nestjs/axios";
import { Module } from "@nestjs/common";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { MongooseModule } from "@nestjs/mongoose";
import { AiModule } from "src/ai/ai.module";
import { AuthModule } from "src/auth/auth.module";
@@ -21,7 +23,11 @@ import { ExpertClaimService } from "./expert-claim.service";
@Module({
imports: [
HttpModule,
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
SandHubModule,
MongooseModule.forFeature([
{ name: ClaimFactorsImage.name, schema: ClaimFactorsImageSchema },

View File

@@ -2429,24 +2429,20 @@ export class ExpertClaimService {
await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCompleted(
claimRequestId,
);
const fanavaranExpertise =
await this.claimRequestManagementService.autoSubmitFanavaranExpertiseOnExpertReply(
claimRequestId,
);
// Expertise (stage 4) is intentionally NOT submitted here.
// It is only triggered after the owner's final approval signature
// (submitOwnerInsurerApprovalSignV2), because until that point the
// expert review is not considered final — the user can still object.
return {
message: this.appendFanavaranAutoSubmitToMessage(
this.appendFanavaranAutoSubmitToMessage(
"Factors were reviewed with expert repricing on rejected lines. The claim is completed without an owner signature (temporary policy; may require owner acceptance later).",
fanavaran,
),
fanavaranExpertise,
"Factors were reviewed with expert repricing on rejected lines. The claim is completed without an owner signature (temporary policy; may require owner acceptance later).",
fanavaran,
),
claimRequestId,
claimStatus: ClaimStatus.APPROVED,
caseStatus: ClaimCaseStatus.COMPLETED,
outcome: "REJECTED_REPRICED_AUTO_COMPLETED",
fanavaran,
fanavaranExpertise,
};
}
@@ -2463,25 +2459,21 @@ export class ExpertClaimService {
await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCompleted(
claimRequestId,
);
const fanavaranExpertise =
await this.claimRequestManagementService.autoSubmitFanavaranExpertiseOnExpertReply(
claimRequestId,
);
// Expertise (stage 4) is intentionally NOT submitted here.
// It is only triggered after the owner's final approval signature
// (submitOwnerInsurerApprovalSignV2), because until that point the
// expert review is not considered final — the user can still object.
return {
message: this.appendFanavaranAutoSubmitToMessage(
this.appendFanavaranAutoSubmitToMessage(
"All factors were approved by the expert. The claim is completed without an additional owner signature.",
fanavaran,
),
fanavaranExpertise,
"All factors were approved by the expert. The claim is completed without an additional owner signature.",
fanavaran,
),
claimRequestId,
claimStatus: ClaimStatus.APPROVED,
caseStatus: ClaimCaseStatus.COMPLETED,
outcome: "ALL_APPROVED_AUTO_COMPLETED",
fanavaran,
fanavaranExpertise,
};
}
@@ -3164,7 +3156,7 @@ export class ExpertClaimService {
receptor: ownerPhoneResend,
fileKind: "claim",
publicId: claim.publicId,
link: this.smsOrchestrationService.buildClaimLink(String(claim._id)),
link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"),
});
}
@@ -3462,21 +3454,11 @@ export class ExpertClaimService {
fileKind: "claim",
publicId: claim.publicId,
expertLastName,
link: this.smsOrchestrationService.buildClaimLink(String(claim._id)),
link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"),
});
}
const fanavaranExpertise = !needsFactorUpload
? await this.claimRequestManagementService.autoSubmitFanavaranExpertiseOnExpertReply(
claimRequestId,
)
: {
attempted: false,
submitted: false,
skipped: true,
skipReason:
"Expertise submit waits until factor-needed repair lines are validated.",
};
// Fanavaran expertise is now triggered on owner final sign, not here.
return {
claimRequestId,
@@ -3490,7 +3472,6 @@ export class ExpertClaimService {
mixedPricingAndFactors: mixedFactorAndPrice,
allPartsFactorNeeded: !!needsFactorUpload && !!allFactorLines,
isFinalReplyAfterObjection,
fanavaranExpertise,
};
}
@@ -3727,14 +3708,19 @@ export class ExpertClaimService {
let claims: any[] = [];
if (actor.role === RoleEnum.FIELD_EXPERT) {
const expertOid = new Types.ObjectId(actor.sub);
// Exclude V4/V5 blame files — same rule as getFieldExpertClaimListV2.
const expertBlameIds = await this.blameRequestDbService
.find(
{ expertInitiated: true, initiatedByFieldExpertId: expertOid },
{
expertInitiated: true,
initiatedByFieldExpertId: expertOid,
isMadeByFileMaker: { $ne: true },
},
{ select: "_id", lean: true },
)
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [
{ initiatedByFieldExpertId: expertOid },
{ initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } },
];
if (expertBlameIds.length > 0) {
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
@@ -4063,15 +4049,22 @@ export class ExpertClaimService {
query: ListQueryV2Dto = {},
): Promise<GetClaimListV2ResponseDto> {
const expertOid = new Types.ObjectId(actor.sub);
// Exclude V4/V5 blame files (isMadeByFileMaker=true) — those belong to
// the FILE_MAKER/FILE_REVIEWER flows, not the V3 field-expert flow.
const expertBlameIds = await this.blameRequestDbService
.find(
{ expertInitiated: true, initiatedByFieldExpertId: expertOid },
{
expertInitiated: true,
initiatedByFieldExpertId: expertOid,
isMadeByFileMaker: { $ne: true },
},
{ select: "_id", lean: true },
)
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
const claimOr: Record<string, unknown>[] = [
{ initiatedByFieldExpertId: expertOid },
// Direct claim link: exclude V5 claims that require FileMaker approval
{ initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } },
];
if (expertBlameIds.length > 0) {
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
@@ -4147,12 +4140,14 @@ export class ExpertClaimService {
/**
* Claim list for FILE_REVIEWER.
*
* Visibility rules:
* Visibility rules (both V4 and V5 files):
* - WAITING_FOR_FILE_REVIEWER files made by a FileMaker that are either:
* (a) not yet assigned to any reviewer, OR
* (b) already assigned to THIS reviewer
* - WAITING_FOR_EXPERT files that are assigned to THIS reviewer
* (they completed the field work and the file is now in damage-expert queue)
* - Files already assigned to THIS reviewer (any post-assignment status)
*
* V4: isMadeByFileMaker=true, requiresFileMakerApproval=false
* V5: isMadeByFileMaker=true, requiresFileMakerApproval=true
*
* All scoped to this reviewer's insurance company via blame party clientId.
*/
@@ -4163,7 +4158,7 @@ export class ExpertClaimService {
const clientKey = requireActorClientKey(actor);
const reviewerOid = new Types.ObjectId(actor.sub);
// Find V4 blame files visible to this reviewer
// Find V4 and V5 blame files visible to this reviewer
const blames = (await this.blameRequestDbService.find(
{
isMadeByFileMaker: true,
@@ -4185,7 +4180,7 @@ export class ExpertClaimService {
{
lean: true,
select:
"_id type parties blameStatus status expert.decision assignedFileReviewerId",
"_id type parties blameStatus status expert.decision assignedFileReviewerId requiresFileMakerApproval",
},
)) as any[];
@@ -4254,6 +4249,9 @@ export class ExpertClaimService {
(!!blame?.isMadeByFileMaker &&
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
assignedToMe: !!assignedToMe,
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0,
fileMakerRejectionReason: (c as any).fileMakerRejectionReason ?? undefined,
};
}) as ClaimListItemV2Dto[];
@@ -4261,8 +4259,9 @@ export class ExpertClaimService {
}
/**
* Claim list for FILE_MAKER — returns only the claims linked to blame files
* they personally created (V4 flow).
* Claim list for FILE_MAKER — returns claims linked to blame files they
* personally created (V4 and V5 flows).
* V4: requiresFileMakerApproval=false · V5: requiresFileMakerApproval=true
*/
private async getFileMakerClaimListV2(
actor: any,
@@ -4272,7 +4271,7 @@ export class ExpertClaimService {
const makerBlames = (await this.blameRequestDbService.find(
{ isMadeByFileMaker: true, initiatedByFieldExpertId: makerOid },
{ lean: true, select: "_id type parties blameStatus status expert.decision assignedFileReviewerId" },
{ lean: true, select: "_id type parties blameStatus status expert.decision assignedFileReviewerId requiresFileMakerApproval" },
)) as any[];
if (makerBlames.length === 0) {
@@ -4280,9 +4279,10 @@ export class ExpertClaimService {
}
const blameIds = makerBlames.map((b) => b._id);
// Include all claims linked to this maker's blames — both V4 (requiresFileMakerApproval=false)
// and V5 (requiresFileMakerApproval=true).
const claims = (await this.claimCaseDbService.find({
blameRequestId: { $in: blameIds },
requiresFileMakerApproval: true,
})) as any[];
const blameById = new Map<string, any>(
@@ -4325,6 +4325,8 @@ export class ExpertClaimService {
createdAt: c.createdAt,
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
fileMakerRejectionCount: (c as any).fileMakerRejectionCount ?? 0,
fileMakerRejectionReason: (c as any).fileMakerRejectionReason ?? undefined,
needsFileReviewerCompletion:
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
(!!blame?.isMadeByFileMaker &&
@@ -4749,8 +4751,19 @@ export class ExpertClaimService {
"This file has been taken by another reviewer.",
);
}
} else if (!claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame)) {
throw new ForbiddenException("This claim is not accessible to you.");
} else {
// FIELD_EXPERT: V3 flow only. Reject V4/V5 files (isMadeByFileMaker)
// even if their ID matches initiatedByFieldExpertId on the blame —
// those are FILE_MAKER files, accessible via the FILE_MAKER role only.
const isV4V5Blame = !!(linkedBlame as any)?.isMadeByFileMaker;
if (isV4V5Blame) {
throw new ForbiddenException(
"Field experts can only access V3 expert-initiated files.",
);
}
if (!claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame)) {
throw new ForbiddenException("This claim is not accessible to you.");
}
}
// Fall through to the detail build below (skip the damage-expert gate)
} else if (actor.role !== RoleEnum.FILE_MAKER) {

View File

@@ -1,3 +1,4 @@
import { readFile } from "node:fs/promises";
import {
Body,
Controller,
@@ -117,6 +118,21 @@ export class ExpertClaimV2Controller {
return this.claimRequestManagementService.getOuterPartsCatalogV2(carType);
}
@Get("inner-parts-catalog")
@ApiOperation({
summary: "Get inner parts catalog",
description: "Returns the full list of inner car parts from the static catalog.",
})
@ApiResponse({ status: 200, description: "Inner parts catalog (object keyed by part name)" })
async getInnerPartsCatalog() {
const raw = await readFile(`${process.cwd()}/src/static/car-part.json`, "utf-8");
try {
return JSON.parse(raw);
} catch {
return raw;
}
}
@Get("branches")
@ApiOperation({
summary: "List insurer branches for this damage expert (V2)",

View File

@@ -76,6 +76,37 @@ export const FANAVARAN_REMOTE_LOOKUPS: FanavaranRemoteLookupDefinition[] = [
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/person-role`,
cacheFile: "person-role.json",
},
{
name: "insurance-corp",
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/insurance-corp`,
cacheFile: "insurance-corp.json",
},
{
name: "file-types",
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/base-info/file-types`,
cacheFile: "file-types.json",
},
// NEW LOOKUPS ADDED
{
name: "cities",
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/base-info/cities`,
cacheFile: "cities.json",
},
{
name: "dmg-case-type",
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/code-list/dmg-case-type`,
cacheFile: "dmg-case-type.json",
},
{
name: "dmg-history-status",
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/code-list/dmg-case-history-status`,
cacheFile: "dmg-history-status.json",
},
{
name: "provinces",
url: `${FANAVARAN_LOOKUP_BASE_URL}/common/base-info/Provinces`,
cacheFile: "provinces.json",
},
];
export const TEJARAT_STATIC_ACCIDENT_FILES = {

View File

@@ -1,9 +1,17 @@
import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { FanavaranLookupService } from "./fanavaran-lookup.service";
@Module({
imports: [HttpModule],
imports: [
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
],
providers: [FanavaranLookupService],
exports: [FanavaranLookupService],
})

View File

@@ -183,24 +183,6 @@ export class FanavaranLookupService {
this.logger.log(
`[${clientKey}] Fanavaran lookup response status=${response.status} dataCount=${dataCount}`,
);
this.logger.log(
`[${clientKey}] Fanavaran lookup raw response: ${JSON.stringify(
response.data,
null,
2,
)}`,
);
if (Array.isArray(response.data) && response.data.length > 0) {
const firstItem = response.data[0];
if (firstItem && typeof firstItem === "object") {
this.logger.log(
`[${clientKey}] Fanavaran lookup first item keys: ${Object.keys(
firstItem,
).join(", ")}`,
);
}
}
return response.data;
} catch (error) {
@@ -255,6 +237,51 @@ export class FanavaranLookupService {
return this.fetchFromFanavaran(clientKey, url);
}
async myPolicies(
clientKey: FanavaranClientKey,
nationalCode: string,
insuranceLineId: number = 5,
): Promise<unknown> {
const url =
`${FANAVARAN_LOOKUP_BASE_URL}/common/Policies/inquiry-my-policies` +
`?InsuranceLineId=${insuranceLineId}` +
`&NationalCode=${encodeURIComponent(nationalCode)}`;
return this.fetchFromFanavaran(clientKey, url);
}
async thirdPartyPolicyById(
clientKey: FanavaranClientKey,
policyId: number,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/third-party-car-policies/${policyId}`;
return this.fetchFromFanavaran(clientKey, url);
}
async bodyPolicyById(
clientKey: FanavaranClientKey,
policyId: number,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicle-hull-policies/${policyId}`;
return this.fetchFromFanavaran(clientKey, url);
}
async vehicleById(
clientKey: FanavaranClientKey,
vehicleId: number,
versionNo: number = 1,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicles/${vehicleId}?versionno=${versionNo}`;
return this.fetchFromFanavaran(clientKey, url);
}
async customerById(
clientKey: FanavaranClientKey,
customerId: number,
): Promise<unknown> {
const url = `${FANAVARAN_LOOKUP_BASE_URL}/common/customers/${customerId}`;
return this.fetchFromFanavaran(clientKey, url);
}
async inquiryByUniqueIdentifier(
clientKey: FanavaranClientKey,
params: {
@@ -273,6 +300,91 @@ export class FanavaranLookupService {
return this.fetchFromFanavaran(clientKey, url);
}
async resolveInsuranceCorpId(
clientKey: FanavaranClientKey,
): Promise<number | null> {
const caption = process.env.INSURANCE_CORP_ID?.trim();
if (!caption) {
this.logger.warn("resolveInsuranceCorpId: INSURANCE_CORP_ID env not set");
return null;
}
// Check resolved cache first
const cachedId = await this.readCacheFile<number>(clientKey, "insurance-corp-id-resolved.json");
if (cachedId !== null) {
this.logger.log(`resolveInsuranceCorpId: using cached id=${cachedId} for "${caption}"`);
return cachedId;
}
// Try fetching the full list directly from Fanavaran
let companies: unknown;
const url = `${FANAVARAN_LOOKUP_BASE_URL}/common/code-list/insurance-corp`;
try {
companies = await this.fetchFromFanavaran(clientKey, url);
} catch (error) {
this.logger.warn(
`resolveInsuranceCorpId: Fanavaran fetch failed, trying local lookup endpoint`,
);
// Fallback: call our own local lookup endpoint
try {
const localPort = process.env.PORT || 3000;
const response = await firstValueFrom(
this.httpService.get(`http://localhost:${localPort}/lookups/fanavaran/insurance-corp`, {
timeout: 10000,
}),
);
companies = response.data;
} catch (localError) {
this.logger.error(
`resolveInsuranceCorpId: both Fanavaran and local lookup failed`,
);
return null;
}
}
if (!Array.isArray(companies)) {
this.logger.warn(
`resolveInsuranceCorpId: insurance-corp response is not an array, type=${typeof companies}`,
);
return null;
}
this.logger.log(
`resolveInsuranceCorpId: got ${companies.length} companies, searching for "${caption}"`,
);
const normalizedCaption = caption
.replace(/\s+/g, " ")
.toLowerCase()
.trim();
const match = companies.find((c: any) => {
if (c?.IsActive !== 1) return false;
if (typeof c?.Id !== "number") return false;
const cCaption = typeof c?.Caption === "string" ? c.Caption : "";
const normalized = cCaption.replace(/\s+/g, " ").toLowerCase().trim();
return normalized.includes(normalizedCaption) || normalizedCaption.includes(normalized);
});
if (!match) {
this.logger.warn(
`resolveInsuranceCorpId: no active company matching "${caption}". Available: ` +
companies
.filter((c: any) => c?.IsActive === 1)
.map((c: any) => `${c.Caption} (${c.Id})`)
.join(", "),
);
return null;
}
const corpId = match.Id as number;
// Cache both the resolved id and the full list for future use
await this.writeCacheFile(clientKey, "insurance-corp-id-resolved.json", corpId);
await this.writeCacheFile(clientKey, "insurance-corp.json", companies);
this.logger.log(`resolveInsuranceCorpId: resolved id=${corpId} for "${caption}"`);
return corpId;
}
mapFanavaranAccidentCausesToReasonOptions(
causes: unknown,
): { id: number; label: string; fanavaran: number }[] {
@@ -297,4 +409,5 @@ export class FanavaranLookupService {
};
});
}
}

View File

@@ -1,14 +1,18 @@
import { Controller, Get, Param, Query } from "@nestjs/common";
import { Controller, Get, Param, ParseIntPipe, Query, UseGuards } from "@nestjs/common";
import {
ApiBearerAuth,
ApiOkResponse,
ApiOperation,
ApiParam,
ApiQuery,
ApiTags,
} from "@nestjs/swagger";
import { AuthGuard } from "src/common/auth/guards";
import { LookupsService } from "./lookups.service";
@ApiTags("lookups")
@ApiBearerAuth()
@UseGuards(AuthGuard)
@Controller("lookups")
export class LookupsController {
constructor(private readonly lookupsService: LookupsService) {}
@@ -210,6 +214,83 @@ export class LookupsController {
return await this.lookupsService.getPersonRole();
}
@Get("file-types")
@ApiOperation({
summary: "Fanavaran file types lookup",
description:
"Returns file type codes from common/base-info/file-types. Use FileTypeId in attachment uploads.",
})
@ApiOkResponse({
description: "Returns Fanavaran file types lookup data",
schema: {
type: "array",
items: {
type: "object",
properties: {
Caption: { type: "string" },
Id: { type: "number" },
IsActive: { type: "number" },
},
},
},
})
async getFileTypes() {
return await this.lookupsService.getFileTypes();
}
@Get("cities")
@ApiOperation({
summary: "Fanavaran cities lookup",
description: "Returns city codes from common/base-info/cities.",
})
@ApiOkResponse({
description: "Returns Fanavaran cities lookup data",
schema: { type: "array", items: { type: "object" } },
})
async cities() {
return await this.lookupsService.getCities();
}
@Get("provinces")
@ApiOperation({
summary: "Fanavaran provinces lookup",
description: "Returns province codes from common/base-info/provinces.",
})
@ApiOkResponse({
description: "Returns Fanavaran provinces lookup data",
schema: { type: "array", items: { type: "object" } },
})
async provinces() {
return await this.lookupsService.getProvinces();
}
@Get("dmg-case-type")
@ApiOperation({
summary: "Fanavaran damage case type lookup",
description: "Returns damage case type codes from car/code-list/dmg-case-type.",
})
@ApiOkResponse({
description: "Returns Fanavaran damage case type lookup data",
schema: { type: "array", items: { type: "object" } },
})
async dmgCaseType() {
return await this.lookupsService.getDmgCaseType();
}
@Get("dmg-history-status")
@ApiOperation({
summary: "Fanavaran damage history status lookup",
description:
"Returns damage history status codes from car/code-list/dmg-case-history-status.",
})
@ApiOkResponse({
description: "Returns Fanavaran damage history status lookup data",
schema: { type: "array", items: { type: "object" } },
})
async dmgHistoryStatus() {
return await this.lookupsService.getDmgHistoryStatus();
}
@Get("inquiry-by-vin")
@ApiOperation({
summary: "Fanavaran vehicle inquiry by VIN",
@@ -371,4 +452,75 @@ export class LookupsController {
async getAccidentFields() {
return await this.lookupsService.getAccidentFields();
}
@Get("my-policies")
@ApiOperation({
summary: "My policies inquiry",
description:
"Returns the list of policies for the given national code via common/Policies/inquiry-my-policies.",
})
@ApiQuery({
name: "nationalCode",
description: "National code of the insured person",
example: "0012345678",
})
@ApiQuery({
name: "insuranceLineId",
description: "Insurance line ID (default: 5 for car)",
required: false,
example: 5,
})
@ApiOkResponse({
description: "Returns list of policies",
schema: { type: "array", items: { type: "object" } },
})
async myPolicies(
@Query("nationalCode") nationalCode: string,
@Query("insuranceLineId") insuranceLineId?: number,
) {
return await this.lookupsService.myPolicies(
nationalCode,
insuranceLineId ?? 5,
);
}
@Get("third-party-policy/:policyId")
@ApiOperation({
summary: "Third-party car policy inquiry by policy ID",
description:
"Returns third-party car insurance policy details for the given policy ID via car/third-party-car-policies/{policyId}.",
})
@ApiParam({
name: "policyId",
description: "Fanavaran policy ID",
example: 12345,
})
@ApiOkResponse({
description: "Returns third-party policy details",
schema: { type: "object" },
})
async thirdPartyPolicyById(
@Param("policyId", ParseIntPipe) policyId: number,
) {
return await this.lookupsService.thirdPartyPolicyById(policyId);
}
@Get("body-policy/:policyId")
@ApiOperation({
summary: "Vehicle hull (body) policy inquiry by policy ID",
description:
"Returns vehicle hull (body) insurance policy details for the given policy ID via car/vehicle-hull-policies/{policyId}.",
})
@ApiParam({
name: "policyId",
description: "Fanavaran policy ID",
example: 12345,
})
@ApiOkResponse({
description: "Returns body policy details",
schema: { type: "object" },
})
async bodyPolicyById(@Param("policyId", ParseIntPipe) policyId: number) {
return await this.lookupsService.bodyPolicyById(policyId);
}
}

View File

@@ -123,11 +123,109 @@ export class LookupsService {
return await this.getClientRemoteLookup("person-role");
}
async getFileTypes(): Promise<any> {
return await this.getClientRemoteLookup("file-types");
}
async getCities(): Promise<any> {
return await this.getClientRemoteLookup("cities");
}
async getProvinces(): Promise<any> {
return await this.getClientRemoteLookup("provinces");
}
async getDmgCaseType(): Promise<any> {
return await this.getClientRemoteLookup("dmg-case-type");
}
async getDmgHistoryStatus(): Promise<any> {
return await this.getClientRemoteLookup("dmg-history-status");
}
async inquiryByVin(vin: string): Promise<unknown> {
const clientKey = this.activeClientKey();
return this.fanavaranLookupService.inquiryByVin(clientKey, vin);
}
async myPolicies(
nationalCode: string,
insuranceLineId: number = 5,
): Promise<unknown> {
const clientKey = this.activeClientKey();
return this.fanavaranLookupService.myPolicies(
clientKey,
nationalCode,
insuranceLineId,
);
}
async mapPolicyDetails(policy: any): Promise<any> {
if (!policy || typeof policy !== "object") {
return policy;
}
const mappedPolicy = { ...policy };
// 1. Map PreviousInsuranceCorpId and TransferorInsuranceCorpId
try {
const companies = (await this.getClientRemoteLookup("insurance-corp")) as any[];
if (Array.isArray(companies)) {
if (typeof policy.PreviousInsuranceCorpId === "number") {
const match = companies.find((c) => c.Id === policy.PreviousInsuranceCorpId);
if (match) {
mappedPolicy.PreviousInsuranceCorpName = match.Caption;
}
}
if (typeof policy.TransferorInsuranceCorpId === "number") {
const match = companies.find((c) => c.Id === policy.TransferorInsuranceCorpId);
if (match) {
mappedPolicy.TransferorInsuranceCorpName = match.Caption;
}
}
}
} catch (e) {
this.logger.warn(`Failed to map insurance-corp lookups: ${e.message}`);
}
// 2. Map PolicyUsageTypeId
try {
const useTypes = (await this.getClientRemoteLookup("vehicle-use-types")) as any[];
if (Array.isArray(useTypes) && typeof policy.PolicyUsageTypeId === "number") {
const match = useTypes.find((t) => t.Id === policy.PolicyUsageTypeId);
if (match) {
mappedPolicy.PolicyUsageTypeName = match.Caption;
}
}
} catch (e) {
this.logger.warn(`Failed to map vehicle-use-types lookups: ${e.message}`);
}
return mappedPolicy;
}
async thirdPartyPolicyById(policyId: number): Promise<unknown> {
const clientKey = this.activeClientKey();
const policy = await this.fanavaranLookupService.thirdPartyPolicyById(clientKey, policyId);
return this.mapPolicyDetails(policy);
}
async bodyPolicyById(policyId: number): Promise<unknown> {
const clientKey = this.activeClientKey();
const policy = await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId);
return this.mapPolicyDetails(policy);
}
async vehicleById(vehicleId: number, versionNo: number = 1): Promise<unknown> {
const clientKey = this.activeClientKey();
return this.fanavaranLookupService.vehicleById(clientKey, vehicleId, versionNo);
}
async customerById(customerId: number): Promise<unknown> {
const clientKey = this.activeClientKey();
return this.fanavaranLookupService.customerById(clientKey, customerId);
}
async getAccidentWay(): Promise<{ id: number; label: string }[]> {
const clientKey = this.activeClientKey();
const fileName = TEJARAT_STATIC_ACCIDENT_FILES.accidentWay;

View File

@@ -4,6 +4,7 @@ import { ClientModule } from "src/client/client.module";
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
import { SandHubModule } from "src/sand-hub/sand-hub.module";
import { UsersModule } from "src/users/users.module";
import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normalizer.module";
import { PlatesModel, PlatesSchema } from "./entites/schema/plate.schema";
import { PlatesService } from "./plates.service";
@@ -12,6 +13,7 @@ import { PlatesService } from "./plates.service";
UsersModule,
SandHubModule,
ClientModule,
PlateNormalizerModule,
MongooseModule.forFeature([
{ name: PlatesModel.name, schema: PlatesSchema },
]),

View File

@@ -7,20 +7,23 @@ import {
import { Types } from "mongoose";
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
@Injectable()
export class PlatesService {
constructor(
private readonly plateDbService: PlateDbService,
private readonly plateNormalizer: PlateNormalizerService,
) {}
async addPlate(currentUser, body: AddPlateDto) {
const { plate, nationalCodeOfInsurer } = body;
const normalizedAlphabet = this.plateNormalizer.normalizePlateText(String(plate.centerAlphabet || ""));
const duplicate = await this.plateDbService.findOne({
userId: currentUser,
leftDigits: plate.leftDigits,
centerAlphabet: plate.centerAlphabet,
centerAlphabet: normalizedAlphabet,
centerDigits: plate.centerDigits,
ir: plate.ir,
nationalCodeOfInsurer,
@@ -31,6 +34,7 @@ export class PlatesService {
const newPlateData = await this.plateDbService.create({
...plate,
centerAlphabet: normalizedAlphabet,
userId: currentUser,
nationalCodeOfInsurer: body.nationalCodeOfInsurer,
});

View File

@@ -0,0 +1,154 @@
import {
Body,
Controller,
Get,
Param,
Post,
UseGuards,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiBody,
ApiOperation,
ApiParam,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
import { RolesGuard } from "src/auth/guards/role.guard";
import { Roles } from "src/decorators/roles.decorator";
import { CurrentUser } from "src/decorators/user.decorator";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { RequestManagementService } from "./request-management.service";
import { RunCallCenterInquiryV6Dto } from "./dto/run-call-center-inquiry-v6.dto";
/**
* V6 call-center blame API.
*
* A call-center agent takes the guilty party's details over the phone
* (plate, national code, birthday), runs the insurance inquiry, then sends
* the blame link via SMS. The user (guilty party) opens the link and
* completes the form through the standard v2 user flow — except the
* initial-form / inquiry step is skipped (`skipInitialFormStep=true`) because
* the agent already did it.
*
* For THIRD_PARTY files: only the guilty party's data is collected here.
* The damaged party sees their own portion of the page and fills their info
* as normal after the blame link is opened.
*/
@ApiTags("call-center-blame (v6)")
@Controller("v6/call-center-blame")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard, RolesGuard)
@Roles(RoleEnum.CALL_CENTER)
export class CallCenterBlameV6Controller {
constructor(
private readonly requestManagementService: RequestManagementService,
) {}
@Get("my-files")
@ApiOperation({ summary: "[V6] List blame files created by this call-center agent" })
@ApiResponse({ status: 200, description: "List of blame files started by this agent" })
getMyFiles(@CurrentUser() agent: any) {
return this.requestManagementService.getMyCallCenterFilesV6(agent);
}
@Post("create")
@ApiOperation({
summary: "[V6] Create a call-centerinitiated blame file",
description:
"Creates a LINK blame file. The call-center agent collects the guilty " +
"party's plate + national-code over the phone, calls run-inquiry to store " +
"the results, then calls send-link to SMS the blame URL to the user. " +
"The user opens the link and fills the form via the normal v2 flow; the " +
"initial-form/inquiry step is automatically skipped because the agent " +
"already ran it.",
})
@ApiBody({
schema: {
type: "object",
required: ["type"],
properties: {
type: {
type: "string",
enum: ["THIRD_PARTY", "CAR_BODY"],
example: "THIRD_PARTY",
},
},
},
})
createFile(
@CurrentUser() agent: any,
@Body("type") type: "THIRD_PARTY" | "CAR_BODY",
) {
return this.requestManagementService.createCallCenterInitiatedBlameV6(agent, { type });
}
@Post("run-inquiry/:requestId")
@ApiOperation({
summary: "[V6] Run plate + insurance inquiry for the guilty party",
description:
"Call after `create`. The agent supplies the plate and national-code data " +
"collected from the caller. Plate + third-party block inquiry is executed " +
"and the results are stored on the blame document. " +
"For THIRD_PARTY files only the guilty party (first party) is inquired here; " +
"the damaged party's inquiry is handled later by the user via the link. " +
"Sheba (IBAN) is not collected here — the user adds it themselves.",
})
@ApiParam({ name: "requestId", description: "Blame request ID from `create`" })
@ApiBody({ type: RunCallCenterInquiryV6Dto })
runInquiry(
@CurrentUser() agent: any,
@Param("requestId") requestId: string,
@Body() dto: RunCallCenterInquiryV6Dto,
) {
return this.requestManagementService.runCallCenterInquiryV6(agent, requestId, dto);
}
@Post("send-link/:requestId")
@ApiOperation({
summary: "[V6] Send blame link to the guilty party via SMS",
description:
"Call after `run-inquiry`. Provide the guilty party's phone number; " +
"the service registers the user if needed, stores them as the first party, " +
"and sends the blame invite link via SMS. The user opens the link and " +
"completes the blame form via the standard v2 user flow (initial-form step skipped).",
})
@ApiParam({ name: "requestId", description: "Blame request ID" })
@ApiBody({
schema: {
type: "object",
required: ["phoneNumber"],
properties: {
phoneNumber: {
type: "string",
example: "09121234567",
description: "Mobile number of the guilty party",
},
},
},
})
sendLink(
@CurrentUser() agent: any,
@Param("requestId") requestId: string,
@Body("phoneNumber") phoneNumber: string,
) {
return this.requestManagementService.sendCallCenterLinkV6(agent, requestId, { phoneNumber });
}
@Get("blame/:requestId")
@ApiOperation({
summary: "[V6] Get a single blame file created by this agent",
description:
"Returns the current status, workflow step, and party data for one blame " +
"file started by this call-center agent. Useful for checking whether the " +
"user has opened the link and progressed through the form.",
})
@ApiParam({ name: "requestId", description: "Blame request ID" })
getBlame(
@CurrentUser() agent: any,
@Param("requestId") requestId: string,
) {
return this.requestManagementService.getCallCenterBlameDetailV6(agent, requestId);
}
}

View File

@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { IsEnum, IsOptional, IsString } from "class-validator";
import { IsBoolean, IsEnum, IsOptional } from "class-validator";
import { CreationMethod } from "../entities/schema/request-management.schema";
export class CreateExpertInitiatedFileDto {
@@ -18,4 +18,17 @@ export class CreateExpertInitiatedFileDto {
})
@IsEnum(CreationMethod)
creationMethod: CreationMethod;
/**
* V5 only. When true the resulting claim will require FileMaker approval
* before fanavaran submission. V4 files must leave this unset (or false).
*/
@ApiPropertyOptional({
description:
"V5 only — when true the claim requires FileMaker approval before fanavaran submission.",
example: false,
})
@IsBoolean()
@IsOptional()
requiresFileMakerApproval?: boolean;
}

View File

@@ -0,0 +1,85 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import {
IsBoolean,
IsNotEmpty,
IsOptional,
IsString,
ValidateNested,
} from "class-validator";
import { Type } from "class-transformer";
class PlateV6Dto {
@ApiProperty({ example: "44", description: "Left two digits" })
@IsString()
@IsNotEmpty()
leftDigits: string;
@ApiProperty({ example: "ب", description: "Center alphabet letter" })
@IsString()
@IsNotEmpty()
centerAlphabet: string;
@ApiProperty({ example: "111", description: "Center three digits" })
@IsString()
@IsNotEmpty()
centerDigits: string;
@ApiProperty({ example: "22", description: "Right two digits (Iran region code)" })
@IsString()
@IsNotEmpty()
ir: string;
}
/**
* Inquiry body for the V6 call-center flow.
* Same as V3 but without `sheba` — the user adds their own IBAN later via the link.
*/
export class RunCallCenterInquiryV6Dto {
@ApiProperty({
type: PlateV6Dto,
description: "Plate segments — Tejarat block / third-party inquiry.",
})
@ValidateNested()
@Type(() => PlateV6Dto)
plate: PlateV6Dto;
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
@IsString()
@IsNotEmpty()
nationalCodeOfInsurer: string;
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
@IsString()
@IsNotEmpty()
nationalCodeOfDriver: string;
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
@IsBoolean()
driverIsInsurer: boolean;
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
insurerBirthday: number | string;
@ApiPropertyOptional({
example: 13780624,
description: "Driver birth date (Jalali). Required when driverIsInsurer is false.",
})
@IsOptional()
driverBirthday?: number | string | null;
@ApiPropertyOptional({
example: "123456789",
description: "Driver license (required when driverIsInsurer is false).",
})
@IsOptional()
@IsString()
driverLicense?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Insurer license (required when driverIsInsurer is true).",
})
@IsOptional()
@IsString()
insurerLicense?: string;
}

View File

@@ -4,6 +4,7 @@ import {
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
ValidateNested,
} from "class-validator";
import { Type } from "class-transformer";
@@ -89,3 +90,66 @@ export class RunInquiriesV3Dto {
@IsString()
insurerLicense?: string;
}
/**
* Body for `POST run-inquiries-vin/:requestId`.
* Identical to RunInquiriesV3Dto but uses `vin` (17-char chassis number) instead of `plate`.
* First call = guilty party (+ auto claim). Second call = damaged party (THIRD_PARTY only).
*/
export class RunInquiriesVinV3Dto {
@ApiProperty({
example: "NAAM01E15HK123456",
description: "17-character VIN / chassis number (شماره شاسی)",
maxLength: 17,
})
@IsString()
@IsNotEmpty()
@MaxLength(17)
vin: string;
@ApiProperty({ example: "1234567890", description: "National code of the policyholder (insurer)" })
@IsString()
@IsNotEmpty()
nationalCodeOfInsurer: string;
@ApiProperty({ example: "1234567890", description: "National code of the driver" })
@IsString()
@IsNotEmpty()
nationalCodeOfDriver: string;
@ApiProperty({ example: true, description: "Whether the driver is the same person as the insurer" })
@IsBoolean()
driverIsInsurer: boolean;
@ApiProperty({ example: 13780624, description: "Insurer birth date (Jalali)" })
insurerBirthday: number | string;
@ApiPropertyOptional({ example: 13780624, description: "Driver birth date (Jalali). Required when driverIsInsurer is false." })
@IsOptional()
driverBirthday?: number | string | null;
@ApiPropertyOptional({
example: "IR123456789012345678901234",
description:
"Sheba (IBAN). Required on the damaged party call (CAR_BODY first call; THIRD_PARTY second call).",
})
@IsOptional()
@IsString()
sheba?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Driver license (required when driverIsInsurer is false).",
})
@IsOptional()
@IsString()
driverLicense?: string;
@ApiPropertyOptional({
example: "123456789",
description: "Insurer license (required when driverIsInsurer is true).",
})
@IsOptional()
@IsString()
insurerLicense?: string;
}

View File

@@ -117,12 +117,40 @@ export class BlameRequest {
@Prop({ default: false })
isMadeByFileMaker?: boolean;
/**
* V5 only. When true the resulting claim requires FileMaker approval before
* fanavaran submission. V4 files never set this; it is written at creation
* time by the V5 controller and propagated to the linked claim.
*/
@Prop({ default: false })
requiresFileMakerApproval?: boolean;
/**
* The FileReviewer who claimed this file for completion (V4 flow only).
* Set when a FileReviewer calls assign on this file; enforces one-reviewer-per-file.
*/
@Prop({ type: Types.ObjectId })
assignedFileReviewerId?: Types.ObjectId;
/**
* V6 call-center flow: true when this blame was started by a call-center agent
* on behalf of the guilty party who called in.
*/
@Prop({ default: false })
callCenterInitiated?: boolean;
/**
* V6 call-center flow: the call-center agent who created this file.
*/
@Prop({ type: Types.ObjectId })
initiatedByCallCenterId?: Types.ObjectId;
/**
* V6 call-center flow: when true the user-side blame page should skip the
* inquiry / initial-form step (the call-center agent already ran the inquiry).
*/
@Prop({ default: false })
skipInitialFormStep?: boolean;
}
export type BlameRequestDocument = HydratedDocument<BlameRequest>;

View File

@@ -41,6 +41,10 @@ export class Person {
@Prop({ type: String })
driverBirthday?: string | null;
/** Cached Fanavaran party ID resolved from nationalCodeOfDriver + driverBirthday + driverIsInsurer */
@Prop({ type: Number })
fanavaranDriverId?: number;
}
export const PersonSchema = SchemaFactory.createForClass(Person);

View File

@@ -31,7 +31,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
import { CreationMethod } from "./entities/schema/request-management.schema";
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
import {
CarBodyFormDto,
DescriptionDto,
@@ -181,6 +181,23 @@ export class ExpertInitiatedBlameV3MirrorController {
return this.requestManagementService.runInquiriesV3(requestId, expert, dto);
}
@Post("run-inquiries-vin/:requestId")
@ApiParam({ name: "requestId" })
@ApiBody({ type: RunInquiriesVinV3Dto })
@ApiOperation({
summary: "Run VIN/chassis inquiries for the current party (V3)",
description:
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
})
async runInquiriesVin(
@CurrentUser() expert: any,
@Param("requestId") requestId: string,
@Body() dto: RunInquiriesVinV3Dto,
) {
return this.requestManagementService.runInquiriesVinV3(requestId, expert, dto);
}
@Post("add-detail-location/:requestId")
@ApiParam({ name: "requestId" })
@ApiBody({ type: LocationDto })

View File

@@ -27,6 +27,7 @@ import { MediaPolicyService } from "src/media-policy/media-policy.service";
import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
import { InitialFormVinDto } from "./dto/create-request-management.dto";
import {
BlameConfessionDtoV2,
CarBodyFormDto,
@@ -34,6 +35,7 @@ import {
LocationDto,
} from "./dto/create-request-management.dto";
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
import { CreationMethod } from "./entities/schema/request-management.schema";
import { SendPartyOtpsDto } from "./dto/send-party-otps.dto";
import { VerifyPartyOtpsDto } from "./dto/verify-party-otps.dto";
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
@@ -75,17 +77,17 @@ export class ExpertInitiatedBlameMirrorController {
@ApiOperation({
summary: "[Expert mirror] Create expert-initiated blame file",
description:
"Use creationMethod=IN_PERSON for the on-site flow. Creates a BlameRequest owned by the parties but filled by the expert.",
"Creates an IN_PERSON blame file filled by the expert on behalf of both parties. creationMethod is always forced to IN_PERSON regardless of what is sent.",
})
@ApiBody({ type: CreateExpertInitiatedFileDto })
async create(
@CurrentUser() expert: any,
@Body() dto: CreateExpertInitiatedFileDto,
) {
return this.requestManagementService.createExpertInitiatedBlameV2(
expert,
dto,
);
return this.requestManagementService.createExpertInitiatedBlameV2(expert, {
...dto,
creationMethod: CreationMethod.IN_PERSON,
});
}
@Post("send-link/:requestId")
@@ -180,6 +182,29 @@ export class ExpertInitiatedBlameMirrorController {
);
}
@Post("/run-inquiries-vin/:requestId")
@ApiParam({ name: "requestId" })
@ApiBody({ type: InitialFormVinDto })
@ApiOperation({
summary: "[Expert mirror] Initial form via VIN/chassis inquiry for current party",
description:
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
"Fills the FIRST or SECOND party insurance/vehicle data depending on the current workflow step.",
})
async initialFormVin(
@Param("requestId") requestId: string,
@Body() body: InitialFormVinDto,
@CurrentUser() expert: any,
@Body("partyRole") partyRole?: string,
) {
return this.requestManagementService.initialFormVinV2(
requestId,
body,
expert,
partyRole,
);
}
@ApiBody({
schema: {
type: "object",

View File

@@ -30,7 +30,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
import { CreationMethod } from "./entities/schema/request-management.schema";
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
import {
CarBodyFormDto,
DescriptionDto,
@@ -87,7 +87,9 @@ export class FileMakerBlameV4Controller {
) {
return this.requestManagementService.createExpertInitiatedBlameV2(
fileMaker,
{ ...dto, creationMethod: CreationMethod.IN_PERSON },
// requiresFileMakerApproval is V5-only; explicitly exclude it from V4 so
// a client that accidentally sends the field cannot poison the blame record.
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: false },
);
}
@@ -191,6 +193,27 @@ export class FileMakerBlameV4Controller {
);
}
@Post("run-inquiries-vin/:requestId")
@ApiParam({ name: "requestId" })
@ApiBody({ type: RunInquiriesVinV3Dto })
@ApiOperation({
summary: "Run VIN/chassis inquiries for the current party (V4)",
description:
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
})
async runInquiriesVin(
@CurrentUser() fileMaker: any,
@Param("requestId") requestId: string,
@Body() dto: RunInquiriesVinV3Dto,
) {
return this.requestManagementService.runInquiriesVinV3(
requestId,
fileMaker,
dto,
);
}
// ─── Party details ────────────────────────────────────────────────────────────
@Post("add-detail-location/:requestId")

View File

@@ -30,7 +30,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
import { CreationMethod } from "./entities/schema/request-management.schema";
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto";
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
import { RunInquiriesV3Dto } from "./dto/run-inquiries-v3.dto";
import { RunInquiriesV3Dto, RunInquiriesVinV3Dto } from "./dto/run-inquiries-v3.dto";
import {
CarBodyFormDto,
DescriptionDto,
@@ -88,7 +88,7 @@ export class FileMakerBlameV5Controller {
) {
return this.requestManagementService.createExpertInitiatedBlameV2(
fileMaker,
{ ...dto, creationMethod: CreationMethod.IN_PERSON },
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: true },
);
}
@@ -192,6 +192,27 @@ export class FileMakerBlameV5Controller {
);
}
@Post("run-inquiries-vin/:requestId")
@ApiParam({ name: "requestId" })
@ApiBody({ type: RunInquiriesVinV3Dto })
@ApiOperation({
summary: "Run VIN/chassis inquiries for the current party (V5)",
description:
"VIN alternative to run-inquiries. Uses ESG chassis lookup instead of plate-based inquiry. " +
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
})
async runInquiriesVin(
@CurrentUser() fileMaker: any,
@Param("requestId") requestId: string,
@Body() dto: RunInquiriesVinV3Dto,
) {
return this.requestManagementService.runInquiriesVinV3(
requestId,
fileMaker,
dto,
);
}
// ─── Party details ────────────────────────────────────────────────────────────
@Post("add-detail-location/:requestId")

View File

@@ -10,6 +10,7 @@ import {
ApiBody,
ApiOperation,
ApiParam,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { IsOptional, IsString } from "class-validator";
@@ -91,9 +92,28 @@ export class FileMakerClaimApprovalV5Controller {
@ApiOperation({
summary: "Reject the completed claim back to FileReviewer (FileMaker V5)",
description:
"Rejects a claim that is in WAITING_FOR_FILE_MAKER_APPROVAL status. " +
"Moves claim to FILE_MAKER_REJECTED so the FileReviewer can re-lock, " +
"adjust the damage assessment, and restart user interaction as needed.",
"Rejects a claim that is in `WAITING_FOR_FILE_MAKER_APPROVAL` status. " +
"Moves the claim back to `WAITING_FOR_DAMAGE_EXPERT` and the linked blame back to " +
"`WAITING_FOR_FILE_REVIEWER` so the FileReviewer can re-lock, adjust the damage " +
"assessment, and restart user interaction as needed.\n\n" +
"**Rejection limit:** the FileMaker may reject at most **2 times** per claim. " +
"On the 3rd attempt the endpoint returns **422** with " +
"`errorCode: FILE_MAKER_REJECTION_LIMIT_EXCEEDED` — the FileMaker must approve instead. " +
"The current count is returned as `fileMakerRejectionCount` in the response and in " +
"`GET v2/expert-claim/requests`.",
})
@ApiResponse({
status: 422,
description:
"Business rule violation: rejection limit exceeded. " +
"`errorCode: FILE_MAKER_REJECTION_LIMIT_EXCEEDED` — the claim has already been rejected twice.",
schema: {
example: {
errorCode: "FILE_MAKER_REJECTION_LIMIT_EXCEEDED",
message:
"This claim has already been rejected twice. You must approve it now — no further rejections are allowed.",
},
},
})
async reject(
@Param("claimRequestId") claimRequestId: string,

View File

@@ -1,11 +1,15 @@
import { extname } from "node:path";
import {
BadRequestException,
Body,
Controller,
Get,
HttpException,
InternalServerErrorException,
Param,
Patch,
Post,
Put,
UploadedFile,
UseGuards,
UseInterceptors,
@@ -316,6 +320,73 @@ export class FileReviewerBlameV4Controller {
);
}
// ─── Owner signature on expert pricing ───────────────────────────────────────
@Put("claim-sign/:claimRequestId")
@ApiParam({ name: "claimRequestId" })
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "Signature file, agreement, and branch",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
properties: {
sign: { type: "string", format: "binary", description: "Signature image" },
agree: { type: "boolean", description: "true to accept, false to reject" },
branchId: { type: "string", description: "Insurer branch ID" },
},
},
})
@ApiOperation({
summary: "Owner signature on expert pricing (V4 — FileReviewer acts on behalf of user)",
description:
"FileReviewer submits the damaged party's signature during the final approval stage. " +
"Delegates to the same service method as the user sign endpoint; the FileReviewer's " +
"identity is resolved to the claim owner via `resolveClaimEffectiveUserId`.",
})
@UseInterceptors(
FileInterceptor("sign", {
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
},
}),
}),
)
async submitOwnerSign(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() fileReviewer: any,
@UploadedFile() sign: Express.Multer.File,
) {
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
const agreed =
typeof agree === "string"
? agree === "true" || agree === "1"
: Boolean(agree);
try {
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
fileReviewer.sub,
fileReviewer,
);
} catch (error) {
if (error instanceof HttpException) throw error;
throw new InternalServerErrorException(
error instanceof Error ? error.message : "Failed to submit signature",
);
}
}
// ─── Walk-around video ────────────────────────────────────────────────────────
@Patch("car-capture/:claimRequestId")

View File

@@ -3,9 +3,12 @@ import {
Body,
Controller,
Get,
HttpException,
InternalServerErrorException,
Param,
Patch,
Post,
Put,
UploadedFile,
UseGuards,
UseInterceptors,
@@ -315,6 +318,73 @@ export class FileReviewerBlameV5Controller {
);
}
// ─── Owner signature on expert pricing ───────────────────────────────────────
@Put("claim-sign/:claimRequestId")
@ApiParam({ name: "claimRequestId" })
@ApiConsumes("multipart/form-data")
@ApiBody({
description: "Signature file, agreement, and branch",
schema: {
type: "object",
required: ["sign", "agree", "branchId"],
properties: {
sign: { type: "string", format: "binary", description: "Signature image" },
agree: { type: "boolean", description: "true to accept, false to reject" },
branchId: { type: "string", description: "Insurer branch ID" },
},
},
})
@ApiOperation({
summary: "Owner signature on expert pricing (V5 — FileReviewer acts on behalf of user)",
description:
"FileReviewer submits the damaged party's signature during the final approval stage. " +
"Delegates to the same service method as the user sign endpoint; the FileReviewer's " +
"identity is resolved to the claim owner via `resolveClaimEffectiveUserId`.",
})
@UseInterceptors(
FileInterceptor("sign", {
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
storage: diskStorage({
destination: "./files/claim-sign",
filename: (req, file, callback) => {
const unique = Date.now();
const ex = extname(file.originalname);
const base = file.originalname.split(/[.,\s-]/)[0] || "sign";
callback(null, `${base}-${unique}${ex}`);
},
}),
}),
)
async submitOwnerSign(
@Param("claimRequestId") claimRequestId: string,
@Body("agree") agree: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() fileReviewer: any,
@UploadedFile() sign: Express.Multer.File,
) {
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
const agreed =
typeof agree === "string"
? agree === "true" || agree === "1"
: Boolean(agree);
try {
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
claimRequestId,
agreed,
typeof branchId === "string" ? branchId : "",
sign,
fileReviewer.sub,
fileReviewer,
);
} catch (error) {
if (error instanceof HttpException) throw error;
throw new InternalServerErrorException(
error instanceof Error ? error.message : "Failed to submit signature",
);
}
}
// ─── Walk-around video ────────────────────────────────────────────────────────
@Patch("car-capture/:claimRequestId")

View File

@@ -7,6 +7,7 @@ import {
import { Types } from "mongoose";
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
import { SandHubService } from "src/sand-hub/sand-hub.service";
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { BlameRequestDbService } from "./entities/db-service/blame-request.db.service";
import { PartyRole } from "./entities/schema/partyRole.enum";
@@ -33,6 +34,7 @@ export class InquiryRefreshService {
private readonly blameRequestDbService: BlameRequestDbService,
private readonly claimCaseDbService: ClaimCaseDbService,
private readonly sandHubService: SandHubService,
private readonly plateNormalizer: PlateNormalizerService,
) {}
async reinquiryInquiries(
@@ -592,7 +594,7 @@ export class InquiryRefreshService {
centerDigits !== undefined &&
ir !== undefined
) {
const plateLetter = String(centerAlphabet).trim();
const plateLetter = this.plateNormalizer.normalizePlateText(String(centerAlphabet));
const parsed: PlateParts = {
leftDigits: Number(leftDigits),
centerAlphabet: plateLetter,
@@ -622,8 +624,7 @@ export class InquiryRefreshService {
const ir = Number(irRaw);
const leftDigits = Number(leftRaw);
const centerDigits = Number(centerRaw);
const centerAlphabet = String(alphaRaw || "").trim();
const centerAlphabet = this.plateNormalizer.normalizePlateText(String(alphaRaw || ""));
if (
!Number.isFinite(ir) ||
!Number.isFinite(leftDigits) ||

View File

@@ -28,6 +28,7 @@ import { MediaPolicyService } from "src/media-policy/media-policy.service";
import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
import { InitialFormVinDto } from "./dto/create-request-management.dto";
import {
CarBodyFormDto,
DescriptionDto,
@@ -165,6 +166,29 @@ export class RegistrarBlameMirrorController {
);
}
@Post("/initial-form-vin/:requestId")
@ApiParam({ name: "requestId" })
@ApiBody({ type: InitialFormVinDto })
@ApiOperation({
summary: "[Registrar mirror] Initial form via VIN/chassis inquiry for current party",
description:
"VIN alternative to initial-form. Uses ESG chassis lookup instead of plate-based inquiry. " +
"Fills the FIRST or SECOND party insurance/vehicle data depending on the current workflow step.",
})
async initialFormVin(
@Param("requestId") requestId: string,
@Body() body: InitialFormVinDto,
@CurrentUser() registrar: any,
@Body("partyRole") partyRole?: string,
) {
return this.requestManagementService.initialFormVinV2(
requestId,
body,
registrar,
partyRole,
);
}
@ApiBody({
schema: {
type: "object",

View File

@@ -12,6 +12,7 @@ import { UsersModule } from "src/users/users.module";
import { CronModule } from "src/utils/cron/cron.module";
import { PublicIdModule } from "src/utils/public-id/public-id.module";
import { HashModule } from "src/utils/hash/hash.module";
import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normalizer.module";
import { SmsOrchestrationModule } from "src/sms-orchestration/sms-orchestration.module";
import { WorkflowStepManagementModule } from "src/workflow-step-management/workflow-step-management.module";
import { AuthModule } from "src/auth/auth.module";
@@ -50,6 +51,7 @@ import { FileReviewerBlameV5Controller } from "./file-reviewer-blame-v5.controll
import { FileMakerClaimApprovalV5Controller } from "./file-maker-claim-approval-v5.controller";
import { InquiryRefreshController } from "./inquiry-refresh.controller";
import { InquiryRefreshService } from "./inquiry-refresh.service";
import { CallCenterBlameV6Controller } from "./call-center-blame-v6.controller";
@Module({
imports: [
@@ -59,6 +61,7 @@ import { InquiryRefreshService } from "./inquiry-refresh.service";
SmsOrchestrationModule,
PublicIdModule,
HashModule,
PlateNormalizerModule,
WorkflowStepManagementModule,
PlatesModule,
MulterModule.register({
@@ -92,6 +95,7 @@ import { InquiryRefreshService } from "./inquiry-refresh.service";
FileReviewerBlameV5Controller,
FileMakerClaimApprovalV5Controller,
InquiryRefreshController,
CallCenterBlameV6Controller,
],
providers: [
RequestManagementService,

File diff suppressed because it is too large Load Diff

View File

@@ -1,16 +1,24 @@
import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { MongooseModule } from "@nestjs/mongoose";
import { ClientModule } from "src/client/client.module";
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normalizer.module";
import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service";
import { SandHubModel, SandHubSchema } from "./entity/schema/sand-hub.schema";
import { SandHubService } from "./sand-hub.service";
@Module({
imports: [
HttpModule,
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
SystemSettingsModule,
PlateNormalizerModule,
ClientModule,
MongooseModule.forFeature([
{ name: SandHubModel.name, schema: SandHubSchema },

View File

@@ -9,6 +9,9 @@ describe("SandHubService inquiry mocks", () => {
isInquiryLive: jest.fn(),
getMockCompanyContext: jest.fn(),
};
const plateNormalizer = {
normalizePlateText: (text: string) => text,
};
let service: SandHubService;
@@ -30,6 +33,7 @@ describe("SandHubService inquiry mocks", () => {
httpService as any,
sandHubDbService as any,
externalInquirySettings as unknown as ExternalInquirySettingsService,
plateNormalizer as any,
);
externalInquirySettings.isInquiryLive.mockResolvedValue(false);
externalInquirySettings.getMockCompanyContext.mockResolvedValue({

View File

@@ -12,6 +12,7 @@ import {
import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service";
import { SandHubModel } from "src/sand-hub/entity/schema/sand-hub.schema";
import { ExternalInquirySettingsService } from "src/client/external-inquiry-settings.service";
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
import type { ExternalInquiryType } from "src/common/types/external-inquiry.types";
import type { MockInquiryCompanyContext } from "src/common/types/external-inquiry.types";
import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto";
@@ -39,6 +40,7 @@ export class SandHubService {
private readonly httpService: HttpService,
private readonly sandHubDbService: SandHubDbService,
private readonly externalInquirySettings: ExternalInquirySettingsService,
private readonly plateNormalizer: PlateNormalizerService,
) {}
private clientRefFrom(options?: SandHubInquiryOptions): string | undefined {
@@ -162,8 +164,8 @@ export class SandHubService {
nationalCodeOfInsurer: nationalCode,
plate: {
leftDigits: Number(payload.part1 ?? payload.leftTwoDigits ?? 16),
centerAlphabet: String(
payload.part2 ?? payload.serialLetter ?? "12",
centerAlphabet: this.plateNormalizer.normalizePlateText(
String(payload.part2 ?? payload.serialLetter ?? "12"),
),
centerDigits: Number(payload.part3 ?? payload.threeDigits ?? 498),
ir: Number(payload.part4 ?? payload.rightTwoDigits ?? 60),

View File

@@ -1,6 +1,7 @@
import { HttpModule } from "@nestjs/axios";
import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { KavenegarService } from "./kavenegar.service";
import { KavenegarSmsGateway } from "./kavenegar-sms.gateway";
@@ -8,7 +9,14 @@ import { ParsianSmsGateway } from "./parsian-sms.gateway";
import { SmsGatewayService } from "./sms-gateway.service";
@Module({
imports: [HttpModule, ConfigModule],
imports: [
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
ConfigModule,
],
providers: [
KavenegarService,
KavenegarSmsGateway,

View File

@@ -6,10 +6,16 @@ import { SmsGatewayModule } from "./provider/sms-gateway.module";
import { OtpGeneratorService } from "./otp-generator.service";
import { SmsOrchestrationService } from "./sms-orchestration.service";
import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
@Module({
imports: [
HttpModule,
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
SmsGatewayModule,
MongooseModule.forFeature([{ name: SmsText.name, schema: SmsTextSchema }]),
],

View File

@@ -37,20 +37,25 @@ export class SmsOrchestrationService implements OnModuleInit {
);
}
buildInviteLink(frontendRoute: string, requestId: string): string {
return `${process.env.URL}/${process.env.USER_BASE_PATH}/${frontendRoute}?token=${requestId}`;
buildInviteLink(
frontendRoute: string,
requestId: string,
versionPrefix: string,
): string {
return `${process.env.URL}/${versionPrefix}/${frontendRoute}?token=${requestId}`;
}
buildBlamePartyLink(
requestId: string,
partyRole: "FIRST" | "SECOND",
versionPrefix: string,
): string {
const route = partyRole === "SECOND" ? "user2" : "user";
return `${process.env.URL}/${process.env.USER_BASE_PATH}/${route}?token=${requestId}`;
return `${process.env.URL}/${versionPrefix}/${route}?token=${requestId}`;
}
buildClaimLink(claimRequestId: string): string {
return `${process.env.URL}/${process.env.USER_BASE_PATH}/caseClaim?token=${claimRequestId}`;
buildClaimLink(claimRequestId: string, versionPrefix: string): string {
return `${process.env.URL}/${versionPrefix}/caseClaim?token=${claimRequestId}`;
}
async sendInviteLink(

View File

@@ -74,3 +74,37 @@ export class CreateRegistrarAdminDto {
@IsNotEmpty()
clientId: string;
}
export class CreateCallCenterAgentDto {
@ApiProperty({ example: "agent@insurer.ir" })
@IsEmail()
email: string;
@ApiProperty({ example: "CallCenter@724" })
@IsString()
@IsNotEmpty()
password: string;
@ApiProperty({ example: "Sara" })
@IsString()
@IsNotEmpty()
firstName: string;
@ApiProperty({ example: "Hosseini" })
@IsString()
@IsNotEmpty()
lastName: string;
@ApiProperty({
example: "664a1b2c3d4e5f6789012345",
description: "Mongo ObjectId of the insurer client this agent belongs to.",
})
@IsString()
@IsNotEmpty()
clientId: string;
@ApiPropertyOptional({ example: "09121234567" })
@IsOptional()
@IsString()
mobile?: string;
}

View File

@@ -1,24 +1,32 @@
import {
BadRequestException,
Body,
Controller,
Get,
Param,
Patch,
Post,
Put,
Query,
UseGuards,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiBody,
ApiOperation,
ApiParam,
ApiQuery,
ApiResponse,
ApiTags,
} from "@nestjs/swagger";
import { Types } from "mongoose";
import { SuperAdminGuard } from "./guards/super-admin.guard";
import { SuperAdminService } from "./super-admin.service";
import {
CreateSuperAdminDto,
CreateFieldExpertAdminDto,
CreateRegistrarAdminDto,
CreateCallCenterAgentDto,
} from "./dto/super-admin.dto";
import { ClientDto } from "src/client/dto/create-client.dto";
import {
@@ -32,6 +40,20 @@ import {
UpdateSystemSettingsDto,
} from "src/system-settings/dto/system-settings.dto";
import { SetExternalInquiriesLiveDto } from "src/client/dto/external-inquiries-live.dto";
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import {
UnifiedFileStatusReportDto,
UnifiedFileStatusReportQueryDto,
} from "src/common/dto/unified-file-status-report.dto";
import { CreateBranchDto } from "src/client/dto/create-branch.dto";
import { FileRating } from "src/request-management/entities/schema/request-management.schema";
import {
CreateBlameExpertByInsurerDto,
CreateClaimExpertByInsurerDto,
CreateFileMakerByInsurerDto,
CreateFileReviewerByInsurerDto,
} from "src/expert-insurer/dto/create-insurer-expert.dto";
@ApiTags("super-admin")
@ApiBearerAuth()
@@ -41,6 +63,7 @@ export class SuperAdminController {
constructor(
private readonly superAdminService: SuperAdminService,
private readonly systemSettingsService: SystemSettingsService,
private readonly expertInsurerService: ExpertInsurerService,
) {}
// ── Super-admin account management ───────────────────────────────────────
@@ -129,6 +152,13 @@ export class SuperAdminController {
return this.superAdminService.createRegistrar(body);
}
@Post("create-call-center-agent")
@ApiOperation({ summary: "Create a call-center agent for a given client" })
@ApiBody({ type: CreateCallCenterAgentDto })
createCallCenterAgent(@Body() body: CreateCallCenterAgentDto) {
return this.superAdminService.createCallCenterAgent(body);
}
// ── System settings ──────────────────────────────────────────────────────
@Get("system-settings")
@@ -159,4 +189,313 @@ export class SuperAdminController {
externalApis: { sandHubUseLiveApi: body?.enabled === true },
});
}
// ── Insurer panel (super-admin proxy) ────────────────────────────────────
@Get("insurer/branches")
@ApiOperation({ summary: "List branches for a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
@ApiQuery({ name: "search", required: false, type: String })
@ApiQuery({ name: "from", required: false, description: "Optional start datetime (ISO string)" })
@ApiQuery({ name: "to", required: false, description: "Optional end datetime (ISO string)" })
@ApiQuery({ name: "isActive", required: false, description: "Filter active state (true/false)" })
getInsuranceBranches(
@Query("clientId") clientId: string,
@Query("search") search?: string,
@Query("from") from?: string,
@Query("to") to?: string,
@Query("isActive") isActive?: string,
) {
return this.expertInsurerService.retrieveInsuranceBranches(
clientId,
{ search, from, to, isActive },
);
}
@Post("insurer/branches")
@ApiOperation({ summary: "Add a branch for a given client" })
@ApiBody({
schema: {
allOf: [
{ $ref: "#/components/schemas/CreateBranchDto" },
{
type: "object",
required: ["clientId"],
properties: { clientId: { type: "string", description: "Client ObjectId" } },
},
],
},
})
addBranch(
@Body("clientId") clientId: string,
@Body() createBranchDto: CreateBranchDto,
) {
return this.expertInsurerService.addBranch(clientId, createBranchDto);
}
@Put("insurer/branches/:branchId/status")
@ApiOperation({ summary: "Set branch active/inactive for a given client" })
@ApiParam({ name: "branchId" })
@ApiBody({
schema: {
type: "object",
properties: {
clientId: { type: "string", description: "Client ObjectId" },
isActive: { type: "boolean" },
},
required: ["clientId", "isActive"],
},
})
setBranchStatus(
@Param("branchId") branchId: string,
@Body("clientId") clientId: string,
@Body("isActive") isActive: unknown,
) {
let active: boolean;
if (typeof isActive === "boolean") {
active = isActive;
} else {
const normalized = String(isActive ?? "").trim().toLowerCase();
if (!["true", "false", "1", "0", "yes", "no"].includes(normalized)) {
throw new BadRequestException("isActive must be a boolean");
}
active = ["true", "1", "yes"].includes(normalized);
}
return this.expertInsurerService.setBranchActive(clientId, branchId, active);
}
@Post("insurer/experts/blame")
@ApiOperation({ summary: "Create a blame expert under a given client" })
@ApiBody({
schema: {
allOf: [
{ $ref: "#/components/schemas/CreateBlameExpertByInsurerDto" },
{
type: "object",
required: ["clientId"],
properties: { clientId: { type: "string", description: "Client ObjectId" } },
},
],
},
})
addBlameExpert(
@Body("clientId") clientId: string,
@Body() body: CreateBlameExpertByInsurerDto,
) {
return this.expertInsurerService.addBlameExpert(clientId, body);
}
@Post("insurer/experts/claim")
@ApiOperation({ summary: "Create a claim expert under a given client" })
@ApiBody({
schema: {
allOf: [
{ $ref: "#/components/schemas/CreateClaimExpertByInsurerDto" },
{
type: "object",
required: ["clientId"],
properties: { clientId: { type: "string", description: "Client ObjectId" } },
},
],
},
})
addClaimExpert(
@Body("clientId") clientId: string,
@Body() body: CreateClaimExpertByInsurerDto,
) {
return this.expertInsurerService.addClaimExpert(clientId, body);
}
@Post("insurer/experts/file-maker")
@ApiOperation({ summary: "Create a FileMaker account under a given client" })
@ApiBody({
schema: {
allOf: [
{ $ref: "#/components/schemas/CreateFileMakerByInsurerDto" },
{
type: "object",
required: ["clientId"],
properties: { clientId: { type: "string", description: "Client ObjectId" } },
},
],
},
})
addFileMaker(
@Body("clientId") clientId: string,
@Body() body: CreateFileMakerByInsurerDto,
) {
return this.expertInsurerService.addFileMaker(clientId, body);
}
@Post("insurer/experts/file-reviewer")
@ApiOperation({ summary: "Create a FileReviewer account under a given client" })
@ApiBody({
schema: {
allOf: [
{ $ref: "#/components/schemas/CreateFileReviewerByInsurerDto" },
{
type: "object",
required: ["clientId"],
properties: { clientId: { type: "string", description: "Client ObjectId" } },
},
],
},
})
addFileReviewer(
@Body("clientId") clientId: string,
@Body() body: CreateFileReviewerByInsurerDto,
) {
return this.expertInsurerService.addFileReviewer(clientId, body);
}
@Get("insurer/experts/list")
@ApiOperation({ summary: "List all experts of a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
@ApiQuery({ name: "page", type: Number })
@ApiQuery({ name: "response_count", type: Number })
getAllExperts(
@Query("clientId") clientId: string,
@Query("page") page: number,
@Query("response_count") count: number,
) {
return this.expertInsurerService.retrieveAllExpertsOfClient(
{ clientKey: clientId },
page,
count,
);
}
@Get("insurer/experts/top")
@ApiOperation({ summary: "Top blame vs claim experts for a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
getTopExperts(@Query("clientId") clientId: string) {
return this.expertInsurerService.getTopExpertsForClient({ clientKey: clientId });
}
@Get("insurer/files")
@ApiOperation({ summary: "List files (blame + claim merged) for a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
getAllFiles(
@Query("clientId") clientId: string,
@Query() query: ListQueryV2Dto,
) {
return this.expertInsurerService.retrieveAllFilesOfClient(clientId, query);
}
@Get("insurer/report/unified-file-statuses")
@ApiOperation({ summary: "Unified file status catalog + counts for a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
@ApiResponse({ status: 200, type: UnifiedFileStatusReportDto })
getUnifiedFileStatusReport(
@Query("clientId") clientId: string,
@Query() query: UnifiedFileStatusReportQueryDto,
): Promise<UnifiedFileStatusReportDto> {
return this.expertInsurerService.getInsurerUnifiedFileStatusReport(
{ clientKey: clientId },
query,
);
}
@Get("insurer/report/status-counts")
@ApiOperation({
summary: "Legacy status counts for a given client",
deprecated: true,
description: "Prefer GET insurer/report/unified-file-statuses.",
})
@ApiQuery({ name: "clientId", required: true, type: String })
@ApiQuery({ name: "from", required: false, description: "Optional start datetime (ISO string)" })
@ApiQuery({ name: "to", required: false, description: "Optional end datetime (ISO string)" })
getInsurerStatusReport(
@Query("clientId") clientId: string,
@Query("from") from?: string,
@Query("to") to?: string,
) {
return this.expertInsurerService.getInsurerFileStatusCounts(
{ clientKey: clientId },
from,
to,
);
}
@Get("insurer/files/:publicId/timeline")
@ApiOperation({ summary: "Activity timeline for a case of a given client" })
@ApiParam({ name: "publicId" })
@ApiQuery({ name: "clientId", required: true, type: String })
getFileTimeline(
@Query("clientId") clientId: string,
@Param("publicId") publicId: string,
) {
return this.expertInsurerService.getFileTimeline(clientId, publicId);
}
@Get("insurer/files/:publicId")
@ApiOperation({ summary: "File details by publicId for a given client" })
@ApiParam({ name: "publicId" })
@ApiQuery({ name: "clientId", required: true, type: String })
getFileDetailsByPublicId(
@Query("clientId") clientId: string,
@Param("publicId") publicId: string,
) {
return this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId);
}
// @Put("insurer/files/:publicId/rating")
// @ApiOperation({ summary: "Rate experts by publicId for a given client" })
// @ApiParam({ name: "publicId" })
// @ApiBody({
// schema: {
// type: "object",
// required: [
// "clientId",
// "collisionMethodAccuracy",
// "evaluationTimeliness",
// "accidentCauseAccuracy",
// "guiltyVehicleIdentification",
// "botRating",
// ],
// properties: {
// clientId: { type: "string", description: "Client ObjectId" },
// collisionMethodAccuracy: { type: "number", minimum: 0, maximum: 5 },
// evaluationTimeliness: { type: "number", minimum: 0, maximum: 5 },
// accidentCauseAccuracy: { type: "number", minimum: 0, maximum: 5 },
// guiltyVehicleIdentification: { type: "number", minimum: 0, maximum: 5 },
// botRating: { type: "number", minimum: 0, maximum: 5 },
// },
// },
// })
// rateExpertsByPublicId(
// @Param("publicId") publicId: string,
// @Body() body: FileRating & { clientId: string },
// ) {
// const { clientId, ...rating } = body;
// return this.expertInsurerService.rateExpertByPublicId(publicId, rating as FileRating, clientId);
// }
@Get("insurer/top-files")
@ApiOperation({ summary: "Top-rated files for a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
getTopFiles(@Query("clientId") clientId: string) {
return this.expertInsurerService.getTopFilesForClient(clientId);
}
@Get("insurer/statistics")
@ApiOperation({ summary: "Expert statistics report for a given client" })
@ApiQuery({ name: "clientId", required: true, type: String })
getExpertStatistics(@Query("clientId") clientId: string) {
return this.expertInsurerService.getExpertStatisticsReport({ clientKey: clientId });
}
@Get("insurer/:expertId")
@ApiOperation({ summary: "Files handled by one roster expert for a given client" })
@ApiParam({ name: "expertId" })
@ApiQuery({ name: "clientId", required: true, type: String })
getExpertFiles(
@Query("clientId") clientId: string,
@Param("expertId") expertId: string,
) {
if (!Types.ObjectId.isValid(expertId)) {
throw new BadRequestException("Invalid expert ID");
}
return this.expertInsurerService.getAllFilesForInsurerExpert(expertId, clientId);
}
}

View File

@@ -3,6 +3,7 @@ import { ClientModule } from "src/client/client.module";
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
import { HashModule } from "src/utils/hash/hash.module";
import { UsersModule } from "src/users/users.module";
import { ExpertInsurerModule } from "src/expert-insurer/expert-insurer.module";
import { SuperAdminController } from "./super-admin.controller";
import { SuperAdminService } from "./super-admin.service";
import { SuperAdminGuard } from "./guards/super-admin.guard";
@@ -26,6 +27,7 @@ import { SuperAdminGuard } from "./guards/super-admin.guard";
SystemSettingsModule,
HashModule,
UsersModule,
ExpertInsurerModule,
],
controllers: [SuperAdminController],
providers: [SuperAdminService, SuperAdminGuard],

View File

@@ -19,10 +19,12 @@ import {
CreateSuperAdminDto,
CreateFieldExpertAdminDto,
CreateRegistrarAdminDto,
CreateCallCenterAgentDto,
} from "./dto/super-admin.dto";
import { RoleEnum } from "src/Types&Enums/role.enum";
import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service";
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service";
@Injectable()
export class SuperAdminService {
@@ -33,6 +35,7 @@ export class SuperAdminService {
private readonly actorAuthService: ActorAuthService,
private readonly fieldExpertDbService: FieldExpertDbService,
private readonly registrarDbService: RegistrarDbService,
private readonly callCenterAgentDbService: CallCenterAgentDbService,
) {}
/** List all super-admin accounts (sans password). */
@@ -99,4 +102,28 @@ export class SuperAdminService {
async createRegistrar(body: CreateRegistrarAdminDto) {
return this.actorAuthService.createRegistrarMock(body);
}
async createCallCenterAgent(body: CreateCallCenterAgentDto) {
const email = body.email.toLowerCase().trim();
const existing = await this.callCenterAgentDbService.findOne({ email });
if (existing) {
throw new ConflictException(
"A call-center agent with this email already exists.",
);
}
const password = await this.hashService.hash(body.password);
const created = await this.callCenterAgentDbService.create({
email,
password,
firstName: body.firstName,
lastName: body.lastName,
clientKey: new Types.ObjectId(body.clientId),
mobile: body.mobile,
role: RoleEnum.CALL_CENTER,
});
const { password: _pw, ...rest } = (created as any).toObject
? (created as any).toObject()
: (created as any);
return rest;
}
}

View File

@@ -0,0 +1,50 @@
import { Injectable } from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose";
import { FilterQuery, Model, Types } from "mongoose";
import { CallCenterAgentModel } from "../schema/call-center-agent.schema";
@Injectable()
export class CallCenterAgentDbService {
constructor(
@InjectModel(CallCenterAgentModel.name)
private readonly model: Model<CallCenterAgentModel>,
) {}
async create(
data: Partial<CallCenterAgentModel> & { password: string },
): Promise<CallCenterAgentModel> {
return this.model.create(data);
}
async findOne(
filter: FilterQuery<CallCenterAgentModel>,
): Promise<CallCenterAgentModel | null> {
return this.model.findOne(filter);
}
async findById(id: string): Promise<CallCenterAgentModel | null> {
return this.model.findOne({ _id: new Types.ObjectId(id) });
}
async findByLoginIdentifier(
identifier: string,
): Promise<CallCenterAgentModel | null> {
const id = identifier.trim();
const or: FilterQuery<CallCenterAgentModel>[] = [
{ email: id },
{ username: id },
];
if (/^\d{10}$/.test(id)) {
or.push({ nationalCode: id });
}
return this.model.findOne({ $or: or });
}
async findAll(
filter: FilterQuery<CallCenterAgentModel>,
): Promise<(CallCenterAgentModel & { _id: Types.ObjectId })[]> {
return this.model.find(filter).lean() as Promise<
(CallCenterAgentModel & { _id: Types.ObjectId })[]
>;
}
}

View File

@@ -0,0 +1,61 @@
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Types } from "mongoose";
import { RoleEnum } from "src/Types&Enums/role.enum";
/**
* Call-center agent actor. Works under an insurance company (clientKey) and
* can start V6 LINK blame files on behalf of callers.
*/
@Schema({
collection: "call-center-agents",
versionKey: false,
timestamps: true,
})
export class CallCenterAgentModel {
_id?: Types.ObjectId;
@Prop({ required: true })
firstName: string;
@Prop({ required: true })
lastName: string;
@Prop({ type: String, unique: true, sparse: true, required: false })
email?: string;
@Prop({ type: String })
username?: string;
@Prop({ type: String, index: true, sparse: true })
nationalCode?: string;
@Prop({ type: Types.ObjectId, index: true })
clientKey?: Types.ObjectId;
@Prop({ required: true })
password: string;
@Prop({ required: false })
mobile?: string;
@Prop({ required: false })
phone?: string;
@Prop({ default: RoleEnum.CALL_CENTER })
role: RoleEnum;
@Prop({ type: "string", default: "" })
otp: string;
createdAt: Date;
}
export const CallCenterAgentDbSchema =
SchemaFactory.createForClass(CallCenterAgentModel);
CallCenterAgentDbSchema.pre("save", function (next) {
if (!this.username) {
this.username = (this as any).email || (this as any).nationalCode;
}
next();
});

View File

@@ -11,6 +11,7 @@ import { UserDbService } from "./entities/db-service/user.db.service";
import { ExpertFileActivityDbService } from "./entities/db-service/expert-file-activity.db.service";
import { FileMakerDbService } from "./entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "./entities/db-service/file-reviewer.db.service";
import { CallCenterAgentDbService } from "./entities/db-service/call-center-agent.db.service";
import {
DamageExpertDbSchema,
DamageExpertModel,
@@ -41,6 +42,10 @@ import {
FileReviewerDbSchema,
FileReviewerModel,
} from "./entities/schema/file-reviewer.schema";
import {
CallCenterAgentDbSchema,
CallCenterAgentModel,
} from "./entities/schema/call-center-agent.schema";
@Module({
imports: [
@@ -54,6 +59,7 @@ import {
{ name: ExpertFileActivity.name, schema: ExpertFileActivitySchema },
{ name: FileMakerModel.name, schema: FileMakerDbSchema },
{ name: FileReviewerModel.name, schema: FileReviewerDbSchema },
{ name: CallCenterAgentModel.name, schema: CallCenterAgentDbSchema },
]),
HashModule,
],
@@ -68,6 +74,7 @@ import {
ExpertFileActivityDbService,
FileMakerDbService,
FileReviewerDbService,
CallCenterAgentDbService,
],
exports: [
UserDbService,
@@ -79,6 +86,7 @@ import {
ExpertFileActivityDbService,
FileMakerDbService,
FileReviewerDbService,
CallCenterAgentDbService,
],
})
export class UsersModule {}

View File

@@ -0,0 +1,8 @@
import { Module } from "@nestjs/common";
import { PlateNormalizerService } from "./plate-normalizer.service";
@Module({
providers: [PlateNormalizerService],
exports: [PlateNormalizerService],
})
export class PlateNormalizerModule {}

View File

@@ -0,0 +1,79 @@
import { Injectable, Logger } from "@nestjs/common";
/**
* Characters stripped from plate text during normalization.
* These invisible Unicode code-points can sneak in via copy-paste
* or OCR and break exact-match lookups against the plate letter map.
*/
const INVISIBLE_CHARS = [
"\u200C", // Zero-Width Non-Joiner
"\u200D", // Zero-Width Joiner
"\u200E", // Left-to-Right Mark
"\u200F", // Right-to-Left Mark
"\uFEFF", // BOM / Zero-Width No-Break Space
];
const INVISIBLE_RE = new RegExp(`[${INVISIBLE_CHARS.join("")}]`, "g");
/**
* Normalize a Persian license-plate character (or short text) so that
* visually-identical Unicode variants collapse to the canonical form
* used in the plate letter mapping.
*
* Steps (in order):
* 1. NFKC normalization — folds compatibility equivalents
* 2. Strip invisible Unicode characters (ZWJ, ZWNJ, LTR/RTL marks, BOM)
* 3. Convert Arabic ي (U+064A) → Persian ی (U+06CC)
* 4. Trim leading/trailing whitespace
*/
export function normalizePlateText(text: string): string {
if (!text) return text;
let result = String(text);
// 1. Unicode NFKC normalization
result = result.normalize("NFKC");
// 2. Remove invisible characters
result = result.replace(INVISIBLE_RE, "");
// 3. Arabic ي → Persian ی
result = result.replace(/\u064A/g, "\u06CC");
// 4. Trim whitespace
result = result.trim();
return result;
}
@Injectable()
export class PlateNormalizerService {
private readonly logger = new Logger(PlateNormalizerService.name);
/** @see module-level {@link normalizePlateText} */
normalizePlateText(text: string): string {
return normalizePlateText(text);
}
/**
* Normalize a plate letter and, if it doesn't resolve in the given
* mapping, log the raw Unicode code-points for debugging.
*
* @returns the numeric code from `mapping`, or `null` when the letter
* is unknown after normalization.
*/
resolvePlateLetterCode(
letter: string,
mapping: Record<string, number>,
): number | null {
const normalized = this.normalizePlateText(letter);
const code = mapping[normalized];
if (code !== undefined) return code;
this.logger.debug(
`Unknown plate letter: ${normalized} [${Array.from(normalized).map((c) => `U+${c.charCodeAt(0).toString(16).toUpperCase().padStart(4, "0")}`).join(", ")}]`,
);
return null;
}
}

View File

@@ -0,0 +1,131 @@
import { PlateNormalizerService, normalizePlateText } from "./plate-normalizer.service";
describe("normalizePlateText (pure function)", () => {
it("returns unchanged text for a clean plate letter", () => {
expect(normalizePlateText("ه")).toBe("ه");
expect(normalizePlateText("الف")).toBe("الف");
});
it("strips Zero-Width Joiner (U+200D)", () => {
// ه + ZWJ — the exact scenario from the issue
const input = "ه\u200D";
expect(normalizePlateText(input)).toBe("ه");
});
it("strips Zero-Width Non-Joiner (U+200C)", () => {
expect(normalizePlateText("ه\u200C")).toBe("ه");
});
it("strips Left-to-Right Mark (U+200E)", () => {
expect(normalizePlateText("ه\u200E")).toBe("ه");
});
it("strips Right-to-Left Mark (U+200F)", () => {
expect(normalizePlateText("ه\u200F")).toBe("ه");
});
it("strips BOM (U+FEFF)", () => {
expect(normalizePlateText("\uFEFFه")).toBe("ه");
});
it("converts Arabic ي (U+064A) to Persian ی (U+06CC)", () => {
expect(normalizePlateText("\u064A")).toBe("\u06CC");
});
it("does not alter already-Persian ی (U+06CC)", () => {
expect(normalizePlateText("\u06CC")).toBe("\u06CC");
});
it("handles a full plate string: 339ه\u200D77 → 339ه77", () => {
expect(normalizePlateText("339ه\u200D77")).toBe("339ه77");
});
it("handles multiple invisible chars interleaved", () => {
const input = "\u200F339\u200Cه\u200D\uFEFF77\u200E";
expect(normalizePlateText(input)).toBe("339ه77");
});
it("trims whitespace", () => {
expect(normalizePlateText(" ه ")).toBe("ه");
});
it("applies NFKC normalization", () => {
// Full-width digit (U+FF13) → ASCII 3
expect(normalizePlateText("")).toBe("3");
});
it("returns empty string for empty input", () => {
expect(normalizePlateText("")).toBe("");
});
});
describe("PlateNormalizerService", () => {
let service: PlateNormalizerService;
beforeEach(() => {
service = new PlateNormalizerService();
});
describe("normalizePlateText", () => {
it("delegates to the pure function", () => {
expect(service.normalizePlateText("ه\u200D")).toBe("ه");
});
});
describe("resolvePlateLetterCode", () => {
const PLATE_LETTER_MAP: Record<string, number> = {
"\u0627\u0644\u0641": 1, // الف
"\u0628": 2,
"\u067E": 3,
"\u062C": 4,
"\u062F": 5,
"\u0633": 6,
"\u0635": 7,
"\u0637": 8,
"\u0639": 9,
"\u0642": 10,
"\u0644": 11,
"\u0645": 12,
"\u0646": 13,
"\u0648": 14,
"\u0647": 15, // ه
"\u06CC": 16, // ی
"\u06A9": 17,
"\u0698": 18,
"\u062A": 19,
"\u062B": 20,
"\u0632": 21,
"\u0634": 22,
"\u0641": 23,
"\u06AF": 24,
};
it("returns 15 for clean ه", () => {
expect(service.resolvePlateLetterCode("ه", PLATE_LETTER_MAP)).toBe(15);
});
it("returns 15 for ه + ZWJ (the bug scenario)", () => {
expect(service.resolvePlateLetterCode("ه\u200D", PLATE_LETTER_MAP)).toBe(
15,
);
});
it("returns 16 for Arabic ي (mapped to Persian ی)", () => {
expect(
service.resolvePlateLetterCode("\u064A", PLATE_LETTER_MAP),
).toBe(16);
});
it("returns null for an unknown letter and logs it", () => {
const spy = jest.spyOn(
(service as any).logger,
"debug",
);
expect(service.resolvePlateLetterCode("؟", PLATE_LETTER_MAP)).toBeNull();
expect(spy).toHaveBeenCalledWith(
expect.stringContaining("Unknown plate letter"),
);
spy.mockRestore();
});
});
});