forked from Yara724/api
Compare commits
143 Commits
d2cb9444f3
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| f2e20b32eb | |||
|
|
c94dd27a96 | ||
| 6e1405c309 | |||
| f053ee1348 | |||
| 182db56e15 | |||
| 9b348d567d | |||
|
|
e4c3b7a16a | ||
| 23fca04705 | |||
|
|
4b9d946bfd | ||
| c85503e598 | |||
|
|
9828aee8af | ||
| 778544c321 | |||
|
|
3afff67336 | ||
| 793ff639ba | |||
|
|
ec15cff557 | ||
| fd42adf9d6 | |||
|
|
4272790fad | ||
| ac65cdb77b | |||
| 8430c68e3a | |||
| 49fe548215 | |||
|
|
777eae1028 | ||
| b67dd733cd | |||
|
|
4818f73252 | ||
| cc8a5354c7 | |||
|
|
2d5ade33d2 | ||
| b73c92c21f | |||
| f9f462d47b | |||
| c3eb36dc41 | |||
|
|
f75ecf5c2c | ||
| 75c4cb6a05 | |||
|
|
7a4277f8b2 | ||
| e50bc78344 | |||
|
|
2c1cd93dd0 | ||
| ffd44df718 | |||
|
|
64865b70f2 | ||
| c207c30be9 | |||
|
|
fcb169e9ac | ||
| 1867292499 | |||
|
|
2cc96f6132 | ||
| 4d5b91d4fe | |||
| 8ba97537a4 | |||
| 70160543a2 | |||
|
|
8460c86820 | ||
| 61f4181065 | |||
|
|
4058cb4a61 | ||
| b2ad43d050 | |||
|
|
9fc4ad9931 | ||
| 213cdd765b | |||
|
|
06d69aa4d0 | ||
| 318a5c74dd | |||
|
|
7241ae3270 | ||
| 1f4a520145 | |||
|
|
59a1b9064e | ||
| 0420eda35f | |||
|
|
482d2b01f1 | ||
|
|
04d7966776 | ||
| b129c1ef9b | |||
|
|
a1fca82cb2 | ||
|
|
5b114c2069 | ||
| 5e4897f609 | |||
| a79c3ca05f | |||
| 36fa1c552e | |||
| 9742fecc11 | |||
| 8007c30efd | |||
| 144f8f3e2a | |||
| 8674dd8762 | |||
|
|
f39c50aeb0 | ||
| 2fda740171 | |||
| 72e5bd616c | |||
| 4b41a60f64 | |||
| 9310285bd4 | |||
|
|
2a8b66bc16 | ||
| 9168a6bdcd | |||
|
|
057bedeb0c | ||
| 808a3b8526 | |||
|
|
da7a4f8890 | ||
| 21e55012be | |||
|
|
385757c3a0 | ||
| a1b122a33b | |||
|
|
aec9e76918 | ||
| 7c59c2407e | |||
|
|
168e52a475 | ||
|
|
4aa6e03afb | ||
|
|
36a34e27b3 | ||
|
|
6387ebaed0 | ||
| 22a5990934 | |||
|
|
e5de99adde | ||
| c7fd2a6b33 | |||
|
|
5595083e86 | ||
| 2296fa5d86 | |||
|
|
72dec7a917 | ||
| 67019851de | |||
|
|
c955deda5c | ||
|
|
9b83db882b | ||
|
|
bced6a0ec7 | ||
| 5d1110b6e9 | |||
|
|
a7fe04c032 | ||
|
|
0dcb2cf2ca | ||
| 8b125af4e7 | |||
| 1559a40213 | |||
|
|
54ae82aa38 | ||
|
|
7a3ddcc7be | ||
|
|
da3f57870e | ||
| ac7ee941b8 | |||
| 5d005d5eee | |||
| b65d9bfe81 | |||
|
|
04f51167c2 | ||
|
|
2c8fd3960f | ||
|
|
e59058520c | ||
| 80122e7772 | |||
| f409d78ede | |||
|
|
24340eb810 | ||
| 41d1de77eb | |||
| 0aadc64cd3 | |||
|
|
1e6c36cbd4 | ||
| ae23a10d33 | |||
| 1c6678d8e4 | |||
|
|
ad5ff28be4 | ||
| 1fe2c77c70 | |||
| 45a51f2c24 | |||
|
|
0514548136 | ||
| 5b4cc0560f | |||
| e9c02811f7 | |||
| 8ab49c9a35 | |||
| f0cd4461a8 | |||
| 3205a89611 | |||
| 14bc075521 | |||
| 1fe66b2d91 | |||
| 033a853b51 | |||
| f05891a112 | |||
| 7641c56440 | |||
| ae83100ef4 | |||
| 9e2cf9bcdf | |||
| ced08fc1f7 | |||
| d525b8dd0d | |||
| b43f1a86dc | |||
|
|
5df39b502e | ||
| 49564cc1c6 | |||
|
|
29939eee20 | ||
| ae789323d8 | |||
|
|
6be9ff16e1 | ||
|
|
0c5a2fe38b | ||
| 5ef8310cb0 |
22
.env.example
22
.env.example
@@ -5,6 +5,10 @@ NODE_ENV =
|
|||||||
PORT =
|
PORT =
|
||||||
CLIENT_ID =
|
CLIENT_ID =
|
||||||
CLIENT_NAME =
|
CLIENT_NAME =
|
||||||
|
FANAVARAN_CLIENT=parsian
|
||||||
|
INSURANCE_CORP_ID='شرکت بيمه پارسيان(بيمه گر)'
|
||||||
|
CLAIM_V2_TOTAL_PAYMENT_CAP_ENABLED=false
|
||||||
|
CLAIM_V2_TOTAL_PAYMENT_CAP_TOMAN=53000000
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
# 🌐 Application URLs
|
# 🌐 Application URLs
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
@@ -36,6 +40,7 @@ MONGO_URI = 'mongodb://${MONGO_USER}:${MONGO_PASS}@${MONGO_HOST}:${MONGO_PORT}/$
|
|||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
JWT_SECRET =
|
JWT_SECRET =
|
||||||
JWT_EXPIRY =
|
JWT_EXPIRY =
|
||||||
|
CAPTCHA_ENABLED = true
|
||||||
|
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
# 🧩 SanHub Microservice
|
# 🧩 SanHub Microservice
|
||||||
@@ -62,6 +67,23 @@ AUTH_SMS_TEMPLATE =
|
|||||||
EXP_OTP_TIME =
|
EXP_OTP_TIME =
|
||||||
FAKE_OTP =
|
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
|
# ⚙️ Application Features / Flags
|
||||||
# ---------------------------------------------
|
# ---------------------------------------------
|
||||||
|
|||||||
142
.woodpecker.yml
Normal file
142
.woodpecker.yml
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
# yara724/api — development deployment (Deploy-Develop)
|
||||||
|
# Manual tasks: see ci-cd/TASK.md
|
||||||
|
# Requires: repo marked Trusted in Woodpecker (host volume mounts)
|
||||||
|
|
||||||
|
when:
|
||||||
|
- event: push
|
||||||
|
branch: main
|
||||||
|
- event: manual
|
||||||
|
|
||||||
|
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: *host_workspace
|
||||||
|
PROJECT_NAME: Yara724 API
|
||||||
|
ENVIRONMENT: Development
|
||||||
|
APPLICATION_URL: https://y724-user.ittalie.ir/api
|
||||||
|
GIT_COMMIT_URL: https://git.ittalie.com/Yara724/api/commit/
|
||||||
|
GIT_BRANCH: main
|
||||||
|
COMPOSE_FILE: docker-compose.yml
|
||||||
|
SUCCESS_COLOR: "#36a64f"
|
||||||
|
FAILURE_COLOR: "#dc3545"
|
||||||
|
|
||||||
|
steps:
|
||||||
|
pull:
|
||||||
|
image: docker.arvancloud.ir/alpine/git:latest
|
||||||
|
environment:
|
||||||
|
<<: *pipeline_env
|
||||||
|
GIT_SSH_COMMAND: ssh -o UserKnownHostsFile=/tmp/known_hosts -o StrictHostKeyChecking=yes
|
||||||
|
volumes:
|
||||||
|
- *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.arvancloud.ir/docker:24-cli
|
||||||
|
environment:
|
||||||
|
<<: *pipeline_env
|
||||||
|
volumes:
|
||||||
|
- /var/run/docker.sock:/var/run/docker.sock
|
||||||
|
- *workspace_volume
|
||||||
|
commands:
|
||||||
|
- cd /workspace
|
||||||
|
- docker compose -f docker-compose.yml up -d --build
|
||||||
|
|
||||||
|
notify-success:
|
||||||
|
image: docker.arvancloud.ir/alpine:3.20
|
||||||
|
environment:
|
||||||
|
<<: *pipeline_env
|
||||||
|
ROCKETCHAT_WEBHOOK:
|
||||||
|
from_secret: rocketchat_webhook
|
||||||
|
volumes:
|
||||||
|
- *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)"
|
||||||
|
DEPLOY_START="$(cat /workspace/.wp-deploy-start)"
|
||||||
|
DEPLOY_END="$(date +%s)"
|
||||||
|
DEPLOY_DURATION="$((DEPLOY_END - DEPLOY_START))"
|
||||||
|
|
||||||
|
COMMIT_1="$(git log -1 --pretty=format:'%s')"
|
||||||
|
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
|
||||||
|
|
||||||
|
🔖 **Commit Hash**: [$COMMIT_HASH]($GIT_COMMIT_URL$COMMIT_HASH)
|
||||||
|
|
||||||
|
📝 **Recent Changes**:
|
||||||
|
|
||||||
|
• $COMMIT_1
|
||||||
|
|
||||||
|
• $COMMIT_2
|
||||||
|
|
||||||
|
• $COMMIT_3
|
||||||
|
|
||||||
|
⏱️ **Deployment Duration**: $${DEPLOY_DURATION}s"
|
||||||
|
|
||||||
|
payload="$(jq -n \
|
||||||
|
--arg title "$TITLE" \
|
||||||
|
--arg text "$TEXT" \
|
||||||
|
--arg color "$SUCCESS_COLOR" \
|
||||||
|
'{text: $title, attachments: [{text: $text, color: $color}]}')"
|
||||||
|
|
||||||
|
curl -fsS -H "Content-Type: application/json" -d "$payload" "$ROCKETCHAT_WEBHOOK" >/dev/null
|
||||||
|
rm -f /workspace/.wp-deploy-start
|
||||||
|
|
||||||
|
notify-failure:
|
||||||
|
image: docker.arvancloud.ir/alpine:3.20
|
||||||
|
environment:
|
||||||
|
<<: *pipeline_env
|
||||||
|
ROCKETCHAT_WEBHOOK:
|
||||||
|
from_secret: rocketchat_webhook
|
||||||
|
volumes:
|
||||||
|
- *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 💥"
|
||||||
|
TEXT="━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
||||||
|
🌐 **Application URL**
|
||||||
|
|
||||||
|
$APPLICATION_URL
|
||||||
|
|
||||||
|
🔖 **Commit**
|
||||||
|
|
||||||
|
\`$COMMIT_HASH\`
|
||||||
|
|
||||||
|
⚠️ **Pipeline failed** — check Woodpecker for the failing step.
|
||||||
|
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
|
||||||
|
|
||||||
|
payload="$(jq -n \
|
||||||
|
--arg title "$TITLE" \
|
||||||
|
--arg text "$TEXT" \
|
||||||
|
--arg color "$FAILURE_COLOR" \
|
||||||
|
'{text: $title, attachments: [{text: $text, color: $color}]}')"
|
||||||
|
|
||||||
|
curl -fsS -H "Content-Type: application/json" -d "$payload" "$ROCKETCHAT_WEBHOOK" >/dev/null || true
|
||||||
|
rm -f /workspace/.wp-deploy-start
|
||||||
BIN
assets/Vazirmatn-Bold.ttf
Normal file
BIN
assets/Vazirmatn-Bold.ttf
Normal file
Binary file not shown.
BIN
assets/Vazirmatn-Regular.ttf
Normal file
BIN
assets/Vazirmatn-Regular.ttf
Normal file
Binary file not shown.
@@ -274,6 +274,20 @@ curl -X GET "$FANAVARAN_BIME_URL/car/code-list/accident-culprit-type" \
|
|||||||
-H "ContractId: $CONTRACT_ID" \
|
-H "ContractId: $CONTRACT_ID" \
|
||||||
-H "Location: $LOCATION" \
|
-H "Location: $LOCATION" \
|
||||||
-H "Content-Type: application/json"
|
-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
|
### 3B. Policy Inquiry By National Code
|
||||||
|
|||||||
@@ -45,6 +45,7 @@
|
|||||||
"pdfkit": "^0.19.1",
|
"pdfkit": "^0.19.1",
|
||||||
"reflect-metadata": "^0.2.2",
|
"reflect-metadata": "^0.2.2",
|
||||||
"rxjs": "^7.8.1",
|
"rxjs": "^7.8.1",
|
||||||
|
"socks-proxy-agent": "^8.0.4",
|
||||||
"svg-captcha": "^1.4.0"
|
"svg-captcha": "^1.4.0"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
|||||||
86
scripts/verify-plate-normalization.mjs
Normal file
86
scripts/verify-plate-normalization.mjs
Normal 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);
|
||||||
@@ -11,6 +11,24 @@ export enum CaseStatus {
|
|||||||
|
|
||||||
WAITING_FOR_SIGNATURES = "WAITING_FOR_SIGNATURES",
|
WAITING_FOR_SIGNATURES = "WAITING_FOR_SIGNATURES",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FileMaker has collected all signatures; the file is sealed and waiting
|
||||||
|
* for a FileReviewer to complete it (accident fields → capture → video).
|
||||||
|
*/
|
||||||
|
WAITING_FOR_FILE_REVIEWER = "WAITING_FOR_FILE_REVIEWER",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 flow only. FileReviewer has completed the claim and the owner has signed;
|
||||||
|
* the FileMaker who created the file must now approve before fanavaran submission.
|
||||||
|
*/
|
||||||
|
WAITING_FOR_FILE_MAKER_APPROVAL = "WAITING_FOR_FILE_MAKER_APPROVAL",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 flow only. FileMaker rejected the file back to FileReviewer
|
||||||
|
* for correction (adjust pricing / back-and-forth with user and re-submit).
|
||||||
|
*/
|
||||||
|
FILE_MAKER_REJECTED = "FILE_MAKER_REJECTED",
|
||||||
|
|
||||||
COMPLETED = "COMPLETED",
|
COMPLETED = "COMPLETED",
|
||||||
|
|
||||||
CANCELLED = "CANCELLED",
|
CANCELLED = "CANCELLED",
|
||||||
|
|||||||
@@ -34,7 +34,27 @@ export enum ClaimCaseStatus {
|
|||||||
|
|
||||||
/** All required factor files are uploaded; damage expert validates factors (`UNDER_REVIEW` @ `EXPERT_COST_EVALUATION`). */
|
/** All required factor files are uploaded; damage expert validates factors (`UNDER_REVIEW` @ `EXPERT_COST_EVALUATION`). */
|
||||||
EXPERT_VALIDATING_REPAIR_FACTORS = "EXPERT_VALIDATING_REPAIR_FACTORS",
|
EXPERT_VALIDATING_REPAIR_FACTORS = "EXPERT_VALIDATING_REPAIR_FACTORS",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V4 split flow only. FileMaker has uploaded all initial required documents;
|
||||||
|
* the file is sealed and waiting for a FileReviewer to pick it up (accident fields,
|
||||||
|
* capture, and final blame video). Transitions to SELECTING_OUTER_PARTS when the
|
||||||
|
* FileReviewer calls select-outer-parts after submitting accident fields.
|
||||||
|
*/
|
||||||
|
WAITING_FOR_FILE_REVIEWER = "WAITING_FOR_FILE_REVIEWER",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 split flow only. The claim is fully evaluated and owner has signed;
|
||||||
|
* the FileMaker who created the file must approve before fanavaran submission.
|
||||||
|
*/
|
||||||
|
WAITING_FOR_FILE_MAKER_APPROVAL = "WAITING_FOR_FILE_MAKER_APPROVAL",
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 split flow only. FileMaker rejected the completed claim back to FileReviewer
|
||||||
|
* for correction (adjust pricing, re-do expert review, back-and-forth with user).
|
||||||
|
*/
|
||||||
|
FILE_MAKER_REJECTED = "FILE_MAKER_REJECTED",
|
||||||
|
|
||||||
// Final states
|
// Final states
|
||||||
COMPLETED = "COMPLETED",
|
COMPLETED = "COMPLETED",
|
||||||
CANCELLED = "CANCELLED",
|
CANCELLED = "CANCELLED",
|
||||||
|
|||||||
@@ -8,4 +8,6 @@ export enum RoleEnum {
|
|||||||
USER = "user",
|
USER = "user",
|
||||||
FILE_MAKER = "file_maker",
|
FILE_MAKER = "file_maker",
|
||||||
FILE_REVIEWER = "file_reviewer",
|
FILE_REVIEWER = "file_reviewer",
|
||||||
|
SUPER_ADMIN = "super_admin",
|
||||||
|
CALL_CENTER = "call_center",
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
import { HttpModule } from "@nestjs/axios";
|
|
||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { AiService } from "./ai.service";
|
import { AiService } from "./ai.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [HttpModule],
|
imports: [],
|
||||||
providers: [AiService],
|
providers: [AiService],
|
||||||
exports: [AiService],
|
exports: [AiService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { join } from "node:path";
|
import { join } from "node:path";
|
||||||
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
|
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
|
||||||
import { Module } from "@nestjs/common";
|
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 { UnicodeDigitsNormalizeInterceptor } from "./common/interceptors/unicode-digits-normalize.interceptor";
|
||||||
import { MongooseModule } from "@nestjs/mongoose";
|
import { MongooseModule } from "@nestjs/mongoose";
|
||||||
import { ServeStaticModule } from "@nestjs/serve-static";
|
import { ServeStaticModule } from "@nestjs/serve-static";
|
||||||
@@ -27,9 +28,16 @@ import { CronModule } from "./utils/cron/cron.module";
|
|||||||
import { WorkflowStepManagementModule } from "./workflow-step-management/workflow-step-management.module";
|
import { WorkflowStepManagementModule } from "./workflow-step-management/workflow-step-management.module";
|
||||||
import { DatabaseModule } from "./core/database/database.module";
|
import { DatabaseModule } from "./core/database/database.module";
|
||||||
import { AppConfigModule } from "./core/config/config.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({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
AppConfigModule,
|
AppConfigModule,
|
||||||
DatabaseModule,
|
DatabaseModule,
|
||||||
CronModule,
|
CronModule,
|
||||||
@@ -59,6 +67,7 @@ import { AppConfigModule } from "./core/config/config.module";
|
|||||||
ExpertInsurerModule,
|
ExpertInsurerModule,
|
||||||
LookupsModule,
|
LookupsModule,
|
||||||
WorkflowStepManagementModule,
|
WorkflowStepManagementModule,
|
||||||
|
SuperAdminModule,
|
||||||
],
|
],
|
||||||
controllers: [],
|
controllers: [],
|
||||||
providers: [
|
providers: [
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ import {
|
|||||||
LegalRegisterDto,
|
LegalRegisterDto,
|
||||||
} from "src/auth/dto/actor/register.actor.dto";
|
} from "src/auth/dto/actor/register.actor.dto";
|
||||||
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
|
||||||
|
import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard";
|
||||||
import { Roles } from "src/decorators/roles.decorator";
|
import { Roles } from "src/decorators/roles.decorator";
|
||||||
import { CurrentUser } from "src/decorators/user.decorator";
|
import { CurrentUser } from "src/decorators/user.decorator";
|
||||||
|
|
||||||
@@ -95,6 +96,7 @@ export class ActorAuthController {
|
|||||||
* will be removed in a future release.
|
* will be removed in a future release.
|
||||||
*/
|
*/
|
||||||
@Post("register/genuine")
|
@Post("register/genuine")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
summary: "[DEPRECATED] Genuine actor registration",
|
summary: "[DEPRECATED] Genuine actor registration",
|
||||||
@@ -111,6 +113,7 @@ export class ActorAuthController {
|
|||||||
* will be removed in a future release.
|
* will be removed in a future release.
|
||||||
*/
|
*/
|
||||||
@Post("register/legal")
|
@Post("register/legal")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
deprecated: true,
|
deprecated: true,
|
||||||
summary: "[DEPRECATED] Legal actor registration",
|
summary: "[DEPRECATED] Legal actor registration",
|
||||||
@@ -123,21 +126,24 @@ export class ActorAuthController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Post("register/insurer")
|
@Post("register/insurer")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
@ApiBody({ type: InsurerRegisterDto })
|
@ApiBody({ type: InsurerRegisterDto })
|
||||||
async registerInsurer(@Body() body: InsurerRegisterDto) {
|
async registerInsurer(@Body() body: InsurerRegisterDto) {
|
||||||
return await this.actorAuthService.insurerRegister(body);
|
return await this.actorAuthService.insurerRegister(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mock: create a field expert for testing. Make private later. */
|
/** Requires super-admin token. */
|
||||||
@Post("create-field-expert")
|
@Post("create-field-expert")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
@ApiBody({ type: CreateFieldExpertDto })
|
@ApiBody({ type: CreateFieldExpertDto })
|
||||||
@ApiAcceptedResponse()
|
@ApiAcceptedResponse()
|
||||||
async createFieldExpert(@Body() body: CreateFieldExpertDto) {
|
async createFieldExpert(@Body() body: CreateFieldExpertDto) {
|
||||||
return await this.actorAuthService.createFieldExpertMock(body);
|
return await this.actorAuthService.createFieldExpertMock(body);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Mock: create a registrar for testing. Make private later. */
|
/** Requires super-admin token. */
|
||||||
@Post("create-registrar")
|
@Post("create-registrar")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
@ApiBody({ type: CreateRegistrarDto })
|
@ApiBody({ type: CreateRegistrarDto })
|
||||||
@ApiAcceptedResponse()
|
@ApiAcceptedResponse()
|
||||||
async createRegistrar(@Body() body: CreateRegistrarDto) {
|
async createRegistrar(@Body() body: CreateRegistrarDto) {
|
||||||
|
|||||||
@@ -29,8 +29,10 @@ import { FieldExpertDbService } from "src/users/entities/db-service/field-expert
|
|||||||
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service";
|
||||||
import { FileMakerDbService } from "src/users/entities/db-service/file-maker.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 { 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 { HashService } from "src/utils/hash/hash.service";
|
||||||
import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service";
|
import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service";
|
||||||
|
import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service";
|
||||||
|
|
||||||
function pick(obj: Record<string, any>, keys: string[]) {
|
function pick(obj: Record<string, any>, keys: string[]) {
|
||||||
const out: Record<string, any> = {};
|
const out: Record<string, any> = {};
|
||||||
@@ -56,6 +58,8 @@ export class ActorAuthService {
|
|||||||
private readonly captchaChallengeService: CaptchaChallengeService,
|
private readonly captchaChallengeService: CaptchaChallengeService,
|
||||||
private readonly fileMakerDbService: FileMakerDbService,
|
private readonly fileMakerDbService: FileMakerDbService,
|
||||||
private readonly fileReviewerDbService: FileReviewerDbService,
|
private readonly fileReviewerDbService: FileReviewerDbService,
|
||||||
|
private readonly superAdminDbService: SuperAdminDbService,
|
||||||
|
private readonly callCenterAgentDbService: CallCenterAgentDbService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
// TODO convrt to class for dynamic controller
|
// TODO convrt to class for dynamic controller
|
||||||
@@ -114,6 +118,21 @@ export class ActorAuthService {
|
|||||||
res =
|
res =
|
||||||
await this.fileReviewerDbService.findByLoginIdentifier(username);
|
await this.fileReviewerDbService.findByLoginIdentifier(username);
|
||||||
break;
|
break;
|
||||||
|
case RoleEnum.SUPER_ADMIN:
|
||||||
|
if (username == null && userId)
|
||||||
|
res = await this.superAdminDbService.findOne({
|
||||||
|
_id: new Types.ObjectId(userId),
|
||||||
|
});
|
||||||
|
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:
|
default:
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ import { UsersModule } from "src/users/users.module";
|
|||||||
import { HashModule } from "src/utils/hash/hash.module";
|
import { HashModule } from "src/utils/hash/hash.module";
|
||||||
import { SmsOrchestrationModule } from "src/sms-orchestration/sms-orchestration.module";
|
import { SmsOrchestrationModule } from "src/sms-orchestration/sms-orchestration.module";
|
||||||
import { CaptchaModule } from "src/captcha/captcha.module";
|
import { CaptchaModule } from "src/captcha/captcha.module";
|
||||||
|
import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service";
|
||||||
|
import {
|
||||||
|
SuperAdminModel,
|
||||||
|
SuperAdminSchema,
|
||||||
|
} from "src/super-admin/entities/schema/super-admin.schema";
|
||||||
|
|
||||||
/** Auth services and guards are app-wide (avoids importing AuthModule in every feature module). */
|
/** Auth services and guards are app-wide (avoids importing AuthModule in every feature module). */
|
||||||
@Global()
|
@Global()
|
||||||
@@ -47,6 +52,7 @@ import { CaptchaModule } from "src/captcha/captcha.module";
|
|||||||
schema: ClaimRequestManagementSchema,
|
schema: ClaimRequestManagementSchema,
|
||||||
},
|
},
|
||||||
{ name: ClaimCase.name, schema: ClaimCaseSchema },
|
{ name: ClaimCase.name, schema: ClaimCaseSchema },
|
||||||
|
{ name: SuperAdminModel.name, schema: SuperAdminSchema },
|
||||||
]),
|
]),
|
||||||
JwtModule.register({
|
JwtModule.register({
|
||||||
signOptions: { expiresIn: "1h" }, // TODO: MAKE IT ENV
|
signOptions: { expiresIn: "1h" }, // TODO: MAKE IT ENV
|
||||||
@@ -61,6 +67,7 @@ import { CaptchaModule } from "src/captcha/captcha.module";
|
|||||||
JwtService,
|
JwtService,
|
||||||
LocalActorAuthGuard,
|
LocalActorAuthGuard,
|
||||||
LocalUserAuthGuard,
|
LocalUserAuthGuard,
|
||||||
|
SuperAdminDbService,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
UserAuthService,
|
UserAuthService,
|
||||||
@@ -68,6 +75,7 @@ import { CaptchaModule } from "src/captcha/captcha.module";
|
|||||||
JwtService,
|
JwtService,
|
||||||
LocalActorAuthGuard,
|
LocalActorAuthGuard,
|
||||||
LocalUserAuthGuard,
|
LocalUserAuthGuard,
|
||||||
|
SuperAdminDbService,
|
||||||
],
|
],
|
||||||
controllers: [UserAuthController, ActorAuthController],
|
controllers: [UserAuthController, ActorAuthController],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ export class LocalActorAuthGuard implements CanActivate {
|
|||||||
RoleEnum.REGISTRAR,
|
RoleEnum.REGISTRAR,
|
||||||
RoleEnum.FILE_MAKER,
|
RoleEnum.FILE_MAKER,
|
||||||
RoleEnum.FILE_REVIEWER,
|
RoleEnum.FILE_REVIEWER,
|
||||||
|
RoleEnum.SUPER_ADMIN,
|
||||||
].includes(payload.role)
|
].includes(payload.role)
|
||||||
) {
|
) {
|
||||||
throw new UnauthorizedException("User role is not authorized");
|
throw new UnauthorizedException("User role is not authorized");
|
||||||
|
|||||||
@@ -12,6 +12,8 @@ const GLOBAL_GUARD_ROLES = new Set<string>([
|
|||||||
RoleEnum.USER,
|
RoleEnum.USER,
|
||||||
RoleEnum.FIELD_EXPERT,
|
RoleEnum.FIELD_EXPERT,
|
||||||
RoleEnum.REGISTRAR,
|
RoleEnum.REGISTRAR,
|
||||||
|
RoleEnum.FILE_MAKER,
|
||||||
|
RoleEnum.FILE_REVIEWER
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import { HashService } from "src/utils/hash/hash.service";
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class CaptchaChallengeService {
|
export class CaptchaChallengeService {
|
||||||
private readonly isDev: boolean;
|
private readonly isDev: boolean;
|
||||||
|
private readonly captchaEnabled: boolean;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
private readonly captchaService: CaptchaService,
|
private readonly captchaService: CaptchaService,
|
||||||
@@ -21,6 +22,7 @@ export class CaptchaChallengeService {
|
|||||||
private readonly configService: ConfigService,
|
private readonly configService: ConfigService,
|
||||||
) {
|
) {
|
||||||
this.isDev = this.configService.get<string>("NODE_ENV") === "development";
|
this.isDev = this.configService.get<string>("NODE_ENV") === "development";
|
||||||
|
this.captchaEnabled = this.configService.get<string>("CAPTCHA_ENABLED") !== "false";
|
||||||
}
|
}
|
||||||
|
|
||||||
async issue(): Promise<CaptchaResponseDto> {
|
async issue(): Promise<CaptchaResponseDto> {
|
||||||
@@ -32,12 +34,17 @@ export class CaptchaChallengeService {
|
|||||||
this.captchaService.normalizeAnswer(generated.text),
|
this.captchaService.normalizeAnswer(generated.text),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// expireAt is the MongoDB TTL sentinel. The TTL reaper fires every ~60 s, so
|
||||||
|
// setting it equal to expiresAt means Mongo can delete the document up to 60 s
|
||||||
|
// BEFORE the application-level expiry check runs — causing the intermittent
|
||||||
|
// "captchaId not found" error under load. Adding a 120 s grace buffer ensures
|
||||||
|
// the document is always present when verify() runs its own expiresAt check.
|
||||||
await this.captchaChallengeDbService.create({
|
await this.captchaChallengeDbService.create({
|
||||||
captchaId,
|
captchaId,
|
||||||
answerHash,
|
answerHash,
|
||||||
image: generated.image,
|
image: generated.image,
|
||||||
expiresAt: generated.expiresAt,
|
expiresAt: generated.expiresAt,
|
||||||
expireAt: new Date(generated.expiresAt),
|
expireAt: new Date(generated.expiresAt + 120_000),
|
||||||
usedAt: null,
|
usedAt: null,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -62,6 +69,11 @@ export class CaptchaChallengeService {
|
|||||||
captchaId: string | undefined,
|
captchaId: string | undefined,
|
||||||
answer: string | undefined,
|
answer: string | undefined,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
// Skip captcha verification if disabled via environment variable
|
||||||
|
if (!this.captchaEnabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (!captchaId?.trim()) {
|
if (!captchaId?.trim()) {
|
||||||
throwCaptchaAuthError(CaptchaAuthErrorCode.CAPTCHA_REQUIRED);
|
throwCaptchaAuthError(CaptchaAuthErrorCode.CAPTCHA_REQUIRED);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,8 +10,8 @@ export class CaptchaChallenge {
|
|||||||
@Prop({ required: true, unique: true, index: true })
|
@Prop({ required: true, unique: true, index: true })
|
||||||
captchaId: string;
|
captchaId: string;
|
||||||
|
|
||||||
@Prop()
|
@Prop({ required: true })
|
||||||
answerHash?: string;
|
answerHash: string;
|
||||||
|
|
||||||
@Prop({ required: true })
|
@Prop({ required: true })
|
||||||
image: string;
|
image: string;
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { MongooseModule } from "@nestjs/mongoose";
|
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 { AiModule } from "src/ai/ai.module";
|
||||||
import { SandHubModule } from "src/sand-hub/sand-hub.module";
|
import { SandHubModule } from "src/sand-hub/sand-hub.module";
|
||||||
import { RequestManagementModule } from "src/request-management/request-management.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 { ClaimAccessGuard } from "src/auth/guards/claim-access.guard";
|
||||||
import { JwtModule } from "@nestjs/jwt";
|
import { JwtModule } from "@nestjs/jwt";
|
||||||
import { MediaPolicyModule } from "src/media-policy/media-policy.module";
|
import { MediaPolicyModule } from "src/media-policy/media-policy.module";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
|
||||||
import { FanavaranAuditModule } from "src/fanavaran/fanavaran-audit.module";
|
import { FanavaranAuditModule } from "src/fanavaran/fanavaran-audit.module";
|
||||||
import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module";
|
import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module";
|
||||||
|
import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normalizer.module";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
FanavaranAuditModule,
|
FanavaranAuditModule,
|
||||||
FanavaranLookupModule,
|
FanavaranLookupModule,
|
||||||
|
PlateNormalizerModule,
|
||||||
PublicIdModule,
|
PublicIdModule,
|
||||||
UsersModule,
|
UsersModule,
|
||||||
RequestManagementModule,
|
RequestManagementModule,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -13,10 +13,19 @@ import {
|
|||||||
Get,
|
Get,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
|
UploadedFiles,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
import { readFile } from "node:fs/promises";
|
import { readFile } from "node:fs/promises";
|
||||||
import { ApiBearerAuth, ApiParam, ApiTags, ApiOperation, ApiResponse, ApiBody, ApiConsumes } from "@nestjs/swagger";
|
import {
|
||||||
import { FileInterceptor } from "@nestjs/platform-express";
|
ApiBearerAuth,
|
||||||
|
ApiParam,
|
||||||
|
ApiTags,
|
||||||
|
ApiOperation,
|
||||||
|
ApiResponse,
|
||||||
|
ApiBody,
|
||||||
|
ApiConsumes,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
|
import { FileInterceptor, FilesInterceptor } from "@nestjs/platform-express";
|
||||||
import { diskStorage } from "multer";
|
import { diskStorage } from "multer";
|
||||||
import { extname } from "node:path";
|
import { extname } from "node:path";
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
@@ -33,9 +42,15 @@ import {
|
|||||||
SelectOuterPartsV2Dto,
|
SelectOuterPartsV2Dto,
|
||||||
SelectOuterPartsV2ResponseDto,
|
SelectOuterPartsV2ResponseDto,
|
||||||
} from "./dto/select-outer-parts-v2.dto";
|
} from "./dto/select-outer-parts-v2.dto";
|
||||||
import { SelectOtherPartsV2Dto, SelectOtherPartsV2ResponseDto } from "./dto/select-other-parts-v2.dto";
|
import {
|
||||||
|
SelectOtherPartsV2Dto,
|
||||||
|
SelectOtherPartsV2ResponseDto,
|
||||||
|
} from "./dto/select-other-parts-v2.dto";
|
||||||
import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-v2.dto";
|
import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-v2.dto";
|
||||||
import { UploadRequiredDocumentV2Dto, UploadRequiredDocumentV2ResponseDto } from "./dto/upload-document-v2.dto";
|
import {
|
||||||
|
UploadRequiredDocumentV2Dto,
|
||||||
|
UploadRequiredDocumentV2ResponseDto,
|
||||||
|
} from "./dto/upload-document-v2.dto";
|
||||||
import {
|
import {
|
||||||
CapturePartV2Dto,
|
CapturePartV2Dto,
|
||||||
CapturePartV2ResponseDto,
|
CapturePartV2ResponseDto,
|
||||||
@@ -52,7 +67,13 @@ import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog";
|
|||||||
@Controller("v2/claim-request-management")
|
@Controller("v2/claim-request-management")
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@UseGuards(GlobalGuard, RolesGuard)
|
@UseGuards(GlobalGuard, RolesGuard)
|
||||||
@Roles(RoleEnum.USER, RoleEnum.FIELD_EXPERT, RoleEnum.REGISTRAR)
|
@Roles(
|
||||||
|
RoleEnum.USER,
|
||||||
|
RoleEnum.FIELD_EXPERT,
|
||||||
|
RoleEnum.REGISTRAR,
|
||||||
|
RoleEnum.FILE_MAKER,
|
||||||
|
RoleEnum.FILE_REVIEWER,
|
||||||
|
)
|
||||||
export class ClaimRequestManagementV2Controller {
|
export class ClaimRequestManagementV2Controller {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
||||||
@@ -142,7 +163,10 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
})
|
})
|
||||||
@ApiParam({ name: "claimRequestId" })
|
@ApiParam({ name: "claimRequestId" })
|
||||||
@ApiResponse({ status: 200, description: "Claim returned to expert queue" })
|
@ApiResponse({ status: 200, description: "Claim returned to expert queue" })
|
||||||
@ApiResponse({ status: 400, description: "Resend requires uploads or wrong step" })
|
@ApiResponse({
|
||||||
|
status: 400,
|
||||||
|
description: "Resend requires uploads or wrong step",
|
||||||
|
})
|
||||||
async acknowledgeExpertResend(
|
async acknowledgeExpertResend(
|
||||||
@Param("claimRequestId") claimRequestId: string,
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
@CurrentUser() user: any,
|
@CurrentUser() user: any,
|
||||||
@@ -156,15 +180,19 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof HttpException) throw error;
|
if (error instanceof HttpException) throw error;
|
||||||
throw new InternalServerErrorException(
|
throw new InternalServerErrorException(
|
||||||
error instanceof Error ? error.message : "Failed to acknowledge expert resend",
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to acknowledge expert resend",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* V2: User objection after expert resend (same intent as v1 PUT …/request/resend/:id/objection).
|
* V2: User objection after expert resend (same intent as v1 PUT …/request/resend/:id/objection).
|
||||||
|
* Accepts multipart/form-data so optional supporting invoices can be attached in the same request.
|
||||||
*/
|
*/
|
||||||
@Put("request/:claimRequestId/objection")
|
@Put("request/:claimRequestId/objection")
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Submit user objection (V2)",
|
summary: "Submit user objection (V2)",
|
||||||
description:
|
description:
|
||||||
@@ -172,30 +200,75 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
"(2) **Legacy resend:** active expert resend (`WAITING_FOR_USER_RESEND` @ `USER_EXPERT_RESEND`).\n\n" +
|
"(2) **Legacy resend:** active expert resend (`WAITING_FOR_USER_RESEND` @ `USER_EXPERT_RESEND`).\n\n" +
|
||||||
"`objectionParts` may only reference **priced** repair lines (`factorNeeded=false`). Factor-only lines cannot be disputed until they have expert pricing.\n\n" +
|
"`objectionParts` may only reference **priced** repair lines (`factorNeeded=false`). Factor-only lines cannot be disputed until they have expert pricing.\n\n" +
|
||||||
"After **`damageExpertReplyFinal`** exists (final reply following a prior objection), **no second objection** — owner uses **owner-insurer-approval/sign** to accept/reject and close the case.\n\n" +
|
"After **`damageExpertReplyFinal`** exists (final reply following a prior objection), **no second objection** — owner uses **owner-insurer-approval/sign** to accept/reject and close the case.\n\n" +
|
||||||
"Stores `evaluation.objection`, clears partial/final owner approval fields, merges `newParts` into `damage.selectedParts`, returns case to `WAITING_FOR_DAMAGE_EXPERT`.",
|
"Stores `evaluation.objection`, clears partial/final owner approval fields, merges `newParts` into `damage.selectedParts`, returns case to `WAITING_FOR_DAMAGE_EXPERT`.\n\n" +
|
||||||
|
"**Invoices:** optionally attach up to 5 supporting documents (images/PDFs) as `invoices` file fields. Stored in `evaluation.objection.invoices[]` and visible to the reviewing expert.",
|
||||||
})
|
})
|
||||||
@ApiParam({
|
@ApiParam({
|
||||||
name: "claimRequestId",
|
name: "claimRequestId",
|
||||||
description: "The claim case ID (MongoDB ObjectId)",
|
description: "The claim case ID (MongoDB ObjectId)",
|
||||||
example: "507f1f77bcf86cd799439011",
|
example: "507f1f77bcf86cd799439011",
|
||||||
})
|
})
|
||||||
@ApiBody({ type: UserObjectionV2Dto })
|
@ApiBody({
|
||||||
|
description:
|
||||||
|
"Objection payload as multipart form fields. `objectionParts` and `newParts` are JSON-encoded strings.",
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
objectionParts: {
|
||||||
|
type: "string",
|
||||||
|
description:
|
||||||
|
'JSON-encoded array of disputed priced parts. Example: `[{"partId":201,"reason":"Price too high"}]`',
|
||||||
|
},
|
||||||
|
newParts: {
|
||||||
|
type: "string",
|
||||||
|
description:
|
||||||
|
'JSON-encoded array of new parts to add. Example: `[{"partName":"سپر جلو","side":"front"}]`',
|
||||||
|
},
|
||||||
|
invoices: {
|
||||||
|
type: "array",
|
||||||
|
items: { type: "string", format: "binary" },
|
||||||
|
description: "Up to 5 supporting invoice or document files (image or PDF).",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
@ApiResponse({ status: 200, description: "Objection stored" })
|
@ApiResponse({ status: 200, description: "Objection stored" })
|
||||||
@ApiResponse({ status: 400, description: "No active resend or empty payload" })
|
@ApiResponse({
|
||||||
|
status: 400,
|
||||||
|
description: "No active resend or empty payload",
|
||||||
|
})
|
||||||
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
||||||
@ApiResponse({ status: 404, description: "Claim not found" })
|
@ApiResponse({ status: 404, description: "Claim not found" })
|
||||||
@ApiResponse({ status: 409, description: "Objection already submitted" })
|
@ApiResponse({ status: 409, description: "Objection already submitted" })
|
||||||
|
@UseInterceptors(
|
||||||
|
FilesInterceptor("invoices", 5, {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-objection-invoices",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now() + "-" + Math.round(Math.random() * 1e6);
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `objection-invoice-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
async submitUserObjectionV2(
|
async submitUserObjectionV2(
|
||||||
@Param("claimRequestId") claimRequestId: string,
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
@Body() body: UserObjectionV2Dto,
|
@Body() body: UserObjectionV2Dto,
|
||||||
@CurrentUser() user: any,
|
@CurrentUser() user: any,
|
||||||
|
@UploadedFiles() invoices?: Express.Multer.File[],
|
||||||
) {
|
) {
|
||||||
|
for (const file of invoices ?? []) {
|
||||||
|
await this.mediaPolicyService.assertForClaim(file, claimRequestId, "image");
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
return await this.claimRequestManagementService.handleUserObjectionV2(
|
return await this.claimRequestManagementService.handleUserObjectionV2(
|
||||||
claimRequestId,
|
claimRequestId,
|
||||||
body,
|
body,
|
||||||
user.sub,
|
user.sub,
|
||||||
user,
|
user,
|
||||||
|
invoices,
|
||||||
);
|
);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof HttpException) throw error;
|
if (error instanceof HttpException) throw error;
|
||||||
@@ -222,7 +295,10 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
})
|
})
|
||||||
@ApiBody({ type: UserRatingDto })
|
@ApiBody({ type: UserRatingDto })
|
||||||
@ApiResponse({ status: 200, description: "Rating saved" })
|
@ApiResponse({ status: 200, description: "Rating saved" })
|
||||||
@ApiResponse({ status: 400, description: "Claim not completed or invalid scores" })
|
@ApiResponse({
|
||||||
|
status: 400,
|
||||||
|
description: "Claim not completed or invalid scores",
|
||||||
|
})
|
||||||
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
||||||
@ApiResponse({ status: 404, description: "Claim not found" })
|
@ApiResponse({ status: 404, description: "Claim not found" })
|
||||||
@ApiResponse({ status: 409, description: "Rating already submitted" })
|
@ApiResponse({ status: 409, description: "Rating already submitted" })
|
||||||
@@ -270,21 +346,32 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
type: "object",
|
type: "object",
|
||||||
required: ["sign", "agree", "branchId"],
|
required: ["sign", "agree", "branchId"],
|
||||||
properties: {
|
properties: {
|
||||||
sign: { type: "string", format: "binary", description: "Signature image" },
|
sign: {
|
||||||
|
type: "string",
|
||||||
|
format: "binary",
|
||||||
|
description: "Signature image",
|
||||||
|
},
|
||||||
agree: {
|
agree: {
|
||||||
type: "boolean",
|
type: "boolean",
|
||||||
description: "true to accept expert pricing and complete the claim",
|
description: "true to accept expert pricing and complete the claim",
|
||||||
},
|
},
|
||||||
branchId: {
|
branchId: {
|
||||||
type: "string",
|
type: "string",
|
||||||
description: "Insurer branch id (must belong to the claim owner's insurer; if pricing lists branch options, must match one of them)",
|
description:
|
||||||
|
"Insurer branch id (must belong to the claim owner's insurer; if pricing lists branch options, must match one of them)",
|
||||||
example: "507f1f77bcf86cd799439011",
|
example: "507f1f77bcf86cd799439011",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 200, description: "Signature stored; claim completed or rejected" })
|
@ApiResponse({
|
||||||
@ApiResponse({ status: 400, description: "Wrong step/status or missing file" })
|
status: 200,
|
||||||
|
description: "Signature stored; claim completed or rejected",
|
||||||
|
})
|
||||||
|
@ApiResponse({
|
||||||
|
status: 400,
|
||||||
|
description: "Wrong step/status or missing file",
|
||||||
|
})
|
||||||
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
||||||
@ApiResponse({ status: 404, description: "Claim not found" })
|
@ApiResponse({ status: 404, description: "Claim not found" })
|
||||||
@ApiResponse({ status: 409, description: "Already signed" })
|
@ApiResponse({ status: 409, description: "Already signed" })
|
||||||
@@ -314,7 +401,9 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
}
|
}
|
||||||
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
|
await this.mediaPolicyService.assertForClaim(sign, claimRequestId, "image");
|
||||||
const agreed =
|
const agreed =
|
||||||
typeof agree === "string" ? agree === "true" || agree === "1" : Boolean(agree);
|
typeof agree === "string"
|
||||||
|
? agree === "true" || agree === "1"
|
||||||
|
: Boolean(agree);
|
||||||
try {
|
try {
|
||||||
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
|
return await this.claimRequestManagementService.submitOwnerInsurerApprovalSignV2(
|
||||||
claimRequestId,
|
claimRequestId,
|
||||||
@@ -453,8 +542,7 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
})
|
})
|
||||||
@ApiBody({
|
@ApiBody({
|
||||||
type: SelectOuterPartsV2Dto,
|
type: SelectOuterPartsV2Dto,
|
||||||
description:
|
description: "Selected vehicle type + selected outer part IDs from catalog",
|
||||||
"Selected vehicle type + selected outer part IDs from catalog",
|
|
||||||
examples: {
|
examples: {
|
||||||
example1: {
|
example1: {
|
||||||
summary: "Sedan - minor front damage",
|
summary: "Sedan - minor front damage",
|
||||||
@@ -522,9 +610,7 @@ export class ClaimRequestManagementV2Controller {
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof HttpException) throw error;
|
if (error instanceof HttpException) throw error;
|
||||||
throw new InternalServerErrorException(
|
throw new InternalServerErrorException(
|
||||||
error instanceof Error
|
error instanceof Error ? error.message : "Failed to select outer parts",
|
||||||
? error.message
|
|
||||||
: "Failed to select outer parts",
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -638,9 +724,7 @@ Optional: upload car green card file in the same step.
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof HttpException) throw error;
|
if (error instanceof HttpException) throw error;
|
||||||
throw new InternalServerErrorException(
|
throw new InternalServerErrorException(
|
||||||
error instanceof Error
|
error instanceof Error ? error.message : "Failed to select other parts",
|
||||||
? error.message
|
|
||||||
: "Failed to select other parts",
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -862,7 +946,7 @@ Returns status of each item (uploaded/captured or not).
|
|||||||
type: "string",
|
type: "string",
|
||||||
example: "front",
|
example: "front",
|
||||||
description:
|
description:
|
||||||
'For angle: front/back/left/right. For part: hood/front_bumper/etc.',
|
"For angle: front/back/left/right. For part: hood/front_bumper/etc.",
|
||||||
},
|
},
|
||||||
file: {
|
file: {
|
||||||
type: "string",
|
type: "string",
|
||||||
@@ -1005,7 +1089,10 @@ Returns status of each item (uploaded/captured or not).
|
|||||||
description: "Video uploaded successfully",
|
description: "Video uploaded successfully",
|
||||||
type: VideoCaptureV2ResponseDto,
|
type: VideoCaptureV2ResponseDto,
|
||||||
})
|
})
|
||||||
@ApiResponse({ status: 400, description: "Wrong workflow step or missing file" })
|
@ApiResponse({
|
||||||
|
status: 400,
|
||||||
|
description: "Wrong workflow step or missing file",
|
||||||
|
})
|
||||||
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
@ApiResponse({ status: 403, description: "Not the claim owner" })
|
||||||
@ApiResponse({ status: 404, description: "Claim not found" })
|
@ApiResponse({ status: 404, description: "Claim not found" })
|
||||||
@ApiResponse({ status: 409, description: "Video already uploaded" })
|
@ApiResponse({ status: 409, description: "Video already uploaded" })
|
||||||
@@ -1025,9 +1112,10 @@ Returns status of each item (uploaded/captured or not).
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
if (error instanceof HttpException) throw error;
|
if (error instanceof HttpException) throw error;
|
||||||
throw new InternalServerErrorException(
|
throw new InternalServerErrorException(
|
||||||
error instanceof Error ? error.message : "Failed to upload car capture video",
|
error instanceof Error
|
||||||
|
? error.message
|
||||||
|
: "Failed to upload car capture video",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||||
import { Type } from "class-transformer";
|
import { Type, Transform } from "class-transformer";
|
||||||
import {
|
import {
|
||||||
IsArray,
|
IsArray,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
@@ -10,23 +10,52 @@ import { HasObjectionEntriesConstraint } from "src/common/validators/has-objecti
|
|||||||
import { NewPartDto, UserObjectionPartDto } from "./user-objection.dto";
|
import { NewPartDto, UserObjectionPartDto } from "./user-objection.dto";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* V2 user objection body — same shape as v1 {@link UserObjectionDto}
|
* V2 user objection body — submitted as multipart/form-data.
|
||||||
* with nested validation enabled for the v2 controller pipeline.
|
* `objectionParts` and `newParts` are JSON-encoded strings in the form fields.
|
||||||
|
* Optional `invoices` files are uploaded as a `invoices` file array.
|
||||||
*/
|
*/
|
||||||
export class UserObjectionV2Dto {
|
export class UserObjectionV2Dto {
|
||||||
@ApiPropertyOptional({ type: [UserObjectionPartDto] })
|
@ApiPropertyOptional({
|
||||||
|
type: [UserObjectionPartDto],
|
||||||
|
description:
|
||||||
|
"JSON-encoded array of disputed priced parts. Pass as a JSON string in the multipart field.",
|
||||||
|
})
|
||||||
@Validate(HasObjectionEntriesConstraint)
|
@Validate(HasObjectionEntriesConstraint)
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@Type(() => UserObjectionPartDto)
|
@Type(() => UserObjectionPartDto)
|
||||||
|
@Transform(({ value }) => {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
try {
|
||||||
|
return JSON.parse(value);
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
})
|
||||||
objectionParts?: UserObjectionPartDto[];
|
objectionParts?: UserObjectionPartDto[];
|
||||||
|
|
||||||
@ApiPropertyOptional({ type: [NewPartDto] })
|
@ApiPropertyOptional({
|
||||||
|
type: [NewPartDto],
|
||||||
|
description:
|
||||||
|
"JSON-encoded array of new parts to add. Pass as a JSON string in the multipart field.",
|
||||||
|
})
|
||||||
@Validate(HasObjectionEntriesConstraint)
|
@Validate(HasObjectionEntriesConstraint)
|
||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsArray()
|
@IsArray()
|
||||||
@ValidateNested({ each: true })
|
@ValidateNested({ each: true })
|
||||||
@Type(() => NewPartDto)
|
@Type(() => NewPartDto)
|
||||||
|
@Transform(({ value }) => {
|
||||||
|
if (typeof value === "string") {
|
||||||
|
try {
|
||||||
|
return JSON.parse(value);
|
||||||
|
} catch {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
})
|
||||||
newParts?: NewPartDto[];
|
newParts?: NewPartDto[];
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -180,6 +180,27 @@ export class ClaimUserObjectionNewPart {
|
|||||||
export const ClaimUserObjectionNewPartSchema =
|
export const ClaimUserObjectionNewPartSchema =
|
||||||
SchemaFactory.createForClass(ClaimUserObjectionNewPart);
|
SchemaFactory.createForClass(ClaimUserObjectionNewPart);
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Objection invoice (supporting document uploaded alongside the objection)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
@Schema({ _id: false })
|
||||||
|
export class ClaimObjectionInvoice {
|
||||||
|
@Prop({ type: Types.ObjectId, default: () => new Types.ObjectId() })
|
||||||
|
fileId: Types.ObjectId;
|
||||||
|
|
||||||
|
@Prop({ type: String, required: true })
|
||||||
|
path: string;
|
||||||
|
|
||||||
|
@Prop({ type: String, required: true })
|
||||||
|
fileName: string;
|
||||||
|
|
||||||
|
@Prop({ type: Date, default: () => new Date() })
|
||||||
|
uploadedAt: Date;
|
||||||
|
}
|
||||||
|
export const ClaimObjectionInvoiceSchema =
|
||||||
|
SchemaFactory.createForClass(ClaimObjectionInvoice);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Full user objection payload (matches v1 DTO: objectionParts + newParts).
|
* Full user objection payload (matches v1 DTO: objectionParts + newParts).
|
||||||
* Stored on {@link ClaimEvaluation.objection}.
|
* Stored on {@link ClaimEvaluation.objection}.
|
||||||
@@ -194,6 +215,10 @@ export class ClaimUserObjectionPayload {
|
|||||||
|
|
||||||
@Prop({ type: Date, default: () => new Date() })
|
@Prop({ type: Date, default: () => new Date() })
|
||||||
submittedAt?: Date;
|
submittedAt?: Date;
|
||||||
|
|
||||||
|
/** Optional supporting invoices uploaded at objection time. */
|
||||||
|
@Prop({ type: [ClaimObjectionInvoiceSchema], default: [] })
|
||||||
|
invoices?: ClaimObjectionInvoice[];
|
||||||
}
|
}
|
||||||
export const ClaimUserObjectionPayloadSchema =
|
export const ClaimUserObjectionPayloadSchema =
|
||||||
SchemaFactory.createForClass(ClaimUserObjectionPayload);
|
SchemaFactory.createForClass(ClaimUserObjectionPayload);
|
||||||
|
|||||||
@@ -86,6 +86,15 @@ export class FanavaranSyncStage {
|
|||||||
|
|
||||||
@Prop({ type: MongooseSchema.Types.Mixed })
|
@Prop({ type: MongooseSchema.Types.Mixed })
|
||||||
response?: unknown;
|
response?: unknown;
|
||||||
|
|
||||||
|
@Prop({ type: Number, default: 0 })
|
||||||
|
retryCount?: number;
|
||||||
|
|
||||||
|
@Prop({ type: Number, default: 2 })
|
||||||
|
maxRetries?: number;
|
||||||
|
|
||||||
|
@Prop({ type: Date })
|
||||||
|
nextRetryAt?: Date;
|
||||||
}
|
}
|
||||||
export const FanavaranSyncStageSchema =
|
export const FanavaranSyncStageSchema =
|
||||||
SchemaFactory.createForClass(FanavaranSyncStage);
|
SchemaFactory.createForClass(FanavaranSyncStage);
|
||||||
@@ -242,6 +251,20 @@ export class ClaimCase {
|
|||||||
@Prop({ type: Types.ObjectId, index: true })
|
@Prop({ type: Types.ObjectId, index: true })
|
||||||
createdByRegistrarId?: Types.ObjectId;
|
createdByRegistrarId?: Types.ObjectId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 split flow: when true, the claim must be approved by the FileMaker
|
||||||
|
* who created the file before fanavaran submission is allowed.
|
||||||
|
*/
|
||||||
|
@Prop({ type: Boolean, default: false })
|
||||||
|
requiresFileMakerApproval?: boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 split flow: ObjectId of the FileMaker who must approve this claim.
|
||||||
|
* Set when the FileReviewer uploads the blame accident video in the V5 flow.
|
||||||
|
*/
|
||||||
|
@Prop({ type: Types.ObjectId, index: true })
|
||||||
|
fileMakerApprovalActorId?: Types.ObjectId;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Legacy fields kept optional to simplify progressive migration.
|
* Legacy fields kept optional to simplify progressive migration.
|
||||||
* If you choose to migrate later, we can remove these.
|
* If you choose to migrate later, we can remove these.
|
||||||
|
|||||||
@@ -4,9 +4,12 @@ import {
|
|||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
|
HttpException,
|
||||||
|
InternalServerErrorException,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
Query,
|
Query,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
@@ -516,6 +519,73 @@ 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")
|
@Patch("car-capture/:claimRequestId")
|
||||||
@ApiConsumes("multipart/form-data")
|
@ApiConsumes("multipart/form-data")
|
||||||
@UseInterceptors(
|
@UseInterceptors(
|
||||||
|
|||||||
@@ -1,11 +1,20 @@
|
|||||||
import { Body, Controller, Get, Patch, Post } from "@nestjs/common";
|
|
||||||
import {
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
UseGuards,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
ApiBody,
|
ApiBody,
|
||||||
ApiOperation,
|
ApiOperation,
|
||||||
ApiResponse,
|
ApiResponse,
|
||||||
ApiTags,
|
ApiTags,
|
||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
import { CurrentUser } from "src/decorators/user.decorator";
|
import { CurrentUser } from "src/decorators/user.decorator";
|
||||||
|
import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard";
|
||||||
import { SystemSettingsResponseDto } from "src/system-settings/dto/system-settings.dto";
|
import { SystemSettingsResponseDto } from "src/system-settings/dto/system-settings.dto";
|
||||||
import { SystemSettingsService } from "src/system-settings/system-settings.service";
|
import { SystemSettingsService } from "src/system-settings/system-settings.service";
|
||||||
import { ClientService } from "./client.service";
|
import { ClientService } from "./client.service";
|
||||||
@@ -21,26 +30,35 @@ export class ClientController {
|
|||||||
) {}
|
) {}
|
||||||
|
|
||||||
@Post()
|
@Post()
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@ApiOperation({ summary: "Create a new insurer client (super-admin only)" })
|
||||||
async addClient(@Body() client: ClientDto) {
|
async addClient(@Body() client: ClientDto) {
|
||||||
return await this.clientService.addClient(client);
|
return await this.clientService.addClient(client);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@ApiBearerAuth()
|
||||||
async getClient(@CurrentUser() user) {
|
async getClient(@CurrentUser() user) {
|
||||||
return await this.clientService.getClients();
|
return await this.clientService.getClients();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Get("list")
|
@Get("list")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@ApiBearerAuth()
|
||||||
async getClientList(@CurrentUser() user) {
|
async getClientList(@CurrentUser() user) {
|
||||||
return await this.clientService.getClientList();
|
return await this.clientService.getClientList();
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Toggle SandHub/Tejarat live HTTP vs mock inquiries (`system_settings.externalApis.sandHubUseLiveApi`). */
|
/** Toggle SandHub/Tejarat live HTTP vs mock inquiries (`system_settings.externalApis.sandHubUseLiveApi`). */
|
||||||
@Patch("external-inquiries-live")
|
@Patch("external-inquiries-live")
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@ApiBearerAuth()
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Enable or disable live external inquiries",
|
summary: "Enable or disable live external inquiries (super-admin only)",
|
||||||
description:
|
description:
|
||||||
"Updates `system_settings.externalApis.sandHubUseLiveApi`. No auth required. Use the request examples below to switch between live Tejarat/SandHub HTTP and offline mock mode.",
|
"Updates `system_settings.externalApis.sandHubUseLiveApi`. Use the request examples below to switch between live Tejarat/SandHub HTTP and offline mock mode.",
|
||||||
})
|
})
|
||||||
@ApiBody({
|
@ApiBody({
|
||||||
type: SetExternalInquiriesLiveDto,
|
type: SetExternalInquiriesLiveDto,
|
||||||
@@ -52,7 +70,8 @@ export class ClientController {
|
|||||||
},
|
},
|
||||||
disableLive: {
|
disableLive: {
|
||||||
summary: "Disable live inquiries (mock mode)",
|
summary: "Disable live inquiries (mock mode)",
|
||||||
description: "Use mocked inquiry responses; flows continue without external connectivity.",
|
description:
|
||||||
|
"Use mocked inquiry responses; flows continue without external connectivity.",
|
||||||
value: { enabled: false },
|
value: { enabled: false },
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -49,6 +49,14 @@ export class ExternalInquiryFlagsDto implements ExternalInquiryFlags {
|
|||||||
})
|
})
|
||||||
@IsBoolean()
|
@IsBoolean()
|
||||||
carOwnership: boolean;
|
carOwnership: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
description:
|
||||||
|
"ESG VIN/chassis-number inquiry (`/inquiry/policyByChassis`). Required for the VIN initial-form path.",
|
||||||
|
example: false,
|
||||||
|
})
|
||||||
|
@IsBoolean()
|
||||||
|
vinChassis: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class UpdateClientExternalInquiriesDto extends PartialType(
|
export class UpdateClientExternalInquiriesDto extends PartialType(
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ export class AuthGuard implements CanActivate {
|
|||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const payload: JwtPayload =
|
const payload: JwtPayload =
|
||||||
await this.jwtService.verifyAsync<JwtPayload>(token);
|
await this.jwtService.verifyAsync<JwtPayload>(token, {
|
||||||
|
secret: `${process.env.JWT_SECRET}`,
|
||||||
|
});
|
||||||
request["user"] = payload;
|
request["user"] = payload;
|
||||||
} catch {
|
} catch {
|
||||||
throw new UnauthorizedException("Invalid or expired token");
|
throw new UnauthorizedException("Invalid or expired token");
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Type } from "class-transformer";
|
|||||||
import {
|
import {
|
||||||
IsIn,
|
IsIn,
|
||||||
IsInt,
|
IsInt,
|
||||||
|
IsISO8601,
|
||||||
IsOptional,
|
IsOptional,
|
||||||
IsString,
|
IsString,
|
||||||
Max,
|
Max,
|
||||||
@@ -102,4 +103,20 @@ export class ListQueryV2Dto {
|
|||||||
@IsOptional()
|
@IsOptional()
|
||||||
@IsIn([...LIST_FILE_TYPE_V2])
|
@IsIn([...LIST_FILE_TYPE_V2])
|
||||||
fileType?: ListFileTypeV2;
|
fileType?: ListFileTypeV2;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: "Filter start date (ISO 8601). Only files created on or after this date are returned.",
|
||||||
|
example: "2025-01-01T00:00:00.000Z",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsISO8601({ strict: false })
|
||||||
|
startDate?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: "Filter end date (ISO 8601). Only files created on or before this date are returned.",
|
||||||
|
example: "2025-12-31T23:59:59.999Z",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsISO8601({ strict: false })
|
||||||
|
endDate?: string;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ export const EXTERNAL_INQUIRY_TYPES = [
|
|||||||
"sheba",
|
"sheba",
|
||||||
"drivingLicense",
|
"drivingLicense",
|
||||||
"carOwnership",
|
"carOwnership",
|
||||||
|
"vinChassis",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type ExternalInquiryType = (typeof EXTERNAL_INQUIRY_TYPES)[number];
|
export type ExternalInquiryType = (typeof EXTERNAL_INQUIRY_TYPES)[number];
|
||||||
@@ -21,6 +22,7 @@ export const DEFAULT_EXTERNAL_INQUIRY_FLAGS: Record<
|
|||||||
sheba: false,
|
sheba: false,
|
||||||
drivingLicense: false,
|
drivingLicense: false,
|
||||||
carOwnership: false,
|
carOwnership: false,
|
||||||
|
vinChassis: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
export type ExternalInquiryFlags = Record<ExternalInquiryType, boolean>;
|
export type ExternalInquiryFlags = Record<ExternalInquiryType, boolean>;
|
||||||
|
|||||||
@@ -37,6 +37,7 @@ export interface FanavaranPayloadDefaults {
|
|||||||
AccidentReportTypeId: number;
|
AccidentReportTypeId: number;
|
||||||
AccidentVehicleUsedId: number;
|
AccidentVehicleUsedId: number;
|
||||||
ClaimExpertId: number;
|
ClaimExpertId: number;
|
||||||
|
ExpertiseClaimExpertId: number;
|
||||||
CompensationReferenceId: number;
|
CompensationReferenceId: number;
|
||||||
CulpritLicenceTypeId: number;
|
CulpritLicenceTypeId: number;
|
||||||
CulpritTypeId: number;
|
CulpritTypeId: number;
|
||||||
@@ -74,7 +75,8 @@ const FANAVARAN_CLIENT_PROFILES: Record<
|
|||||||
AccidentCityId: 701,
|
AccidentCityId: 701,
|
||||||
AccidentReportTypeId: 155,
|
AccidentReportTypeId: 155,
|
||||||
AccidentVehicleUsedId: 1,
|
AccidentVehicleUsedId: 1,
|
||||||
ClaimExpertId: 1589,
|
ClaimExpertId: 4543092,
|
||||||
|
ExpertiseClaimExpertId: 4543092,
|
||||||
CompensationReferenceId: 167,
|
CompensationReferenceId: 167,
|
||||||
CulpritLicenceTypeId: 2,
|
CulpritLicenceTypeId: 2,
|
||||||
CulpritTypeId: 337,
|
CulpritTypeId: 337,
|
||||||
@@ -84,7 +86,7 @@ const FANAVARAN_CLIENT_PROFILES: Record<
|
|||||||
PlaqueSampleId: 10,
|
PlaqueSampleId: 10,
|
||||||
DriverIsOwner: 0,
|
DriverIsOwner: 0,
|
||||||
FaultPercent: 100,
|
FaultPercent: 100,
|
||||||
ClaimFileTypeId: 70,
|
ClaimFileTypeId: 23,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
parsian: {
|
parsian: {
|
||||||
@@ -103,6 +105,7 @@ const FANAVARAN_CLIENT_PROFILES: Record<
|
|||||||
AccidentReportTypeId: 155,
|
AccidentReportTypeId: 155,
|
||||||
AccidentVehicleUsedId: 1,
|
AccidentVehicleUsedId: 1,
|
||||||
ClaimExpertId: 154,
|
ClaimExpertId: 154,
|
||||||
|
ExpertiseClaimExpertId: 29,
|
||||||
CompensationReferenceId: 167,
|
CompensationReferenceId: 167,
|
||||||
CulpritLicenceTypeId: 2,
|
CulpritLicenceTypeId: 2,
|
||||||
CulpritTypeId: 337,
|
CulpritTypeId: 337,
|
||||||
|
|||||||
26
src/core/config/http-proxy.factory.ts
Normal file
26
src/core/config/http-proxy.factory.ts
Normal 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 {};
|
||||||
|
}
|
||||||
@@ -121,6 +121,12 @@ export class AllRequestDtoV2 {
|
|||||||
unifiedFileStatus?: string;
|
unifiedFileStatus?: string;
|
||||||
partiesInitialForms: { firstParty: string; secondParty: string };
|
partiesInitialForms: { firstParty: string; secondParty: string };
|
||||||
partiesVehicles: { firstPartyVehicle: string; secondPartyVehicle: string };
|
partiesVehicles: { firstPartyVehicle: string; secondPartyVehicle: string };
|
||||||
|
/**
|
||||||
|
* True when the file is in WAITING_FOR_FILE_REVIEWER status — the FileReviewer
|
||||||
|
* must complete accident fields, capture, and upload-video via v4 endpoints
|
||||||
|
* before the file enters the normal expert-blame review queue.
|
||||||
|
*/
|
||||||
|
needsFileReviewerCompletion?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class AllRequestDtoRsV2 {
|
export class AllRequestDtoRsV2 {
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
assertBlameCaseForExpertTenant,
|
assertBlameCaseForExpertTenant,
|
||||||
blameCaseAccessibleToExpert,
|
blameCaseAccessibleToExpert,
|
||||||
blameCaseInitiatedByFieldExpert,
|
blameCaseInitiatedByFieldExpert,
|
||||||
|
blameCaseTouchesClient,
|
||||||
requireActorClientKey,
|
requireActorClientKey,
|
||||||
} from "src/helpers/tenant-scope";
|
} from "src/helpers/tenant-scope";
|
||||||
import {
|
import {
|
||||||
@@ -438,6 +439,9 @@ export class ExpertBlameService {
|
|||||||
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
||||||
return this.getFieldExpertBlameListV2(actor, query);
|
return this.getFieldExpertBlameListV2(actor, query);
|
||||||
}
|
}
|
||||||
|
if (actor.role === RoleEnum.FILE_REVIEWER) {
|
||||||
|
return this.getFileReviewerBlameListV2(actor, query);
|
||||||
|
}
|
||||||
requireActorClientKey(actor);
|
requireActorClientKey(actor);
|
||||||
const expertId = actor.sub;
|
const expertId = actor.sub;
|
||||||
|
|
||||||
@@ -579,6 +583,44 @@ export class ExpertBlameService {
|
|||||||
return pagedResult;
|
return pagedResult;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Blame inbox for FILE_REVIEWER — all expert-initiated IN_PERSON files that
|
||||||
|
* have been sealed by a FileMaker (WAITING_FOR_FILE_REVIEWER) and belong to
|
||||||
|
* this reviewer's insurance company (clientKey).
|
||||||
|
*
|
||||||
|
* Once the FileReviewer completes their steps the file moves to
|
||||||
|
* WAITING_FOR_EXPERT (via upload-video), after which it is visible in the
|
||||||
|
* standard expert-blame panel as usual.
|
||||||
|
*/
|
||||||
|
private async getFileReviewerBlameListV2(
|
||||||
|
actor: { sub: string; clientKey?: string },
|
||||||
|
query: ListQueryV2Dto = {},
|
||||||
|
): Promise<AllRequestDtoRsV2> {
|
||||||
|
const clientKey = requireActorClientKey(actor);
|
||||||
|
|
||||||
|
const allSealed = (await this.blameRequestDbService.find(
|
||||||
|
{
|
||||||
|
expertInitiated: true,
|
||||||
|
status: {
|
||||||
|
$in: [
|
||||||
|
CaseStatus.WAITING_FOR_FILE_REVIEWER,
|
||||||
|
CaseStatus.WAITING_FOR_EXPERT,
|
||||||
|
CaseStatus.COMPLETED,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ lean: true },
|
||||||
|
)) as Record<string, unknown>[];
|
||||||
|
|
||||||
|
// Scope to this reviewer's insurance company via blame party clientId
|
||||||
|
const visibleCases = allSealed.filter((doc) =>
|
||||||
|
blameCaseTouchesClient(doc, clientKey),
|
||||||
|
);
|
||||||
|
|
||||||
|
const pagedResult = await this.paginateBlameListV2(visibleCases, query);
|
||||||
|
return pagedResult;
|
||||||
|
}
|
||||||
|
|
||||||
private async paginateBlameListV2(
|
private async paginateBlameListV2(
|
||||||
visibleCases: Record<string, unknown>[],
|
visibleCases: Record<string, unknown>[],
|
||||||
query: ListQueryV2Dto,
|
query: ListQueryV2Dto,
|
||||||
@@ -588,11 +630,21 @@ export class ExpertBlameService {
|
|||||||
String((d as { publicId?: string }).publicId ?? ""),
|
String((d as { publicId?: string }).publicId ?? ""),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
const filtered = this.filterBlameDocsByUnifiedStatus(
|
let filtered = this.filterBlameDocsByUnifiedStatus(
|
||||||
visibleCases,
|
visibleCases,
|
||||||
claimByPublicId,
|
claimByPublicId,
|
||||||
query.unifiedStatus,
|
query.unifiedStatus,
|
||||||
);
|
);
|
||||||
|
const { fromDate, toDate } = parseListDateRange(query.startDate, query.endDate);
|
||||||
|
if (fromDate || toDate) {
|
||||||
|
filtered = filtered.filter((doc) =>
|
||||||
|
isInListDateRange(
|
||||||
|
(doc as { createdAt?: Date }).createdAt,
|
||||||
|
fromDate,
|
||||||
|
toDate,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const paged = applyListQueryV2(
|
const paged = applyListQueryV2(
|
||||||
filtered,
|
filtered,
|
||||||
@@ -727,6 +779,10 @@ export class ExpertBlameService {
|
|||||||
secondParty?.vehicle?.inquiry?.mapped?.CarName ||
|
secondParty?.vehicle?.inquiry?.mapped?.CarName ||
|
||||||
"",
|
"",
|
||||||
},
|
},
|
||||||
|
needsFileReviewerCompletion:
|
||||||
|
String(doc.status ?? "") === CaseStatus.WAITING_FOR_FILE_REVIEWER ||
|
||||||
|
(!!(doc as any).isMadeByFileMaker &&
|
||||||
|
String(doc.status ?? "") === CaseStatus.WAITING_FOR_EXPERT),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1815,6 +1871,7 @@ export class ExpertBlameService {
|
|||||||
link: this.smsOrchestrationService.buildBlamePartyLink(
|
link: this.smsOrchestrationService.buildBlamePartyLink(
|
||||||
requestIdToken,
|
requestIdToken,
|
||||||
role,
|
role,
|
||||||
|
"v1",
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -2009,6 +2066,7 @@ export class ExpertBlameService {
|
|||||||
link: this.smsOrchestrationService.buildBlamePartyLink(
|
link: this.smsOrchestrationService.buildBlamePartyLink(
|
||||||
requestIdToken,
|
requestIdToken,
|
||||||
linkRole,
|
linkRole,
|
||||||
|
"v1",
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -38,7 +38,7 @@ import { ResendRequestDto } from "./dto/resend.dto";
|
|||||||
@Controller("v2/expert-blame")
|
@Controller("v2/expert-blame")
|
||||||
@ApiBearerAuth()
|
@ApiBearerAuth()
|
||||||
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||||
@Roles(RoleEnum.EXPERT, RoleEnum.FIELD_EXPERT, RoleEnum.FILE_REVIEWER, RoleEnum.FILE_MAKER)
|
@Roles(RoleEnum.EXPERT, RoleEnum.FIELD_EXPERT)
|
||||||
export class ExpertBlameV2Controller {
|
export class ExpertBlameV2Controller {
|
||||||
constructor(private readonly expertBlameService: ExpertBlameService) {}
|
constructor(private readonly expertBlameService: ExpertBlameService) {}
|
||||||
|
|
||||||
|
|||||||
@@ -131,16 +131,26 @@ export class ClaimDetailV2ResponseDto {
|
|||||||
})
|
})
|
||||||
awaitingFactorValidation?: boolean;
|
awaitingFactorValidation?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
"True for V5 files — the FileMaker must approve or reject the claim before it is submitted to fanavaran. False (or absent) for V4 files which go straight through.",
|
||||||
|
example: true,
|
||||||
|
})
|
||||||
|
requiresFileMakerApproval?: boolean;
|
||||||
|
|
||||||
@ApiPropertyOptional({
|
@ApiPropertyOptional({
|
||||||
description:
|
description:
|
||||||
"Slice of `claim.evaluation` exposed to the damage expert. " +
|
"Slice of `claim.evaluation` exposed to the damage expert. " +
|
||||||
"`damageExpertReply` / `damageExpertReplyFinal` are returned only while " +
|
"`damageExpertReply` / `damageExpertReplyFinal` are returned whenever " +
|
||||||
"awaiting factor validation. `ownerInsurerApproval` and " +
|
"present, regardless of the current claim status — historical assessment " +
|
||||||
"`ownerPricedPartsApproval` are returned whenever they exist on the " +
|
"data remains visible once the expert has submitted it. " +
|
||||||
"claim — each carries `signLink` (resolved from `signDetailId`) so the " +
|
"`ownerInsurerApproval` and `ownerPricedPartsApproval` are returned " +
|
||||||
"front-end can render the user signature directly. Likewise, " +
|
"whenever they exist on the claim — each carries `signLink` (resolved " +
|
||||||
"`damageExpertReply.userComment` / `damageExpertReplyFinal.userComment` " +
|
"from `signDetailId`) so the front-end can render the user signature " +
|
||||||
"expose `signLink` when a user comment signature is present.",
|
"directly. Likewise, `damageExpertReply.userComment` / " +
|
||||||
|
"`damageExpertReplyFinal.userComment` expose `signLink` when a user " +
|
||||||
|
"comment signature is present. `priceDrop` is included whenever it " +
|
||||||
|
"has been saved, not only during the expert review phase.",
|
||||||
})
|
})
|
||||||
evaluation?: {
|
evaluation?: {
|
||||||
damageExpertReply?: unknown;
|
damageExpertReply?: unknown;
|
||||||
|
|||||||
@@ -56,6 +56,12 @@ export class ClaimListItemV2Dto {
|
|||||||
})
|
})
|
||||||
carBodyFirstForm?: { car?: boolean; object?: boolean };
|
carBodyFirstForm?: { car?: boolean; object?: boolean };
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: 'Linked blame file ID (present when the claim originates from a blame case)',
|
||||||
|
example: '6a3a6f171aadfa0cc313c582',
|
||||||
|
})
|
||||||
|
blameRequestId?: string;
|
||||||
|
|
||||||
@ApiProperty({ description: 'Submission date', example: '2026-02-22T10:00:00.000Z' })
|
@ApiProperty({ description: 'Submission date', example: '2026-02-22T10:00:00.000Z' })
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
|
||||||
@@ -64,6 +70,13 @@ export class ClaimListItemV2Dto {
|
|||||||
"True in the expert repair-factor validation queue: `status=EXPERT_VALIDATING_REPAIR_FACTORS` (or legacy `WAITING_FOR_INSURER_APPROVAL`) with `claimStatus=UNDER_REVIEW` and `currentStep=EXPERT_COST_EVALUATION`.",
|
"True in the expert repair-factor validation queue: `status=EXPERT_VALIDATING_REPAIR_FACTORS` (or legacy `WAITING_FOR_INSURER_APPROVAL`) with `claimStatus=UNDER_REVIEW` and `currentStep=EXPERT_COST_EVALUATION`.",
|
||||||
})
|
})
|
||||||
awaitingFactorValidation?: boolean;
|
awaitingFactorValidation?: boolean;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description:
|
||||||
|
"True for V5 files — the FileMaker must approve or reject the claim before it is submitted to fanavaran. False (or absent) for V4 files which go straight through.",
|
||||||
|
example: true,
|
||||||
|
})
|
||||||
|
requiresFileMakerApproval?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class GetClaimListV2ResponseDto {
|
export class GetClaimListV2ResponseDto {
|
||||||
|
|||||||
25
src/expert-claim/exceptions/business-rule.exception.ts
Normal file
25
src/expert-claim/exceptions/business-rule.exception.ts
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
import { HttpException, HttpStatus } from "@nestjs/common";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when a well-formed request violates a business rule that cannot be
|
||||||
|
* expressed as a generic validation error. Returns HTTP 422 with a structured
|
||||||
|
* body so the frontend can branch on `errorCode` without string-matching the
|
||||||
|
* human-readable `message`.
|
||||||
|
*
|
||||||
|
* Response body shape:
|
||||||
|
* ```json
|
||||||
|
* { "errorCode": "SOME_CODE", "message": "Human-readable explanation." }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
export class BusinessRuleException extends HttpException {
|
||||||
|
constructor(
|
||||||
|
public readonly errorCode: string,
|
||||||
|
message: string,
|
||||||
|
) {
|
||||||
|
super({ errorCode, message }, HttpStatus.UNPROCESSABLE_ENTITY);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const BusinessErrorCode = {
|
||||||
|
DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED: "DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED",
|
||||||
|
} as const;
|
||||||
@@ -1,5 +1,7 @@
|
|||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
import { Module } from "@nestjs/common";
|
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 { MongooseModule } from "@nestjs/mongoose";
|
||||||
import { AiModule } from "src/ai/ai.module";
|
import { AiModule } from "src/ai/ai.module";
|
||||||
import { AuthModule } from "src/auth/auth.module";
|
import { AuthModule } from "src/auth/auth.module";
|
||||||
@@ -21,7 +23,11 @@ import { ExpertClaimService } from "./expert-claim.service";
|
|||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
SandHubModule,
|
SandHubModule,
|
||||||
MongooseModule.forFeature([
|
MongooseModule.forFeature([
|
||||||
{ name: ClaimFactorsImage.name, schema: ClaimFactorsImageSchema },
|
{ name: ClaimFactorsImage.name, schema: ClaimFactorsImageSchema },
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from "@nestjs/common";
|
} from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
BusinessErrorCode,
|
||||||
|
BusinessRuleException,
|
||||||
|
} from "./exceptions/business-rule.exception";
|
||||||
import { distance as stringDistance } from "fastest-levenshtein"; // حتما نصب بشه
|
import { distance as stringDistance } from "fastest-levenshtein"; // حتما نصب بشه
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import { lastValueFrom } from "rxjs";
|
import { lastValueFrom } from "rxjs";
|
||||||
@@ -59,6 +63,7 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
|
|||||||
import {
|
import {
|
||||||
assertClaimCaseForTenant,
|
assertClaimCaseForTenant,
|
||||||
assertClaimCaseForExpertActor,
|
assertClaimCaseForExpertActor,
|
||||||
|
blameCaseTouchesClient,
|
||||||
claimCaseInitiatedByFieldExpert,
|
claimCaseInitiatedByFieldExpert,
|
||||||
claimCaseTouchesClient,
|
claimCaseTouchesClient,
|
||||||
requireActorClientKey,
|
requireActorClientKey,
|
||||||
@@ -367,6 +372,21 @@ export class ExpertClaimService {
|
|||||||
await enrichApproval("ownerInsurerApproval");
|
await enrichApproval("ownerInsurerApproval");
|
||||||
await enrichApproval("ownerPricedPartsApproval");
|
await enrichApproval("ownerPricedPartsApproval");
|
||||||
|
|
||||||
|
// Resolve objection invoice paths to downloadable URLs.
|
||||||
|
const objection = ev.objection as Record<string, unknown> | undefined;
|
||||||
|
if (objection) {
|
||||||
|
const invoices = objection.invoices as Array<Record<string, unknown>> | undefined;
|
||||||
|
if (Array.isArray(invoices) && invoices.length > 0) {
|
||||||
|
ev.objection = {
|
||||||
|
...objection,
|
||||||
|
invoices: invoices.map((inv) => ({
|
||||||
|
...inv,
|
||||||
|
url: inv.path ? buildFileLink(inv.path as string) : undefined,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return ev;
|
return ev;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -383,6 +403,12 @@ export class ExpertClaimService {
|
|||||||
claim: any,
|
claim: any,
|
||||||
actor: any,
|
actor: any,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
|
// FILE_REVIEWER: by the time we reach this method the caller has already
|
||||||
|
// verified that actor.sub === blame.assignedFileReviewerId (Phase 2 of
|
||||||
|
// assignClaimForReviewV2). The generic tenant-scope check would incorrectly
|
||||||
|
// reject them because initiatedByFieldExpertId belongs to the FileMaker, not
|
||||||
|
// the reviewer. Skip it — the assignment check is the access proof.
|
||||||
|
if ((actor as any).role === RoleEnum.FILE_REVIEWER) return;
|
||||||
const blame = await this.loadBlameForClaim(claim);
|
const blame = await this.loadBlameForClaim(claim);
|
||||||
assertClaimCaseForExpertActor(claim, actor, blame);
|
assertClaimCaseForExpertActor(claim, actor, blame);
|
||||||
}
|
}
|
||||||
@@ -540,6 +566,23 @@ export class ExpertClaimService {
|
|||||||
return this.expertVehicleFromPartyVehicle(party?.vehicle);
|
return this.expertVehicleFromPartyVehicle(party?.vehicle);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Extract car name / model from the inquiry snapshot embedded on the claim. */
|
||||||
|
private vehicleNamesFromClaimInquiries(claim: any): {
|
||||||
|
carName?: string;
|
||||||
|
carModel?: string;
|
||||||
|
} {
|
||||||
|
// Claim copies inquiries from blame at creation time.
|
||||||
|
// Try thirdParty first, then carBody.
|
||||||
|
const mapped =
|
||||||
|
claim?.inquiries?.thirdParty?.data?.FIRST?.mapped ??
|
||||||
|
claim?.inquiries?.carBody?.data?.FIRST?.mapped ??
|
||||||
|
{};
|
||||||
|
const carName: string | undefined =
|
||||||
|
mapped.MapTypNam || mapped.SystemField || undefined;
|
||||||
|
const carModel: string | undefined = mapped.TypeField || undefined;
|
||||||
|
return { carName, carModel };
|
||||||
|
}
|
||||||
|
|
||||||
private vehicleForExpertFromClaimAndBlameMap(
|
private vehicleForExpertFromClaimAndBlameMap(
|
||||||
claim: any,
|
claim: any,
|
||||||
blameById: Map<string, any>,
|
blameById: Map<string, any>,
|
||||||
@@ -553,10 +596,24 @@ export class ExpertClaimService {
|
|||||||
| undefined {
|
| undefined {
|
||||||
const cv = claim?.vehicle;
|
const cv = claim?.vehicle;
|
||||||
if (cv && (cv.carName || cv.carModel || cv.carType || (cv as any).plate)) {
|
if (cv && (cv.carName || cv.carModel || cv.carType || (cv as any).plate)) {
|
||||||
|
const carType: string | undefined = cv.carType;
|
||||||
|
// carName/carModel that match the enum value (e.g. "sedan") are invalid —
|
||||||
|
// the expert may have accidentally copied the carType value into those fields.
|
||||||
|
// Fall back to the inquiry snapshot for the real brand / variant strings.
|
||||||
|
let carName: string | undefined = cv.carName;
|
||||||
|
let carModel: string | undefined = cv.carModel;
|
||||||
|
if (
|
||||||
|
(!carName || carName === carType) ||
|
||||||
|
(!carModel || carModel === carType)
|
||||||
|
) {
|
||||||
|
const fromInquiry = this.vehicleNamesFromClaimInquiries(claim);
|
||||||
|
if (!carName || carName === carType) carName = fromInquiry.carName;
|
||||||
|
if (!carModel || carModel === carType) carModel = fromInquiry.carModel;
|
||||||
|
}
|
||||||
return {
|
return {
|
||||||
carName: cv.carName,
|
carName,
|
||||||
carModel: cv.carModel,
|
carModel,
|
||||||
carType: cv.carType,
|
carType,
|
||||||
...((cv as any).plate ? { plate: (cv as any).plate } : {}),
|
...((cv as any).plate ? { plate: (cv as any).plate } : {}),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -2476,6 +2533,104 @@ export class ExpertClaimService {
|
|||||||
throw new HttpException(error.response, error.claimStatus);
|
throw new HttpException(error.response, error.claimStatus);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* FILE_REVIEWER path: atomically assign this reviewer to the linked V4 blame
|
||||||
|
* file. Operates on the blame document (not the claim workflow lock).
|
||||||
|
*
|
||||||
|
* Rules:
|
||||||
|
* - Blame must be isMadeByFileMaker, IN_PERSON, expertInitiated.
|
||||||
|
* - Status must be WAITING_FOR_FILE_REVIEWER.
|
||||||
|
* - No other reviewer may have taken it (assignedFileReviewerId absent/null).
|
||||||
|
* - Idempotent: same reviewer calling again gets "already_assigned_to_you".
|
||||||
|
*/
|
||||||
|
private async assignFileReviewerToV4Blame(
|
||||||
|
claimRequestId: string,
|
||||||
|
claim: any,
|
||||||
|
actor: { sub: string; fullName?: string; clientKey?: string },
|
||||||
|
): Promise<ExpertFileAssignResultDto> {
|
||||||
|
if (!claim.blameRequestId) {
|
||||||
|
throw new BadRequestException({
|
||||||
|
success: false,
|
||||||
|
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "This claim has no linked blame file.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const blame = await this.blameRequestDbService.findById(
|
||||||
|
String(claim.blameRequestId),
|
||||||
|
);
|
||||||
|
if (!blame) {
|
||||||
|
throw new NotFoundException("Linked blame file not found.");
|
||||||
|
}
|
||||||
|
if (!(blame as any).isMadeByFileMaker) {
|
||||||
|
throw new BadRequestException({
|
||||||
|
success: false,
|
||||||
|
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "Only V4 FileMaker files can be assigned to a FileReviewer.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if ((blame as any).status !== "WAITING_FOR_FILE_REVIEWER") {
|
||||||
|
throw new BadRequestException({
|
||||||
|
success: false,
|
||||||
|
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||||
|
message: `Blame file is not ready for FileReviewer. Status: ${(blame as any).status}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = (blame as any).assignedFileReviewerId;
|
||||||
|
if (existing) {
|
||||||
|
if (String(existing) === actor.sub) {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
status: "already_assigned_to_you",
|
||||||
|
message: "You have already taken this file.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
throw new ConflictException({
|
||||||
|
success: false,
|
||||||
|
status: "locked" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "Another FileReviewer has already taken this file.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Atomically claim it — findOneAndUpdate with null/missing guard
|
||||||
|
const reviewerOid = new Types.ObjectId(actor.sub);
|
||||||
|
const updated = await this.blameRequestDbService.findOneAndUpdate(
|
||||||
|
{
|
||||||
|
_id: (blame as any)._id,
|
||||||
|
$or: [
|
||||||
|
{ assignedFileReviewerId: { $exists: false } },
|
||||||
|
{ assignedFileReviewerId: null },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ $set: { assignedFileReviewerId: reviewerOid } },
|
||||||
|
{ new: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!updated) {
|
||||||
|
// Another reviewer won the race
|
||||||
|
throw new ConflictException({
|
||||||
|
success: false,
|
||||||
|
status: "locked" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "Another FileReviewer has already taken this file.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
this.logger.log(
|
||||||
|
`FileReviewer ${actor.sub} assigned to V4 blame ${String((blame as any)._id)} / claim ${claimRequestId}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
status: "assigned",
|
||||||
|
assignedAt: now.toISOString(),
|
||||||
|
message: "File assigned to you. Proceed with accident fields and field capture.",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Assign the current damage expert to a claim for review (V2).
|
* Assign the current damage expert to a claim for review (V2).
|
||||||
* Free cases are locked atomically; already-assigned-to-self is idempotent.
|
* Free cases are locked atomically; already-assigned-to-self is idempotent.
|
||||||
@@ -2489,7 +2644,10 @@ export class ExpertClaimService {
|
|||||||
role?: string;
|
role?: string;
|
||||||
},
|
},
|
||||||
): Promise<ExpertFileAssignResultDto> {
|
): Promise<ExpertFileAssignResultDto> {
|
||||||
if ((actor as any).role !== RoleEnum.FIELD_EXPERT)
|
if (
|
||||||
|
(actor as any).role !== RoleEnum.FIELD_EXPERT &&
|
||||||
|
(actor as any).role !== RoleEnum.FILE_REVIEWER
|
||||||
|
)
|
||||||
requireActorClientKey(actor);
|
requireActorClientKey(actor);
|
||||||
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
|
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
|
||||||
|
|
||||||
@@ -2498,6 +2656,57 @@ export class ExpertClaimService {
|
|||||||
throw new NotFoundException("Claim request not found");
|
throw new NotFoundException("Claim request not found");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// FILE_REVIEWER: two-phase lock behaviour.
|
||||||
|
// Phase 1 — blame is WAITING_FOR_FILE_REVIEWER: atomically set
|
||||||
|
// assignedFileReviewerId on the blame document.
|
||||||
|
// Phase 2 — blame is already past WAITING_FOR_FILE_REVIEWER (i.e. the
|
||||||
|
// reviewer finished field work and blame moved to WAITING_FOR_EXPERT):
|
||||||
|
// the reviewer now needs the standard damage-expert workflow lock
|
||||||
|
// so they can perform damage assessment. Fall through to the
|
||||||
|
// damage-expert path below; assertExpertActorOnClaim will verify
|
||||||
|
// tenant scope via the reviewer's clientKey.
|
||||||
|
if ((actor as any).role === RoleEnum.FILE_REVIEWER) {
|
||||||
|
if (!claim.blameRequestId) {
|
||||||
|
throw new BadRequestException({
|
||||||
|
success: false,
|
||||||
|
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "This claim has no linked blame file.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const reviewerBlame = await this.blameRequestDbService.findById(
|
||||||
|
String(claim.blameRequestId),
|
||||||
|
);
|
||||||
|
if (!reviewerBlame) {
|
||||||
|
throw new NotFoundException("Linked blame file not found.");
|
||||||
|
}
|
||||||
|
const blameStatus = (reviewerBlame as any).status as string;
|
||||||
|
if (blameStatus === "WAITING_FOR_FILE_REVIEWER") {
|
||||||
|
// Phase 1: blame-assign path
|
||||||
|
return this.assignFileReviewerToV4Blame(claimRequestId, claim, actor);
|
||||||
|
}
|
||||||
|
// Phase 2: blame is past the initial assignment step.
|
||||||
|
// Only the reviewer who was assigned during Phase 1 may proceed.
|
||||||
|
const assignedReviewerId = (reviewerBlame as any).assignedFileReviewerId
|
||||||
|
? String((reviewerBlame as any).assignedFileReviewerId)
|
||||||
|
: null;
|
||||||
|
if (!assignedReviewerId) {
|
||||||
|
throw new BadRequestException({
|
||||||
|
success: false,
|
||||||
|
status: "unavailable" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "No reviewer has been assigned to this file yet.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (assignedReviewerId !== actor.sub) {
|
||||||
|
throw new ConflictException({
|
||||||
|
success: false,
|
||||||
|
status: "locked" satisfies ExpertFileAssignStatus,
|
||||||
|
message: "This file is assigned to another reviewer.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
// Assigned reviewer — fall through to the damage-expert workflow lock below.
|
||||||
|
// (actor.role stays FILE_REVIEWER; assertExpertActorOnClaim checks clientKey scope)
|
||||||
|
}
|
||||||
|
|
||||||
await this.assertExpertActorOnClaim(claim, actor);
|
await this.assertExpertActorOnClaim(claim, actor);
|
||||||
|
|
||||||
const isFieldExpertOwner =
|
const isFieldExpertOwner =
|
||||||
@@ -2873,7 +3082,8 @@ export class ExpertClaimService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (existingResend?.fulfilledAt) {
|
if (existingResend?.fulfilledAt) {
|
||||||
throw new BadRequestException(
|
throw new BusinessRuleException(
|
||||||
|
BusinessErrorCode.DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED,
|
||||||
"The owner has already fulfilled a damage-expert resend for this claim. You cannot request another resend.",
|
"The owner has already fulfilled a damage-expert resend for this claim. You cannot request another resend.",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -2954,7 +3164,7 @@ export class ExpertClaimService {
|
|||||||
receptor: ownerPhoneResend,
|
receptor: ownerPhoneResend,
|
||||||
fileKind: "claim",
|
fileKind: "claim",
|
||||||
publicId: claim.publicId,
|
publicId: claim.publicId,
|
||||||
link: this.smsOrchestrationService.buildClaimLink(String(claim._id)),
|
link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3252,21 +3462,11 @@ export class ExpertClaimService {
|
|||||||
fileKind: "claim",
|
fileKind: "claim",
|
||||||
publicId: claim.publicId,
|
publicId: claim.publicId,
|
||||||
expertLastName,
|
expertLastName,
|
||||||
link: this.smsOrchestrationService.buildClaimLink(String(claim._id)),
|
link: this.smsOrchestrationService.buildClaimLink(String(claim._id), "v1"),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const fanavaranExpertise = !needsFactorUpload
|
// Fanavaran expertise is now triggered on owner final sign, not here.
|
||||||
? await this.claimRequestManagementService.autoSubmitFanavaranExpertiseOnExpertReply(
|
|
||||||
claimRequestId,
|
|
||||||
)
|
|
||||||
: {
|
|
||||||
attempted: false,
|
|
||||||
submitted: false,
|
|
||||||
skipped: true,
|
|
||||||
skipReason:
|
|
||||||
"Expertise submit waits until factor-needed repair lines are validated.",
|
|
||||||
};
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
claimRequestId,
|
claimRequestId,
|
||||||
@@ -3280,7 +3480,6 @@ export class ExpertClaimService {
|
|||||||
mixedPricingAndFactors: mixedFactorAndPrice,
|
mixedPricingAndFactors: mixedFactorAndPrice,
|
||||||
allPartsFactorNeeded: !!needsFactorUpload && !!allFactorLines,
|
allPartsFactorNeeded: !!needsFactorUpload && !!allFactorLines,
|
||||||
isFinalReplyAfterObjection,
|
isFinalReplyAfterObjection,
|
||||||
fanavaranExpertise,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -3335,6 +3534,7 @@ export class ExpertClaimService {
|
|||||||
|
|
||||||
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
|
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
|
||||||
claimStatus: ClaimStatus.NEEDS_REVISION,
|
claimStatus: ClaimStatus.NEEDS_REVISION,
|
||||||
|
status: ClaimCaseStatus.COMPLETED,
|
||||||
"workflow.locked": false,
|
"workflow.locked": false,
|
||||||
$unset: {
|
$unset: {
|
||||||
"workflow.lockedAt": "",
|
"workflow.lockedAt": "",
|
||||||
@@ -3372,7 +3572,7 @@ export class ExpertClaimService {
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
claimRequestId,
|
claimRequestId,
|
||||||
status: claim.status,
|
status: ClaimCaseStatus.COMPLETED,
|
||||||
claimStatus: ClaimStatus.NEEDS_REVISION,
|
claimStatus: ClaimStatus.NEEDS_REVISION,
|
||||||
message: "In-person visit requested. User will be notified.",
|
message: "In-person visit requested. User will be notified.",
|
||||||
};
|
};
|
||||||
@@ -3516,14 +3716,19 @@ export class ExpertClaimService {
|
|||||||
let claims: any[] = [];
|
let claims: any[] = [];
|
||||||
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
||||||
const expertOid = new Types.ObjectId(actor.sub);
|
const expertOid = new Types.ObjectId(actor.sub);
|
||||||
|
// Exclude V4/V5 blame files — same rule as getFieldExpertClaimListV2.
|
||||||
const expertBlameIds = await this.blameRequestDbService
|
const expertBlameIds = await this.blameRequestDbService
|
||||||
.find(
|
.find(
|
||||||
{ expertInitiated: true, initiatedByFieldExpertId: expertOid },
|
{
|
||||||
|
expertInitiated: true,
|
||||||
|
initiatedByFieldExpertId: expertOid,
|
||||||
|
isMadeByFileMaker: { $ne: true },
|
||||||
|
},
|
||||||
{ select: "_id", lean: true },
|
{ select: "_id", lean: true },
|
||||||
)
|
)
|
||||||
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
||||||
const claimOr: Record<string, unknown>[] = [
|
const claimOr: Record<string, unknown>[] = [
|
||||||
{ initiatedByFieldExpertId: expertOid },
|
{ initiatedByFieldExpertId: expertOid, requiresFileMakerApproval: { $ne: true } },
|
||||||
];
|
];
|
||||||
if (expertBlameIds.length > 0) {
|
if (expertBlameIds.length > 0) {
|
||||||
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
||||||
@@ -3603,6 +3808,12 @@ export class ExpertClaimService {
|
|||||||
(item) => item.unifiedFileStatus === query.unifiedStatus,
|
(item) => item.unifiedFileStatus === query.unifiedStatus,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
const { fromDate, toDate } = parseListDateRange(query.startDate, query.endDate);
|
||||||
|
if (fromDate || toDate) {
|
||||||
|
filtered = filtered.filter((item) =>
|
||||||
|
isInListDateRange(item.createdAt, fromDate, toDate),
|
||||||
|
);
|
||||||
|
}
|
||||||
const paged = applyListQueryV2(
|
const paged = applyListQueryV2(
|
||||||
filtered,
|
filtered,
|
||||||
{
|
{
|
||||||
@@ -3648,6 +3859,12 @@ export class ExpertClaimService {
|
|||||||
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
||||||
return this.getFieldExpertClaimListV2(actor, query);
|
return this.getFieldExpertClaimListV2(actor, query);
|
||||||
}
|
}
|
||||||
|
if (actor.role === RoleEnum.FILE_REVIEWER) {
|
||||||
|
return this.getFileReviewerClaimListV2(actor, query);
|
||||||
|
}
|
||||||
|
if (actor.role === RoleEnum.FILE_MAKER) {
|
||||||
|
return this.getFileMakerClaimListV2(actor, query);
|
||||||
|
}
|
||||||
requireActorClientKey(actor);
|
requireActorClientKey(actor);
|
||||||
const actorId = actor.sub;
|
const actorId = actor.sub;
|
||||||
const clientKey = actor.clientKey as string;
|
const clientKey = actor.clientKey as string;
|
||||||
@@ -3776,7 +3993,7 @@ export class ExpertClaimService {
|
|||||||
blameIds.length > 0
|
blameIds.length > 0
|
||||||
? ((await this.blameRequestDbService.find(
|
? ((await this.blameRequestDbService.find(
|
||||||
{ _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } },
|
{ _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } },
|
||||||
{ lean: true, select: "type parties expert.decision blameStatus" },
|
{ lean: true, select: "type parties expert.decision blameStatus status isMadeByFileMaker" },
|
||||||
)) as any[])
|
)) as any[])
|
||||||
: [];
|
: [];
|
||||||
const blameById = new Map<string, any>(
|
const blameById = new Map<string, any>(
|
||||||
@@ -3822,6 +4039,7 @@ export class ExpertClaimService {
|
|||||||
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
|
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
|
||||||
: undefined,
|
: undefined,
|
||||||
...fileCtx,
|
...fileCtx,
|
||||||
|
blameRequestId: c.blameRequestId?.toString(),
|
||||||
createdAt: c.createdAt,
|
createdAt: c.createdAt,
|
||||||
awaitingFactorValidation,
|
awaitingFactorValidation,
|
||||||
};
|
};
|
||||||
@@ -3839,15 +4057,22 @@ export class ExpertClaimService {
|
|||||||
query: ListQueryV2Dto = {},
|
query: ListQueryV2Dto = {},
|
||||||
): Promise<GetClaimListV2ResponseDto> {
|
): Promise<GetClaimListV2ResponseDto> {
|
||||||
const expertOid = new Types.ObjectId(actor.sub);
|
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
|
const expertBlameIds = await this.blameRequestDbService
|
||||||
.find(
|
.find(
|
||||||
{ expertInitiated: true, initiatedByFieldExpertId: expertOid },
|
{
|
||||||
|
expertInitiated: true,
|
||||||
|
initiatedByFieldExpertId: expertOid,
|
||||||
|
isMadeByFileMaker: { $ne: true },
|
||||||
|
},
|
||||||
{ select: "_id", lean: true },
|
{ select: "_id", lean: true },
|
||||||
)
|
)
|
||||||
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
.then((docs) => docs.map((d) => (d as { _id: unknown })._id));
|
||||||
|
|
||||||
const claimOr: Record<string, unknown>[] = [
|
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) {
|
if (expertBlameIds.length > 0) {
|
||||||
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
|
||||||
@@ -3868,7 +4093,7 @@ export class ExpertClaimService {
|
|||||||
blameIds.length > 0
|
blameIds.length > 0
|
||||||
? ((await this.blameRequestDbService.find(
|
? ((await this.blameRequestDbService.find(
|
||||||
{ _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } },
|
{ _id: { $in: blameIds.map((id) => new Types.ObjectId(id)) } },
|
||||||
{ lean: true, select: "type parties expert.decision blameStatus" },
|
{ lean: true, select: "type parties expert.decision blameStatus status" },
|
||||||
)) as any[])
|
)) as any[])
|
||||||
: [];
|
: [];
|
||||||
const blameById = new Map<string, any>(
|
const blameById = new Map<string, any>(
|
||||||
@@ -3907,8 +4132,207 @@ export class ExpertClaimService {
|
|||||||
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
|
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
|
||||||
: undefined,
|
: undefined,
|
||||||
...fileCtx,
|
...fileCtx,
|
||||||
|
blameRequestId: c.blameRequestId?.toString(),
|
||||||
createdAt: c.createdAt,
|
createdAt: c.createdAt,
|
||||||
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
|
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
|
||||||
|
needsFileReviewerCompletion:
|
||||||
|
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
|
||||||
|
(!!blame?.isMadeByFileMaker &&
|
||||||
|
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
|
||||||
|
};
|
||||||
|
}) as ClaimListItemV2Dto[];
|
||||||
|
|
||||||
|
return this.paginateClaimListV2(list, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Claim list for FILE_REVIEWER.
|
||||||
|
*
|
||||||
|
* Visibility rules:
|
||||||
|
* - 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)
|
||||||
|
*
|
||||||
|
* All scoped to this reviewer's insurance company via blame party clientId.
|
||||||
|
*/
|
||||||
|
private async getFileReviewerClaimListV2(
|
||||||
|
actor: any,
|
||||||
|
query: ListQueryV2Dto = {},
|
||||||
|
): Promise<GetClaimListV2ResponseDto> {
|
||||||
|
const clientKey = requireActorClientKey(actor);
|
||||||
|
const reviewerOid = new Types.ObjectId(actor.sub);
|
||||||
|
|
||||||
|
// Find V4 blame files visible to this reviewer
|
||||||
|
const blames = (await this.blameRequestDbService.find(
|
||||||
|
{
|
||||||
|
isMadeByFileMaker: true,
|
||||||
|
expertInitiated: true,
|
||||||
|
creationMethod: "IN_PERSON",
|
||||||
|
$or: [
|
||||||
|
// Open: sealed by FileMaker, not yet taken by any reviewer
|
||||||
|
{
|
||||||
|
status: "WAITING_FOR_FILE_REVIEWER",
|
||||||
|
$or: [
|
||||||
|
{ assignedFileReviewerId: { $exists: false } },
|
||||||
|
{ assignedFileReviewerId: null },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
// Taken by this reviewer (any post-assignment status)
|
||||||
|
{ assignedFileReviewerId: reviewerOid },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
lean: true,
|
||||||
|
select:
|
||||||
|
"_id type parties blameStatus status expert.decision assignedFileReviewerId",
|
||||||
|
},
|
||||||
|
)) as any[];
|
||||||
|
|
||||||
|
if (blames.length === 0) {
|
||||||
|
return this.paginateClaimListV2([], query);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Scope to this reviewer's insurer via blame party clientId
|
||||||
|
const scopedBlames = blames.filter((b) =>
|
||||||
|
blameCaseTouchesClient(b, clientKey),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (scopedBlames.length === 0) {
|
||||||
|
return this.paginateClaimListV2([], query);
|
||||||
|
}
|
||||||
|
|
||||||
|
const scopedBlameIds = scopedBlames.map((b) => b._id);
|
||||||
|
const claims = (await this.claimCaseDbService.find({
|
||||||
|
blameRequestId: { $in: scopedBlameIds },
|
||||||
|
})) as any[];
|
||||||
|
|
||||||
|
const blameById = new Map<string, any>(
|
||||||
|
scopedBlames.map((b) => [String(b._id), b]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const list = claims.map((c) => {
|
||||||
|
const blame = c.blameRequestId
|
||||||
|
? blameById.get(c.blameRequestId.toString())
|
||||||
|
: undefined;
|
||||||
|
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
|
||||||
|
const fileCtx = blame ? this.blameFileContextForExpert(blame) : {};
|
||||||
|
const lockActive = !!(
|
||||||
|
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
|
||||||
|
);
|
||||||
|
const assignedToMe =
|
||||||
|
blame?.assignedFileReviewerId &&
|
||||||
|
String(blame.assignedFileReviewerId) === actor.sub;
|
||||||
|
return {
|
||||||
|
claimRequestId: c._id.toString(),
|
||||||
|
publicId: c.publicId,
|
||||||
|
status: c.status,
|
||||||
|
unifiedFileStatus: resolveUnifiedFileStatus({
|
||||||
|
blameStatus: blame?.status,
|
||||||
|
claimStatus: c.status,
|
||||||
|
}),
|
||||||
|
currentStep: c.workflow?.currentStep || "",
|
||||||
|
locked: lockActive,
|
||||||
|
lockedBy:
|
||||||
|
lockActive && c.workflow?.lockedBy
|
||||||
|
? {
|
||||||
|
actorId: c.workflow.lockedBy.actorId?.toString(),
|
||||||
|
actorName: c.workflow.lockedBy.actorName,
|
||||||
|
lockedAt: (c.workflow as any).lockedAt?.toISOString?.(),
|
||||||
|
expiredAt: (c.workflow as any).expiredAt?.toISOString?.(),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
vehicle: v
|
||||||
|
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
|
||||||
|
: undefined,
|
||||||
|
...fileCtx,
|
||||||
|
blameRequestId: c.blameRequestId?.toString(),
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
|
||||||
|
needsFileReviewerCompletion:
|
||||||
|
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
|
||||||
|
(!!blame?.isMadeByFileMaker &&
|
||||||
|
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
|
||||||
|
assignedToMe: !!assignedToMe,
|
||||||
|
};
|
||||||
|
}) as ClaimListItemV2Dto[];
|
||||||
|
|
||||||
|
return this.paginateClaimListV2(list, query);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Claim list for FILE_MAKER — returns only the claims linked to blame files
|
||||||
|
* they personally created (V4 flow).
|
||||||
|
*/
|
||||||
|
private async getFileMakerClaimListV2(
|
||||||
|
actor: any,
|
||||||
|
query: ListQueryV2Dto = {},
|
||||||
|
): Promise<GetClaimListV2ResponseDto> {
|
||||||
|
const makerOid = new Types.ObjectId(actor.sub);
|
||||||
|
|
||||||
|
const makerBlames = (await this.blameRequestDbService.find(
|
||||||
|
{ isMadeByFileMaker: true, initiatedByFieldExpertId: makerOid },
|
||||||
|
{ lean: true, select: "_id type parties blameStatus status expert.decision assignedFileReviewerId" },
|
||||||
|
)) as any[];
|
||||||
|
|
||||||
|
if (makerBlames.length === 0) {
|
||||||
|
return this.paginateClaimListV2([], query);
|
||||||
|
}
|
||||||
|
|
||||||
|
const blameIds = makerBlames.map((b) => b._id);
|
||||||
|
const claims = (await this.claimCaseDbService.find({
|
||||||
|
blameRequestId: { $in: blameIds },
|
||||||
|
requiresFileMakerApproval: true,
|
||||||
|
})) as any[];
|
||||||
|
|
||||||
|
const blameById = new Map<string, any>(
|
||||||
|
makerBlames.map((b) => [String(b._id), b]),
|
||||||
|
);
|
||||||
|
|
||||||
|
const list = claims.map((c) => {
|
||||||
|
const blame = c.blameRequestId
|
||||||
|
? blameById.get(c.blameRequestId.toString())
|
||||||
|
: undefined;
|
||||||
|
const v = this.vehicleForExpertFromClaimAndBlameMap(c, blameById);
|
||||||
|
const fileCtx = blame ? this.blameFileContextForExpert(blame) : {};
|
||||||
|
const lockActive = !!(
|
||||||
|
c.workflow?.locked && this.isClaimV2WorkflowLockCurrentlyEnforced(c)
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
claimRequestId: c._id.toString(),
|
||||||
|
publicId: c.publicId,
|
||||||
|
status: c.status,
|
||||||
|
unifiedFileStatus: resolveUnifiedFileStatus({
|
||||||
|
blameStatus: blame?.status,
|
||||||
|
claimStatus: c.status,
|
||||||
|
}),
|
||||||
|
currentStep: c.workflow?.currentStep || "",
|
||||||
|
locked: lockActive,
|
||||||
|
lockedBy:
|
||||||
|
lockActive && c.workflow?.lockedBy
|
||||||
|
? {
|
||||||
|
actorId: c.workflow.lockedBy.actorId?.toString(),
|
||||||
|
actorName: c.workflow.lockedBy.actorName,
|
||||||
|
lockedAt: (c.workflow as any).lockedAt?.toISOString?.(),
|
||||||
|
expiredAt: (c.workflow as any).expiredAt?.toISOString?.(),
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
vehicle: v
|
||||||
|
? { carName: v.carName, carModel: v.carModel, carType: v.carType }
|
||||||
|
: undefined,
|
||||||
|
...fileCtx,
|
||||||
|
blameRequestId: c.blameRequestId?.toString(),
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
awaitingFactorValidation: claimIsAwaitingExpertFactorValidationV2(c),
|
||||||
|
requiresFileMakerApproval: !!(c as any).requiresFileMakerApproval,
|
||||||
|
needsFileReviewerCompletion:
|
||||||
|
String(blame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER" ||
|
||||||
|
(!!blame?.isMadeByFileMaker &&
|
||||||
|
String(blame?.status ?? "") === "WAITING_FOR_EXPERT"),
|
||||||
|
assignedFileReviewerId: blame?.assignedFileReviewerId
|
||||||
|
? String(blame.assignedFileReviewerId)
|
||||||
|
: undefined,
|
||||||
};
|
};
|
||||||
}) as ClaimListItemV2Dto[];
|
}) as ClaimListItemV2Dto[];
|
||||||
|
|
||||||
@@ -4092,7 +4516,11 @@ export class ExpertClaimService {
|
|||||||
clientKey?: string;
|
clientKey?: string;
|
||||||
role?: string;
|
role?: string;
|
||||||
}): Promise<void> {
|
}): Promise<void> {
|
||||||
if ((actor as any).role === RoleEnum.FIELD_EXPERT) return;
|
if (
|
||||||
|
(actor as any).role === RoleEnum.FIELD_EXPERT ||
|
||||||
|
(actor as any).role === RoleEnum.FILE_REVIEWER ||
|
||||||
|
(actor as any).role === RoleEnum.FILE_MAKER
|
||||||
|
) return;
|
||||||
const clientKey = requireActorClientKey(actor);
|
const clientKey = requireActorClientKey(actor);
|
||||||
const lockTtlMs = EXPERT_WORKFLOW_LOCK_TTL_MS;
|
const lockTtlMs = EXPERT_WORKFLOW_LOCK_TTL_MS;
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
@@ -4252,7 +4680,11 @@ export class ExpertClaimService {
|
|||||||
actor: any,
|
actor: any,
|
||||||
): Promise<ClaimDetailV2ResponseDto> {
|
): Promise<ClaimDetailV2ResponseDto> {
|
||||||
const actorId = actor.sub;
|
const actorId = actor.sub;
|
||||||
if (actor.role !== RoleEnum.FIELD_EXPERT) {
|
if (
|
||||||
|
actor.role !== RoleEnum.FIELD_EXPERT &&
|
||||||
|
actor.role !== RoleEnum.FILE_MAKER &&
|
||||||
|
actor.role !== RoleEnum.FILE_REVIEWER
|
||||||
|
) {
|
||||||
await this.reconcileStaleExpertReviewingClaimLocksForTenant(actor);
|
await this.reconcileStaleExpertReviewingClaimLocksForTenant(actor);
|
||||||
}
|
}
|
||||||
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
|
await this.expireClaimWorkflowLockV2IfStale(claimRequestId);
|
||||||
@@ -4263,7 +4695,12 @@ export class ExpertClaimService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const linkedBlame = await this.loadBlameForClaim(claim);
|
const linkedBlame = await this.loadBlameForClaim(claim);
|
||||||
assertClaimCaseForExpertActor(claim, actor, linkedBlame);
|
// FILE_REVIEWER access is validated by the role-specific gate below
|
||||||
|
// (isAssignedToMe || isOpen). Skip the generic tenant-scope assert which
|
||||||
|
// would incorrectly reject them via the initiatedByFieldExpertId path.
|
||||||
|
if (actor.role !== RoleEnum.FILE_REVIEWER) {
|
||||||
|
assertClaimCaseForExpertActor(claim, actor, linkedBlame);
|
||||||
|
}
|
||||||
|
|
||||||
// Variables used both in the gate block and in the detail-build section below
|
// Variables used both in the gate block and in the detail-build section below
|
||||||
const isDamageExpertPhase =
|
const isDamageExpertPhase =
|
||||||
@@ -4272,13 +4709,63 @@ export class ExpertClaimService {
|
|||||||
const isFactorValidationPending =
|
const isFactorValidationPending =
|
||||||
claimIsAwaitingExpertFactorValidationV2(claim);
|
claimIsAwaitingExpertFactorValidationV2(claim);
|
||||||
|
|
||||||
// Field experts can always view their own initiated claims regardless of status
|
// FileMaker: can view any file they created (both during filing and approval phase).
|
||||||
if (actor.role === RoleEnum.FIELD_EXPERT) {
|
// The list endpoint already filters to V5-only; detail access is scoped by ownership.
|
||||||
if (!claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame)) {
|
if (actor.role === RoleEnum.FILE_MAKER) {
|
||||||
throw new ForbiddenException("This claim was not initiated by you.");
|
const isOwn = claimCaseInitiatedByFieldExpert(claim, actor, linkedBlame);
|
||||||
|
if (!isOwn) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
"FileMakers can only view files they created.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Fall through to the detail build below
|
||||||
|
} else if (
|
||||||
|
// Field experts and FileReviewers can view IN_PERSON expert-initiated claims
|
||||||
|
// regardless of claim status (they work across multiple non-standard steps).
|
||||||
|
actor.role === RoleEnum.FIELD_EXPERT ||
|
||||||
|
actor.role === RoleEnum.FILE_REVIEWER
|
||||||
|
) {
|
||||||
|
if (actor.role === RoleEnum.FILE_REVIEWER) {
|
||||||
|
// FILE_REVIEWER: must be a V4/V5 file AND (they are the assigned reviewer OR
|
||||||
|
// the file is still open — WAITING_FOR_FILE_REVIEWER with no reviewer yet).
|
||||||
|
const isV4V5Blame =
|
||||||
|
(linkedBlame as any)?.isMadeByFileMaker &&
|
||||||
|
linkedBlame?.expertInitiated &&
|
||||||
|
linkedBlame?.creationMethod === "IN_PERSON";
|
||||||
|
if (!isV4V5Blame) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
"FileReviewers can only access V4/V5 FileMaker files.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const assignedReviewerId = (linkedBlame as any)?.assignedFileReviewerId
|
||||||
|
? String((linkedBlame as any).assignedFileReviewerId)
|
||||||
|
: null;
|
||||||
|
const isAssignedToMe =
|
||||||
|
assignedReviewerId && assignedReviewerId === actorId;
|
||||||
|
const isOpen =
|
||||||
|
!assignedReviewerId &&
|
||||||
|
String(linkedBlame?.status ?? "") === "WAITING_FOR_FILE_REVIEWER";
|
||||||
|
if (!isAssignedToMe && !isOpen) {
|
||||||
|
throw new ForbiddenException(
|
||||||
|
"This file has been taken by another reviewer.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} 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)
|
// Fall through to the detail build below (skip the damage-expert gate)
|
||||||
} else {
|
} else if (actor.role !== RoleEnum.FILE_MAKER) {
|
||||||
const isResendPending =
|
const isResendPending =
|
||||||
claim.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND;
|
claim.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND;
|
||||||
|
|
||||||
@@ -4443,6 +4930,24 @@ export class ExpertClaimService {
|
|||||||
if (fromBlame) vehiclePayload = fromBlame;
|
if (fromBlame) vehiclePayload = fromBlame;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Patch up carName/carModel when they equal carType (invalid — expert copied the enum value).
|
||||||
|
if (vehiclePayload) {
|
||||||
|
const carType: string | undefined = vehiclePayload.carType;
|
||||||
|
if (
|
||||||
|
carType &&
|
||||||
|
((!vehiclePayload.carName || vehiclePayload.carName === carType) ||
|
||||||
|
(!vehiclePayload.carModel || vehiclePayload.carModel === carType))
|
||||||
|
) {
|
||||||
|
const fromInquiry = this.vehicleNamesFromClaimInquiries(claim);
|
||||||
|
if (!vehiclePayload.carName || vehiclePayload.carName === carType) {
|
||||||
|
vehiclePayload = { ...vehiclePayload, carName: fromInquiry.carName };
|
||||||
|
}
|
||||||
|
if (!vehiclePayload.carModel || vehiclePayload.carModel === carType) {
|
||||||
|
vehiclePayload = { ...vehiclePayload, carModel: fromInquiry.carModel };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const blameFileContext = blameLean
|
const blameFileContext = blameLean
|
||||||
? this.blameFileContextForExpert(blameLean)
|
? this.blameFileContextForExpert(blameLean)
|
||||||
: {};
|
: {};
|
||||||
@@ -4495,15 +5000,18 @@ export class ExpertClaimService {
|
|||||||
let evaluationForApi: Record<string, unknown> | undefined;
|
let evaluationForApi: Record<string, unknown> | undefined;
|
||||||
if (enrichedEvaluation) {
|
if (enrichedEvaluation) {
|
||||||
evaluationForApi = {};
|
evaluationForApi = {};
|
||||||
if (isFactorValidationPending) {
|
// damageExpertReply / damageExpertReplyFinal: include whenever present.
|
||||||
if (enrichedEvaluation.damageExpertReply !== undefined) {
|
// Previously these were gated on isFactorValidationPending, which hid the
|
||||||
evaluationForApi.damageExpertReply =
|
// expert assessment once the claim moved to user-side statuses such as
|
||||||
enrichedEvaluation.damageExpertReply;
|
// INSURER_REVIEW_AWAITING_OWNER_SIGN. Historical assessment data should
|
||||||
}
|
// always be visible once submitted.
|
||||||
if (enrichedEvaluation.damageExpertReplyFinal !== undefined) {
|
if (enrichedEvaluation.damageExpertReply !== undefined) {
|
||||||
evaluationForApi.damageExpertReplyFinal =
|
evaluationForApi.damageExpertReply =
|
||||||
enrichedEvaluation.damageExpertReplyFinal;
|
enrichedEvaluation.damageExpertReply;
|
||||||
}
|
}
|
||||||
|
if (enrichedEvaluation.damageExpertReplyFinal !== undefined) {
|
||||||
|
evaluationForApi.damageExpertReplyFinal =
|
||||||
|
enrichedEvaluation.damageExpertReplyFinal;
|
||||||
}
|
}
|
||||||
if (enrichedEvaluation.ownerInsurerApproval !== undefined) {
|
if (enrichedEvaluation.ownerInsurerApproval !== undefined) {
|
||||||
evaluationForApi.ownerInsurerApproval =
|
evaluationForApi.ownerInsurerApproval =
|
||||||
@@ -4513,9 +5021,14 @@ export class ExpertClaimService {
|
|||||||
evaluationForApi.ownerPricedPartsApproval =
|
evaluationForApi.ownerPricedPartsApproval =
|
||||||
enrichedEvaluation.ownerPricedPartsApproval;
|
enrichedEvaluation.ownerPricedPartsApproval;
|
||||||
}
|
}
|
||||||
if (isDamageExpertPhase && enrichedEvaluation.priceDrop !== undefined) {
|
// priceDrop: include whenever present, not only during the expert phase.
|
||||||
|
if (enrichedEvaluation.priceDrop !== undefined) {
|
||||||
evaluationForApi.priceDrop = enrichedEvaluation.priceDrop;
|
evaluationForApi.priceDrop = enrichedEvaluation.priceDrop;
|
||||||
}
|
}
|
||||||
|
// objection: include when present so experts can see the disputed parts and any attached invoices.
|
||||||
|
if (enrichedEvaluation.objection !== undefined) {
|
||||||
|
evaluationForApi.objection = enrichedEvaluation.objection;
|
||||||
|
}
|
||||||
if (Object.keys(evaluationForApi).length === 0) {
|
if (Object.keys(evaluationForApi).length === 0) {
|
||||||
evaluationForApi = undefined;
|
evaluationForApi = undefined;
|
||||||
}
|
}
|
||||||
@@ -4558,6 +5071,7 @@ export class ExpertClaimService {
|
|||||||
carAngles,
|
carAngles,
|
||||||
damagedParts,
|
damagedParts,
|
||||||
awaitingFactorValidation: isFactorValidationPending,
|
awaitingFactorValidation: isFactorValidationPending,
|
||||||
|
requiresFileMakerApproval: !!(claim as any).requiresFileMakerApproval,
|
||||||
evaluation:
|
evaluation:
|
||||||
(evaluationForApi as
|
(evaluationForApi as
|
||||||
| ClaimDetailV2ResponseDto["evaluation"]
|
| ClaimDetailV2ResponseDto["evaluation"]
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import { readFile } from "node:fs/promises";
|
||||||
import {
|
import {
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
@@ -117,6 +118,21 @@ export class ExpertClaimV2Controller {
|
|||||||
return this.claimRequestManagementService.getOuterPartsCatalogV2(carType);
|
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")
|
@Get("branches")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "List insurer branches for this damage expert (V2)",
|
summary: "List insurer branches for this damage expert (V2)",
|
||||||
@@ -153,7 +169,7 @@ export class ExpertClaimV2Controller {
|
|||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Get claim request detail for damage expert",
|
summary: "Get claim request detail for damage expert",
|
||||||
description:
|
description:
|
||||||
"Returns full claim details including captured images, required documents, damage selections, `evaluation.priceDrop` during damage review, `videoCapture` (from claim-video-capture via media.videoCaptureId), and `blameCase` (linked blameCases document with party video/voice URLs like expert-blame detail). Allowed when status is WAITING_FOR_DAMAGE_EXPERT (if locked, only the locking expert) or when awaiting factor validation.",
|
"Returns full claim details including captured images, required documents, damage selections, `evaluation.priceDrop` (included whenever saved, regardless of current status), `videoCapture` (from claim-video-capture via media.videoCaptureId), and `blameCase` (linked blameCases document with party video/voice URLs like expert-blame detail). `evaluation.damageExpertReply` / `damageExpertReplyFinal` are always returned once submitted. Allowed when status is WAITING_FOR_DAMAGE_EXPERT (if locked, only the locking expert) or when awaiting factor validation.",
|
||||||
})
|
})
|
||||||
@ApiParam({ name: "claimRequestId" })
|
@ApiParam({ name: "claimRequestId" })
|
||||||
async getClaimDetailV2(
|
async getClaimDetailV2(
|
||||||
@@ -281,7 +297,20 @@ export class ExpertClaimV2Controller {
|
|||||||
description:
|
description:
|
||||||
"Claim must be locked by this expert (`EXPERT_REVIEWING`). Sets `WAITING_FOR_USER_RESEND`, `USER_EXPERT_RESEND`, `NEEDS_REVISION`, clears the lock, and stores `evaluation.damageExpertResend`. " +
|
"Claim must be locked by this expert (`EXPERT_REVIEWING`). Sets `WAITING_FOR_USER_RESEND`, `USER_EXPERT_RESEND`, `NEEDS_REVISION`, clears the lock, and stores `evaluation.damageExpertResend`. " +
|
||||||
"Owner completes via document/capture endpoints or `POST .../expert-resend/acknowledge` when only instructions were given.\n\n" +
|
"Owner completes via document/capture endpoints or `POST .../expert-resend/acknowledge` when only instructions were given.\n\n" +
|
||||||
"**One resend per claim lifecycle:** if the owner has already fulfilled a resend (`damageExpertResend.fulfilledAt`), this endpoint returns **400**—the expert may only submit a priced reply or request in-person visit afterward.",
|
"**One resend per claim lifecycle:** if the owner has already fulfilled a resend (`damageExpertResend.fulfilledAt`), this endpoint returns **422** with `errorCode: DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED`—the expert may only submit a priced reply or request in-person visit afterward.",
|
||||||
|
})
|
||||||
|
@ApiResponse({
|
||||||
|
status: 422,
|
||||||
|
description:
|
||||||
|
"Business rule violation: resend limit exceeded. " +
|
||||||
|
"`errorCode: DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED` — the owner has already fulfilled a prior resend request for this claim.",
|
||||||
|
schema: {
|
||||||
|
example: {
|
||||||
|
errorCode: "DAMAGE_EXPERT_RESEND_LIMIT_EXCEEDED",
|
||||||
|
message:
|
||||||
|
"The owner has already fulfilled a damage-expert resend for this claim. You cannot request another resend.",
|
||||||
|
},
|
||||||
|
},
|
||||||
})
|
})
|
||||||
@ApiParam({ name: "claimRequestId" })
|
@ApiParam({ name: "claimRequestId" })
|
||||||
@ApiBody({ type: ClaimSubmitResendV2Dto })
|
@ApiBody({ type: ClaimSubmitResendV2Dto })
|
||||||
|
|||||||
@@ -99,20 +99,32 @@ export class ExpertInsurerController {
|
|||||||
|
|
||||||
@Put("branches/:branchId/status")
|
@Put("branches/:branchId/status")
|
||||||
@ApiParam({ name: "branchId" })
|
@ApiParam({ name: "branchId" })
|
||||||
@ApiQuery({ name: "isActive", type: Boolean })
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: { isActive: { type: "boolean" } },
|
||||||
|
required: ["isActive"],
|
||||||
|
},
|
||||||
|
})
|
||||||
async setBranchStatus(
|
async setBranchStatus(
|
||||||
@CurrentUser() insurer,
|
@CurrentUser() insurer,
|
||||||
@Param("branchId") branchId: string,
|
@Param("branchId") branchId: string,
|
||||||
@Query("isActive") isActive: string,
|
@Body("isActive") isActive: unknown,
|
||||||
) {
|
) {
|
||||||
if (!insurer) {
|
if (!insurer) {
|
||||||
throw new UnauthorizedException("Could not identify the current user.");
|
throw new UnauthorizedException("Could not identify the current user.");
|
||||||
}
|
}
|
||||||
const normalized = String(isActive).trim().toLowerCase();
|
// Accept native boolean (JSON body) or string coercion (legacy query/form usage)
|
||||||
if (!["true", "false", "1", "0", "yes", "no"].includes(normalized)) {
|
let active: boolean;
|
||||||
throw new BadRequestException("isActive must be true/false");
|
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);
|
||||||
}
|
}
|
||||||
const active = ["true", "1", "yes"].includes(normalized);
|
|
||||||
return this.expertInsurerService.setBranchActive(
|
return this.expertInsurerService.setBranchActive(
|
||||||
insurer.clientKey,
|
insurer.clientKey,
|
||||||
branchId,
|
branchId,
|
||||||
@@ -228,6 +240,23 @@ export class ExpertInsurerController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get("files/:publicId/timeline")
|
||||||
|
@ApiParam({ name: "publicId" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Activity timeline for a case",
|
||||||
|
description:
|
||||||
|
"Returns a chronological list of all history events for the blame and/or claim associated with the given publicId. Each event has: source, type, timestamp, actor, metadata.",
|
||||||
|
})
|
||||||
|
async getFileTimeline(
|
||||||
|
@CurrentUser() insurer,
|
||||||
|
@Param("publicId") publicId: string,
|
||||||
|
) {
|
||||||
|
return await this.expertInsurerService.getFileTimeline(
|
||||||
|
insurer.clientKey,
|
||||||
|
publicId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Get("files/:publicId")
|
@Get("files/:publicId")
|
||||||
@ApiParam({ name: "publicId" })
|
@ApiParam({ name: "publicId" })
|
||||||
async getFileDetailsByPublicId(
|
async getFileDetailsByPublicId(
|
||||||
|
|||||||
@@ -75,6 +75,7 @@ import {
|
|||||||
extractExpertNamesFromBlame,
|
extractExpertNamesFromBlame,
|
||||||
extractExpertNamesFromClaim,
|
extractExpertNamesFromClaim,
|
||||||
} from "./helper/insurer.helper";
|
} from "./helper/insurer.helper";
|
||||||
|
import { getEventFaLabel } from "./helper/timeline-fa-labels";
|
||||||
import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher";
|
import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
@@ -1334,6 +1335,12 @@ export class ExpertInsurerService {
|
|||||||
(f) => f.unifiedFileStatus === query.unifiedStatus,
|
(f) => f.unifiedFileStatus === query.unifiedStatus,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
const { fromDate, toDate } = parseListDateRange(query.startDate, query.endDate);
|
||||||
|
if (fromDate || toDate) {
|
||||||
|
files = files.filter((f) =>
|
||||||
|
isInListDateRange(f.createdAt, fromDate, toDate),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const paged = applyListQueryV2(
|
const paged = applyListQueryV2(
|
||||||
files,
|
files,
|
||||||
@@ -1519,6 +1526,7 @@ export class ExpertInsurerService {
|
|||||||
ClaimCaseStatus.SELECTING_OTHER_PARTS,
|
ClaimCaseStatus.SELECTING_OTHER_PARTS,
|
||||||
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
|
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
|
||||||
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
|
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
|
||||||
|
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
|
||||||
ClaimCaseStatus.WAITING_FOR_USER_RESEND,
|
ClaimCaseStatus.WAITING_FOR_USER_RESEND,
|
||||||
ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
|
ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
|
||||||
ClaimCaseStatus.EXPERT_REVIEWING,
|
ClaimCaseStatus.EXPERT_REVIEWING,
|
||||||
@@ -2081,4 +2089,77 @@ export class ExpertInsurerService {
|
|||||||
waiting_for_documents_resend: counts.WAITING_FOR_DOCUMENT_RESEND ?? 0,
|
waiting_for_documents_resend: counts.WAITING_FOR_DOCUMENT_RESEND ?? 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getFileTimeline(
|
||||||
|
insurerId: string,
|
||||||
|
publicId: string,
|
||||||
|
): Promise<{ publicId: string; events: object[] }> {
|
||||||
|
if (!publicId?.trim()) {
|
||||||
|
throw new BadRequestException("publicId is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
const id = this.getClientId(insurerId);
|
||||||
|
const [blameFiles, claimFiles] = await Promise.all([
|
||||||
|
this.getClientBlameFiles(id),
|
||||||
|
this.getClientClaimFiles(id),
|
||||||
|
]);
|
||||||
|
|
||||||
|
const blame = blameFiles.find(
|
||||||
|
(b) => String((b as any).publicId) === publicId,
|
||||||
|
);
|
||||||
|
const claim = claimFiles.find(
|
||||||
|
(c) => String((c as any).publicId) === publicId,
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!blame && !claim) {
|
||||||
|
throw new NotFoundException("File not found for this publicId");
|
||||||
|
}
|
||||||
|
|
||||||
|
const events: object[] = [];
|
||||||
|
|
||||||
|
if (blame) {
|
||||||
|
const blameDoc = await this.blameRequestDbService.findById(
|
||||||
|
String((blame as any)._id),
|
||||||
|
);
|
||||||
|
const blameHistory: any[] = (blameDoc as any)?.history ?? [];
|
||||||
|
for (const ev of blameHistory) {
|
||||||
|
events.push({
|
||||||
|
source: "blame",
|
||||||
|
type: ev.type,
|
||||||
|
faLabel: getEventFaLabel(ev),
|
||||||
|
timestamp: ev.timestamp,
|
||||||
|
actor: ev.actor ?? null,
|
||||||
|
metadata: ev.metadata ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (claim) {
|
||||||
|
const claimId = String((claim as any)._id);
|
||||||
|
const rows = (await this.claimCaseDbService.find(
|
||||||
|
{ _id: new Types.ObjectId(claimId) },
|
||||||
|
{ lean: true, select: "history createdAt" },
|
||||||
|
)) as Record<string, unknown>[];
|
||||||
|
const claimHistory: any[] = (rows[0] as any)?.history ?? [];
|
||||||
|
for (const ev of claimHistory) {
|
||||||
|
events.push({
|
||||||
|
source: "claim",
|
||||||
|
type: ev.type,
|
||||||
|
faLabel: getEventFaLabel(ev),
|
||||||
|
timestamp: ev.timestamp,
|
||||||
|
actor: ev.actor ?? null,
|
||||||
|
metadata: ev.metadata ?? null,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
events.sort((a: any, b: any) => {
|
||||||
|
const ta = a.timestamp ? new Date(a.timestamp).getTime() : 0;
|
||||||
|
const tb = b.timestamp ? new Date(b.timestamp).getTime() : 0;
|
||||||
|
return ta - tb;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Resolve insurer's client name for context if needed — just return raw events
|
||||||
|
return { publicId, events };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
196
src/expert-insurer/helper/timeline-fa-labels.ts
Normal file
196
src/expert-insurer/helper/timeline-fa-labels.ts
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
/**
|
||||||
|
* Persian (Farsi) display labels for every timeline event `type` that can
|
||||||
|
* appear in a blame or claim history array.
|
||||||
|
*
|
||||||
|
* For generic `STEP_COMPLETED` / `V3_STEP_COMPLETED` events the label is
|
||||||
|
* derived from the `metadata.stepKey` value; those keys are listed at the
|
||||||
|
* bottom under STEP_KEY_FA_LABELS.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* const label = EVENT_TYPE_FA_LABELS[event.type]
|
||||||
|
* ?? resolveStepCompletedFaLabel(event)
|
||||||
|
* ?? event.type;
|
||||||
|
*/
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Blame-phase events (recorded on BlameRequest.history)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
export const EVENT_TYPE_FA_LABELS: Record<string, string> = {
|
||||||
|
// File creation
|
||||||
|
FILE_CREATED_BY_REGISTRAR: "پرونده توسط ثبتکننده ایجاد شد",
|
||||||
|
FILE_CREATED_BY_FIELD_EXPERT: "پرونده توسط کارشناس میدانی ایجاد شد",
|
||||||
|
|
||||||
|
// Expert link / OTP flow
|
||||||
|
LINK_SENT: "لینک ارسال شد",
|
||||||
|
PARTY_OTP_SENT: "کد تأیید ارسال شد",
|
||||||
|
PARTY_OTP_VERIFIED: "کد تأیید تأیید شد",
|
||||||
|
PARTY_OTPS_VERIFIED: "کدهای تأیید هر دو طرف تأیید شدند",
|
||||||
|
SECOND_PARTY_OTP_SENT: "کد تأیید طرف دوم ارسال شد",
|
||||||
|
SECOND_PARTY_OTP_VERIFIED_ADVANCED: "کد طرف دوم تأیید و پیشرفت انجام شد",
|
||||||
|
|
||||||
|
// Confession / accident type
|
||||||
|
FIRST_BLAME_CONFESSION_SUBMITTED: "اقرار اولیه طرف اول ثبت شد",
|
||||||
|
CAR_BODY_ACCIDENT_TYPE_SUBMITTED: "نوع تصادف بدنه خودرو ثبت شد",
|
||||||
|
AUTO_ADVANCED_TO_CAR_BODY_FORM: "پیشرفت خودکار به فرم بدنه خودرو",
|
||||||
|
AUTO_CONFESSION_SKIPPED: "مرحله اقرار بهصورت خودکار رد شد",
|
||||||
|
|
||||||
|
// First video
|
||||||
|
FIRST_VIDEO_UPLOADED: "ویدیوی اول بارگذاری شد",
|
||||||
|
|
||||||
|
// Second party invitation
|
||||||
|
SECOND_PARTY_INVITED: "طرف دوم دعوت شد",
|
||||||
|
|
||||||
|
// Accident fields / expert in-person completion
|
||||||
|
ACCIDENT_FIELDS_SAVED_ADVANCED_TO_SIGNATURES:
|
||||||
|
"اطلاعات تصادف ذخیره و به مرحله امضاها پیشرفت شد",
|
||||||
|
EXPERT_COMPLETED_CAR_BODY_FORM_V2: "کارشناس فرم بدنه خودرو را تکمیل کرد",
|
||||||
|
EXPERT_COMPLETED_THIRD_PARTY_FORM_V2: "کارشناس فرم شخص ثالث را تکمیل کرد",
|
||||||
|
EXPERT_ADDED_LOCATIONS_V2: "کارشناس موقعیت مکانی را ثبت کرد",
|
||||||
|
EXPERT_UPLOADED_VIDEO_V2: "کارشناس ویدیو را بارگذاری کرد",
|
||||||
|
EXPERT_UPLOADED_VOICE_V2: "کارشناس صدا را بارگذاری کرد",
|
||||||
|
|
||||||
|
// Party rejection / disagreement
|
||||||
|
PARTY_REJECTED_EXPERT_DECISION: "طرف حساب با نظر کارشناس مخالفت کرد",
|
||||||
|
PARTIES_DISAGREED_ON_EXPERT_DECISION: "طرفین با نظر کارشناس توافق نکردند",
|
||||||
|
|
||||||
|
// Document resend (blame)
|
||||||
|
BLAME_DOCUMENT_RESEND_STARTED: "درخواست ارسال مجدد مدارک پرونده شروع شد",
|
||||||
|
BLAME_DOCUMENT_RESEND_CLEARED: "ارسال مجدد مدارک پرونده پاکسازی شد",
|
||||||
|
|
||||||
|
// Expert assignment (blame)
|
||||||
|
BLAME_ASSIGNED: "پرونده به کارشناس تخصیص داده شد",
|
||||||
|
AUTO_ASSIGNED_TO_EXPERT: "پرونده بهصورت خودکار به کارشناس تخصیص یافت",
|
||||||
|
|
||||||
|
// Auto-assignment helpers
|
||||||
|
READY_FOR_EXPERT_EVALUATION: "پرونده آماده ارزیابی کارشناس شد",
|
||||||
|
SECOND_PARTY_DESCRIPTION_COMPLETED: "توضیحات طرف دوم تکمیل شد",
|
||||||
|
|
||||||
|
// V3 blame steps
|
||||||
|
V3_PARTY_SIGNATURE_RECORDED: "امضای طرف ثبت شد",
|
||||||
|
V3_ACCIDENT_FIELDS_SAVED: "اطلاعات تصادف ثبت شد",
|
||||||
|
V3_BLAME_ACCIDENT_VIDEO_UPLOADED: "ویدیوی تصادف بارگذاری شد",
|
||||||
|
V3_PARTY_VOICE_UPLOADED: "صدای طرف بارگذاری شد",
|
||||||
|
V3_PARTY_LOCATION_SAVED: "موقعیت مکانی طرف ذخیره شد",
|
||||||
|
V3_PARTY_DESCRIPTION_SAVED: "توضیحات طرف ذخیره شد",
|
||||||
|
V3_CAR_BODY_ACCIDENT_TYPE_SAVED: "نوع تصادف بدنه خودرو ذخیره شد",
|
||||||
|
|
||||||
|
// V5 blame steps
|
||||||
|
V5_BLAME_ACCIDENT_VIDEO_UPLOADED: "ویدیوی تصادف (نسخه ۵) بارگذاری شد",
|
||||||
|
V5_FILE_MAKER_APPROVED: "پروندهساز پرونده را تأیید کرد",
|
||||||
|
V5_FILE_MAKER_REJECTED: "پروندهساز پرونده را رد کرد",
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Claim-phase events (recorded on ClaimCase.history)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Claim creation
|
||||||
|
CLAIM_CREATED: "پرونده خسارت ایجاد شد",
|
||||||
|
|
||||||
|
// Expert assignment (claim)
|
||||||
|
CLAIM_ASSIGNED: "پرونده خسارت به کارشناس ارزیابی تخصیص داده شد",
|
||||||
|
|
||||||
|
// Expert actions on claim
|
||||||
|
EXPERT_RESEND_REQUESTED: "کارشناس درخواست ارسال مجدد مدارک داد",
|
||||||
|
EXPERT_RESEND_FULFILLED: "مدارک درخواستی ارسال شد",
|
||||||
|
IN_PERSON_VISIT_REQUESTED: "کارشناس بازدید حضوری درخواست کرد",
|
||||||
|
EXPERT_DAMAGED_PARTS_UPDATED: "کارشناس قطعات آسیبدیده را بهروزرسانی کرد",
|
||||||
|
|
||||||
|
// Workflow steps (generic)
|
||||||
|
STEP_COMPLETED: "مرحله تکمیل شد",
|
||||||
|
V3_STEP_COMPLETED: "مرحله تکمیل شد",
|
||||||
|
|
||||||
|
// Documents & media
|
||||||
|
DOCUMENT_UPLOADED: "مدرک بارگذاری شد",
|
||||||
|
VIDEO_CAPTURE_UPLOADED: "تصویر ویدیویی بارگذاری شد",
|
||||||
|
ALL_FACTORS_UPLOADED_PENDING_VALIDATION:
|
||||||
|
"تمام فاکتورها بارگذاری شدند و در انتظار تأیید هستند",
|
||||||
|
|
||||||
|
// User responses
|
||||||
|
USER_OBJECTION_SUBMITTED: "اعتراض کاربر ثبت شد",
|
||||||
|
USER_RATING_SUBMITTED: "امتیاز کاربر ثبت شد",
|
||||||
|
|
||||||
|
// Owner insurer approval
|
||||||
|
OWNER_SIGNED_INSURER_APPROVAL: "صاحب خودرو قرارداد بیمه را امضا کرد",
|
||||||
|
OWNER_REJECTED_INSURER_APPROVAL_PRICING: "صاحب خودرو قیمتگذاری بیمه را رد کرد",
|
||||||
|
OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD:
|
||||||
|
"صاحب خودرو قطعات قیمتگذاریشده را امضا کرد و در انتظار بارگذاری فاکتور",
|
||||||
|
OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS:
|
||||||
|
"صاحب خودرو قطعات قیمتگذاریشده را پیش از فاکتور رد کرد",
|
||||||
|
|
||||||
|
// Fanavaran sync
|
||||||
|
FANAVARAN_AUTO_SUBMIT_SUCCEEDED: "ارسال خودکار به فناوران موفق بود",
|
||||||
|
FANAVARAN_AUTO_SUBMIT_FAILED: "ارسال خودکار به فناوران ناموفق بود",
|
||||||
|
FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED: "ارسال زودهنگام خودکار به فناوران موفق بود",
|
||||||
|
FANAVARAN_EARLY_AUTO_SUBMIT_FAILED: "ارسال زودهنگام خودکار به فناوران ناموفق بود",
|
||||||
|
FANAVARAN_EXPERTISE_AUTO_SUBMIT_SUCCEEDED:
|
||||||
|
"ارسال خودکار کارشناسی به فناوران موفق بود",
|
||||||
|
FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED:
|
||||||
|
"ارسال خودکار کارشناسی به فناوران ناموفق بود",
|
||||||
|
FANAVARAN_ATTACHMENT_AUTO_SUBMIT_SUCCEEDED:
|
||||||
|
"ارسال خودکار پیوست به فناوران موفق بود",
|
||||||
|
FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED:
|
||||||
|
"ارسال خودکار پیوست به فناوران ناموفق بود",
|
||||||
|
FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_SUCCEEDED:
|
||||||
|
"ارسال خودکار پرونده خسارت به فناوران موفق بود",
|
||||||
|
FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_FAILED:
|
||||||
|
"ارسال خودکار پرونده خسارت به فناوران ناموفق بود",
|
||||||
|
|
||||||
|
// V5 claim
|
||||||
|
V5_HELD_FOR_FILE_MAKER_APPROVAL: "پرونده در انتظار تأیید پروندهساز متوقف شد",
|
||||||
|
};
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Persian labels for `metadata.stepKey` inside STEP_COMPLETED events
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
export const STEP_KEY_FA_LABELS: Record<string, string> = {
|
||||||
|
// Claim workflow steps
|
||||||
|
CLAIM_CREATED: "ایجاد پرونده خسارت",
|
||||||
|
SELECT_OUTER_PARTS: "انتخاب قطعات بیرونی آسیبدیده",
|
||||||
|
SELECT_OTHER_PARTS: "انتخاب سایر اطلاعات و قطعات",
|
||||||
|
CAPTURE_PART_DAMAGES: "عکسبرداری از آسیبهای قطعات",
|
||||||
|
UPLOAD_REQUIRED_DOCUMENTS: "بارگذاری مدارک مورد نیاز",
|
||||||
|
USER_SUBMISSION_COMPLETE: "ارسال اطلاعات توسط کاربر",
|
||||||
|
USER_EXPERT_RESEND: "ارسال مجدد مدارک توسط کاربر",
|
||||||
|
EXPERT_DAMAGE_ASSESSMENT: "ارزیابی خسارت توسط کارشناس",
|
||||||
|
EXPERT_FINAL_REPLY: "پاسخ نهایی کارشناس",
|
||||||
|
EXPERT_COST_EVALUATION: "ارزیابی هزینه توسط کارشناس",
|
||||||
|
OWNER_UPLOAD_FACTOR_DOCUMENTS: "بارگذاری فاکتورهای تعمیر توسط مالک",
|
||||||
|
INSURER_REVIEW: "بررسی توسط بیمهگر",
|
||||||
|
CLAIM_COMPLETED: "پرونده خسارت تکمیل شد",
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* For `STEP_COMPLETED` and `V3_STEP_COMPLETED` events whose final label
|
||||||
|
* depends on the `metadata.stepKey` value, this function returns the
|
||||||
|
* most specific Persian label available.
|
||||||
|
*/
|
||||||
|
export function resolveStepCompletedFaLabel(event: {
|
||||||
|
type: string;
|
||||||
|
metadata?: any;
|
||||||
|
}): string | undefined {
|
||||||
|
if (
|
||||||
|
event.type !== "STEP_COMPLETED" &&
|
||||||
|
event.type !== "V3_STEP_COMPLETED"
|
||||||
|
) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
const stepKey: string | undefined = event.metadata?.stepKey;
|
||||||
|
if (stepKey && STEP_KEY_FA_LABELS[stepKey]) {
|
||||||
|
return STEP_KEY_FA_LABELS[stepKey];
|
||||||
|
}
|
||||||
|
return "مرحله تکمیل شد";
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the best Persian label for any timeline event.
|
||||||
|
*/
|
||||||
|
export function getEventFaLabel(event: {
|
||||||
|
type: string;
|
||||||
|
metadata?: any;
|
||||||
|
}): string {
|
||||||
|
return (
|
||||||
|
resolveStepCompletedFaLabel(event) ??
|
||||||
|
EVENT_TYPE_FA_LABELS[event.type] ??
|
||||||
|
event.type
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -66,6 +66,47 @@ export const FANAVARAN_REMOTE_LOOKUPS: FanavaranRemoteLookupDefinition[] = [
|
|||||||
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/code-list/expert-status`,
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/code-list/expert-status`,
|
||||||
cacheFile: "expert-status.json",
|
cacheFile: "expert-status.json",
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
name: "vehicle-kinds",
|
||||||
|
url: `${FANAVARAN_LOOKUP_BASE_URL}/car/base-info/vehicle-kinds`,
|
||||||
|
cacheFile: "vehicle-kinds.json",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "person-role",
|
||||||
|
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 = {
|
export const TEJARAT_STATIC_ACCIDENT_FILES = {
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
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";
|
import { FanavaranLookupService } from "./fanavaran-lookup.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [HttpModule],
|
imports: [
|
||||||
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
|
],
|
||||||
providers: [FanavaranLookupService],
|
providers: [FanavaranLookupService],
|
||||||
exports: [FanavaranLookupService],
|
exports: [FanavaranLookupService],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
type FanavaranClientKey,
|
type FanavaranClientKey,
|
||||||
} from "src/core/config/fanavaran-client.config";
|
} from "src/core/config/fanavaran-client.config";
|
||||||
import {
|
import {
|
||||||
|
FANAVARAN_LOOKUP_BASE_URL,
|
||||||
fanavaranLookupCacheDir,
|
fanavaranLookupCacheDir,
|
||||||
tejaratStaticAccidentFilePath,
|
tejaratStaticAccidentFilePath,
|
||||||
} from "./fanavaran-lookup.config";
|
} from "./fanavaran-lookup.config";
|
||||||
@@ -182,24 +183,6 @@ export class FanavaranLookupService {
|
|||||||
this.logger.log(
|
this.logger.log(
|
||||||
`[${clientKey}] Fanavaran lookup response status=${response.status} dataCount=${dataCount}`,
|
`[${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;
|
return response.data;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -246,6 +229,162 @@ export class FanavaranLookupService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async inquiryByVin(
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
vin: string,
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url = `${FANAVARAN_LOOKUP_BASE_URL}/car/vehicles/inquiry-by-vin?vin=${encodeURIComponent(vin)}`;
|
||||||
|
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: {
|
||||||
|
nationalCode: string;
|
||||||
|
birthYear: number;
|
||||||
|
birthMonth: number;
|
||||||
|
birthDay: number;
|
||||||
|
},
|
||||||
|
): Promise<unknown> {
|
||||||
|
const url =
|
||||||
|
`${FANAVARAN_LOOKUP_BASE_URL}/common/parties/inquiry-by-unique-identifier` +
|
||||||
|
`?NationalCode=${encodeURIComponent(params.nationalCode)}` +
|
||||||
|
`&BirthYear=${params.birthYear}` +
|
||||||
|
`&BirthMonth=${params.birthMonth}` +
|
||||||
|
`&BirthDay=${params.birthDay}`;
|
||||||
|
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(
|
mapFanavaranAccidentCausesToReasonOptions(
|
||||||
causes: unknown,
|
causes: unknown,
|
||||||
): { id: number; label: string; fanavaran: number }[] {
|
): { id: number; label: string; fanavaran: number }[] {
|
||||||
@@ -270,4 +409,5 @@ export class FanavaranLookupService {
|
|||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import {
|
import {
|
||||||
BadRequestException,
|
BadRequestException,
|
||||||
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
Param,
|
Param,
|
||||||
@@ -105,11 +106,13 @@ export class FanavaranController {
|
|||||||
async submit(
|
async submit(
|
||||||
@Param("client") client: string,
|
@Param("client") client: string,
|
||||||
@Param("claimCaseId") claimCaseId: string,
|
@Param("claimCaseId") claimCaseId: string,
|
||||||
|
@Body() body?: Record<string, unknown>,
|
||||||
) {
|
) {
|
||||||
const clientKey = this.parseClientParam(client);
|
const clientKey = this.parseClientParam(client);
|
||||||
return await this.claimRequestManagementService.submitFanavaranV2(
|
return await this.claimRequestManagementService.submitFanavaranV2(
|
||||||
claimCaseId,
|
claimCaseId,
|
||||||
clientKey,
|
clientKey,
|
||||||
|
body && Object.keys(body).length > 0 ? body : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -157,11 +160,13 @@ export class FanavaranController {
|
|||||||
async submitDamageCase(
|
async submitDamageCase(
|
||||||
@Param("client") client: string,
|
@Param("client") client: string,
|
||||||
@Param("claimCaseId") claimCaseId: string,
|
@Param("claimCaseId") claimCaseId: string,
|
||||||
|
@Body() body?: Record<string, unknown>,
|
||||||
) {
|
) {
|
||||||
const clientKey = this.parseClientParam(client);
|
const clientKey = this.parseClientParam(client);
|
||||||
return await this.claimRequestManagementService.submitFanavaranDamageCaseV2(
|
return await this.claimRequestManagementService.submitFanavaranDamageCaseV2(
|
||||||
claimCaseId,
|
claimCaseId,
|
||||||
clientKey,
|
clientKey,
|
||||||
|
body && Object.keys(body).length > 0 ? body : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,11 +266,13 @@ export class FanavaranController {
|
|||||||
async submitExpertise(
|
async submitExpertise(
|
||||||
@Param("client") client: string,
|
@Param("client") client: string,
|
||||||
@Param("claimCaseId") claimCaseId: string,
|
@Param("claimCaseId") claimCaseId: string,
|
||||||
|
@Body() body?: Record<string, unknown>,
|
||||||
) {
|
) {
|
||||||
const clientKey = this.parseClientParam(client);
|
const clientKey = this.parseClientParam(client);
|
||||||
return await this.claimRequestManagementService.submitFanavaranExpertiseV2(
|
return await this.claimRequestManagementService.submitFanavaranExpertiseV2(
|
||||||
claimCaseId,
|
claimCaseId,
|
||||||
clientKey,
|
clientKey,
|
||||||
|
body && Object.keys(body).length > 0 ? body : undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,12 @@ export const CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS = [
|
|||||||
"damaged_metal_plate",
|
"damaged_metal_plate",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
|
/** Metal-plate keys that are optional in the V4/V5 FileMaker flow. */
|
||||||
|
export const OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5 = [
|
||||||
|
"damaged_metal_plate",
|
||||||
|
"guilty_metal_plate",
|
||||||
|
] as const;
|
||||||
|
|
||||||
export type CapturePhaseSequence =
|
export type CapturePhaseSequence =
|
||||||
| "parts"
|
| "parts"
|
||||||
| "angles"
|
| "angles"
|
||||||
@@ -52,7 +58,7 @@ function isRequiredDocumentUploadedOnClaim(
|
|||||||
|
|
||||||
export function getClaimCaptureProgress(
|
export function getClaimCaptureProgress(
|
||||||
claimCase: any,
|
claimCase: any,
|
||||||
options?: { assumeCapturePhaseDocKey?: string },
|
options?: { assumeCapturePhaseDocKey?: string; skipMetalPlate?: boolean },
|
||||||
): ClaimCaptureProgress {
|
): ClaimCaptureProgress {
|
||||||
const carType = claimCase?.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
|
const carType = claimCase?.vehicle?.carType as ClaimVehicleTypeV2 | undefined;
|
||||||
const selectedNorm = normalizeDamageSelectedParts(
|
const selectedNorm = normalizeDamageSelectedParts(
|
||||||
@@ -83,6 +89,7 @@ export function getClaimCaptureProgress(
|
|||||||
|
|
||||||
const capturePhaseDocsRemaining = CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS.filter(
|
const capturePhaseDocsRemaining = CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS.filter(
|
||||||
(k) => {
|
(k) => {
|
||||||
|
if (options?.skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)) return false;
|
||||||
if (k === options?.assumeCapturePhaseDocKey) return false;
|
if (k === options?.assumeCapturePhaseDocKey) return false;
|
||||||
return !isRequiredDocumentUploadedOnClaim(claimCase, k);
|
return !isRequiredDocumentUploadedOnClaim(claimCase, k);
|
||||||
},
|
},
|
||||||
@@ -111,8 +118,11 @@ export function getClaimCaptureProgress(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isClaimCaptureStepComplete(claimCase: any): boolean {
|
export function isClaimCaptureStepComplete(
|
||||||
const p = getClaimCaptureProgress(claimCase);
|
claimCase: any,
|
||||||
|
options?: { skipMetalPlate?: boolean },
|
||||||
|
): boolean {
|
||||||
|
const p = getClaimCaptureProgress(claimCase, options);
|
||||||
return (
|
return (
|
||||||
p.partsComplete && p.anglesComplete && p.capturePhaseDocsComplete
|
p.partsComplete && p.anglesComplete && p.capturePhaseDocsComplete
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -263,8 +263,6 @@ export function buildClaimDetailsV2OwnerGuidance(
|
|||||||
shape.mixedFactorAndPrice &&
|
shape.mixedFactorAndPrice &&
|
||||||
!claim.evaluation?.ownerPricedPartsApproval?.signedAt
|
!claim.evaluation?.ownerPricedPartsApproval?.signedAt
|
||||||
) {
|
) {
|
||||||
const ow = objectionWindowForOwner(claim);
|
|
||||||
const allowObj = ow.pricingEligible;
|
|
||||||
return {
|
return {
|
||||||
phaseKey: "SIGN_PRICED_LINES",
|
phaseKey: "SIGN_PRICED_LINES",
|
||||||
headline: "Sign acceptance of priced lines",
|
headline: "Sign acceptance of priced lines",
|
||||||
@@ -278,13 +276,12 @@ export function buildClaimDetailsV2OwnerGuidance(
|
|||||||
"Multipart sign + agree + branchId",
|
"Multipart sign + agree + branchId",
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
objectionAllowed: allowObj,
|
objectionAllowed,
|
||||||
objectionHint: objectionHintWhen(allowObj),
|
objectionHint,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
/** NEEDS_REVISION at INSURER_REVIEW without mixed gate — all-factor initial sign not used; fallback */
|
/** NEEDS_REVISION at INSURER_REVIEW without mixed gate — all-factor initial sign not used; fallback */
|
||||||
const allowObj = objectionWindowForOwner(claim).pricingEligible;
|
|
||||||
return {
|
return {
|
||||||
phaseKey: "INSURER_REVIEW_NEEDS_REVISION",
|
phaseKey: "INSURER_REVIEW_NEEDS_REVISION",
|
||||||
headline: "Insurer approval — action pending",
|
headline: "Insurer approval — action pending",
|
||||||
@@ -298,13 +295,12 @@ export function buildClaimDetailsV2OwnerGuidance(
|
|||||||
"Sign if prompted by app state",
|
"Sign if prompted by app state",
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
objectionAllowed: allowObj,
|
objectionAllowed,
|
||||||
objectionHint: objectionHintWhen(allowObj),
|
objectionHint,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
if (cs === ClaimStatus.APPROVED && !claim.evaluation?.ownerInsurerApproval?.signedAt) {
|
if (cs === ClaimStatus.APPROVED && !claim.evaluation?.ownerInsurerApproval?.signedAt) {
|
||||||
const allowObj = objectionWindowForOwner(claim).pricingEligible;
|
|
||||||
return {
|
return {
|
||||||
phaseKey: "FINAL_SIGN_OR_REJECT",
|
phaseKey: "FINAL_SIGN_OR_REJECT",
|
||||||
headline: "Accept or reject final pricing",
|
headline: "Accept or reject final pricing",
|
||||||
@@ -323,8 +319,8 @@ export function buildClaimDetailsV2OwnerGuidance(
|
|||||||
"Dispute priced lines before signing",
|
"Dispute priced lines before signing",
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
objectionAllowed: allowObj,
|
objectionAllowed,
|
||||||
objectionHint: objectionHintWhen(allowObj),
|
objectionHint,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ const CLAIM_IN_PROGRESS_STATUSES = new Set<string>([
|
|||||||
ClaimCaseStatus.SELECTING_OTHER_PARTS,
|
ClaimCaseStatus.SELECTING_OTHER_PARTS,
|
||||||
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
|
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
|
||||||
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
|
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
|
||||||
|
// V4 split flow: sealed by FileMaker, pending FileReviewer pickup.
|
||||||
|
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export function blameCaseStatusToReportBucket(status: string): string {
|
export function blameCaseStatusToReportBucket(status: string): string {
|
||||||
|
|||||||
@@ -22,20 +22,18 @@ const LABEL_COLUMN_X = COLON_X + 10;
|
|||||||
|
|
||||||
function resolveFontFile(variant: "regular" | "bold"): string {
|
function resolveFontFile(variant: "regular" | "bold"): string {
|
||||||
const file =
|
const file =
|
||||||
variant === "bold"
|
variant === "bold" ? "Vazirmatn-Bold.ttf" : "Vazirmatn-Regular.ttf";
|
||||||
? "NotoKufiArabic-Bold.ttf"
|
|
||||||
: "NotoKufiArabic-Regular.ttf";
|
|
||||||
const candidates = [
|
const candidates = [
|
||||||
|
join(process.cwd(), "assets", file),
|
||||||
join(process.cwd(), "assets", "fonts", file),
|
join(process.cwd(), "assets", "fonts", file),
|
||||||
join(process.cwd(), "dist", "fonts", file),
|
join(process.cwd(), "dist", "assets", file),
|
||||||
join(process.cwd(), "dist", "assets", "fonts", file),
|
join(process.cwd(), "dist", "assets", "fonts", file),
|
||||||
join("/usr/share/fonts/truetype/noto", file),
|
|
||||||
];
|
];
|
||||||
for (const path of candidates) {
|
for (const path of candidates) {
|
||||||
if (existsSync(path)) return path;
|
if (existsSync(path)) return path;
|
||||||
}
|
}
|
||||||
throw new Error(
|
throw new Error(
|
||||||
`Persian PDF font not found (${file}). Place it under assets/fonts/ or install noto fonts on the host.`,
|
`Persian PDF font not found (${file}). Place it under assets/ or assets/fonts/.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,6 +44,16 @@ export type PersianPdfDocument = InstanceType<typeof PDFDocument> & {
|
|||||||
addBlank: (lines?: number) => void;
|
addBlank: (lines?: number) => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/** Ensure at least `neededPts` of vertical space remain; add a page if not. */
|
||||||
|
function ensureSpace(
|
||||||
|
doc: InstanceType<typeof PDFDocument>,
|
||||||
|
neededPts: number,
|
||||||
|
): void {
|
||||||
|
if (doc.y + neededPts > doc.page.maxY()) {
|
||||||
|
doc.addPage();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function drawRtlLine(
|
function drawRtlLine(
|
||||||
doc: InstanceType<typeof PDFDocument>,
|
doc: InstanceType<typeof PDFDocument>,
|
||||||
text: string,
|
text: string,
|
||||||
@@ -69,6 +77,9 @@ function drawKeyValueRow(
|
|||||||
label: string,
|
label: string,
|
||||||
value: string,
|
value: string,
|
||||||
): void {
|
): void {
|
||||||
|
// Reserve one row height (font 10pt ≈ 14 pts with leading) before drawing.
|
||||||
|
ensureSpace(doc, 16);
|
||||||
|
|
||||||
const y = doc.y;
|
const y = doc.y;
|
||||||
const { label: faLabel, value: faValue } = pdfKitRtlKeyValue(label, value);
|
const { label: faLabel, value: faValue } = pdfKitRtlKeyValue(label, value);
|
||||||
|
|
||||||
@@ -118,6 +129,9 @@ export function createPersianPdfDocument(): PersianPdfDocument {
|
|||||||
};
|
};
|
||||||
|
|
||||||
doc.addSection = (text: string) => {
|
doc.addSection = (text: string) => {
|
||||||
|
// Reserve space for the gap + section heading + at least one data row below it,
|
||||||
|
// so the heading is never stranded alone at the bottom of a page.
|
||||||
|
ensureSpace(doc, 60);
|
||||||
doc.moveDown(0.5);
|
doc.moveDown(0.5);
|
||||||
drawRtlLine(doc, text, 13, true);
|
drawRtlLine(doc, text, 13, true);
|
||||||
doc.font("FaRegular").fontSize(10);
|
doc.font("FaRegular").fontSize(10);
|
||||||
|
|||||||
@@ -8,18 +8,31 @@ export function normalizePersianPdfText(text: string): string {
|
|||||||
.trim();
|
.trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* pdfkit renders glyphs strictly left-to-right.
|
||||||
|
* fontkit already reshapes each word's glyphs into visual (LTR) order,
|
||||||
|
* but it does NOT reorder words — so a multi-word RTL string like
|
||||||
|
* "نام صاحب خودرو" has its words placed LTR on the page and reads
|
||||||
|
* backwards. Reversing the word sequence here makes pdfkit emit the
|
||||||
|
* words in the correct visual order for a right-to-left PDF reader.
|
||||||
|
*/
|
||||||
|
function reverseRtlWords(text: string): string {
|
||||||
|
if (!/[\u0600-\u06FF]/.test(text)) return text;
|
||||||
|
return text.split(" ").reverse().join(" ");
|
||||||
|
}
|
||||||
|
|
||||||
export function pdfKitRtlKeyValue(
|
export function pdfKitRtlKeyValue(
|
||||||
label: string,
|
label: string,
|
||||||
value: string,
|
value: string,
|
||||||
): { label: string; value: string } {
|
): { label: string; value: string } {
|
||||||
return {
|
return {
|
||||||
label: normalizePersianPdfText(label),
|
label: reverseRtlWords(normalizePersianPdfText(label)),
|
||||||
value: normalizePersianPdfText(value),
|
value: reverseRtlWords(normalizePersianPdfText(value)),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export function pdfKitRtlParagraph(text: string): string {
|
export function pdfKitRtlParagraph(text: string): string {
|
||||||
return normalizePersianPdfText(text);
|
return reverseRtlWords(normalizePersianPdfText(text));
|
||||||
}
|
}
|
||||||
|
|
||||||
export function isMostlyAscii(text: string): boolean {
|
export function isMostlyAscii(text: string): boolean {
|
||||||
|
|||||||
@@ -31,6 +31,8 @@ const CLAIM_USER_PHASE = new Set<string>([
|
|||||||
ClaimCaseStatus.SELECTING_OTHER_PARTS,
|
ClaimCaseStatus.SELECTING_OTHER_PARTS,
|
||||||
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
|
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
|
||||||
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
|
ClaimCaseStatus.CAPTURING_PART_DAMAGES,
|
||||||
|
// V4 split flow: FileMaker sealed the file; FileReviewer hasn't picked it up yet.
|
||||||
|
ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const INSURER_REVIEW_CLAIM_STATUSES = new Set<string>([
|
const INSURER_REVIEW_CLAIM_STATUSES = new Set<string>([
|
||||||
|
|||||||
@@ -1,13 +1,18 @@
|
|||||||
import { Controller, Get, Param } from "@nestjs/common";
|
import { Controller, Get, Param, ParseIntPipe, Query, UseGuards } from "@nestjs/common";
|
||||||
import {
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
ApiOkResponse,
|
ApiOkResponse,
|
||||||
ApiOperation,
|
ApiOperation,
|
||||||
ApiParam,
|
ApiParam,
|
||||||
|
ApiQuery,
|
||||||
ApiTags,
|
ApiTags,
|
||||||
} from "@nestjs/swagger";
|
} from "@nestjs/swagger";
|
||||||
|
import { AuthGuard } from "src/common/auth/guards";
|
||||||
import { LookupsService } from "./lookups.service";
|
import { LookupsService } from "./lookups.service";
|
||||||
|
|
||||||
@ApiTags("lookups")
|
@ApiTags("lookups")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(AuthGuard)
|
||||||
@Controller("lookups")
|
@Controller("lookups")
|
||||||
export class LookupsController {
|
export class LookupsController {
|
||||||
constructor(private readonly lookupsService: LookupsService) {}
|
constructor(private readonly lookupsService: LookupsService) {}
|
||||||
@@ -171,6 +176,140 @@ export class LookupsController {
|
|||||||
return await this.lookupsService.getExpertStatus();
|
return await this.lookupsService.getExpertStatus();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Get("vehicle-kinds")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran GEN.12 vehicle kind lookup",
|
||||||
|
description:
|
||||||
|
"Returns values for damage case payload field VehicleKindId from car/base-info/vehicle-kinds.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran vehicle kinds lookup data",
|
||||||
|
schema: { type: "array", items: { type: "object" } },
|
||||||
|
})
|
||||||
|
async getVehicleKinds() {
|
||||||
|
return await this.lookupsService.getVehicleKinds();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("person-role")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Fanavaran person role lookup",
|
||||||
|
description:
|
||||||
|
"Returns person role codes from common/code-list/person-role.",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran person role lookup data",
|
||||||
|
schema: {
|
||||||
|
type: "array",
|
||||||
|
items: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
Caption: { type: "string" },
|
||||||
|
Id: { type: "number" },
|
||||||
|
IsActive: { type: "number" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async getPersonRole() {
|
||||||
|
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",
|
||||||
|
description:
|
||||||
|
"Returns vehicle details from Fanavaran for the given VIN number via car/vehicles/inquiry-by-vin.",
|
||||||
|
})
|
||||||
|
@ApiQuery({
|
||||||
|
name: "vin",
|
||||||
|
description: "Vehicle Identification Number (VIN)",
|
||||||
|
example: "IRNKAEK4150012345",
|
||||||
|
})
|
||||||
|
@ApiOkResponse({
|
||||||
|
description: "Returns Fanavaran vehicle inquiry data for the VIN",
|
||||||
|
schema: { type: "object" },
|
||||||
|
})
|
||||||
|
async inquiryByVin(@Query("vin") vin: string) {
|
||||||
|
return await this.lookupsService.inquiryByVin(vin);
|
||||||
|
}
|
||||||
|
|
||||||
@Get("fanavaran")
|
@Get("fanavaran")
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "List configured Fanavaran remote lookups",
|
summary: "List configured Fanavaran remote lookups",
|
||||||
@@ -313,4 +452,75 @@ export class LookupsController {
|
|||||||
async getAccidentFields() {
|
async getAccidentFields() {
|
||||||
return await this.lookupsService.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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -115,6 +115,117 @@ export class LookupsService {
|
|||||||
return await this.getClientRemoteLookup("expert-status");
|
return await this.getClientRemoteLookup("expert-status");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async getVehicleKinds(): Promise<any> {
|
||||||
|
return await this.getClientRemoteLookup("vehicle-kinds");
|
||||||
|
}
|
||||||
|
|
||||||
|
async getPersonRole(): Promise<any> {
|
||||||
|
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 }[]> {
|
async getAccidentWay(): Promise<{ id: number; label: string }[]> {
|
||||||
const clientKey = this.activeClientKey();
|
const clientKey = this.activeClientKey();
|
||||||
const fileName = TEJARAT_STATIC_ACCIDENT_FILES.accidentWay;
|
const fileName = TEJARAT_STATIC_ACCIDENT_FILES.accidentWay;
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { ClientModule } from "src/client/client.module";
|
|||||||
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
|
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
|
||||||
import { SandHubModule } from "src/sand-hub/sand-hub.module";
|
import { SandHubModule } from "src/sand-hub/sand-hub.module";
|
||||||
import { UsersModule } from "src/users/users.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 { PlatesModel, PlatesSchema } from "./entites/schema/plate.schema";
|
||||||
import { PlatesService } from "./plates.service";
|
import { PlatesService } from "./plates.service";
|
||||||
|
|
||||||
@@ -12,6 +13,7 @@ import { PlatesService } from "./plates.service";
|
|||||||
UsersModule,
|
UsersModule,
|
||||||
SandHubModule,
|
SandHubModule,
|
||||||
ClientModule,
|
ClientModule,
|
||||||
|
PlateNormalizerModule,
|
||||||
MongooseModule.forFeature([
|
MongooseModule.forFeature([
|
||||||
{ name: PlatesModel.name, schema: PlatesSchema },
|
{ name: PlatesModel.name, schema: PlatesSchema },
|
||||||
]),
|
]),
|
||||||
|
|||||||
@@ -7,20 +7,23 @@ import {
|
|||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
|
import { PlateDbService } from "src/plates/entites/db-service/plate.db.service";
|
||||||
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
||||||
|
import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service";
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class PlatesService {
|
export class PlatesService {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly plateDbService: PlateDbService,
|
private readonly plateDbService: PlateDbService,
|
||||||
|
private readonly plateNormalizer: PlateNormalizerService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async addPlate(currentUser, body: AddPlateDto) {
|
async addPlate(currentUser, body: AddPlateDto) {
|
||||||
const { plate, nationalCodeOfInsurer } = body;
|
const { plate, nationalCodeOfInsurer } = body;
|
||||||
|
|
||||||
|
const normalizedAlphabet = this.plateNormalizer.normalizePlateText(String(plate.centerAlphabet || ""));
|
||||||
const duplicate = await this.plateDbService.findOne({
|
const duplicate = await this.plateDbService.findOne({
|
||||||
userId: currentUser,
|
userId: currentUser,
|
||||||
leftDigits: plate.leftDigits,
|
leftDigits: plate.leftDigits,
|
||||||
centerAlphabet: plate.centerAlphabet,
|
centerAlphabet: normalizedAlphabet,
|
||||||
centerDigits: plate.centerDigits,
|
centerDigits: plate.centerDigits,
|
||||||
ir: plate.ir,
|
ir: plate.ir,
|
||||||
nationalCodeOfInsurer,
|
nationalCodeOfInsurer,
|
||||||
@@ -31,6 +34,7 @@ export class PlatesService {
|
|||||||
|
|
||||||
const newPlateData = await this.plateDbService.create({
|
const newPlateData = await this.plateDbService.create({
|
||||||
...plate,
|
...plate,
|
||||||
|
centerAlphabet: normalizedAlphabet,
|
||||||
userId: currentUser,
|
userId: currentUser,
|
||||||
nationalCodeOfInsurer: body.nationalCodeOfInsurer,
|
nationalCodeOfInsurer: body.nationalCodeOfInsurer,
|
||||||
});
|
});
|
||||||
|
|||||||
154
src/request-management/call-center-blame-v6.controller.ts
Normal file
154
src/request-management/call-center-blame-v6.controller.ts
Normal 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-center–initiated 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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||||
|
import { IsNotEmpty, IsString, MaxLength } from "class-validator";
|
||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
|
||||||
import { StepsEnum } from "src/Types&Enums/blame-request-management/steps.enum";
|
import { StepsEnum } from "src/Types&Enums/blame-request-management/steps.enum";
|
||||||
@@ -190,6 +191,52 @@ export class BlameConfessionDtoV2 {
|
|||||||
imGuilty?: boolean;
|
imGuilty?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V2 initial-form step submitted with a VIN/chassis number instead of a plate.
|
||||||
|
* All identity and license fields from {@link AddPlateDto} are preserved; only
|
||||||
|
* `plate` is replaced by `vin` (the 17-character chassis / VIN string).
|
||||||
|
*/
|
||||||
|
export class InitialFormVinDto {
|
||||||
|
@ApiProperty({
|
||||||
|
type: String,
|
||||||
|
required: true,
|
||||||
|
description: "17-character VIN / chassis number (شماره شاسی)",
|
||||||
|
example: "NAAM01E15HK123456",
|
||||||
|
maxLength: 17,
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
@MaxLength(17)
|
||||||
|
vin: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: String, required: true })
|
||||||
|
nationalCodeOfInsurer: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: String, required: true })
|
||||||
|
nationalCodeOfDriver: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: String, required: true })
|
||||||
|
insurerLicense: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: String, required: true })
|
||||||
|
driverLicense: string;
|
||||||
|
|
||||||
|
@ApiProperty({ type: Boolean, required: true })
|
||||||
|
driverIsInsurer: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ type: Boolean, required: true, default: false })
|
||||||
|
isNewCar: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ type: Boolean, required: true })
|
||||||
|
userNoCertificate: boolean;
|
||||||
|
|
||||||
|
@ApiProperty({ type: Number, required: true })
|
||||||
|
insurerBirthday: number;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ type: String, required: false })
|
||||||
|
driverBirthday: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
// export class DocsOfThisFile {
|
// export class DocsOfThisFile {
|
||||||
// @ApiProperty()
|
// @ApiProperty()
|
||||||
// firstPartyFile?: FirstPartyFileDto;
|
// firstPartyFile?: FirstPartyFileDto;
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
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";
|
import { CreationMethod } from "../entities/schema/request-management.schema";
|
||||||
|
|
||||||
export class CreateExpertInitiatedFileDto {
|
export class CreateExpertInitiatedFileDto {
|
||||||
@@ -18,4 +18,17 @@ export class CreateExpertInitiatedFileDto {
|
|||||||
})
|
})
|
||||||
@IsEnum(CreationMethod)
|
@IsEnum(CreationMethod)
|
||||||
creationMethod: 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;
|
||||||
}
|
}
|
||||||
|
|||||||
85
src/request-management/dto/run-call-center-inquiry-v6.dto.ts
Normal file
85
src/request-management/dto/run-call-center-inquiry-v6.dto.ts
Normal 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;
|
||||||
|
}
|
||||||
@@ -109,6 +109,48 @@ export class BlameRequest {
|
|||||||
/** Who fills the blame data: CUSTOMER (LINK) or EXPERT (IN_PERSON). */
|
/** Who fills the blame data: CUSTOMER (LINK) or EXPERT (IN_PERSON). */
|
||||||
@Prop({ type: String, enum: FilledBy })
|
@Prop({ type: String, enum: FilledBy })
|
||||||
filledBy?: FilledBy;
|
filledBy?: FilledBy;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True when this file was created by a FileMaker (V4 split flow).
|
||||||
|
* These files are sealed by the FileMaker and completed by a FileReviewer.
|
||||||
|
*/
|
||||||
|
@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>;
|
export type BlameRequestDocument = HydratedDocument<BlameRequest>;
|
||||||
|
|||||||
@@ -41,6 +41,10 @@ export class Person {
|
|||||||
|
|
||||||
@Prop({ type: String })
|
@Prop({ type: String })
|
||||||
driverBirthday?: string | null;
|
driverBirthday?: string | null;
|
||||||
|
|
||||||
|
/** Cached Fanavaran party ID resolved from nationalCodeOfDriver + driverBirthday + driverIsInsurer */
|
||||||
|
@Prop({ type: Number })
|
||||||
|
fanavaranDriverId?: number;
|
||||||
}
|
}
|
||||||
export const PersonSchema = SchemaFactory.createForClass(Person);
|
export const PersonSchema = SchemaFactory.createForClass(Person);
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { extname } from "node:path";
|
import { extname } from "node:path";
|
||||||
import {
|
import {
|
||||||
BadRequestException,
|
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Param,
|
Param,
|
||||||
@@ -35,6 +34,7 @@ import {
|
|||||||
LocationDto,
|
LocationDto,
|
||||||
} from "./dto/create-request-management.dto";
|
} from "./dto/create-request-management.dto";
|
||||||
import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.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 { SendPartyOtpsDto } from "./dto/send-party-otps.dto";
|
||||||
import { VerifyPartyOtpsDto } from "./dto/verify-party-otps.dto";
|
import { VerifyPartyOtpsDto } from "./dto/verify-party-otps.dto";
|
||||||
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
import { SendPartyOtpDto, VerifyPartyOtpDto } from "./dto/party-otp.dto";
|
||||||
@@ -76,17 +76,17 @@ export class ExpertInitiatedBlameMirrorController {
|
|||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "[Expert mirror] Create expert-initiated blame file",
|
summary: "[Expert mirror] Create expert-initiated blame file",
|
||||||
description:
|
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 })
|
@ApiBody({ type: CreateExpertInitiatedFileDto })
|
||||||
async create(
|
async create(
|
||||||
@CurrentUser() expert: any,
|
@CurrentUser() expert: any,
|
||||||
@Body() dto: CreateExpertInitiatedFileDto,
|
@Body() dto: CreateExpertInitiatedFileDto,
|
||||||
) {
|
) {
|
||||||
return this.requestManagementService.createExpertInitiatedBlameV2(
|
return this.requestManagementService.createExpertInitiatedBlameV2(expert, {
|
||||||
expert,
|
...dto,
|
||||||
dto,
|
creationMethod: CreationMethod.IN_PERSON,
|
||||||
);
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("send-link/:requestId")
|
@Post("send-link/:requestId")
|
||||||
@@ -159,7 +159,7 @@ export class ExpertInitiatedBlameMirrorController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("/initial-form/:requestId")
|
@Post("/run-inquiries/:requestId")
|
||||||
@ApiParam({ name: "requestId" })
|
@ApiParam({ name: "requestId" })
|
||||||
@ApiBody({ type: AddPlateDto })
|
@ApiBody({ type: AddPlateDto })
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
@@ -362,20 +362,6 @@ export class ExpertInitiatedBlameMirrorController {
|
|||||||
@CurrentUser() expert: any,
|
@CurrentUser() expert: any,
|
||||||
@UploadedFile() sign: Express.Multer.File,
|
@UploadedFile() sign: Express.Multer.File,
|
||||||
) {
|
) {
|
||||||
// Guard: accident fields (accidentWay, etc.) must be filled before signing.
|
|
||||||
// This prevents the expert from bypassing add-accident-fields and avoids the
|
|
||||||
// double-sign bug where add-accident-fields re-enters WAITING_FOR_SIGNATURES
|
|
||||||
// after a signature was already recorded.
|
|
||||||
const requestData = await this.requestManagementService.getBlameRequestV2(
|
|
||||||
requestId,
|
|
||||||
expert,
|
|
||||||
);
|
|
||||||
if (!(requestData?.expert?.decision as any)?.fields?.accidentWay) {
|
|
||||||
throw new BadRequestException(
|
|
||||||
"Accident fields (accidentWay, accidentReason, accidentType) must be submitted via add-accident-fields before signing.",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
await this.mediaPolicyService.assertForBlame(sign, requestId, "image");
|
await this.mediaPolicyService.assertForBlame(sign, requestId, "image");
|
||||||
const partyRole =
|
const partyRole =
|
||||||
body?.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST;
|
body?.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST;
|
||||||
@@ -389,7 +375,7 @@ export class ExpertInitiatedBlameMirrorController {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Post("add-accident-fields/:requestId")
|
@Post("accident-fields/:requestId")
|
||||||
@ApiParam({ name: "requestId" })
|
@ApiParam({ name: "requestId" })
|
||||||
@ApiBody({ type: ExpertAccidentFieldsDto })
|
@ApiBody({ type: ExpertAccidentFieldsDto })
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
|
|||||||
@@ -87,7 +87,9 @@ export class FileMakerBlameV4Controller {
|
|||||||
) {
|
) {
|
||||||
return this.requestManagementService.createExpertInitiatedBlameV2(
|
return this.requestManagementService.createExpertInitiatedBlameV2(
|
||||||
fileMaker,
|
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 },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
390
src/request-management/file-maker-blame-v5.controller.ts
Normal file
390
src/request-management/file-maker-blame-v5.controller.ts
Normal file
@@ -0,0 +1,390 @@
|
|||||||
|
import { extname } from "node:path";
|
||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
UploadedFile,
|
||||||
|
UseGuards,
|
||||||
|
UseInterceptors,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiConsumes,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
|
import { FileInterceptor } from "@nestjs/platform-express";
|
||||||
|
import { diskStorage } from "multer";
|
||||||
|
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 { 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 { 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 {
|
||||||
|
CarBodyFormDto,
|
||||||
|
DescriptionDto,
|
||||||
|
LocationDto,
|
||||||
|
} from "./dto/create-request-management.dto";
|
||||||
|
import { RequestManagementService } from "./request-management.service";
|
||||||
|
import { PartyRole } from "./entities/schema/partyRole.enum";
|
||||||
|
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||||
|
import {
|
||||||
|
UploadRequiredDocumentV2Dto,
|
||||||
|
UploadRequiredDocumentV2ResponseDto,
|
||||||
|
} from "src/claim-request-management/dto/upload-document-v2.dto";
|
||||||
|
import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-management/dto/capture-requirements-v2.dto";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 FileMaker flow — identical to V4 but under the /v5/ prefix.
|
||||||
|
*
|
||||||
|
* The only behavioural difference in the V5 flow is in the FileReviewer's final
|
||||||
|
* step: instead of moving directly to WAITING_FOR_EXPERT, the blame video moves
|
||||||
|
* the file to WAITING_FOR_FINANCIAL_EXPERT so a FinancialExpert can approve or
|
||||||
|
* reject before fanavaran submission.
|
||||||
|
*
|
||||||
|
* The FileMaker side is unchanged; all sequence and endpoints are the same.
|
||||||
|
*
|
||||||
|
* THIRD_PARTY sequence:
|
||||||
|
* create → send-party-otp (guilty) → verify-party-otp (guilty)
|
||||||
|
* → [car-body-form if CAR_BODY] → run-inquiries (guilty + auto claim)
|
||||||
|
* → add-detail-location / add-detail-description / upload-voice (guilty)
|
||||||
|
* → sign (guilty)
|
||||||
|
* → send-party-otp (damaged) → verify-party-otp (damaged)
|
||||||
|
* → run-inquiries (damaged)
|
||||||
|
* → add-detail-location / add-detail-description / upload-voice (damaged)
|
||||||
|
* → sign (damaged) ← FileMaker job done here
|
||||||
|
*/
|
||||||
|
@ApiTags("v5 FileMaker — blame file creation (with FinancialExpert approval)")
|
||||||
|
@Controller("v5/file-maker/blame-request-management")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||||
|
@Roles(RoleEnum.FILE_MAKER)
|
||||||
|
export class FileMakerBlameV5Controller {
|
||||||
|
constructor(
|
||||||
|
private readonly requestManagementService: RequestManagementService,
|
||||||
|
private readonly mediaPolicyService: MediaPolicyService,
|
||||||
|
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ─── File creation ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post()
|
||||||
|
@ApiOperation({ summary: "Create IN_PERSON blame file (FileMaker V5)" })
|
||||||
|
@ApiBody({ type: CreateExpertInitiatedFileDto })
|
||||||
|
async create(
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Body() dto: CreateExpertInitiatedFileDto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.createExpertInitiatedBlameV2(
|
||||||
|
fileMaker,
|
||||||
|
{ ...dto, creationMethod: CreationMethod.IN_PERSON, requiresFileMakerApproval: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("claim-id/:requestId")
|
||||||
|
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Get linked claim ID",
|
||||||
|
description:
|
||||||
|
"Returns the claim auto-created during guilty-party run-inquiries. " +
|
||||||
|
"Share this claim ID with the FileReviewer.",
|
||||||
|
})
|
||||||
|
async getLinkedClaimId(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.getV3LinkedClaimForExpert(
|
||||||
|
fileMaker,
|
||||||
|
requestId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── OTP ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("send-party-otp/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: SendPartyOtpDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Send OTP to one party",
|
||||||
|
description:
|
||||||
|
"Guilty party first; damaged party after guilty party has signed (THIRD_PARTY).",
|
||||||
|
})
|
||||||
|
async sendPartyOtp(
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: SendPartyOtpDto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.sendPartyOtpV2(
|
||||||
|
fileMaker,
|
||||||
|
requestId,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("verify-party-otp/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: VerifyPartyOtpDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Verify one party OTP",
|
||||||
|
description: "FIRST (guilty) then SECOND (damaged) on THIRD_PARTY files.",
|
||||||
|
})
|
||||||
|
async verifyPartyOtp(
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: VerifyPartyOtpDto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.verifyPartyOtpV2(
|
||||||
|
fileMaker,
|
||||||
|
requestId,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Pre-inquiry form ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("car-body-form/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: CarBodyFormDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "CAR_BODY only — accident type before inquiries",
|
||||||
|
description: "Submit after guilty-party OTP verify, before run-inquiries.",
|
||||||
|
})
|
||||||
|
async carBodyForm(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: CarBodyFormDto,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.carBodyAccidentTypeFormV3(
|
||||||
|
requestId,
|
||||||
|
body,
|
||||||
|
fileMaker,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("run-inquiries/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: RunInquiriesV3Dto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Run external inquiries for the current party",
|
||||||
|
description:
|
||||||
|
"1st call = guilty party (+ auto claim). 2nd call = damaged party (THIRD_PARTY, after guilty sign).",
|
||||||
|
})
|
||||||
|
async runInquiries(
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() dto: RunInquiriesV3Dto,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.runInquiriesV3(
|
||||||
|
requestId,
|
||||||
|
fileMaker,
|
||||||
|
dto,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Party details ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("add-detail-location/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: LocationDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Add location for current party (partyRole FIRST or SECOND)",
|
||||||
|
})
|
||||||
|
async addLocation(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: LocationDto,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Body("partyRole") partyRole?: string,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.addPartyLocationV3(
|
||||||
|
requestId,
|
||||||
|
fileMaker,
|
||||||
|
body,
|
||||||
|
partyRole,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("add-detail-description/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: DescriptionDto })
|
||||||
|
@ApiOperation({ summary: "Add description for current party" })
|
||||||
|
async addDescription(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: DescriptionDto,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@Body("partyRole") partyRole?: string,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.addPartyDescriptionV3(
|
||||||
|
requestId,
|
||||||
|
fileMaker,
|
||||||
|
body,
|
||||||
|
partyRole,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
file: { type: "string", format: "binary" },
|
||||||
|
partyRole: { type: "string", enum: ["FIRST", "SECOND"] },
|
||||||
|
},
|
||||||
|
required: ["file"],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("file", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/voice",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `v5-filemaker-voice-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
@Post("upload-voice/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiOperation({ summary: "Upload voice for current party" })
|
||||||
|
async uploadVoice(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@UploadedFile() voice: Express.Multer.File,
|
||||||
|
@Body("partyRole") partyRole?: string,
|
||||||
|
) {
|
||||||
|
await this.mediaPolicyService.assertForBlame(voice, requestId, "voice");
|
||||||
|
return this.requestManagementService.addPartyVoiceV3(
|
||||||
|
requestId,
|
||||||
|
fileMaker,
|
||||||
|
voice,
|
||||||
|
partyRole,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Signatures (final FileMaker step) ───────────────────────────────────────
|
||||||
|
|
||||||
|
@Put("sign/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Party on-site signature (FileMaker final step)",
|
||||||
|
description:
|
||||||
|
"Collect FIRST (guilty) then SECOND (damaged) signatures. " +
|
||||||
|
"After the last signature the file is ready for FileReviewer pickup.",
|
||||||
|
})
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["partyRole", "sign"],
|
||||||
|
properties: {
|
||||||
|
partyRole: { type: "string", enum: ["FIRST", "SECOND"] },
|
||||||
|
isAccept: { type: "boolean", default: true },
|
||||||
|
sign: { type: "string", format: "binary" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("sign", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/signs",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `v5-filemaker-party-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
async sign(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: { partyRole?: string; isAccept?: string | boolean },
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
@UploadedFile() sign: Express.Multer.File,
|
||||||
|
) {
|
||||||
|
await this.mediaPolicyService.assertForBlame(sign, requestId, "image");
|
||||||
|
const partyRole =
|
||||||
|
body?.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST;
|
||||||
|
const isAccept = !(body?.isAccept === false || body?.isAccept === "false");
|
||||||
|
return this.requestManagementService.expertUploadPartySignatureV3(
|
||||||
|
fileMaker,
|
||||||
|
requestId,
|
||||||
|
partyRole,
|
||||||
|
isAccept,
|
||||||
|
sign,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Claim document upload ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("upload-document/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("file", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-documents",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `${file.originalname.split(".")[0]}-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Upload one required claim document (FileMaker)",
|
||||||
|
description:
|
||||||
|
"Upload licenses and car cards against the auto-created claim. " +
|
||||||
|
"Use claim-id/:requestId to obtain the claimRequestId after run-inquiries.",
|
||||||
|
})
|
||||||
|
async uploadDocument(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body() body: UploadRequiredDocumentV2Dto,
|
||||||
|
@UploadedFile() file: Express.Multer.File,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
): Promise<UploadRequiredDocumentV2ResponseDto> {
|
||||||
|
await this.mediaPolicyService.assertForClaim(file, claimRequestId, "image");
|
||||||
|
return this.claimRequestManagementService.uploadRequiredDocumentV3(
|
||||||
|
claimRequestId,
|
||||||
|
body,
|
||||||
|
file,
|
||||||
|
fileMaker.sub,
|
||||||
|
fileMaker,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("capture-requirements/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Capture requirements (step-aware)",
|
||||||
|
description:
|
||||||
|
"Initial documents phase: pre-capture docs only (no chassis/engine/metal plate). " +
|
||||||
|
"CAPTURE_PART_DAMAGES phase: damaged parts + angles via capture-part, then chassis/engine/metal plate via upload-document. " +
|
||||||
|
"Use `captureSequencePhase` and `captureSequenceHint` to drive the UI.",
|
||||||
|
})
|
||||||
|
async getCaptureRequirements(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
): Promise<GetCaptureRequirementsV2ResponseDto> {
|
||||||
|
return this.claimRequestManagementService.getCaptureRequirementsV3(
|
||||||
|
claimRequestId,
|
||||||
|
fileMaker.sub,
|
||||||
|
fileMaker,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Param,
|
||||||
|
Post,
|
||||||
|
UseGuards,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
|
import { IsOptional, IsString } from "class-validator";
|
||||||
|
import { ApiPropertyOptional } 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 { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||||
|
|
||||||
|
class FileMakerRejectDto {
|
||||||
|
@ApiPropertyOptional({
|
||||||
|
description: "Reason for rejection (visible to FileReviewer)",
|
||||||
|
example: "Damage assessment is incorrect — please re-evaluate parts X and Y",
|
||||||
|
})
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
reason?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 FileMaker approval panel.
|
||||||
|
*
|
||||||
|
* After the full claim flow completes (FileReviewer does damage assessment via
|
||||||
|
* expert-claim APIs, user signs), the claim lands in WAITING_FOR_FILE_MAKER_APPROVAL.
|
||||||
|
* The FileMaker who created the blame file can then:
|
||||||
|
*
|
||||||
|
* approve → triggers fanavaran submission (claim → COMPLETED)
|
||||||
|
* reject → sends claim back to WAITING_FOR_DAMAGE_EXPERT so the FileReviewer
|
||||||
|
* can re-lock, adjust pricing, and redo the user interaction
|
||||||
|
*
|
||||||
|
* All endpoints operate on `claimRequestId` (the claim case ID, not the blame ID).
|
||||||
|
* Use `GET v5/file-maker/blame-request-management/claim-id/:requestId` to obtain
|
||||||
|
* the claimRequestId from the original blame request ID.
|
||||||
|
*/
|
||||||
|
@ApiTags("v5 FileMaker — claim approval before fanavaran")
|
||||||
|
@Controller("v5/file-maker/claim-approval")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||||
|
@Roles(RoleEnum.FILE_MAKER)
|
||||||
|
export class FileMakerClaimApprovalV5Controller {
|
||||||
|
constructor(
|
||||||
|
private readonly requestManagementService: RequestManagementService,
|
||||||
|
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
@Post("approve/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Approve the completed claim (FileMaker V5)",
|
||||||
|
description:
|
||||||
|
"Approves a claim that is in WAITING_FOR_FILE_MAKER_APPROVAL status. " +
|
||||||
|
"Marks the claim COMPLETED and triggers fanavaran submission.",
|
||||||
|
})
|
||||||
|
async approve(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
) {
|
||||||
|
const result = await this.requestManagementService.fileMakerApproveV5(
|
||||||
|
fileMaker,
|
||||||
|
claimRequestId,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Trigger fanavaran auto-submit now that the claim is COMPLETED and the gate
|
||||||
|
// (requiresFileMakerApproval) has been cleared.
|
||||||
|
const fanavaran =
|
||||||
|
await this.claimRequestManagementService.autoSubmitToFanavaranV2OnClaimCompleted(
|
||||||
|
claimRequestId,
|
||||||
|
);
|
||||||
|
|
||||||
|
return { ...result, fanavaran };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("reject/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiBody({ type: FileMakerRejectDto })
|
||||||
|
@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.",
|
||||||
|
})
|
||||||
|
async reject(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body() body: FileMakerRejectDto,
|
||||||
|
@CurrentUser() fileMaker: any,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.fileMakerRejectV5(
|
||||||
|
fileMaker,
|
||||||
|
claimRequestId,
|
||||||
|
body?.reason,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,11 +1,15 @@
|
|||||||
import { extname } from "node:path";
|
import { extname } from "node:path";
|
||||||
import {
|
import {
|
||||||
|
BadRequestException,
|
||||||
Body,
|
Body,
|
||||||
Controller,
|
Controller,
|
||||||
Get,
|
Get,
|
||||||
|
HttpException,
|
||||||
|
InternalServerErrorException,
|
||||||
Param,
|
Param,
|
||||||
Patch,
|
Patch,
|
||||||
Post,
|
Post,
|
||||||
|
Put,
|
||||||
UploadedFile,
|
UploadedFile,
|
||||||
UseGuards,
|
UseGuards,
|
||||||
UseInterceptors,
|
UseInterceptors,
|
||||||
@@ -51,8 +55,7 @@ import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-managemen
|
|||||||
*
|
*
|
||||||
* The FileReviewer picks up a sealed file (both signatures collected by the
|
* The FileReviewer picks up a sealed file (both signatures collected by the
|
||||||
* FileMaker) and completes the damage-assessment portion: accident fields,
|
* FileMaker) and completes the damage-assessment portion: accident fields,
|
||||||
* documents, part selection, photo capture, walk-around video, and the final
|
* documents, part selection, photo capture, and walk-around video (final step).
|
||||||
* blame accident video that moves the file to WAITING_FOR_EXPERT.
|
|
||||||
*
|
*
|
||||||
* Sequence:
|
* Sequence:
|
||||||
* accident-fields
|
* accident-fields
|
||||||
@@ -61,9 +64,11 @@ import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-managemen
|
|||||||
* → select-outer-parts
|
* → select-outer-parts
|
||||||
* → select-other-parts
|
* → select-other-parts
|
||||||
* → capture-part (damaged-part photos + four angles)
|
* → capture-part (damaged-part photos + four angles)
|
||||||
* → upload-document (chassis / engine / metal plate — capture phase)
|
* → upload-document (chassis / engine — capture phase)
|
||||||
* → car-capture (walk-around video)
|
* → car-capture (walk-around video — FINAL FileReviewer step)
|
||||||
* → upload-video (blame accident video — final, moves to WAITING_FOR_EXPERT)
|
* ↳ claim → WAITING_FOR_DAMAGE_EXPERT, blame → COMPLETED
|
||||||
|
*
|
||||||
|
* NOTE: upload-video is a no-op for V4 (blame is already COMPLETED by car-capture).
|
||||||
*/
|
*/
|
||||||
@ApiTags("v4 FileReviewer — blame file review & capture")
|
@ApiTags("v4 FileReviewer — blame file review & capture")
|
||||||
@Controller("v4/file-reviewer/blame-request-management")
|
@Controller("v4/file-reviewer/blame-request-management")
|
||||||
@@ -315,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 ────────────────────────────────────────────────────────
|
// ─── Walk-around video ────────────────────────────────────────────────────────
|
||||||
|
|
||||||
@Patch("car-capture/:claimRequestId")
|
@Patch("car-capture/:claimRequestId")
|
||||||
@@ -341,9 +413,10 @@ export class FileReviewerBlameV4Controller {
|
|||||||
},
|
},
|
||||||
})
|
})
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Walk-around video",
|
summary: "Walk-around video (final FileReviewer step — V4)",
|
||||||
description:
|
description:
|
||||||
"Upload after capture-part is complete (parts, angles, capture-phase docs). Required before the final blame accident video.",
|
"Last FileReviewer action. Upload after capture-part is complete (parts, angles, chassis/engine docs). " +
|
||||||
|
"Finalises the claim → WAITING_FOR_DAMAGE_EXPERT and marks the blame as COMPLETED.",
|
||||||
})
|
})
|
||||||
async carCapture(
|
async carCapture(
|
||||||
@Param("claimRequestId") claimRequestId: string,
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
@@ -364,7 +437,6 @@ export class FileReviewerBlameV4Controller {
|
|||||||
@ApiBody({
|
@ApiBody({
|
||||||
schema: {
|
schema: {
|
||||||
type: "object",
|
type: "object",
|
||||||
required: ["file"],
|
|
||||||
properties: { file: { type: "string", format: "binary" } },
|
properties: { file: { type: "string", format: "binary" } },
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -385,17 +457,19 @@ export class FileReviewerBlameV4Controller {
|
|||||||
@Post("upload-video/:requestId")
|
@Post("upload-video/:requestId")
|
||||||
@ApiParam({ name: "requestId" })
|
@ApiParam({ name: "requestId" })
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Blame accident video (FileReviewer final step)",
|
summary: "Blame accident video (no-op for V4 — car-capture is the final step)",
|
||||||
description:
|
description:
|
||||||
"Last step of the V4 flow. Requires claim walk-around video and completed capture. " +
|
"Deprecated for V4. The blame is already COMPLETED by car-capture. " +
|
||||||
"Sets blame status to WAITING_FOR_EXPERT.",
|
"Calling this endpoint returns an idempotent success response.",
|
||||||
})
|
})
|
||||||
async uploadBlameVideo(
|
async uploadBlameVideo(
|
||||||
@Param("requestId") requestId: string,
|
@Param("requestId") requestId: string,
|
||||||
@CurrentUser() fileReviewer: any,
|
@CurrentUser() fileReviewer: any,
|
||||||
@UploadedFile() file: Express.Multer.File,
|
@UploadedFile() file: Express.Multer.File,
|
||||||
) {
|
) {
|
||||||
await this.mediaPolicyService.assertForBlame(file, requestId, "video");
|
if (file) {
|
||||||
|
await this.mediaPolicyService.assertForBlame(file, requestId, "video");
|
||||||
|
}
|
||||||
return this.requestManagementService.expertUploadBlameVideoV3(
|
return this.requestManagementService.expertUploadBlameVideoV3(
|
||||||
fileReviewer,
|
fileReviewer,
|
||||||
requestId,
|
requestId,
|
||||||
|
|||||||
480
src/request-management/file-reviewer-blame-v5.controller.ts
Normal file
480
src/request-management/file-reviewer-blame-v5.controller.ts
Normal file
@@ -0,0 +1,480 @@
|
|||||||
|
import { extname } from "node:path";
|
||||||
|
import {
|
||||||
|
Body,
|
||||||
|
Controller,
|
||||||
|
Get,
|
||||||
|
HttpException,
|
||||||
|
InternalServerErrorException,
|
||||||
|
Param,
|
||||||
|
Patch,
|
||||||
|
Post,
|
||||||
|
Put,
|
||||||
|
UploadedFile,
|
||||||
|
UseGuards,
|
||||||
|
UseInterceptors,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import {
|
||||||
|
ApiBearerAuth,
|
||||||
|
ApiBody,
|
||||||
|
ApiConsumes,
|
||||||
|
ApiOperation,
|
||||||
|
ApiParam,
|
||||||
|
ApiTags,
|
||||||
|
} from "@nestjs/swagger";
|
||||||
|
import { FileInterceptor } from "@nestjs/platform-express";
|
||||||
|
import { diskStorage } from "multer";
|
||||||
|
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 { 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 { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto";
|
||||||
|
import { RequestManagementService } from "./request-management.service";
|
||||||
|
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
|
||||||
|
import {
|
||||||
|
SelectOuterPartsV2Dto,
|
||||||
|
SelectOuterPartsV2ResponseDto,
|
||||||
|
} from "src/claim-request-management/dto/select-outer-parts-v2.dto";
|
||||||
|
import { SelectOtherPartsV2ResponseDto } from "src/claim-request-management/dto/select-other-parts-v2.dto";
|
||||||
|
import { SelectOtherPartsV3Dto } from "src/claim-request-management/dto/select-other-parts-v3.dto";
|
||||||
|
import {
|
||||||
|
UploadRequiredDocumentV2Dto,
|
||||||
|
UploadRequiredDocumentV2ResponseDto,
|
||||||
|
} from "src/claim-request-management/dto/upload-document-v2.dto";
|
||||||
|
import {
|
||||||
|
CapturePartV2Dto,
|
||||||
|
CapturePartV2ResponseDto,
|
||||||
|
} from "src/claim-request-management/dto/capture-part-v2.dto";
|
||||||
|
import { GetCaptureRequirementsV2ResponseDto } from "src/claim-request-management/dto/capture-requirements-v2.dto";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V5 FileReviewer flow — same as V4 except after the damage expert completes
|
||||||
|
* their review, the claim goes to WAITING_FOR_FILE_MAKER_APPROVAL instead of
|
||||||
|
* being submitted directly to fanavaran.
|
||||||
|
*
|
||||||
|
* Sequence:
|
||||||
|
* accident-fields
|
||||||
|
* → capture-requirements (via linked claimRequestId)
|
||||||
|
* → upload-document (licenses, car cards)
|
||||||
|
* → select-outer-parts
|
||||||
|
* → select-other-parts
|
||||||
|
* → capture-part (damaged-part photos + four angles)
|
||||||
|
* → upload-document (chassis / engine — capture phase)
|
||||||
|
* → car-capture (walk-around video — FINAL FileReviewer step)
|
||||||
|
* ↳ claim → WAITING_FOR_DAMAGE_EXPERT, blame → COMPLETED
|
||||||
|
* ↳ after expert review: claim → WAITING_FOR_FILE_MAKER_APPROVAL
|
||||||
|
*
|
||||||
|
* NOTE: upload-video is a no-op for V5 (blame is already COMPLETED by car-capture).
|
||||||
|
*/
|
||||||
|
@ApiTags("v5 FileReviewer — blame file review & capture (with FinancialExpert approval)")
|
||||||
|
@Controller("v5/file-reviewer/blame-request-management")
|
||||||
|
@ApiBearerAuth()
|
||||||
|
@UseGuards(LocalActorAuthGuard, RolesGuard)
|
||||||
|
@Roles(RoleEnum.FILE_REVIEWER)
|
||||||
|
export class FileReviewerBlameV5Controller {
|
||||||
|
constructor(
|
||||||
|
private readonly requestManagementService: RequestManagementService,
|
||||||
|
private readonly claimRequestManagementService: ClaimRequestManagementService,
|
||||||
|
private readonly mediaPolicyService: MediaPolicyService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ─── Linked claim lookup ──────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get("claim-id/:requestId")
|
||||||
|
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Get linked claim ID",
|
||||||
|
description:
|
||||||
|
"Returns the claim auto-created during FileMaker's guilty-party run-inquiries. " +
|
||||||
|
"Use this claim ID for all capture/document/parts endpoints below.",
|
||||||
|
})
|
||||||
|
async getLinkedClaimId(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.getV3LinkedClaimForExpert(
|
||||||
|
fileReviewer,
|
||||||
|
requestId,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Accident fields ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("accident-fields/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiBody({ type: ExpertAccidentFieldsDto })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Accident type / fields (FileReviewer first step)",
|
||||||
|
description:
|
||||||
|
"Saves accident fields on the sealed file. " +
|
||||||
|
"Does not move to WAITING_FOR_FINANCIAL_EXPERT — that happens after the final blame accident video.",
|
||||||
|
})
|
||||||
|
async addAccidentFields(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() fields: ExpertAccidentFieldsDto,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.expertAddAccidentFieldsForBlameV3(
|
||||||
|
fileReviewer,
|
||||||
|
requestId,
|
||||||
|
fields,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Capture requirements ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Get("capture-requirements/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Capture requirements (step-aware)",
|
||||||
|
description:
|
||||||
|
"Initial documents phase: pre-capture docs only (no chassis/engine/metal plate). " +
|
||||||
|
"CAPTURE_PART_DAMAGES phase: damaged parts + angles via capture-part, then chassis/engine/metal plate via upload-document. " +
|
||||||
|
"Use `captureSequencePhase` and `captureSequenceHint` to drive the UI.",
|
||||||
|
})
|
||||||
|
async getCaptureRequirements(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
): Promise<GetCaptureRequirementsV2ResponseDto> {
|
||||||
|
return this.claimRequestManagementService.getCaptureRequirementsV3(
|
||||||
|
claimRequestId,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Document upload ──────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("upload-document/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("file", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-documents",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `${file.originalname.split(".")[0]}-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Upload one required claim document",
|
||||||
|
description:
|
||||||
|
"Initial phase (UPLOAD_REQUIRED_DOCUMENTS): licenses and car cards only. " +
|
||||||
|
"Capture phase (CAPTURE_PART_DAMAGES, after parts + angles): chassis, engine, metal plate only.",
|
||||||
|
})
|
||||||
|
async uploadDocument(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body() body: UploadRequiredDocumentV2Dto,
|
||||||
|
@UploadedFile() file: Express.Multer.File,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
): Promise<UploadRequiredDocumentV2ResponseDto> {
|
||||||
|
await this.mediaPolicyService.assertForClaim(file, claimRequestId, "image");
|
||||||
|
return this.claimRequestManagementService.uploadRequiredDocumentV3(
|
||||||
|
claimRequestId,
|
||||||
|
body,
|
||||||
|
file,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Part selection ───────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Patch("select-outer-parts/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId" })
|
||||||
|
@ApiBody({ type: SelectOuterPartsV2Dto })
|
||||||
|
@ApiOperation({ summary: "Select damaged outer parts" })
|
||||||
|
async selectOuterParts(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body() body: SelectOuterPartsV2Dto,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
): Promise<SelectOuterPartsV2ResponseDto> {
|
||||||
|
return this.claimRequestManagementService.selectOuterPartsV3(
|
||||||
|
claimRequestId,
|
||||||
|
body,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch("select-other-parts/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId", example: "507f1f77bcf86cd799439011" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Select other damaged parts (V5)",
|
||||||
|
description:
|
||||||
|
"Other parts only — sheba and national code were collected during FileMaker's run-inquiries. Optional car green card file.",
|
||||||
|
})
|
||||||
|
@ApiBody({
|
||||||
|
description:
|
||||||
|
"Other parts selection. Bank info is already on the claim from run-inquiries.",
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: {
|
||||||
|
otherParts: {
|
||||||
|
oneOf: [
|
||||||
|
{
|
||||||
|
type: "array",
|
||||||
|
items: {
|
||||||
|
type: "string",
|
||||||
|
enum: [
|
||||||
|
"engine",
|
||||||
|
"suspension",
|
||||||
|
"brake_system",
|
||||||
|
"electrical",
|
||||||
|
"radiator",
|
||||||
|
"transmission",
|
||||||
|
"exhaust",
|
||||||
|
"headlight",
|
||||||
|
"taillight",
|
||||||
|
"mirror",
|
||||||
|
"glass",
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ type: "string", description: "JSON string array for multipart" },
|
||||||
|
],
|
||||||
|
example: ["engine", "suspension"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async selectOtherParts(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body() body: SelectOtherPartsV3Dto,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
): Promise<SelectOtherPartsV2ResponseDto> {
|
||||||
|
return this.claimRequestManagementService.selectOtherPartsV3(
|
||||||
|
claimRequestId,
|
||||||
|
body,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Photo capture ────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("capture-part/:claimRequestId")
|
||||||
|
@ApiParam({ name: "claimRequestId", example: "507f1f77bcf86cd799439011" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("file", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/claim-captures",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `v5-capture-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Car angles and damaged-part photos",
|
||||||
|
description:
|
||||||
|
"CAPTURE_PART_DAMAGES: (1) all damaged-part photos, (2) four car angles, " +
|
||||||
|
"(3) chassis/engine/metal-plate via upload-document. Then car-capture walk-around video.",
|
||||||
|
})
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["captureType", "captureKey", "file"],
|
||||||
|
properties: {
|
||||||
|
captureType: {
|
||||||
|
type: "string",
|
||||||
|
enum: ["angle", "part"],
|
||||||
|
example: "angle",
|
||||||
|
},
|
||||||
|
captureKey: {
|
||||||
|
type: "string",
|
||||||
|
example: "front",
|
||||||
|
description:
|
||||||
|
"For angle: front/back/left/right. For part: hood/front_bumper/etc.",
|
||||||
|
},
|
||||||
|
file: { type: "string", format: "binary" },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
async capturePart(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@Body() body: CapturePartV2Dto,
|
||||||
|
@UploadedFile() file: Express.Multer.File,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
): Promise<CapturePartV2ResponseDto> {
|
||||||
|
await this.mediaPolicyService.assertForClaim(file, claimRequestId, "image");
|
||||||
|
return this.claimRequestManagementService.capturePartV3(
|
||||||
|
claimRequestId,
|
||||||
|
body,
|
||||||
|
file,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── 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")
|
||||||
|
@ApiParam({ name: "claimRequestId", example: "507f1f77bcf86cd799439011" })
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("file", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/car-capture-videos/",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `v5-claim-video-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
required: ["file"],
|
||||||
|
properties: { file: { type: "string", format: "binary" } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Walk-around video (final FileReviewer step — V5)",
|
||||||
|
description:
|
||||||
|
"Last FileReviewer action. Upload after capture-part is complete (parts, angles, chassis/engine docs). " +
|
||||||
|
"Finalises the claim → WAITING_FOR_DAMAGE_EXPERT and marks the blame as COMPLETED. " +
|
||||||
|
"After the damage expert review completes the claim moves to WAITING_FOR_FILE_MAKER_APPROVAL.",
|
||||||
|
})
|
||||||
|
async carCapture(
|
||||||
|
@Param("claimRequestId") claimRequestId: string,
|
||||||
|
@UploadedFile("file") file: Express.Multer.File,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
) {
|
||||||
|
await this.mediaPolicyService.assertForClaim(file, claimRequestId, "video");
|
||||||
|
return this.claimRequestManagementService.setVideoCaptureV3(
|
||||||
|
claimRequestId,
|
||||||
|
file,
|
||||||
|
fileReviewer.sub,
|
||||||
|
fileReviewer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Final blame video ─────────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
|
||||||
|
@ApiBody({
|
||||||
|
schema: {
|
||||||
|
type: "object",
|
||||||
|
properties: { file: { type: "string", format: "binary" } },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
@ApiConsumes("multipart/form-data")
|
||||||
|
@UseInterceptors(
|
||||||
|
FileInterceptor("file", {
|
||||||
|
limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES },
|
||||||
|
storage: diskStorage({
|
||||||
|
destination: "./files/video",
|
||||||
|
filename: (req, file, callback) => {
|
||||||
|
const unique = Date.now();
|
||||||
|
const ex = extname(file.originalname);
|
||||||
|
callback(null, `v5-blame-accident-${unique}${ex}`);
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
@Post("upload-video/:requestId")
|
||||||
|
@ApiParam({ name: "requestId" })
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Blame accident video (no-op for V5 — car-capture is the final step)",
|
||||||
|
description:
|
||||||
|
"Deprecated for V5. The blame is already COMPLETED by car-capture. " +
|
||||||
|
"Calling this endpoint returns an idempotent success response.",
|
||||||
|
})
|
||||||
|
async uploadBlameVideo(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@CurrentUser() fileReviewer: any,
|
||||||
|
@UploadedFile() file: Express.Multer.File,
|
||||||
|
) {
|
||||||
|
if (file) {
|
||||||
|
await this.mediaPolicyService.assertForBlame(file, requestId, "video");
|
||||||
|
}
|
||||||
|
return this.requestManagementService.expertUploadBlameVideoV5(
|
||||||
|
fileReviewer,
|
||||||
|
requestId,
|
||||||
|
file,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
import { Types } from "mongoose";
|
import { Types } from "mongoose";
|
||||||
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service";
|
||||||
import { SandHubService } from "src/sand-hub/sand-hub.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 { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
|
||||||
import { BlameRequestDbService } from "./entities/db-service/blame-request.db.service";
|
import { BlameRequestDbService } from "./entities/db-service/blame-request.db.service";
|
||||||
import { PartyRole } from "./entities/schema/partyRole.enum";
|
import { PartyRole } from "./entities/schema/partyRole.enum";
|
||||||
@@ -33,6 +34,7 @@ export class InquiryRefreshService {
|
|||||||
private readonly blameRequestDbService: BlameRequestDbService,
|
private readonly blameRequestDbService: BlameRequestDbService,
|
||||||
private readonly claimCaseDbService: ClaimCaseDbService,
|
private readonly claimCaseDbService: ClaimCaseDbService,
|
||||||
private readonly sandHubService: SandHubService,
|
private readonly sandHubService: SandHubService,
|
||||||
|
private readonly plateNormalizer: PlateNormalizerService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
async reinquiryInquiries(
|
async reinquiryInquiries(
|
||||||
@@ -367,7 +369,8 @@ export class InquiryRefreshService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
next.insurance.policyNumber =
|
next.insurance.policyNumber =
|
||||||
mapped.LastCompanyDocumentNumber ||
|
mapped.PrntPlcyCmpDocNo ||
|
||||||
|
mapped.printNumber ||
|
||||||
mapped.insuranceNumber ||
|
mapped.insuranceNumber ||
|
||||||
next.insurance.policyNumber;
|
next.insurance.policyNumber;
|
||||||
next.insurance.company =
|
next.insurance.company =
|
||||||
@@ -591,7 +594,7 @@ export class InquiryRefreshService {
|
|||||||
centerDigits !== undefined &&
|
centerDigits !== undefined &&
|
||||||
ir !== undefined
|
ir !== undefined
|
||||||
) {
|
) {
|
||||||
const plateLetter = String(centerAlphabet).trim();
|
const plateLetter = this.plateNormalizer.normalizePlateText(String(centerAlphabet));
|
||||||
const parsed: PlateParts = {
|
const parsed: PlateParts = {
|
||||||
leftDigits: Number(leftDigits),
|
leftDigits: Number(leftDigits),
|
||||||
centerAlphabet: plateLetter,
|
centerAlphabet: plateLetter,
|
||||||
@@ -621,8 +624,7 @@ export class InquiryRefreshService {
|
|||||||
const ir = Number(irRaw);
|
const ir = Number(irRaw);
|
||||||
const leftDigits = Number(leftRaw);
|
const leftDigits = Number(leftRaw);
|
||||||
const centerDigits = Number(centerRaw);
|
const centerDigits = Number(centerRaw);
|
||||||
const centerAlphabet = String(alphaRaw || "").trim();
|
const centerAlphabet = this.plateNormalizer.normalizePlateText(String(alphaRaw || ""));
|
||||||
|
|
||||||
if (
|
if (
|
||||||
!Number.isFinite(ir) ||
|
!Number.isFinite(ir) ||
|
||||||
!Number.isFinite(leftDigits) ||
|
!Number.isFinite(leftDigits) ||
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { UsersModule } from "src/users/users.module";
|
|||||||
import { CronModule } from "src/utils/cron/cron.module";
|
import { CronModule } from "src/utils/cron/cron.module";
|
||||||
import { PublicIdModule } from "src/utils/public-id/public-id.module";
|
import { PublicIdModule } from "src/utils/public-id/public-id.module";
|
||||||
import { HashModule } from "src/utils/hash/hash.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 { SmsOrchestrationModule } from "src/sms-orchestration/sms-orchestration.module";
|
||||||
import { WorkflowStepManagementModule } from "src/workflow-step-management/workflow-step-management.module";
|
import { WorkflowStepManagementModule } from "src/workflow-step-management/workflow-step-management.module";
|
||||||
import { AuthModule } from "src/auth/auth.module";
|
import { AuthModule } from "src/auth/auth.module";
|
||||||
@@ -45,8 +46,12 @@ import { RegistrarBlameMirrorController } from "./registrar-blame.mirror.control
|
|||||||
import { ExpertInitiatedBlameV3MirrorController } from "./expert-initiated-blame-v3.mirror.controller";
|
import { ExpertInitiatedBlameV3MirrorController } from "./expert-initiated-blame-v3.mirror.controller";
|
||||||
import { FileMakerBlameV4Controller } from "./file-maker-blame-v4.controller";
|
import { FileMakerBlameV4Controller } from "./file-maker-blame-v4.controller";
|
||||||
import { FileReviewerBlameV4Controller } from "./file-reviewer-blame-v4.controller";
|
import { FileReviewerBlameV4Controller } from "./file-reviewer-blame-v4.controller";
|
||||||
|
import { FileMakerBlameV5Controller } from "./file-maker-blame-v5.controller";
|
||||||
|
import { FileReviewerBlameV5Controller } from "./file-reviewer-blame-v5.controller";
|
||||||
|
import { FileMakerClaimApprovalV5Controller } from "./file-maker-claim-approval-v5.controller";
|
||||||
import { InquiryRefreshController } from "./inquiry-refresh.controller";
|
import { InquiryRefreshController } from "./inquiry-refresh.controller";
|
||||||
import { InquiryRefreshService } from "./inquiry-refresh.service";
|
import { InquiryRefreshService } from "./inquiry-refresh.service";
|
||||||
|
import { CallCenterBlameV6Controller } from "./call-center-blame-v6.controller";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -56,6 +61,7 @@ import { InquiryRefreshService } from "./inquiry-refresh.service";
|
|||||||
SmsOrchestrationModule,
|
SmsOrchestrationModule,
|
||||||
PublicIdModule,
|
PublicIdModule,
|
||||||
HashModule,
|
HashModule,
|
||||||
|
PlateNormalizerModule,
|
||||||
WorkflowStepManagementModule,
|
WorkflowStepManagementModule,
|
||||||
PlatesModule,
|
PlatesModule,
|
||||||
MulterModule.register({
|
MulterModule.register({
|
||||||
@@ -85,7 +91,11 @@ import { InquiryRefreshService } from "./inquiry-refresh.service";
|
|||||||
RegistrarBlameMirrorController,
|
RegistrarBlameMirrorController,
|
||||||
FileMakerBlameV4Controller,
|
FileMakerBlameV4Controller,
|
||||||
FileReviewerBlameV4Controller,
|
FileReviewerBlameV4Controller,
|
||||||
|
FileMakerBlameV5Controller,
|
||||||
|
FileReviewerBlameV5Controller,
|
||||||
|
FileMakerClaimApprovalV5Controller,
|
||||||
InquiryRefreshController,
|
InquiryRefreshController,
|
||||||
|
CallCenterBlameV6Controller,
|
||||||
],
|
],
|
||||||
providers: [
|
providers: [
|
||||||
RequestManagementService,
|
RequestManagementService,
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -40,6 +40,7 @@ import {
|
|||||||
BlameConfessionDtoV2,
|
BlameConfessionDtoV2,
|
||||||
CreateBlameRequestDtoV2,
|
CreateBlameRequestDtoV2,
|
||||||
DescriptionDto,
|
DescriptionDto,
|
||||||
|
InitialFormVinDto,
|
||||||
LocationDto,
|
LocationDto,
|
||||||
CarBodyFormDto,
|
CarBodyFormDto,
|
||||||
} from "./dto/create-request-management.dto";
|
} from "./dto/create-request-management.dto";
|
||||||
@@ -197,6 +198,26 @@ export class RequestManagementV2Controller {
|
|||||||
return this.requestManagementService.initialFormV2(requestId, body, user);
|
return this.requestManagementService.initialFormV2(requestId, body, user);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Post("/initial-form-vin/:requestId")
|
||||||
|
@ApiParam({ name: "requestId", description: "Blame request ID" })
|
||||||
|
@ApiBody({
|
||||||
|
type: InitialFormVinDto,
|
||||||
|
description:
|
||||||
|
"Same identity/license fields as the plate form, but with `vin` (17-char chassis number) instead of `plate`.",
|
||||||
|
})
|
||||||
|
@UseGuards(GlobalGuard)
|
||||||
|
async initialFormVinV2(
|
||||||
|
@Param("requestId") requestId: string,
|
||||||
|
@Body() body: InitialFormVinDto,
|
||||||
|
@CurrentUser() user,
|
||||||
|
) {
|
||||||
|
return this.requestManagementService.initialFormVinV2(
|
||||||
|
requestId,
|
||||||
|
body,
|
||||||
|
user,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@Post("/add-detail-location/:requestId")
|
@Post("/add-detail-location/:requestId")
|
||||||
@ApiParam({ name: "requestId" })
|
@ApiParam({ name: "requestId" })
|
||||||
@ApiBody({ type: LocationDto })
|
@ApiBody({ type: LocationDto })
|
||||||
|
|||||||
@@ -1,16 +1,24 @@
|
|||||||
import { Module } from "@nestjs/common";
|
import { Module } from "@nestjs/common";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
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 { MongooseModule } from "@nestjs/mongoose";
|
||||||
import { ClientModule } from "src/client/client.module";
|
import { ClientModule } from "src/client/client.module";
|
||||||
import { SystemSettingsModule } from "src/system-settings/system-settings.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 { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service";
|
||||||
import { SandHubModel, SandHubSchema } from "./entity/schema/sand-hub.schema";
|
import { SandHubModel, SandHubSchema } from "./entity/schema/sand-hub.schema";
|
||||||
import { SandHubService } from "./sand-hub.service";
|
import { SandHubService } from "./sand-hub.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
SystemSettingsModule,
|
SystemSettingsModule,
|
||||||
|
PlateNormalizerModule,
|
||||||
ClientModule,
|
ClientModule,
|
||||||
MongooseModule.forFeature([
|
MongooseModule.forFeature([
|
||||||
{ name: SandHubModel.name, schema: SandHubSchema },
|
{ name: SandHubModel.name, schema: SandHubSchema },
|
||||||
|
|||||||
@@ -9,6 +9,9 @@ describe("SandHubService inquiry mocks", () => {
|
|||||||
isInquiryLive: jest.fn(),
|
isInquiryLive: jest.fn(),
|
||||||
getMockCompanyContext: jest.fn(),
|
getMockCompanyContext: jest.fn(),
|
||||||
};
|
};
|
||||||
|
const plateNormalizer = {
|
||||||
|
normalizePlateText: (text: string) => text,
|
||||||
|
};
|
||||||
|
|
||||||
let service: SandHubService;
|
let service: SandHubService;
|
||||||
|
|
||||||
@@ -30,6 +33,7 @@ describe("SandHubService inquiry mocks", () => {
|
|||||||
httpService as any,
|
httpService as any,
|
||||||
sandHubDbService as any,
|
sandHubDbService as any,
|
||||||
externalInquirySettings as unknown as ExternalInquirySettingsService,
|
externalInquirySettings as unknown as ExternalInquirySettingsService,
|
||||||
|
plateNormalizer as any,
|
||||||
);
|
);
|
||||||
externalInquirySettings.isInquiryLive.mockResolvedValue(false);
|
externalInquirySettings.isInquiryLive.mockResolvedValue(false);
|
||||||
externalInquirySettings.getMockCompanyContext.mockResolvedValue({
|
externalInquirySettings.getMockCompanyContext.mockResolvedValue({
|
||||||
@@ -81,5 +85,33 @@ describe("SandHubService inquiry mocks", () => {
|
|||||||
expect(httpService.post).not.toHaveBeenCalled();
|
expect(httpService.post).not.toHaveBeenCalled();
|
||||||
expect(result.mapped?.CompanyName).toBe("بیمه پارسیان");
|
expect(result.mapped?.CompanyName).toBe("بیمه پارسیان");
|
||||||
expect(result.mapped?.CompanyCode).toBe("8");
|
expect(result.mapped?.CompanyCode).toBe("8");
|
||||||
|
// PrntPlcyCmpDocNo must be populated from the mock raw field
|
||||||
|
expect(result.mapped?.PrntPlcyCmpDocNo).toBe("1404/1143-70591/200/123");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps printNumber → PrntPlcyCmpDocNo when raw response uses new field name", async () => {
|
||||||
|
// Simulate a real-API response where the policy number arrives as printNumber
|
||||||
|
const rawNewFormat = {
|
||||||
|
printNumber: "1405/1143-NEWAPI/200/1",
|
||||||
|
CompanyName: "بیمه آزمایشی",
|
||||||
|
CompanyCode: "99",
|
||||||
|
FinancialCvrCptl: "5000000000",
|
||||||
|
IssueDate: "1405/01/01",
|
||||||
|
EndDate: "1406/01/01",
|
||||||
|
};
|
||||||
|
const mapped = (service as any).mapNewApiResponseToOldFormat(rawNewFormat);
|
||||||
|
|
||||||
|
expect(mapped.PrntPlcyCmpDocNo).toBe("1405/1143-NEWAPI/200/1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps insuranceNumber → PrntPlcyCmpDocNo when raw response uses legacy field name", async () => {
|
||||||
|
const rawLegacy = {
|
||||||
|
insuranceNumber: "1405/1143-LEGACY/200/1",
|
||||||
|
CompanyName: "بیمه آزمایشی",
|
||||||
|
CompanyCode: "99",
|
||||||
|
};
|
||||||
|
const mapped = (service as any).mapNewApiResponseToOldFormat(rawLegacy);
|
||||||
|
|
||||||
|
expect(mapped.PrntPlcyCmpDocNo).toBe("1405/1143-LEGACY/200/1");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import {
|
|||||||
import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service";
|
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 { SandHubModel } from "src/sand-hub/entity/schema/sand-hub.schema";
|
||||||
import { ExternalInquirySettingsService } from "src/client/external-inquiry-settings.service";
|
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 { ExternalInquiryType } from "src/common/types/external-inquiry.types";
|
||||||
import type { MockInquiryCompanyContext } 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";
|
import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto";
|
||||||
@@ -39,6 +40,7 @@ export class SandHubService {
|
|||||||
private readonly httpService: HttpService,
|
private readonly httpService: HttpService,
|
||||||
private readonly sandHubDbService: SandHubDbService,
|
private readonly sandHubDbService: SandHubDbService,
|
||||||
private readonly externalInquirySettings: ExternalInquirySettingsService,
|
private readonly externalInquirySettings: ExternalInquirySettingsService,
|
||||||
|
private readonly plateNormalizer: PlateNormalizerService,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
private clientRefFrom(options?: SandHubInquiryOptions): string | undefined {
|
private clientRefFrom(options?: SandHubInquiryOptions): string | undefined {
|
||||||
@@ -162,8 +164,8 @@ export class SandHubService {
|
|||||||
nationalCodeOfInsurer: nationalCode,
|
nationalCodeOfInsurer: nationalCode,
|
||||||
plate: {
|
plate: {
|
||||||
leftDigits: Number(payload.part1 ?? payload.leftTwoDigits ?? 16),
|
leftDigits: Number(payload.part1 ?? payload.leftTwoDigits ?? 16),
|
||||||
centerAlphabet: String(
|
centerAlphabet: this.plateNormalizer.normalizePlateText(
|
||||||
payload.part2 ?? payload.serialLetter ?? "12",
|
String(payload.part2 ?? payload.serialLetter ?? "12"),
|
||||||
),
|
),
|
||||||
centerDigits: Number(payload.part3 ?? payload.threeDigits ?? 498),
|
centerDigits: Number(payload.part3 ?? payload.threeDigits ?? 498),
|
||||||
ir: Number(payload.part4 ?? payload.rightTwoDigits ?? 60),
|
ir: Number(payload.part4 ?? payload.rightTwoDigits ?? 60),
|
||||||
@@ -893,6 +895,48 @@ export class SandHubService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ESG VIN/chassis-number inquiry (`/inquiry/policyByChassis`).
|
||||||
|
*
|
||||||
|
* When `vinChassis` inquiry is disabled (mock mode) the response shape mirrors
|
||||||
|
* `buildMockPlateInquiryRaw` so the downstream mapper (`mapEsgPolicyByPlateToOldFormat`)
|
||||||
|
* can normalise it into the same `{ raw, mapped }` contract used by the plate path.
|
||||||
|
*
|
||||||
|
* @param chassisNo - 17-character VIN / chassis number
|
||||||
|
* @param options - optional per-tenant client scope
|
||||||
|
*/
|
||||||
|
async getPolicyByChassisInquiry(
|
||||||
|
chassisNo: string,
|
||||||
|
options?: SandHubInquiryOptions,
|
||||||
|
): Promise<{ raw: any; mapped: any }> {
|
||||||
|
const baseUrl = process.env.ESG_URL ?? "http://192.168.20.22:8085";
|
||||||
|
const requestUrl = `${baseUrl}/inquiry/policyByChassis`;
|
||||||
|
const requestPayload = { chassisNo };
|
||||||
|
|
||||||
|
const live = await this.isInquiryLive("vinChassis", options);
|
||||||
|
|
||||||
|
if (!live) {
|
||||||
|
const ctx = await this.mockCompanyContext(options);
|
||||||
|
const raw = this.buildMockPlateInquiryRaw(ctx);
|
||||||
|
this.logger.debug(
|
||||||
|
`[MOCK] getPolicyByChassisInquiry chassisNo=${chassisNo}`,
|
||||||
|
);
|
||||||
|
const mapped = this.mapEsgPolicyByPlateToOldFormat(raw);
|
||||||
|
return { raw, mapped };
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = await this.makeEsgRequest(
|
||||||
|
requestUrl,
|
||||||
|
requestPayload,
|
||||||
|
"vinChassis",
|
||||||
|
options,
|
||||||
|
);
|
||||||
|
const mapped = this.mapEsgPolicyByPlateToOldFormat(raw);
|
||||||
|
return { raw, mapped };
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
private async makeSandHubRequest(
|
private async makeSandHubRequest(
|
||||||
url: string,
|
url: string,
|
||||||
payload: any,
|
payload: any,
|
||||||
@@ -970,11 +1014,20 @@ export class SandHubService {
|
|||||||
IssueDate: newResponse.persianStartDate || newResponse.IssueDate,
|
IssueDate: newResponse.persianStartDate || newResponse.IssueDate,
|
||||||
EndDate: newResponse.persianEndDate || newResponse.EndDate,
|
EndDate: newResponse.persianEndDate || newResponse.EndDate,
|
||||||
|
|
||||||
|
// Insurance policy number — canonical Tejarat name is PrntPlcyCmpDocNo;
|
||||||
|
// newer API formats surface it as printNumber or insuranceNumber.
|
||||||
|
PrntPlcyCmpDocNo:
|
||||||
|
newResponse.PrntPlcyCmpDocNo ||
|
||||||
|
newResponse.printNumber ||
|
||||||
|
newResponse.insuranceNumber ||
|
||||||
|
null,
|
||||||
|
|
||||||
// Insurance details
|
// Insurance details
|
||||||
LastCompanyDocumentNumber:
|
LastCompanyDocumentNumber:
|
||||||
newResponse.lastCompanyInsuranceNumber ||
|
newResponse.lastCompanyInsuranceNumber ||
|
||||||
newResponse.LastCompanyDocumentNumber ||
|
newResponse.LastCompanyDocumentNumber ||
|
||||||
newResponse.insuranceNumber,
|
newResponse.insuranceNumber ||
|
||||||
|
null,
|
||||||
|
|
||||||
// Technical details
|
// Technical details
|
||||||
MtrNum: newResponse.MtrNum || newResponse.mtrnum,
|
MtrNum: newResponse.MtrNum || newResponse.mtrnum,
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
import { Module } from "@nestjs/common";
|
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 { KavenegarService } from "./kavenegar.service";
|
||||||
import { KavenegarSmsGateway } from "./kavenegar-sms.gateway";
|
import { KavenegarSmsGateway } from "./kavenegar-sms.gateway";
|
||||||
@@ -8,7 +9,14 @@ import { ParsianSmsGateway } from "./parsian-sms.gateway";
|
|||||||
import { SmsGatewayService } from "./sms-gateway.service";
|
import { SmsGatewayService } from "./sms-gateway.service";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [HttpModule, ConfigModule],
|
imports: [
|
||||||
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
|
ConfigModule,
|
||||||
|
],
|
||||||
providers: [
|
providers: [
|
||||||
KavenegarService,
|
KavenegarService,
|
||||||
KavenegarSmsGateway,
|
KavenegarSmsGateway,
|
||||||
|
|||||||
@@ -6,10 +6,16 @@ import { SmsGatewayModule } from "./provider/sms-gateway.module";
|
|||||||
import { OtpGeneratorService } from "./otp-generator.service";
|
import { OtpGeneratorService } from "./otp-generator.service";
|
||||||
import { SmsOrchestrationService } from "./sms-orchestration.service";
|
import { SmsOrchestrationService } from "./sms-orchestration.service";
|
||||||
import { HttpModule } from "@nestjs/axios";
|
import { HttpModule } from "@nestjs/axios";
|
||||||
|
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||||
|
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
HttpModule,
|
HttpModule.registerAsync({
|
||||||
|
imports: [ConfigModule],
|
||||||
|
inject: [ConfigService],
|
||||||
|
useFactory: createHttpModuleOptions,
|
||||||
|
}),
|
||||||
SmsGatewayModule,
|
SmsGatewayModule,
|
||||||
MongooseModule.forFeature([{ name: SmsText.name, schema: SmsTextSchema }]),
|
MongooseModule.forFeature([{ name: SmsText.name, schema: SmsTextSchema }]),
|
||||||
],
|
],
|
||||||
|
|||||||
@@ -37,20 +37,25 @@ export class SmsOrchestrationService implements OnModuleInit {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
buildInviteLink(frontendRoute: string, requestId: string): string {
|
buildInviteLink(
|
||||||
return `${process.env.URL}/${process.env.USER_BASE_PATH}/${frontendRoute}?token=${requestId}`;
|
frontendRoute: string,
|
||||||
|
requestId: string,
|
||||||
|
versionPrefix: string,
|
||||||
|
): string {
|
||||||
|
return `${process.env.URL}/${versionPrefix}/${frontendRoute}?token=${requestId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
buildBlamePartyLink(
|
buildBlamePartyLink(
|
||||||
requestId: string,
|
requestId: string,
|
||||||
partyRole: "FIRST" | "SECOND",
|
partyRole: "FIRST" | "SECOND",
|
||||||
|
versionPrefix: string,
|
||||||
): string {
|
): string {
|
||||||
const route = partyRole === "SECOND" ? "user2" : "user";
|
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 {
|
buildClaimLink(claimRequestId: string, versionPrefix: string): string {
|
||||||
return `${process.env.URL}/${process.env.USER_BASE_PATH}/caseClaim?token=${claimRequestId}`;
|
return `${process.env.URL}/${versionPrefix}/caseClaim?token=${claimRequestId}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
async sendInviteLink(
|
async sendInviteLink(
|
||||||
|
|||||||
@@ -218,5 +218,9 @@
|
|||||||
"دمنده بخاری": false,
|
"دمنده بخاری": false,
|
||||||
"کمپرسور کولر": false,
|
"کمپرسور کولر": false,
|
||||||
"کندانسور": false,
|
"کندانسور": false,
|
||||||
"اواپراتور": false
|
"اواپراتور": false,
|
||||||
|
"لاستیک": false,
|
||||||
|
"مه شکن": false,
|
||||||
|
"رینگ": false,
|
||||||
|
"فن": false
|
||||||
}
|
}
|
||||||
110
src/super-admin/dto/super-admin.dto.ts
Normal file
110
src/super-admin/dto/super-admin.dto.ts
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
|
||||||
|
import { IsEmail, IsNotEmpty, IsOptional, IsString } from "class-validator";
|
||||||
|
|
||||||
|
export class CreateSuperAdminDto {
|
||||||
|
@ApiProperty({
|
||||||
|
example: "ops@yara724.ir",
|
||||||
|
description: "Email address for the new super-admin account.",
|
||||||
|
})
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Str0ngP@ss!" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: "Operations" })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
firstName?: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: "Team" })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
lastName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateFieldExpertAdminDto {
|
||||||
|
@ApiProperty({ example: "expert@insurer.ir" })
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Expert@724" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Ali" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
firstName: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Mohammadi" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
lastName: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "09121234567" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
mobile: string;
|
||||||
|
|
||||||
|
@ApiPropertyOptional({ example: "02112345678" })
|
||||||
|
@IsOptional()
|
||||||
|
@IsString()
|
||||||
|
phone?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class CreateRegistrarAdminDto {
|
||||||
|
@ApiProperty({ example: "registrar@insurer.ir" })
|
||||||
|
@IsEmail()
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@ApiProperty({ example: "Registrar@724" })
|
||||||
|
@IsString()
|
||||||
|
@IsNotEmpty()
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@ApiProperty({
|
||||||
|
example: "664a1b2c3d4e5f6789012345",
|
||||||
|
description: "Mongo ObjectId of the insurer client this registrar belongs to.",
|
||||||
|
})
|
||||||
|
@IsString()
|
||||||
|
@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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
import { Injectable, Logger, OnModuleInit } from "@nestjs/common";
|
||||||
|
import { InjectModel } from "@nestjs/mongoose";
|
||||||
|
import { FilterQuery, Model } from "mongoose";
|
||||||
|
import { HashService } from "src/utils/hash/hash.service";
|
||||||
|
import {
|
||||||
|
SuperAdminModel,
|
||||||
|
SuperAdminDocument,
|
||||||
|
} from "../schema/super-admin.schema";
|
||||||
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
|
|
||||||
|
@Injectable()
|
||||||
|
export class SuperAdminDbService implements OnModuleInit {
|
||||||
|
private readonly logger = new Logger(SuperAdminDbService.name);
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
@InjectModel(SuperAdminModel.name)
|
||||||
|
private readonly superAdminModel: Model<SuperAdminDocument>,
|
||||||
|
private readonly hashService: HashService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seeds the default super-admin account on first boot.
|
||||||
|
* Reads credentials from environment variables:
|
||||||
|
* SUPER_ADMIN_EMAIL (default: super-admin@yara724.ir)
|
||||||
|
* SUPER_ADMIN_PASSWORD (default: SuperAdmin@724)
|
||||||
|
*/
|
||||||
|
async onModuleInit() {
|
||||||
|
const email = (
|
||||||
|
process.env.SUPER_ADMIN_EMAIL ?? "super-admin@yara724.ir"
|
||||||
|
).toLowerCase().trim();
|
||||||
|
|
||||||
|
const existing = await this.superAdminModel.findOne({ email }).lean();
|
||||||
|
if (existing) {
|
||||||
|
this.logger.log(`Super-admin already exists (email=${email}), skipping seed.`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawPassword = process.env.SUPER_ADMIN_PASSWORD ?? "SuperAdmin@724";
|
||||||
|
const password = await this.hashService.hash(rawPassword);
|
||||||
|
|
||||||
|
await this.superAdminModel.create({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role: RoleEnum.SUPER_ADMIN,
|
||||||
|
firstName: "Super",
|
||||||
|
lastName: "Admin",
|
||||||
|
});
|
||||||
|
|
||||||
|
this.logger.log(`Default super-admin seeded (email=${email}).`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findOne(
|
||||||
|
filter: FilterQuery<SuperAdminDocument>,
|
||||||
|
): Promise<SuperAdminDocument | null> {
|
||||||
|
return this.superAdminModel.findOne(filter).lean() as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
async findByLoginIdentifier(identifier: string): Promise<SuperAdminDocument | null> {
|
||||||
|
const id = identifier.trim();
|
||||||
|
return this.superAdminModel.findOne({ email: id }).lean() as any;
|
||||||
|
}
|
||||||
|
|
||||||
|
async create(data: Partial<SuperAdminModel>): Promise<SuperAdminDocument> {
|
||||||
|
return this.superAdminModel.create(data);
|
||||||
|
}
|
||||||
|
|
||||||
|
async updateOne(filter: FilterQuery<SuperAdminDocument>, update: any) {
|
||||||
|
return this.superAdminModel.updateOne(filter, update);
|
||||||
|
}
|
||||||
|
|
||||||
|
async findAll(): Promise<SuperAdminDocument[]> {
|
||||||
|
return this.superAdminModel.find().lean() as any;
|
||||||
|
}
|
||||||
|
}
|
||||||
30
src/super-admin/entities/schema/super-admin.schema.ts
Normal file
30
src/super-admin/entities/schema/super-admin.schema.ts
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
|
||||||
|
import { HydratedDocument } from "mongoose";
|
||||||
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
|
|
||||||
|
@Schema({
|
||||||
|
collection: "super-admins",
|
||||||
|
versionKey: false,
|
||||||
|
timestamps: true,
|
||||||
|
})
|
||||||
|
export class SuperAdminModel {
|
||||||
|
@Prop({ required: true, unique: true, index: true })
|
||||||
|
email: string;
|
||||||
|
|
||||||
|
@Prop({ required: true })
|
||||||
|
password: string;
|
||||||
|
|
||||||
|
@Prop({ required: true, default: RoleEnum.SUPER_ADMIN })
|
||||||
|
role: RoleEnum;
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
firstName?: string;
|
||||||
|
|
||||||
|
@Prop()
|
||||||
|
lastName?: string;
|
||||||
|
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type SuperAdminDocument = HydratedDocument<SuperAdminModel>;
|
||||||
|
export const SuperAdminSchema = SchemaFactory.createForClass(SuperAdminModel);
|
||||||
49
src/super-admin/guards/super-admin.guard.ts
Normal file
49
src/super-admin/guards/super-admin.guard.ts
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
import {
|
||||||
|
CanActivate,
|
||||||
|
ExecutionContext,
|
||||||
|
Injectable,
|
||||||
|
UnauthorizedException,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { JwtService } from "@nestjs/jwt";
|
||||||
|
import { Request } from "express";
|
||||||
|
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies a Bearer JWT and restricts access to `super_admin` role only.
|
||||||
|
* Use this guard on all endpoints that should be reachable only by the
|
||||||
|
* super-admin panel.
|
||||||
|
*/
|
||||||
|
@Injectable()
|
||||||
|
export class SuperAdminGuard implements CanActivate {
|
||||||
|
constructor(private readonly jwtService: JwtService) {}
|
||||||
|
|
||||||
|
async canActivate(context: ExecutionContext): Promise<boolean> {
|
||||||
|
const request = context.switchToHttp().getRequest<Request>();
|
||||||
|
const token = this.extractTokenFromHeader(request);
|
||||||
|
if (!token) {
|
||||||
|
throw new UnauthorizedException("Token not found");
|
||||||
|
}
|
||||||
|
|
||||||
|
let payload: any;
|
||||||
|
try {
|
||||||
|
payload = await this.jwtService.verifyAsync(token, {
|
||||||
|
secret: `${process.env.JWT_SECRET}`,
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
throw new UnauthorizedException("Invalid or expired token");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (payload?.role !== RoleEnum.SUPER_ADMIN) {
|
||||||
|
throw new UnauthorizedException("Super-admin access required");
|
||||||
|
}
|
||||||
|
|
||||||
|
(request as any).user = payload;
|
||||||
|
(request as any).identity = payload;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
private extractTokenFromHeader(request: Request): string | undefined {
|
||||||
|
const [type, token] = request.headers.authorization?.split(" ") ?? [];
|
||||||
|
return type === "Bearer" ? token : undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
501
src/super-admin/super-admin.controller.ts
Normal file
501
src/super-admin/super-admin.controller.ts
Normal file
@@ -0,0 +1,501 @@
|
|||||||
|
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 {
|
||||||
|
InsurerRegisterDto,
|
||||||
|
GenuineRegisterDto,
|
||||||
|
LegalRegisterDto,
|
||||||
|
} from "src/auth/dto/actor/register.actor.dto";
|
||||||
|
import { SystemSettingsService } from "src/system-settings/system-settings.service";
|
||||||
|
import {
|
||||||
|
SystemSettingsResponseDto,
|
||||||
|
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()
|
||||||
|
@UseGuards(SuperAdminGuard)
|
||||||
|
@Controller("super-admin")
|
||||||
|
export class SuperAdminController {
|
||||||
|
constructor(
|
||||||
|
private readonly superAdminService: SuperAdminService,
|
||||||
|
private readonly systemSettingsService: SystemSettingsService,
|
||||||
|
private readonly expertInsurerService: ExpertInsurerService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
// ── Super-admin account management ───────────────────────────────────────
|
||||||
|
|
||||||
|
@Get("accounts")
|
||||||
|
@ApiOperation({ summary: "List all super-admin accounts" })
|
||||||
|
listSuperAdmins() {
|
||||||
|
return this.superAdminService.listSuperAdmins();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("accounts")
|
||||||
|
@ApiOperation({ summary: "Create an additional super-admin account" })
|
||||||
|
@ApiBody({ type: CreateSuperAdminDto })
|
||||||
|
createSuperAdmin(@Body() body: CreateSuperAdminDto) {
|
||||||
|
return this.superAdminService.createSuperAdmin(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Client / insurer management ──────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("clients")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Create a new insurer client",
|
||||||
|
description: "Registers a new insurer (client) in the platform.",
|
||||||
|
})
|
||||||
|
@ApiBody({ type: ClientDto })
|
||||||
|
createClient(@Body() body: ClientDto) {
|
||||||
|
return this.superAdminService.createClient(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("clients")
|
||||||
|
@ApiOperation({ summary: "List all insurer clients" })
|
||||||
|
listClients() {
|
||||||
|
return this.superAdminService.listClients();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Get("clients/names")
|
||||||
|
@ApiOperation({ summary: "List insurer client names and IDs" })
|
||||||
|
listClientNames() {
|
||||||
|
return this.superAdminService.listClientNames();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Actor registration ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Post("register/insurer")
|
||||||
|
@ApiOperation({ summary: "Register a new insurer (company) actor" })
|
||||||
|
@ApiBody({ type: InsurerRegisterDto })
|
||||||
|
registerInsurer(@Body() body: InsurerRegisterDto) {
|
||||||
|
return this.superAdminService.registerInsurer(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("register/genuine")
|
||||||
|
@ApiOperation({
|
||||||
|
deprecated: true,
|
||||||
|
summary: "[DEPRECATED] Register a genuine actor",
|
||||||
|
description:
|
||||||
|
"Kept for legacy clients. Use the unified onboarding flow instead.",
|
||||||
|
})
|
||||||
|
@ApiBody({ type: GenuineRegisterDto })
|
||||||
|
registerGenuine(@Body() body: GenuineRegisterDto) {
|
||||||
|
return this.superAdminService.registerGenuine(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("register/legal")
|
||||||
|
@ApiOperation({
|
||||||
|
deprecated: true,
|
||||||
|
summary: "[DEPRECATED] Register a legal actor",
|
||||||
|
description:
|
||||||
|
"Kept for legacy clients. Use the unified onboarding flow instead.",
|
||||||
|
})
|
||||||
|
@ApiBody({ type: LegalRegisterDto })
|
||||||
|
registerLegal(@Body() body: LegalRegisterDto) {
|
||||||
|
return this.superAdminService.registerLegal(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("create-field-expert")
|
||||||
|
@ApiOperation({ summary: "Create a field expert" })
|
||||||
|
@ApiBody({ type: CreateFieldExpertAdminDto })
|
||||||
|
createFieldExpert(@Body() body: CreateFieldExpertAdminDto) {
|
||||||
|
return this.superAdminService.createFieldExpert(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Post("create-registrar")
|
||||||
|
@ApiOperation({ summary: "Create a registrar" })
|
||||||
|
@ApiBody({ type: CreateRegistrarAdminDto })
|
||||||
|
createRegistrar(@Body() body: CreateRegistrarAdminDto) {
|
||||||
|
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")
|
||||||
|
@ApiOperation({ summary: "Get global system settings" })
|
||||||
|
@ApiResponse({ status: 200, type: SystemSettingsResponseDto })
|
||||||
|
getSystemSettings() {
|
||||||
|
return this.systemSettingsService.getSettingsView();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch("system-settings")
|
||||||
|
@ApiOperation({ summary: "Update global system settings" })
|
||||||
|
@ApiBody({ type: UpdateSystemSettingsDto })
|
||||||
|
@ApiResponse({ status: 200, type: SystemSettingsResponseDto })
|
||||||
|
updateSystemSettings(@Body() body: UpdateSystemSettingsDto) {
|
||||||
|
return this.systemSettingsService.updateSettings(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Patch("external-inquiries-live")
|
||||||
|
@ApiOperation({
|
||||||
|
summary: "Enable or disable live external inquiries globally",
|
||||||
|
description:
|
||||||
|
"Updates `system_settings.externalApis.sandHubUseLiveApi`. When disabled, all inquiry flows use mocks.",
|
||||||
|
})
|
||||||
|
@ApiBody({ type: SetExternalInquiriesLiveDto })
|
||||||
|
@ApiResponse({ status: 200, type: SystemSettingsResponseDto })
|
||||||
|
setExternalInquiriesLive(@Body() body: SetExternalInquiriesLiveDto) {
|
||||||
|
return this.systemSettingsService.updateSettings({
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
36
src/super-admin/super-admin.module.ts
Normal file
36
src/super-admin/super-admin.module.ts
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
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";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Super-admin feature module.
|
||||||
|
*
|
||||||
|
* The `SuperAdminDbService` and its Mongoose model are registered in `AuthModule`
|
||||||
|
* (which is `@Global()`) to keep login routing central. This module only needs
|
||||||
|
* to import the other feature modules it proxies.
|
||||||
|
*
|
||||||
|
* Dependency chain:
|
||||||
|
* SuperAdminGuard ← JwtService (global via AuthModule JwtModule)
|
||||||
|
* SuperAdminService ← ActorAuthService (global), ClientService (ClientModule),
|
||||||
|
* SuperAdminDbService (global via AuthModule),
|
||||||
|
* FieldExpertDbService + RegistrarDbService (UsersModule)
|
||||||
|
*/
|
||||||
|
@Module({
|
||||||
|
imports: [
|
||||||
|
ClientModule,
|
||||||
|
SystemSettingsModule,
|
||||||
|
HashModule,
|
||||||
|
UsersModule,
|
||||||
|
ExpertInsurerModule,
|
||||||
|
],
|
||||||
|
controllers: [SuperAdminController],
|
||||||
|
providers: [SuperAdminService, SuperAdminGuard],
|
||||||
|
exports: [SuperAdminService, SuperAdminGuard],
|
||||||
|
})
|
||||||
|
export class SuperAdminModule {}
|
||||||
129
src/super-admin/super-admin.service.ts
Normal file
129
src/super-admin/super-admin.service.ts
Normal file
@@ -0,0 +1,129 @@
|
|||||||
|
import {
|
||||||
|
BadRequestException,
|
||||||
|
ConflictException,
|
||||||
|
Injectable,
|
||||||
|
NotFoundException,
|
||||||
|
} from "@nestjs/common";
|
||||||
|
import { Types } from "mongoose";
|
||||||
|
import { HashService } from "src/utils/hash/hash.service";
|
||||||
|
import { ClientService } from "src/client/client.service";
|
||||||
|
import { ClientDto } from "src/client/dto/create-client.dto";
|
||||||
|
import { ActorAuthService } from "src/auth/auth-services/actor.auth.service";
|
||||||
|
import {
|
||||||
|
InsurerRegisterDto,
|
||||||
|
GenuineRegisterDto,
|
||||||
|
LegalRegisterDto,
|
||||||
|
} from "src/auth/dto/actor/register.actor.dto";
|
||||||
|
import { SuperAdminDbService } from "./entities/db-service/super-admin.db.service";
|
||||||
|
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 {
|
||||||
|
constructor(
|
||||||
|
private readonly superAdminDbService: SuperAdminDbService,
|
||||||
|
private readonly hashService: HashService,
|
||||||
|
private readonly clientService: ClientService,
|
||||||
|
private readonly actorAuthService: ActorAuthService,
|
||||||
|
private readonly fieldExpertDbService: FieldExpertDbService,
|
||||||
|
private readonly registrarDbService: RegistrarDbService,
|
||||||
|
private readonly callCenterAgentDbService: CallCenterAgentDbService,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
/** List all super-admin accounts (sans password). */
|
||||||
|
async listSuperAdmins() {
|
||||||
|
const admins = await this.superAdminDbService.findAll();
|
||||||
|
return admins.map(({ password: _pw, ...rest }) => rest);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Create an additional super-admin account. */
|
||||||
|
async createSuperAdmin(body: CreateSuperAdminDto) {
|
||||||
|
const email = body.email.toLowerCase().trim();
|
||||||
|
const existing = await this.superAdminDbService.findOne({ email });
|
||||||
|
if (existing) {
|
||||||
|
throw new ConflictException(
|
||||||
|
"A super-admin with this email already exists.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const password = await this.hashService.hash(body.password);
|
||||||
|
const created = await this.superAdminDbService.create({
|
||||||
|
email,
|
||||||
|
password,
|
||||||
|
role: RoleEnum.SUPER_ADMIN,
|
||||||
|
firstName: body.firstName,
|
||||||
|
lastName: body.lastName,
|
||||||
|
});
|
||||||
|
const { password: _pw, ...rest } = (created as any).toObject
|
||||||
|
? (created as any).toObject()
|
||||||
|
: (created as any);
|
||||||
|
return rest;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Client management ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async createClient(body: ClientDto) {
|
||||||
|
return this.clientService.addClient(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
async listClients() {
|
||||||
|
return this.clientService.getClients();
|
||||||
|
}
|
||||||
|
|
||||||
|
async listClientNames() {
|
||||||
|
return this.clientService.getClientList();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Actor registration proxies ───────────────────────────────────────────
|
||||||
|
|
||||||
|
async registerInsurer(body: InsurerRegisterDto) {
|
||||||
|
return this.actorAuthService.insurerRegister(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
async registerGenuine(body: GenuineRegisterDto) {
|
||||||
|
return this.actorAuthService.genuineRegister(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
async registerLegal(body: LegalRegisterDto) {
|
||||||
|
return this.actorAuthService.legalRegister(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
async createFieldExpert(body: CreateFieldExpertAdminDto) {
|
||||||
|
return this.actorAuthService.createFieldExpertMock(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -23,7 +23,7 @@ export class SystemSettingsController {
|
|||||||
|
|
||||||
@Get()
|
@Get()
|
||||||
@UseGuards(SettingsJwtGuard, RolesGuard)
|
@UseGuards(SettingsJwtGuard, RolesGuard)
|
||||||
@Roles(RoleEnum.ADMIN, RoleEnum.COMPANY)
|
@Roles(RoleEnum.ADMIN, RoleEnum.COMPANY, RoleEnum.SUPER_ADMIN)
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Get global system settings (external API toggles)",
|
summary: "Get global system settings (external API toggles)",
|
||||||
description:
|
description:
|
||||||
@@ -36,7 +36,7 @@ export class SystemSettingsController {
|
|||||||
|
|
||||||
@Patch()
|
@Patch()
|
||||||
@UseGuards(SettingsJwtGuard, RolesGuard)
|
@UseGuards(SettingsJwtGuard, RolesGuard)
|
||||||
@Roles(RoleEnum.ADMIN)
|
@Roles(RoleEnum.ADMIN, RoleEnum.SUPER_ADMIN)
|
||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Update global system settings",
|
summary: "Update global system settings",
|
||||||
description:
|
description:
|
||||||
|
|||||||
@@ -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 })[]
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
}
|
||||||
61
src/users/entities/schema/call-center-agent.schema.ts
Normal file
61
src/users/entities/schema/call-center-agent.schema.ts
Normal 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();
|
||||||
|
});
|
||||||
@@ -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 { ExpertFileActivityDbService } from "./entities/db-service/expert-file-activity.db.service";
|
||||||
import { FileMakerDbService } from "./entities/db-service/file-maker.db.service";
|
import { FileMakerDbService } from "./entities/db-service/file-maker.db.service";
|
||||||
import { FileReviewerDbService } from "./entities/db-service/file-reviewer.db.service";
|
import { FileReviewerDbService } from "./entities/db-service/file-reviewer.db.service";
|
||||||
|
import { CallCenterAgentDbService } from "./entities/db-service/call-center-agent.db.service";
|
||||||
import {
|
import {
|
||||||
DamageExpertDbSchema,
|
DamageExpertDbSchema,
|
||||||
DamageExpertModel,
|
DamageExpertModel,
|
||||||
@@ -41,6 +42,10 @@ import {
|
|||||||
FileReviewerDbSchema,
|
FileReviewerDbSchema,
|
||||||
FileReviewerModel,
|
FileReviewerModel,
|
||||||
} from "./entities/schema/file-reviewer.schema";
|
} from "./entities/schema/file-reviewer.schema";
|
||||||
|
import {
|
||||||
|
CallCenterAgentDbSchema,
|
||||||
|
CallCenterAgentModel,
|
||||||
|
} from "./entities/schema/call-center-agent.schema";
|
||||||
|
|
||||||
@Module({
|
@Module({
|
||||||
imports: [
|
imports: [
|
||||||
@@ -54,6 +59,7 @@ import {
|
|||||||
{ name: ExpertFileActivity.name, schema: ExpertFileActivitySchema },
|
{ name: ExpertFileActivity.name, schema: ExpertFileActivitySchema },
|
||||||
{ name: FileMakerModel.name, schema: FileMakerDbSchema },
|
{ name: FileMakerModel.name, schema: FileMakerDbSchema },
|
||||||
{ name: FileReviewerModel.name, schema: FileReviewerDbSchema },
|
{ name: FileReviewerModel.name, schema: FileReviewerDbSchema },
|
||||||
|
{ name: CallCenterAgentModel.name, schema: CallCenterAgentDbSchema },
|
||||||
]),
|
]),
|
||||||
HashModule,
|
HashModule,
|
||||||
],
|
],
|
||||||
@@ -68,6 +74,7 @@ import {
|
|||||||
ExpertFileActivityDbService,
|
ExpertFileActivityDbService,
|
||||||
FileMakerDbService,
|
FileMakerDbService,
|
||||||
FileReviewerDbService,
|
FileReviewerDbService,
|
||||||
|
CallCenterAgentDbService,
|
||||||
],
|
],
|
||||||
exports: [
|
exports: [
|
||||||
UserDbService,
|
UserDbService,
|
||||||
@@ -79,6 +86,7 @@ import {
|
|||||||
ExpertFileActivityDbService,
|
ExpertFileActivityDbService,
|
||||||
FileMakerDbService,
|
FileMakerDbService,
|
||||||
FileReviewerDbService,
|
FileReviewerDbService,
|
||||||
|
CallCenterAgentDbService,
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
export class UsersModule {}
|
export class UsersModule {}
|
||||||
|
|||||||
8
src/utils/plate-normalizer/plate-normalizer.module.ts
Normal file
8
src/utils/plate-normalizer/plate-normalizer.module.ts
Normal file
@@ -0,0 +1,8 @@
|
|||||||
|
import { Module } from "@nestjs/common";
|
||||||
|
import { PlateNormalizerService } from "./plate-normalizer.service";
|
||||||
|
|
||||||
|
@Module({
|
||||||
|
providers: [PlateNormalizerService],
|
||||||
|
exports: [PlateNormalizerService],
|
||||||
|
})
|
||||||
|
export class PlateNormalizerModule {}
|
||||||
79
src/utils/plate-normalizer/plate-normalizer.service.ts
Normal file
79
src/utils/plate-normalizer/plate-normalizer.service.ts
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
131
src/utils/plate-normalizer/plate-normalizer.spec.ts
Normal file
131
src/utils/plate-normalizer/plate-normalizer.spec.ts
Normal 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 3 (U+FF13) → ASCII 3
|
||||||
|
expect(normalizePlateText("3")).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();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user