From a2aa8c07111f1bfc3b4a4268f17e2a22a2b774c3 Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Tue, 29 Sep 2026 16:51:24 +0330 Subject: [PATCH] update --- scripts/data/fanavaran-flow-ui.html | 1658 +++++ scripts/fanavaran-flow-ui-server.js | 877 +++ .../claim-request-management.service.ts | 6011 ----------------- 3 files changed, 2535 insertions(+), 6011 deletions(-) create mode 100644 scripts/data/fanavaran-flow-ui.html create mode 100755 scripts/fanavaran-flow-ui-server.js diff --git a/scripts/data/fanavaran-flow-ui.html b/scripts/data/fanavaran-flow-ui.html new file mode 100644 index 0000000..278f46d --- /dev/null +++ b/scripts/data/fanavaran-flow-ui.html @@ -0,0 +1,1658 @@ + + + + + + Fanavaran ثالث — تست ۴ مرحله + + + + + + +
+
+

Fanavaran ثالث — تست مرحله‌ای

+
فرم → ذخیره env → Submit هر مرحله روی Fanavaran
+
+
+
+ + در حال اتصال… +
+ +
+
+ +
+
+
+

0 اطلاعات خودروها

+

جدا از ۴ مرحله Submit — پلاک: ۵۶ ی ۷۷۳ | ۱۰

+
+ +
+

خودرو مقصر پلاک + هویت خودرو

+
+ + +
+
+ + +
+
+
+
دو رقم
+
حرف
+
سه رقم
+
+
+
+
I.R.
+
ایران
+ +
+
+
56 د 394 | 66
+
+ +
+
+
نتیجه استعلام / مشخصات فنی
+
+ + + +
+
+ +
+ +
+

خودرو زیان‌دیده GEN.12

+
+ + +
+
+ + +
+
+
+
دو رقم
+
حرف
+
سه رقم
+
+
+
+
I.R.
+
ایران
+ +
+
+
95 ی 773 | 10
+
+ +
+
+
نتیجه استعلام / مشخصات فنی و بیمه‌نامه
+
+ + + + + + + + +
+
+ +
+
+ +
+
+

1 تنانت / شعبه / کارشناس

+
+ + + + + + + + + +
+
+ +
+

2 طرف اول — مقصر

+ +

+
+

بیمه‌گذار (Policy inquiry)

+
+ + + +
+
+
+

مالک

+
+ + + +
+
+
+

راننده مقصر

+
+ + + + + + +
+
+
+ +
+

3 طرف دوم — زیان‌دیده

+ +

+
+

راننده زیان‌دیده (GEN.12)

+
+ + + + + + +
+
+
+ +
+

4 حادثه / مبالغ / پیوست

+
+ + + + + + + + + + +
+
+
+ +
+
+

▶ مراحل Submit

+
+
+ + + + +
+

برای پرونده جدید اول این دکمه را بزنید تا CLAIM_ID / DMG_CASE_ID و بقیه idها پاک شوند؛ داده‌های فرم می‌مانند.

+
+
+
+
+

۱ — GEN.03 Base

+

Policy inquiry + پرونده ثالث

+
+ +
+
+
+
+
+

۲ — GEN.12 Damage

+

Driver inquiry / GEN.44 + dmg-case

+
+ +
+
+
+
+
+

۳ — GEN.07 Attachments

+

آپلود فایل پیوست

+
+ +
+
+
+
+
+

۴ — GEN.08 Expertise

+

ثبت کارشناسی

+
+ +
+
+
+

+
Ready. Start server if pill is red: +node scripts/fanavaran-flow-ui-server.js
+
+ +
+

env خروجی

+
+ + +
+ +
+
+
+ + + + diff --git a/scripts/fanavaran-flow-ui-server.js b/scripts/fanavaran-flow-ui-server.js new file mode 100755 index 0000000..b0099c7 --- /dev/null +++ b/scripts/fanavaran-flow-ui-server.js @@ -0,0 +1,877 @@ +#!/usr/bin/env node +/** + * Local UI server for Fanavaran third-party flow test. + * + * node scripts/fanavaran-flow-ui-server.js + * open http://127.0.0.1:17824 + */ +const http = require("http"); +const fs = require("fs"); +const path = require("path"); +const { spawn } = require("child_process"); + +const ROOT = path.resolve(__dirname, ".."); +const UI_HTML = path.join(__dirname, "data", "fanavaran-flow-ui.html"); +const ENV_PATH = path.join(__dirname, "data", "fanavaran-flow.parsian.env"); +const SCRIPT = path.join(__dirname, "fanavaran-flow-test.sh"); +const OFFLINE_SEEDS = path.join(__dirname, "data", "offline-plate-seeds.json"); +const CASES_DIR = path.join(__dirname, "data", "fanavaran-flow-cases"); +const PORT = Number(process.env.FANAVARAN_FLOW_UI_PORT || 17824); +const HOST = process.env.FANAVARAN_FLOW_UI_HOST || "127.0.0.1"; + +loadRootDotEnv(); + +let running = false; +let sandhubToken = null; +let sandhubTokenAt = 0; + +function loadRootDotEnv() { + const file = path.join(ROOT, ".env"); + if (!fs.existsSync(file)) return; + for (const line of fs.readFileSync(file, "utf8").split("\n")) { + const t = line.trim(); + if (!t || t.startsWith("#")) continue; + const i = t.indexOf("="); + if (i < 0) continue; + const key = t.slice(0, i).trim(); + let val = t.slice(i + 1).trim(); + if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { + val = val.slice(1, -1); + } + if (val.includes("${")) continue; + if (!process.env[key]) process.env[key] = val; + } +} + +function httpJson(method, url, body, headers) { + return new Promise((resolve) => { + const args = ["-sS", "--max-time", "45", "-X", method, url, "-H", "Accept: application/json"]; + for (const [k, v] of Object.entries(headers || {})) { + args.push("-H", `${k}: ${v}`); + } + if (body !== undefined) { + args.push("-H", "Content-Type: application/json", "--data", JSON.stringify(body)); + } + const child = spawn("curl", args); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (d) => { + stdout += d.toString(); + }); + child.stderr.on("data", (d) => { + stderr += d.toString(); + }); + child.on("close", (code) => { + let json = null; + try { + json = JSON.parse(stdout || "null"); + } catch { + json = null; + } + resolve({ code, stdout, stderr, json }); + }); + }); +} + +function normalizeDigits(v) { + return String(v || "") + .replace(/[۰-۹]/g, (d) => "۰۱۲۳۴۵۶۷۸۹".indexOf(d)) + .replace(/[٠-٩]/g, (d) => "٠١٢٣٤٥٦٧٨٩".indexOf(d)) + .replace(/\D/g, ""); +} + +function normalizeLetter(v) { + return String(v || "") + .replace(/[\u200c\u200d]/g, "") + .replace(/ي/g, "ی") + .replace(/ك/g, "ک") + .trim(); +} + +function pickVehicleFields(src) { + const d = src && typeof src === "object" ? src : {}; + const data = d.data && typeof d.data === "object" ? { ...d, ...d.data } : d; + const motor = + data.MotorNo || data.MtrNum || data.mtrnum || data.EngineNumberField || data.motorNumber || ""; + const chassis = + data.ChassisNo || data.ShsNum || data.ShsNam || data.shsNam || data.ChassisNumberField || data.chassisNumber || ""; + const vin = data.VIN || data.vin || data.VinNumberField || chassis || ""; + const built = + data.BuiltYear || data.PrdDte || data.ModelField || data.ModelCii || data.builtYear || ""; + const policyNo = + data.PolicyNo || data.PrntCmpDocNo || data.PrntPlcyCmpDocNo || data.printNumber || ""; + const policyCi = data.PolicyCINumber || data.PlcyUnqCod || data.ThirdPolicyCode || ""; + const begin = data.BeginDate || data.HBgnDte || data.StartDate || ""; + const end = data.EndDate || data.HEndDte || data.EndDate || ""; + return { + MOTOR_NO: String(motor || ""), + CHASSIS_NO: String(chassis || ""), + VIN: String(vin || ""), + BUILT_YEAR: String(built || "").replace(/\D/g, "").slice(0, 4), + POLICY_NO: String(policyNo || ""), + POLICY_CI_NUMBER: String(policyCi || ""), + BEGIN_DATE: String(begin || ""), + END_DATE: String(end || ""), + }; +} + +function findOfflinePlate(input) { + if (!fs.existsSync(OFFLINE_SEEDS)) return null; + const rows = JSON.parse(fs.readFileSync(OFFLINE_SEEDS, "utf8")); + const nc = normalizeDigits(input.nationalCode); + const mode = String(input.mode || "plate").toLowerCase(); + let hit = null; + if (mode === "vin") { + const vin = String(input.vin || input.chassisNo || "") + .trim() + .toUpperCase(); + if (!vin) return null; + hit = rows.find( + (r) => + normalizeDigits(r.nationalCode) === nc && + String(r.vehicle?.VIN || r.vehicle?.ChassisNo || "") + .trim() + .toUpperCase() === vin, + ); + } else { + const left = normalizeDigits(input.left); + const letter = normalizeLetter(input.letter); + const right = normalizeDigits(input.right); + const serial = normalizeDigits(input.serial); + hit = rows.find( + (r) => + normalizeDigits(r.nationalCode) === nc && + normalizeDigits(r.plate?.leftDigits) === left && + normalizeLetter(r.plate?.centerAlphabet) === letter && + normalizeDigits(r.plate?.centerDigits) === right && + normalizeDigits(r.plate?.ir) === serial, + ); + } + if (!hit) return null; + return { + source: "OFFLINE_SEED", + label: hit.label || "", + mode, + vehicle: pickVehicleFields(hit.vehicle || {}), + plate: hit.plate || null, + raw: hit, + }; +} + +async function getSandhubToken() { + if (sandhubToken && Date.now() - sandhubTokenAt < 20 * 60 * 1000) return sandhubToken; + const loginUrl = process.env.SANHUB_URL_LOGIN || "http://82.99.202.245:3027/user/login"; + const user = process.env.SANHUB_USERNAME || "default@admin.com"; + const pass = process.env.SANHUB_PASSWORD || "123321"; + const res = await httpJson("POST", loginUrl, { email: user, password: pass }); + const token = res.json?.accessToken || res.json?.data?.accessToken; + if (!token) { + throw new Error(res.json?.message || res.stderr || "SandHub login failed"); + } + sandhubToken = token; + sandhubTokenAt = Date.now(); + return token; +} + +async function esgLoginToken(esgUrl) { + const login = await httpJson("POST", `${esgUrl.replace(/\/$/, "")}/auth/login`, { + username: process.env.ESG_USERNAME || "", + password: process.env.ESG_PASSWORD || "", + }); + return login.json?.accessToken || login.json?.data?.accessToken || ""; +} + +async function livePlateInquiry(input) { + const esgUrl = process.env.ESG_URL; + if (esgUrl) { + const token = await esgLoginToken(esgUrl); + if (token) { + const res = await httpJson( + "POST", + `${esgUrl.replace(/\/$/, "")}/inquiry/carByPlate`, + { + nationalCode: normalizeDigits(input.nationalCode), + plk1: normalizeDigits(input.left), + plk2: normalizeLetter(input.letter), + plk3: normalizeDigits(input.right), + plksrl: normalizeDigits(input.serial), + }, + { Authorization: `Bearer ${token}` }, + ); + if (res.json && !res.json.Error) { + return { + source: "ESG_carByPlate", + mode: "plate", + vehicle: pickVehicleFields(res.json), + raw: res.json, + }; + } + } + } + + const token = await getSandhubToken(); + const base = (process.env.SANHUB_BASE_URL || "http://82.99.202.245:3027").replace(/\/$/, ""); + const res = await httpJson( + "POST", + `${base}/block-inquiry-tejarat`, + { + leftTwoDigits: normalizeDigits(input.left), + serialLetter: normalizeLetter(input.letter), + threeDigits: normalizeDigits(input.right), + rightTwoDigits: normalizeDigits(input.serial), + nationalCode: normalizeDigits(input.nationalCode), + }, + { Authorization: `Bearer ${token}` }, + ); + if (!res.json) { + throw new Error(res.stderr || "empty inquiry response"); + } + if (res.json.Error || res.json.HasError) { + const msg = + res.json.Error?.Message || + res.json.Message || + res.json.message || + "plate inquiry failed"; + throw new Error(String(msg)); + } + return { + source: "TEJARAT_block-inquiry", + mode: "plate", + vehicle: pickVehicleFields(res.json), + raw: res.json, + }; +} + +async function liveVinInquiry(input) { + const vin = String(input.vin || input.chassisNo || "").trim(); + if (!vin) throw new Error("VIN / chassis required"); + const esgUrl = process.env.ESG_URL; + if (!esgUrl) { + throw new Error("ESG_URL not set — VIN inquiry needs ESG carByChassis"); + } + const token = await esgLoginToken(esgUrl); + if (!token) throw new Error("ESG login failed for VIN inquiry"); + const res = await httpJson( + "POST", + `${esgUrl.replace(/\/$/, "")}/inquiry/carByChassis`, + { + nationalCode: normalizeDigits(input.nationalCode), + chassisNo: vin, + }, + { Authorization: `Bearer ${token}` }, + ); + if (!res.json) throw new Error(res.stderr || "empty VIN inquiry response"); + if (res.json.Error || res.json.HasError) { + const msg = + res.json.Error?.Message || + res.json.Message || + res.json.message || + "VIN inquiry failed"; + throw new Error(String(msg)); + } + return { + source: "ESG_carByChassis", + mode: "vin", + vehicle: pickVehicleFields(res.json), + raw: res.json, + }; +} + +async function inquireVehicle(input) { + const mode = String(input.mode || "plate").toLowerCase() === "vin" ? "vin" : "plate"; + const payload = { ...input, mode }; + const offline = findOfflinePlate(payload); + if (offline) return { ok: true, ...offline }; + try { + const live = + mode === "vin" ? await liveVinInquiry(payload) : await livePlateInquiry(payload); + return { ok: true, ...live }; + } catch (err) { + return { ok: false, error: String(err.message || err), mode }; + } +} + +async function inquirePlate(input) { + return inquireVehicle({ ...input, mode: "plate" }); +} + +const LOOKUP_CACHE = { + vehicleKinds: null, + carComponents: null, +}; + +function loadLookupJson(relPath) { + const full = path.join(ROOT, "files", "fanavaran-lookups", "parsian", relPath); + if (!fs.existsSync(full)) return []; + const data = JSON.parse(fs.readFileSync(full, "utf8")); + return Array.isArray(data) ? data : data.value || data.data || []; +} + +function getVehicleKinds() { + if (!LOOKUP_CACHE.vehicleKinds) { + LOOKUP_CACHE.vehicleKinds = loadLookupJson("vehicle-kinds.json") + .filter((r) => r && r.Id != null) + .map((r) => ({ + id: String(r.Id), + caption: String(r.Caption || ""), + system: String(r.VehicleSystemCaption || ""), + active: Number(r.IsActive) === 1, + })); + } + return LOOKUP_CACHE.vehicleKinds; +} + +function getCarComponents() { + if (!LOOKUP_CACHE.carComponents) { + LOOKUP_CACHE.carComponents = loadLookupJson("car-components.json") + .filter((r) => r && r.Id != null) + .map((r) => ({ + id: String(r.Id), + caption: String(r.Caption || ""), + })); + } + return LOOKUP_CACHE.carComponents; +} + +function filterOptions(rows, q, limit = 40) { + const query = String(q || "").trim().toLowerCase(); + let list = rows; + if (query) { + list = rows.filter((r) => { + const hay = `${r.id} ${r.caption} ${r.system || ""}`.toLowerCase(); + return hay.includes(query); + }); + list.sort((a, b) => { + const aId = a.id === query ? 0 : a.id.startsWith(query) ? 1 : 2; + const bId = b.id === query ? 0 : b.id.startsWith(query) ? 1 : 2; + if (aId !== bId) return aId - bId; + return a.caption.localeCompare(b.caption, "fa"); + }); + } else { + list = rows.slice().sort((a, b) => Number(a.id) - Number(b.id)); + } + return list.slice(0, limit); +} + +function loadAuthTokens(client) { + const file = path.join(ROOT, "files", "fanavaran-auth", client, "tokens.env"); + if (!fs.existsSync(file)) return null; + return parseEnvText(fs.readFileSync(file, "utf8")); +} + +function curlJson(method, url, headers, proxy) { + return new Promise((resolve) => { + const args = ["-sS", "--max-time", "40", "-X", method, url]; + if (proxy) args.push("--proxy", proxy); + for (const [k, v] of Object.entries(headers || {})) { + args.push("-H", `${k}: ${v}`); + } + const child = spawn("curl", args); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (d) => { + stdout += d.toString(); + }); + child.stderr.on("data", (d) => { + stderr += d.toString(); + }); + child.on("close", (code) => { + let json = null; + try { + json = JSON.parse(stdout || "null"); + } catch { + json = null; + } + resolve({ code, stdout, stderr, json }); + }); + }); +} + +async function inquireParties({ nationalCode, birthYear, birthMonth, birthDay, client, location, proxy }) { + const tokens = loadAuthTokens(client || "parsian"); + if (!tokens || !tokens.AUTHENTICATION_TOKEN) { + return { ok: false, error: "No cached Fanavaran token. Run a stage once or scripts/fanavaran-auth.sh parsian" }; + } + const base = + tokens.FANAVARAN_BIME_URL || + "https://apimanager.iraneit.com/BimeApiManager/api/BimeApi/v2.0"; + const qs = new URLSearchParams({ + NationalCode: String(nationalCode || ""), + BirthYear: String(birthYear || ""), + BirthMonth: String(birthMonth || ""), + BirthDay: String(birthDay || ""), + }); + const url = `${base}/common/parties/inquiry-by-unique-identifier?${qs}`; + const result = await curlJson( + "GET", + url, + { + authenticationToken: tokens.AUTHENTICATION_TOKEN, + CorpId: tokens.CORP_ID || "543", + ContractId: tokens.CONTRACT_ID || "28", + Location: location || tokens.LOCATION || "210110", + }, + proxy || "", + ); + const rows = Array.isArray(result.json) + ? result.json + : result.json?.value || result.json?.data || []; + if (!Array.isArray(rows)) { + return { + ok: false, + error: result.json?.Message || result.stderr || "inquiry failed", + raw: result.json, + }; + } + const options = rows + .filter((r) => r && r.Id != null) + .map((r) => ({ + id: String(r.Id), + caption: [r.Name, r.LastName].filter(Boolean).join(" ").trim() || String(r.NationalCode || r.Id), + roleId: r.RoleId, + nationalCode: r.NationalCode, + fatherName: r.FatherName || "", + })); + return { ok: true, options, count: options.length }; +} + +function readBody(req) { + return new Promise((resolve, reject) => { + const chunks = []; + req.on("data", (c) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + if (!raw) return resolve({}); + try { + resolve(JSON.parse(raw)); + } catch (err) { + reject(err); + } + }); + req.on("error", reject); + }); +} + +function send(res, status, data, type = "application/json; charset=utf-8") { + const body = typeof data === "string" ? data : JSON.stringify(data, null, 2); + res.writeHead(status, { + "Content-Type": type, + "Cache-Control": "no-store", + }); + res.end(body); +} + +function parseEnvText(text) { + const out = {}; + for (const line of text.split("\n")) { + const t = line.trim(); + if (!t || t.startsWith("#")) continue; + const i = t.indexOf("="); + if (i < 0) continue; + let v = t.slice(i + 1); + if ( + (v.startsWith('"') && v.endsWith('"')) || + (v.startsWith("'") && v.endsWith("'")) + ) { + v = v.slice(1, -1); + } + out[t.slice(0, i)] = v; + } + return out; +} + +function envObjectToText(obj) { + const order = [ + "FANAVARAN_CLIENT", + "CURL_PROXY", + "LOCATION", + "", + "CLAIM_EXPERT_ID", + "EXPERTISE_CLAIM_EXPERT_ID", + "ACCIDENT_CULPRIT_ID", + "CLAIM_FILE_TYPE_ID", + "VEHICLE_KIND_ID", + "DMG_SECTION_ID", + "INSURANCE_CORP_ID", + "", + "CULPRIT_TYPE_ID", + "GUILTY_NATIONAL_CODE", + "ACCIDENT_DATE", + "ACCIDENT_TIME", + "CULPRIT_LICENCE_NO", + "CULPRIT_LICENCE_ISSU_DATE", + "", + "DRIVER_NATIONAL_CODE", + "DRIVER_BIRTH_YEAR", + "DRIVER_BIRTH_MONTH", + "DRIVER_BIRTH_DAY", + "DRIVER_IS_INSURER", + "DRIVER_IS_OWNER", + "LICENCE_NO", + "LICENCE_ISSU_DATE", + "DESC", + "", + "PLAQUE_LEFT_NO", + "PLAQUE_RIGHT_NO", + "PLAQUE_SERIAL", + "PLAQUE_MIDDLE_CODE_ID", + "PLAQUE_NO", + "BUILT_YEAR", + "VIN", + "CHASSIS_NO", + "MOTOR_NO", + "POLICY_NO", + "POLICY_CI_NUMBER", + "BEGIN_DATE", + "END_DATE", + "", + "ATTACHMENT_FILE", + "", + "DMG_ASSESSMENT_DATE", + "INSPECTION_TIME", + "ESTIMATE_AMOUNT", + "REPAIR_WAGE", + "COMPONENT_REPLACEMENT_COST", + "WASTE_VALUE", + "", + "POLICY_ID", + "CLAIM_ID", + "CLAIM_NO", + "DRIVER_ID", + "INSURANCE_CORP_ID_NUM", + "DMG_CASE_ID", + "EXPERTISE_ID", + ]; + const seen = new Set(); + const lines = ["# Generated by fanavaran-flow-ui"]; + for (const key of order) { + if (key === "") { + lines.push(""); + continue; + } + seen.add(key); + const val = obj[key] ?? ""; + lines.push(`${key}=${val}`); + } + for (const [k, v] of Object.entries(obj)) { + if (seen.has(k)) continue; + lines.push(`${k}=${v ?? ""}`); + } + lines.push(""); + return lines.join("\n"); +} + +function writeEnv(obj) { + fs.writeFileSync(ENV_PATH, envObjectToText(obj), "utf8"); +} + +function loadEnv() { + if (!fs.existsSync(ENV_PATH)) return {}; + return parseEnvText(fs.readFileSync(ENV_PATH, "utf8")); +} + +function ensureCasesDir() { + fs.mkdirSync(CASES_DIR, { recursive: true }); +} + +function casePath(claimId) { + const id = String(claimId || "").replace(/[^\w.-]/g, ""); + if (!id) throw new Error("CLAIM_ID required"); + return path.join(CASES_DIR, `${id}.json`); +} + +function saveCaseSnapshot(claimId, payload) { + ensureCasesDir(); + const file = casePath(claimId); + const body = { + claimId: String(claimId), + savedAt: new Date().toISOString(), + env: payload.env || {}, + ui: payload.ui || {}, + }; + fs.writeFileSync(file, JSON.stringify(body, null, 2) + "\n", "utf8"); + return body; +} + +function loadCaseSnapshot(claimId) { + const file = casePath(claimId); + if (!fs.existsSync(file)) return null; + return JSON.parse(fs.readFileSync(file, "utf8")); +} + +function listCaseSnapshots() { + ensureCasesDir(); + return fs + .readdirSync(CASES_DIR) + .filter((f) => f.endsWith(".json")) + .map((f) => { + try { + const j = JSON.parse(fs.readFileSync(path.join(CASES_DIR, f), "utf8")); + return { + claimId: j.claimId || f.replace(/\.json$/, ""), + claimNo: j.env?.CLAIM_NO || "", + savedAt: j.savedAt || "", + location: j.env?.LOCATION || "", + }; + } catch { + return { claimId: f.replace(/\.json$/, ""), savedAt: "" }; + } + }) + .sort((a, b) => String(b.savedAt).localeCompare(String(a.savedAt))); +} + +function runStage(stage) { + return new Promise((resolve) => { + const args = ["--env", ENV_PATH, "--stages", stage, "--yes"]; + const child = spawn("bash", [SCRIPT, ...args], { + cwd: ROOT, + env: process.env, + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (d) => { + stdout += d.toString(); + }); + child.stderr.on("data", (d) => { + stderr += d.toString(); + }); + child.on("close", (code) => { + const env = loadEnv(); + resolve({ + ok: code === 0, + code, + stage, + stdout, + stderr, + ids: { + POLICY_ID: env.POLICY_ID || "", + CLAIM_ID: env.CLAIM_ID || "", + CLAIM_NO: env.CLAIM_NO || "", + DRIVER_ID: env.DRIVER_ID || "", + INSURANCE_CORP_ID_NUM: env.INSURANCE_CORP_ID_NUM || "", + DMG_CASE_ID: env.DMG_CASE_ID || "", + EXPERTISE_ID: env.EXPERTISE_ID || "", + ACCIDENT_CULPRIT_ID: env.ACCIDENT_CULPRIT_ID || "", + }, + }); + }); + }); +} + +const server = http.createServer(async (req, res) => { + const url = new URL(req.url, `http://${HOST}:${PORT}`); + + try { + if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) { + send(res, 200, fs.readFileSync(UI_HTML, "utf8"), "text/html; charset=utf-8"); + return; + } + + if (req.method === "GET" && url.pathname === "/api/health") { + send(res, 200, { ok: true, running, envPath: ENV_PATH }); + return; + } + + if (req.method === "GET" && url.pathname === "/api/env") { + send(res, 200, { env: loadEnv(), path: ENV_PATH }); + return; + } + + if (req.method === "POST" && url.pathname === "/api/env") { + const body = await readBody(req); + if (!body || typeof body.env !== "object") { + send(res, 400, { ok: false, error: "body.env required" }); + return; + } + writeEnv(body.env); + const claimId = body.env.CLAIM_ID || body.claimId || ""; + let savedCase = null; + if (claimId) { + savedCase = saveCaseSnapshot(claimId, { env: body.env, ui: body.ui || {} }); + } + send(res, 200, { ok: true, env: loadEnv(), case: savedCase }); + return; + } + + if (req.method === "GET" && url.pathname === "/api/cases") { + send(res, 200, { cases: listCaseSnapshots() }); + return; + } + + if (req.method === "GET" && url.pathname.startsWith("/api/cases/")) { + const claimId = decodeURIComponent(url.pathname.slice("/api/cases/".length)); + const snap = loadCaseSnapshot(claimId); + if (!snap) { + send(res, 404, { ok: false, error: "case not found" }); + return; + } + send(res, 200, { ok: true, ...snap }); + return; + } + + if (req.method === "POST" && url.pathname.startsWith("/api/cases/")) { + const claimId = decodeURIComponent(url.pathname.slice("/api/cases/".length)); + const body = await readBody(req); + const env = body.env || loadEnv(); + env.CLAIM_ID = env.CLAIM_ID || claimId; + writeEnv(env); + const saved = saveCaseSnapshot(claimId, { env, ui: body.ui || {} }); + send(res, 200, { ok: true, ...saved }); + return; + } + + if (req.method === "GET" && url.pathname === "/api/lookups/vehicle-kinds") { + const q = url.searchParams.get("q") || ""; + const id = url.searchParams.get("id") || ""; + const rows = getVehicleKinds(); + if (id) { + const one = rows.find((r) => r.id === String(id)); + send(res, 200, { options: one ? [one] : [], total: rows.length }); + return; + } + send(res, 200, { + options: filterOptions(rows, q, Number(url.searchParams.get("limit") || 40)), + total: rows.length, + }); + return; + } + + if (req.method === "GET" && url.pathname === "/api/lookups/car-components") { + const q = url.searchParams.get("q") || ""; + const id = url.searchParams.get("id") || ""; + const rows = getCarComponents(); + if (id) { + const one = rows.find((r) => r.id === String(id)); + send(res, 200, { options: one ? [one] : [], total: rows.length }); + return; + } + send(res, 200, { + options: filterOptions(rows, q, Number(url.searchParams.get("limit") || 80)), + total: rows.length, + }); + return; + } + + if (req.method === "GET" && url.pathname === "/api/parties/inquiry") { + const nationalCode = url.searchParams.get("nationalCode") || ""; + const birth = (url.searchParams.get("birth") || "").replace(/\D/g, ""); + let birthYear = url.searchParams.get("birthYear") || ""; + let birthMonth = url.searchParams.get("birthMonth") || ""; + let birthDay = url.searchParams.get("birthDay") || ""; + if (birth.length === 8) { + birthYear = birth.slice(0, 4); + birthMonth = String(Number(birth.slice(4, 6))); + birthDay = String(Number(birth.slice(6, 8))); + } + if (!nationalCode || !birthYear) { + send(res, 400, { ok: false, error: "nationalCode + birth (YYYYMMDD) required" }); + return; + } + const env = loadEnv(); + const result = await inquireParties({ + nationalCode, + birthYear, + birthMonth, + birthDay, + client: env.FANAVARAN_CLIENT || "parsian", + location: env.LOCATION || url.searchParams.get("location") || "210110", + proxy: env.CURL_PROXY || process.env.CURL_PROXY || "", + }); + send(res, result.ok ? 200 : 502, result); + return; + } + + if (req.method === "POST" && url.pathname === "/api/plate-inquiry") { + const body = await readBody(req); + const mode = String(body.mode || "plate").toLowerCase() === "vin" ? "vin" : "plate"; + const nationalCode = body.nationalCode || ""; + if (!nationalCode) { + send(res, 400, { ok: false, error: "nationalCode required" }); + return; + } + if (mode === "vin") { + const vin = body.vin || body.chassisNo || body.VIN || ""; + if (!String(vin).trim()) { + send(res, 400, { ok: false, error: "nationalCode + VIN/chassis required" }); + return; + } + const result = await inquireVehicle({ nationalCode, vin, mode: "vin" }); + send(res, result.ok ? 200 : 502, result); + return; + } + const left = body.left || body.plk1 || ""; + const letter = body.letter || body.plk2 || ""; + const right = body.right || body.plk3 || ""; + const serial = body.serial || body.plksrl || ""; + if (!left || !letter || !right || !serial) { + send(res, 400, { + ok: false, + error: "nationalCode + plate parts (left, letter, right, serial) required", + }); + return; + } + const result = await inquireVehicle({ + nationalCode, + left, + letter, + right, + serial, + mode: "plate", + }); + send(res, result.ok ? 200 : 502, result); + return; + } + + if (req.method === "POST" && url.pathname === "/api/run") { + if (running) { + send(res, 409, { ok: false, error: "A stage is already running" }); + return; + } + const body = await readBody(req); + const stage = String(body.stage || "").toLowerCase(); + const allowed = new Set(["base", "damage", "attachments", "expertise", "all"]); + if (!allowed.has(stage)) { + send(res, 400, { ok: false, error: "stage must be base|damage|attachments|expertise|all" }); + return; + } + if (body.env && typeof body.env === "object") { + writeEnv(body.env); + } + if (stage === "attachments") { + const env = loadEnv(); + const file = env.ATTACHMENT_FILE || "/tmp/fanavaran-tp-attach.jpg"; + if (!fs.existsSync(file)) { + fs.writeFileSync(file, Buffer.from([0xff, 0xd8, 0xff, 0xd9])); + } + } + running = true; + try { + const result = await runStage(stage); + if (result.ids?.CLAIM_ID) { + try { + saveCaseSnapshot(result.ids.CLAIM_ID, { + env: loadEnv(), + ui: body.ui || {}, + }); + } catch { + /* ignore */ + } + } + send(res, result.ok ? 200 : 500, result); + } finally { + running = false; + } + return; + } + + send(res, 404, { ok: false, error: "not found" }); + } catch (err) { + running = false; + send(res, 500, { ok: false, error: String(err && err.message ? err.message : err) }); + } +}); + +server.listen(PORT, HOST, () => { + console.log(`Fanavaran flow UI → http://${HOST}:${PORT}`); + console.log(`Env file → ${ENV_PATH}`); +}); diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index d8291a8..a05be89 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -7763,6014 +7763,3 @@ export class ClaimRequestManagementService { }; } if (claimCase.expertiseId != null) { - // Product decision: an already-completed Fanavaran stage must not send SMS. - return { - attempted: false, - submitted: false, - skipped: true, - skipReason: "Expertise already submitted to Fanavaran", - claimId: claimCase.claimId, - dmgCaseId: claimCase.dmgCaseId, - expertiseId: claimCase.expertiseId, - }; - } - - if (!claimCase.claimId) { - await this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId); - claimCase = await this.claimCaseDbService.findById(claimCaseId); - } - const product = await this.resolveFanavaranClaimProduct(claimCaseId); - if (fanavaranHasDamageCaseStage(product) && !claimCase?.dmgCaseId) { - await this.autoSubmitFanavaranDamageCaseOnOuterPartsSelected( - claimCaseId, - claimCase?.damage?.selectedParts ?? [], - ); - claimCase = await this.claimCaseDbService.findById(claimCaseId); - } - - const { payload, warnings } = await this.buildFanavaranExpertisePayload({ - claimCase, - clientKey, - }); - this.assertFanavaranExpertisePayloadReady(payload, warnings, { - ...hullExpertiseAssertFields(product), - }); - - const fanavaranResponse = await this.executeFanavaranExpertiseSubmit( - claimCaseId, - clientKey, - payload, - FanavaranAuditSource.AUTO_SUBMIT, - ); - const expertiseId = fanavaranResponse?.Id; - - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $push: { - history: { - type: "FANAVARAN_EXPERTISE_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { - clientKey, - claimId: claimCase?.claimId, - dmgCaseId: claimCase?.dmgCaseId, - expertiseId, - }, - }, - }, - }); - - return { - attempted: true, - submitted: true, - claimId: claimCase?.claimId, - dmgCaseId: claimCase?.dmgCaseId, - expertiseId, - fanavaranResponse, - }; - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - this.logger.warn(`${logPrefix} Expertise auto-submit failed: ${warning}`); - try { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - "fanavaranSync.expertise.status": "failed", - "fanavaranSync.expertise.lastTriedAt": new Date(), - "fanavaranSync.expertise.lastError": warning, - }, - $push: { - history: { - type: "FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { clientKey, error: warning }, - }, - }, - }); - } catch (historyError) { - this.logger.error( - `${logPrefix} Failed to record Fanavaran expertise failure history`, - historyError, - ); - } - - // Schedule retry for expertise - await this.scheduleFanavaranRetry( - claimCaseId, - "expertise", - () => this.autoSubmitFanavaranExpertiseOnExpertReply(claimCaseId), - logPrefix, - { error, clientKey }, - ); - - return { - attempted: true, - submitted: false, - warning, - }; - } - } - - private withFanavaranAutoSubmitMessage( - baseMessage: string, - fanavaran: FanavaranAutoSubmitResult, - ): string { - if (fanavaran.submitted) { - return `${baseMessage} The initial Fanavaran case was sent successfully.`; - } - if (fanavaran.warning) { - return `${baseMessage} ${fanavaran.warning}`; - } - return baseMessage; - } - - private async getFanavaranAutoSubmitSkipReason( - claimCase: any, - ): Promise { - if (claimCase.claimId != null || claimCase.claimNo != null) { - return "Already submitted to Fanavaran"; - } - - if (!claimCase.blameRequestId) { - return "Blame case not linked to claim case"; - } - - const blameCase = await this.blameRequestDbService.findById( - claimCase.blameRequestId, - ); - if (!blameCase) { - return "Blame case not found"; - } - - if (!isFanavaranSubmitSupportedBlameType(blameCase.type)) { - return "Fanavaran submit only applies to THIRD_PARTY and CAR_BODY claims"; - } - - return null; - } - - /** - * Soft-ensure Fanavaran base claim exists before a later stage (damage / - * attachments / expertise). Reuses claimId when present; otherwise submits - * GEN.03 once. Does not invent a fake claimId on failure. - */ - private async ensureFanavaranBaseClaim( - claimCaseId: string, - clientKey: FanavaranClientKey, - auditSource: FanavaranAuditSource, - ): Promise<{ claimId: number; claimNo?: string; created: boolean }> { - const existing = await this.claimCaseDbService.findById(claimCaseId); - if (!existing) { - throw new NotFoundException("Claim case not found"); - } - if (existing.claimId != null) { - return { - claimId: Number(existing.claimId), - claimNo: - existing.claimNo != null ? String(existing.claimNo) : undefined, - created: false, - }; - } - - this.logger.log( - `[Fanavaran ${clientKey}] Soft-ensuring base claim before next stage claimCaseId=${claimCaseId}`, - ); - await this.executeFanavaranV2Submit( - claimCaseId, - clientKey, - undefined, - auditSource, - ); - - const refreshed = await this.claimCaseDbService.findById(claimCaseId); - if (refreshed?.claimId == null) { - throw new BadRequestException( - "Fanavaran base claim is missing and could not be created before the next stage. Fix base claim first.", - ); - } - return { - claimId: Number(refreshed.claimId), - claimNo: - refreshed.claimNo != null ? String(refreshed.claimNo) : undefined, - created: true, - }; - } - - /** - * Soft-ensure damage case exists (creates base claim first if needed). - */ - private async ensureFanavaranDamageCase( - claimCaseId: string, - clientKey: FanavaranClientKey, - auditSource: FanavaranAuditSource, - selectedParts?: unknown[], - ): Promise<{ - claimId: number; - dmgCaseId: number | null; - created: boolean; - }> { - await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource); - - const existing = await this.claimCaseDbService.findById(claimCaseId); - if (existing?.dmgCaseId != null && existing.claimId != null) { - return { - claimId: Number(existing.claimId), - dmgCaseId: Number(existing.dmgCaseId), - created: false, - }; - } - - const product = await this.resolveFanavaranClaimProduct(claimCaseId); - if (!fanavaranHasDamageCaseStage(product)) { - if (existing?.claimId == null) { - throw new BadRequestException( - "Fanavaran claimId is required before the next hull stage.", - ); - } - return { - claimId: Number(existing.claimId), - dmgCaseId: null, - created: false, - }; - } - - this.logger.log( - `[Fanavaran ${clientKey}] Soft-ensuring damage case before next stage claimCaseId=${claimCaseId}`, - ); - await this.executeFanavaranDamageCaseSubmit( - claimCaseId, - clientKey, - selectedParts ?? existing?.damage?.selectedParts ?? [], - auditSource, - ); - - const refreshed = await this.claimCaseDbService.findById(claimCaseId); - if (refreshed?.claimId == null || refreshed.dmgCaseId == null) { - throw new BadRequestException( - "Fanavaran damage case is missing and could not be created before the next stage.", - ); - } - return { - claimId: Number(refreshed.claimId), - dmgCaseId: Number(refreshed.dmgCaseId), - created: true, - }; - } - - private async postFanavaranJson( - url: string, - payload: Record, - clientKey: FanavaranClientKey, - auditSession?: FanavaranAuditSession, - claimCaseId?: string, - ) { - this.fanavaranAuthService.assertNotInBackoff(clientKey); - const headers = await this.getFanavaranAuthHeaders( - clientKey, - auditSession, - claimCaseId, - ); - - try { - const response = await firstValueFrom( - this.httpService.post(url, payload, { - headers: { - ...headers, - "Content-Type": "application/json", - }, - }), - ); - this.fanavaranAuthService.clearBackoff(clientKey); - return response; - } catch (error) { - this.fanavaranAuthService.registerFailure(clientKey, error); - throw error; - } - } - - private async putFanavaranJson( - url: string, - payload: Record, - clientKey: FanavaranClientKey, - auditSession?: FanavaranAuditSession, - claimCaseId?: string, - ) { - this.fanavaranAuthService.assertNotInBackoff(clientKey); - const headers = await this.getFanavaranAuthHeaders( - clientKey, - auditSession, - claimCaseId, - ); - - try { - const response = await firstValueFrom( - this.httpService.put(url, payload, { - headers: { - ...headers, - "Content-Type": "application/json", - }, - }), - ); - this.fanavaranAuthService.clearBackoff(clientKey); - return response; - } catch (error) { - this.fanavaranAuthService.registerFailure(clientKey, error); - throw error; - } - } - - /** - * Nested hull files/expertise look up a بدنه پرونده. Create often echoed a ثالث-shaped - * body; PUT the GEN.03 hull shape onto the existing Id before follow-up stages. - */ - private async syncFanavaranHullBaseClaim( - claimCaseId: string, - clientKey: FanavaranClientKey, - ): Promise { - const product = await this.resolveFanavaranClaimProduct(claimCaseId); - if (product !== "car-body") return; - const claimCase = await this.claimCaseDbService.findById(claimCaseId); - const nestedId = fanavaranHullNestedClaimId({ - claimId: claimCase?.claimId, - claimNo: claimCase?.claimNo, - }); - if (nestedId == null) return; - - const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, { - requirePolicyId: true, - persistPayload: true, - }); - const hull = toFanavaranHullBaseClaimPayload( - built && typeof built === "object" && "payload" in built - ? (built as { payload: Record }).payload - : built, - ); - const url = `${fanavaranClaimsBaseUrl("car-body")}/${nestedId}`; - this.logger.log( - `[Fanavaran hull sync] PUT ${url} keys=${Object.keys(hull).join(",")}`, - ); - try { - await this.putFanavaranJson(url, hull, clientKey, undefined, claimCaseId); - } catch (error) { - // Parsian bonyan often has no PUT route on vehicle-hull-claims/{Id} - // ("No HTTP resource was found.../vehicle-hull-claims/{Id}"). Do not - // block GEN.05 files / GEN.06 expertise on that. - this.logger.warn( - `[Fanavaran hull sync] PUT ${url} failed; continuing with nested stages: ${ - error instanceof Error ? error.message : error - }`, - ); - } - } - - private async postFanavaranMultipart( - url: string, - content: Record, - files: Array<{ path: string; fileName: string }>, - clientKey: FanavaranClientKey, - auditSession?: FanavaranAuditSession, - claimCaseId?: string, - ) { - this.fanavaranAuthService.assertNotInBackoff(clientKey); - const headers = await this.getFanavaranAuthHeaders( - clientKey, - auditSession, - claimCaseId, - ); - const form = new FormData(); - - form.append("Param", JSON.stringify(content), { - contentType: "application/json", - }); - for (const file of files) { - form.append("Param1", createReadStream(resolve(file.path)), { - filename: file.fileName, - }); - } - - const curlParts = [ - `curl -X POST '${url}'`, - `-H 'authenticationToken: ${headers.authenticationToken}'`, - `-H 'CorpId: ${headers.CorpId}'`, - `-H 'ContractId: ${headers.ContractId}'`, - `-H 'Location: ${headers.Location}'`, - `-F 'Param=${JSON.stringify(content)}'`, - ...files.map((f) => `-F 'Param1=@${f.path};filename=${f.fileName}'`), - ]; - this.logger.log(`\n====== COPY THIS CURL ======\n${curlParts.join(" \\\n ")}\n====== END CURL ======\n`); - - const logPrefix = `[Fanavaran Multipart]`; - this.logger.log( - `${logPrefix} REQUEST: url=${url} | Param=${JSON.stringify(content)} | files=[${files.map((f) => f.fileName).join(", ")}] | fileCount=${files.length}`, - ); - - try { - const response = await firstValueFrom( - this.httpService.post(url, form, { - headers: { - ...form.getHeaders(), - ...headers, - }, - maxBodyLength: Infinity, - maxContentLength: Infinity, - }), - ); - - this.logger.log( - `${logPrefix} RESPONSE: status=${response.status} | body=${JSON.stringify(response.data)}`, - ); - this.fanavaranAuthService.clearBackoff(clientKey); - return response; - } catch (error) { - this.fanavaranAuthService.registerFailure(clientKey, error); - throw error; - } - } - - private async executeFanavaranDamageCaseSubmit( - claimCaseId: string, - clientKey: FanavaranClientKey, - selectedParts?: unknown[], - auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT, - bodyOverride?: Record, - ): Promise { - const profile = getFanavaranClientProfile(clientKey); - let claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) { - throw new NotFoundException("Claim case not found"); - } - if (!claimCase.claimId) { - await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource); - claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase?.claimId) { - throw new BadRequestException( - "Fanavaran claimId is required before submitting damage case", - ); - } - } - if (claimCase.dmgCaseId != null) { - this.logger.log( - `[executeFanavaranDamageCaseSubmit] Already have dmgCaseId=${claimCase.dmgCaseId}; skipping Fanavaran POST`, - ); - return ( - (claimCase as any)?.fanavaranSync?.damageCase?.response ?? { - Id: claimCase.dmgCaseId, - } - ); - } - if (!claimCase.blameRequestId) { - throw new BadRequestException("Blame case not linked to claim case"); - } - - const blameCase = await this.blameRequestDbService.findById( - claimCase.blameRequestId, - ); - if (!blameCase) { - throw new NotFoundException("Blame case not found"); - } - if (!isFanavaranSubmitSupportedBlameType(blameCase.type)) { - throw new BadRequestException( - "Fanavaran damage-case submit only applies to THIRD_PARTY and CAR_BODY claims", - ); - } - - const product = fanavaranClaimProductFromBlameType(blameCase.type); - const url = fanavaranClaimStageUrl( - product, - "damage-case", - claimCase.claimId, - ); - if (url == null) { - this.logger.log( - `[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} skipping hull dmg-cases`, - ); - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - "fanavaranSync.damageCase": { - status: "skipped", - lastTriedAt: new Date(), - lastError: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, - claimId: claimCase.claimId, - }, - }, - }); - return { - skipped: true, - skipReason: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, - claimId: claimCase.claimId, - }; - } - - const builtPayload = await this.buildFanavaranDamageCasePayload({ - claimCase, - blameCase, - selectedParts: selectedParts ?? claimCase.damage?.selectedParts ?? [], - clientKey, - defaults: profile.defaults, - registerMissingPerson: true, - }); - const payload = applyFanavaranManualPayloadOverrides( - builtPayload, - bodyOverride, - FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS, - ); - - // Guardrail: never send empty/null licence fields even if manual overrides arrive. - payload.LicenceNo = this.ensureFanavaranNonEmptyLicenceNo(payload.LicenceNo); - - this.logger.log( - `[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? "NULL"} payload keys=${Object.keys(payload).join(", ")}`, - ); - const startedAt = Date.now(); - const auditSession: FanavaranAuditSession = { - trackingCode: this.fanavaranAuditService.generateTrackingCode(), - clientKey, - source: auditSource, - claimCaseId, - }; - - await this.fanavaranAuditService.recordStep({ - session: auditSession, - step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE, - status: FanavaranAuditStatus.STARTED, - requestUrl: url, - requestMethod: "POST", - requestBody: payload, - requestMeta: { claimId: claimCase.claimId }, - }); - - try { - const response = await this.postFanavaranJson( - url, - payload, - clientKey, - auditSession, - ); - const dmgCaseId = response.data?.Id; - const exchange = - this.fanavaranAuditService.captureAxiosExchange(response); - - await this.fanavaranAuditService.recordStep({ - session: auditSession, - step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE, - status: FanavaranAuditStatus.SUCCESS, - requestUrl: url, - requestMethod: "POST", - httpStatus: response.status, - requestBody: payload, - responseHeaders: exchange.responseHeaders, - responseBody: exchange.responseBody, - responseMeta: { dmgCaseId, claimId: claimCase.claimId }, - durationMs: Date.now() - startedAt, - }); - - if (dmgCaseId !== undefined) { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - dmgCaseId, - "fanavaranSync.damageCase": { - status: "success", - lastTriedAt: new Date(), - claimId: claimCase.claimId, - dmgCaseId, - response: response.data, - }, - }, - }); - } - - return response.data; - } catch (error) { - const errDetail = isAxiosError(error) - ? `status=${error.response?.status} data=${JSON.stringify(error.response?.data)}` - : error instanceof Error - ? error.message - : String(error); - this.logger.error( - `[executeFanavaranDamageCaseSubmit] FAILED claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? "NULL"} error: ${errDetail}`, - ); - const exchange = this.fanavaranAuditService.captureAxiosExchange(error); - await this.fanavaranAuditService.recordStep({ - session: auditSession, - step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE, - status: FanavaranAuditStatus.FAILURE, - requestUrl: url, - requestMethod: "POST", - httpStatus: exchange.httpStatus, - requestBody: payload, - responseHeaders: exchange.responseHeaders, - responseBody: exchange.responseBody, - errorMessage: this.fanavaranAuditService.extractErrorMessage(error), - errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error), - durationMs: Date.now() - startedAt, - }); - throw error; - } - } - - async autoSubmitFanavaranDamageCaseOnOuterPartsSelected( - claimCaseId: string, - selectedParts: unknown[], - ): Promise { - const clientKey = resolveFanavaranClientKey(); - const logPrefix = `[Fanavaran ${clientKey} V2 DamageCase Auto] claimCaseId=${claimCaseId}`; - - try { - let claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) { - return { - attempted: false, - submitted: false, - warning: "Claim case not found for Fanavaran damage-case submit.", - }; - } - if (claimCase.dmgCaseId != null) { - return { - attempted: false, - submitted: false, - skipped: true, - skipReason: "Damage case already submitted to Fanavaran", - claimId: claimCase.claimId, - dmgCaseId: claimCase.dmgCaseId, - }; - } - - if (!claimCase.claimId) { - await this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId); - claimCase = await this.claimCaseDbService.findById(claimCaseId); - } - - if (!claimCase?.claimId) { - const warning = - "Fanavaran base claim is missing, so damage case was not submitted."; - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - "fanavaranSync.damageCase": { - status: "skipped", - lastTriedAt: new Date(), - lastError: warning, - }, - }, - }); - return { - attempted: false, - submitted: false, - skipped: true, - skipReason: warning, - warning, - }; - } - - const fanavaranResponse = await this.executeFanavaranDamageCaseSubmit( - claimCaseId, - clientKey, - selectedParts, - ); - if (fanavaranResponse?.skipped) { - return { - attempted: false, - submitted: false, - skipped: true, - skipReason: - fanavaranResponse.skipReason ?? FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, - claimId: claimCase.claimId, - }; - } - const dmgCaseId = fanavaranResponse?.Id; - - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $push: { - history: { - type: "FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { - clientKey, - claimId: claimCase.claimId, - dmgCaseId, - }, - }, - }, - }); - - return { - attempted: true, - submitted: true, - claimId: claimCase.claimId, - dmgCaseId, - fanavaranResponse, - }; - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - this.logger.warn( - `${logPrefix} Damage-case auto-submit failed: ${warning}`, - ); - - try { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - "fanavaranSync.damageCase.status": "failed", - "fanavaranSync.damageCase.lastTriedAt": new Date(), - "fanavaranSync.damageCase.lastError": warning, - }, - $push: { - history: { - type: "FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { clientKey, error: warning }, - }, - }, - }); - } catch (historyError) { - this.logger.error( - `${logPrefix} Failed to record Fanavaran damage-case failure history`, - historyError, - ); - } - - // Schedule retry for damage case - await this.scheduleFanavaranRetry( - claimCaseId, - "damageCase", - () => - this.autoSubmitFanavaranDamageCaseOnOuterPartsSelected( - claimCaseId, - selectedParts, - ), - logPrefix, - { error, clientKey }, - ); - - return { - attempted: true, - submitted: false, - warning, - }; - } - } - - /** - * Auto-submit the minimum Fanavaran claim as soon as the local - * claim case exists. This preserves progress in Fanavaran even if parties stop - * later in the damage-assessment flow. - */ - async autoSubmitToFanavaranV2OnClaimCreated( - claimCaseId: string, - ): Promise { - const clientKey = resolveFanavaranClientKey(); - const logPrefix = `[Fanavaran ${clientKey} V2 Early Auto] claimCaseId=${claimCaseId}`; - - const locked = await this.withFanavaranStageLock( - claimCaseId, - "baseClaim", - async () => { - try { - const claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) { - return { - attempted: false, - submitted: false, - warning: - "Claim case not found for Fanavaran early submit. Retry manually when available.", - }; - } - - const skipReason = await this.getFanavaranAutoSubmitSkipReason(claimCase); - if (skipReason) { - return { - attempted: false, - submitted: false, - skipped: true, - skipReason, - claimId: claimCase.claimId, - claimNo: claimCase.claimNo, - }; - } - - const fanavaranResponse = await this.executeFanavaranV2Submit( - claimCaseId, - clientKey, - undefined, - FanavaranAuditSource.AUTO_SUBMIT, - ); - - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $push: { - history: { - type: "FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { - clientKey, - claimNo: fanavaranResponse?.ClaimNo, - claimId: fanavaranResponse?.Id, - }, - }, - }, - }); - - return { - attempted: true, - submitted: true, - claimNo: fanavaranResponse?.ClaimNo, - claimId: fanavaranResponse?.Id, - fanavaranResponse, - }; - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - this.logger.warn(`${logPrefix} Early auto-submit failed: ${warning}`); - - try { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - "fanavaranSync.baseClaim.status": "failed", - "fanavaranSync.baseClaim.lastTriedAt": new Date(), - "fanavaranSync.baseClaim.lastError": warning, - }, - $push: { - history: { - type: "FANAVARAN_EARLY_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { clientKey, error: warning }, - }, - }, - }); - } catch (historyError) { - this.logger.error( - `${logPrefix} Failed to record Fanavaran early auto-submit failure history`, - historyError, - ); - } - - await this.scheduleFanavaranRetry( - claimCaseId, - "baseClaim", - () => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId), - logPrefix, - { error, clientKey }, - ); - - return { - attempted: true, - submitted: false, - warning: `${warning} Initial case was not sent to Fanavaran. Retry manually via POST ${fanavaranSubmitPath(clientKey, claimCaseId)}.`, - }; - } - }, - ); - - if (locked && typeof locked === "object" && "skipped" in locked && locked.skipped) { - return { - attempted: false, - submitted: false, - skipped: true, - skipReason: locked.skipReason, - }; - } - return locked as FanavaranAutoSubmitResult; - } - - /** - * Auto-submit to Fanavaran when a claim case reaches COMPLETED. - * Uses FANAVARAN_CLIENT env (or CLIENT_ID fallback) to pick the tenant. - * Never throws — failures are returned as warnings so the main flow continues. - */ - async autoSubmitToFanavaranV2OnClaimCompleted( - claimCaseId: string, - ): Promise { - const clientKey = resolveFanavaranClientKey(); - const logPrefix = `[Fanavaran ${clientKey} V2 Auto] claimCaseId=${claimCaseId}`; - - try { - const claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) { - return { - attempted: false, - submitted: false, - warning: - "Claim case not found for Fanavaran auto-submit. Retry manually when available.", - }; - } - - // V5 flow: FileMaker approval required before fanavaran. - // Cross-check the blame record — only V5 blame files carry requiresFileMakerApproval. - // V4 claims may have the flag set from an old bug; we ignore it if the blame - // itself does not carry the flag. - if ((claimCase as any).requiresFileMakerApproval) { - const blameId = (claimCase as any).blameRequestId; - const blame = blameId - ? await this.blameRequestDbService.findById(String(blameId)) - : null; - const isV5 = !!(blame as any)?.requiresFileMakerApproval; - - if (isV5) { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { status: ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL }, - $push: { - history: { - type: "V5_HELD_FOR_FILE_MAKER_APPROVAL", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { claimCaseId }, - }, - }, - }); - return { - attempted: false, - submitted: false, - skipped: true, - skipReason: - "V5 flow: FileMaker approval required before Fanavaran submission. " + - "Claim is now in WAITING_FOR_FILE_MAKER_APPROVAL.", - }; - } - // V4 claim with stale flag — clear it so this path is not hit again. - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $unset: { requiresFileMakerApproval: "" }, - }); - } - - const skipReason = await this.getFanavaranAutoSubmitSkipReason(claimCase); - if (skipReason) { - return { - attempted: false, - submitted: false, - skipped: true, - skipReason, - claimId: claimCase.claimId, - claimNo: claimCase.claimNo, - }; - } - - const fanavaranResponse = await this.executeFanavaranV2Submit( - claimCaseId, - clientKey, - ); - - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $push: { - history: { - type: "FANAVARAN_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { - clientKey, - claimNo: fanavaranResponse?.ClaimNo, - claimId: fanavaranResponse?.Id, - }, - }, - }, - }); - - return { - attempted: true, - submitted: true, - claimNo: fanavaranResponse?.ClaimNo, - claimId: fanavaranResponse?.Id, - fanavaranResponse, - }; - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - this.logger.warn(`${logPrefix} Auto-submit failed: ${warning}`); - - try { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $push: { - history: { - type: "FANAVARAN_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { clientKey, error: warning }, - }, - }, - }); - } catch (historyError) { - this.logger.error( - `${logPrefix} Failed to record Fanavaran auto-submit failure history`, - historyError, - ); - } - - // Schedule retry for base claim - await this.scheduleFanavaranRetry( - claimCaseId, - "baseClaim", - () => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId), - logPrefix, - { error, clientKey }, - ); - - return { - attempted: true, - submitted: false, - warning: `${warning} Case was not sent to Fanavaran. Retry manually via POST ${fanavaranSubmitPath(clientKey, claimCaseId)}.`, - }; - } - } - - /** @deprecated Use autoSubmitToFanavaranV2OnClaimCompleted */ - async autoSubmitToFanavaranParsianV2OnClaimCompleted( - claimCaseId: string, - ): Promise { - return this.autoSubmitToFanavaranV2OnClaimCompleted(claimCaseId); - } - - private extractFanavaranErrorMessage(error: unknown): string { - if (isAxiosError(error)) { - return ( - error.response?.data?.message || - error.response?.data?.Message || - (typeof error.response?.data === "string" - ? error.response.data - : undefined) || - error.message || - "Failed to submit data to Fanavaran API" - ); - } - if (error instanceof HttpException) { - const response = error.getResponse(); - if (typeof response === "string") return response; - if (response && typeof response === "object" && "message" in response) { - const message = (response as { message?: string | string[] }).message; - return Array.isArray(message) ? message.join(", ") : String(message); - } - } - if (error instanceof Error) { - return error.message; - } - return "Failed to submit data to Fanavaran API"; - } - - private static readonly FANAVARAN_RETRY_DELAY_MS = 5 * 60 * 1000; // 5 minutes - private static readonly FANAVARAN_TRANSIENT_RETRY_DELAY_MS = 10 * 60 * 1000; // 10 minutes - private static readonly FANAVARAN_MAX_RETRIES = 2; - - private fanavaranRetryKey( - claimCaseId: string, - stage: "baseClaim" | "damageCase" | "attachments" | "expertise", - ): string { - return `${claimCaseId}:${stage}`; - } - - private async withFanavaranStageLock( - claimCaseId: string, - stage: string, - fn: () => Promise, - ): Promise { - const key = `${claimCaseId}:${stage}`; - if (this.fanavaranInFlightStages.has(key)) { - this.logger.warn( - `[Fanavaran] Skipping concurrent ${stage} for claimCaseId=${claimCaseId}`, - ); - return { - skipped: true, - skipReason: `Fanavaran ${stage} already in flight for this claim`, - }; - } - this.fanavaranInFlightStages.add(key); - try { - return await fn(); - } finally { - this.fanavaranInFlightStages.delete(key); - } - } - - /** - * After a Fanavaran stage failure, schedule a single deferred retry. - * Dedupes in-process timers and Mongo `nextRetryAt` so concurrent failures - * cannot enqueue multiple setTimeouts for the same claim/stage. - */ - private async scheduleFanavaranRetry( - claimCaseId: string, - stage: "baseClaim" | "damageCase" | "attachments" | "expertise", - retryFn: () => Promise, - logPrefix: string, - options?: { error?: unknown; clientKey?: FanavaranClientKey }, - ): Promise { - const key = this.fanavaranRetryKey(claimCaseId, stage); - const claimCase = await this.claimCaseDbService.findById(claimCaseId); - const syncStage = (claimCase as any)?.fanavaranSync?.[stage]; - const retryCount = syncStage?.retryCount ?? 0; - const maxRetries = - syncStage?.maxRetries ?? - ClaimRequestManagementService.FANAVARAN_MAX_RETRIES; - - if (retryCount >= maxRetries) { - this.logger.warn( - `${logPrefix} Max retries (${maxRetries}) exhausted for ${stage}.`, - ); - return false; - } - - // Already scheduled in DB for the future — do not add another timer. - const existingNext = syncStage?.nextRetryAt - ? new Date(syncStage.nextRetryAt).getTime() - : 0; - if ( - syncStage?.status === "pending" && - existingNext > Date.now() + 5_000 - ) { - this.logger.log( - `${logPrefix} Retry already pending for ${stage} at ${new Date(existingNext).toISOString()}; skipping duplicate schedule.`, - ); - return false; - } - - // In-process timer already armed for this key. - if (this.fanavaranRetryTimers.has(key)) { - this.logger.log( - `${logPrefix} In-process retry timer already exists for ${stage}; skipping duplicate.`, - ); - return false; - } - - const transient = FanavaranAuthService.isTransientTryLaterError( - options?.error, - ); - const delayMs = transient - ? ClaimRequestManagementService.FANAVARAN_TRANSIENT_RETRY_DELAY_MS - : ClaimRequestManagementService.FANAVARAN_RETRY_DELAY_MS; - - if (options?.clientKey && options?.error) { - this.fanavaranAuthService.registerFailure( - options.clientKey, - options.error, - ); - } - - const nextRetryCount = retryCount + 1; - const nextRetryAt = new Date(Date.now() + delayMs); - - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - [`fanavaranSync.${stage}.retryCount`]: nextRetryCount, - [`fanavaranSync.${stage}.maxRetries`]: maxRetries, - [`fanavaranSync.${stage}.nextRetryAt`]: nextRetryAt, - [`fanavaranSync.${stage}.status`]: "pending", - [`fanavaranSync.${stage}.lastTriedAt`]: new Date(), - ...(options?.error - ? { - [`fanavaranSync.${stage}.lastError`]: - this.extractFanavaranErrorMessage(options.error), - } - : {}), - }, - }); - - this.logger.log( - `${logPrefix} Scheduling retry ${nextRetryCount}/${maxRetries} for ${stage} at ${nextRetryAt.toISOString()} (delay=${delayMs}ms${transient ? ", transient backoff" : ""})`, - ); - - const timer = setTimeout(async () => { - this.fanavaranRetryTimers.delete(key); - try { - const fresh = await this.claimCaseDbService.findById(claimCaseId); - const freshStage = (fresh as any)?.fanavaranSync?.[stage]; - if (freshStage?.status === "pending") { - await retryFn(); - } - } catch (retryError) { - this.logger.error( - `${logPrefix} Retry ${nextRetryCount}/${maxRetries} for ${stage} failed`, - retryError, - ); - } - }, delayMs); - - this.fanavaranRetryTimers.set(key, timer); - return true; - } - - private async executeFanavaranV2Submit( - claimCaseId: string, - clientKey: FanavaranClientKey, - bodyOverride?: Record, - auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT, - ): Promise { - const logPrefix = `[Fanavaran ${clientKey} V2]`; - - this.logger.log( - `${logPrefix} Starting submission for claimCaseId: ${claimCaseId}`, - ); - - const existing = await this.claimCaseDbService.findById(claimCaseId); - if (existing?.claimId != null) { - this.logger.log( - `${logPrefix} Base claim already exists claimId=${existing.claimId}; skipping Fanavaran POST`, - ); - return ( - (existing as any)?.fanavaranSync?.baseClaim?.response ?? { - Id: existing.claimId, - ClaimNo: existing.claimNo, - } - ); - } - - const auditSession: FanavaranAuditSession = { - trackingCode: this.fanavaranAuditService.generateTrackingCode(), - clientKey, - source: auditSource, - claimCaseId, - }; - - const built = - await this.previewFanavaranSubmitV2(claimCaseId, clientKey, { - requirePolicyId: true, - auditSession, - persistPayload: true, - forceRefreshPolicy: true, - forceRefreshUsedId: true, - }); - const fanavaranData = applyFanavaranManualPayloadOverrides( - built, - bodyOverride, - FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS, - ); - - // Guardrail: never send empty/null licence fields even if manual overrides arrive. - fanavaranData.CulpritLicenceNo = this.ensureFanavaranNonEmptyLicenceNo( - fanavaranData.CulpritLicenceNo, - ); - - this.logger.log( - `${logPrefix} Mapped data prepared:`, - JSON.stringify(fanavaranData, null, 2), - ); - - if ( - fanavaranData.AccidentCauseId === undefined || - fanavaranData.AccidentCauseId === null - ) { - this.logger.error( - `${logPrefix} CRITICAL: AccidentCauseId is missing or null!`, - ); - } else { - this.logger.log( - `${logPrefix} AccidentCauseId validated: ${fanavaranData.AccidentCauseId}`, - ); - } - - this.fanavaranAuthService.assertNotInBackoff(clientKey); - const headers = await this.getFanavaranAuthHeaders( - clientKey, - auditSession, - claimCaseId, - ); - const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId); - - const requestHeaders = { - ...headers, - "Content-Type": "application/json", - }; - await this.fanavaranAuditService.recordStep({ - session: auditSession, - step: FanavaranAuditStep.SUBMIT_CLAIM, - status: FanavaranAuditStatus.STARTED, - requestUrl: submitUrl, - requestMethod: "POST", - requestHeaders, - requestBody: fanavaranData, - requestMeta: { policyId: fanavaranData?.PolicyId ?? null }, - }); - const startedAt = Date.now(); - - try { - const response = await firstValueFrom( - this.httpService.post(submitUrl, fanavaranData, { - headers: requestHeaders, - }), - ); - - this.logger.log(`${logPrefix} API Response Status: ${response.status}`); - this.logger.log( - `${logPrefix} API Response Data:`, - JSON.stringify(response.data, null, 2), - ); - - this.fanavaranAuthService.clearBackoff(clientKey); - - const exchange = this.fanavaranAuditService.captureAxiosExchange( - response, - requestHeaders, - ); - await this.fanavaranAuditService.recordStep({ - session: auditSession, - step: FanavaranAuditStep.SUBMIT_CLAIM, - status: FanavaranAuditStatus.SUCCESS, - requestUrl: submitUrl, - requestMethod: "POST", - httpStatus: response.status, - requestHeaders: exchange.requestHeaders, - requestBody: fanavaranData, - responseHeaders: exchange.responseHeaders, - responseBody: exchange.responseBody, - responseMeta: { - claimId: response.data?.Id, - claimNo: response.data?.ClaimNo, - }, - durationMs: Date.now() - startedAt, - }); - - if (response.data) { - const claimNo = response.data.ClaimNo; - const claimId = response.data.Id; - - const updateData: any = { $set: {} as Record }; - if (claimNo !== undefined) { - updateData.$set.claimNo = claimNo; - } - if (claimId !== undefined) { - updateData.$set.claimId = claimId; - } - updateData.$set["fanavaranSync.baseClaim.status"] = "success"; - updateData.$set["fanavaranSync.baseClaim.lastTriedAt"] = new Date(); - updateData.$set["fanavaranSync.baseClaim.claimId"] = claimId; - updateData.$set["fanavaranSync.baseClaim.claimNo"] = claimNo; - updateData.$set["fanavaranSync.baseClaim.response"] = response.data; - if (fanavaranData?.PolicyId != null) { - updateData.$set["fanavaranSync.baseClaim.policyId"] = - fanavaranData.PolicyId; - } - - await this.claimCaseDbService.findByIdAndUpdate( - claimCaseId, - updateData, - ); - } - - return response.data; - } catch (error) { - this.fanavaranAuthService.registerFailure(clientKey, error); - const exchange = this.fanavaranAuditService.captureAxiosExchange( - error, - requestHeaders, - ); - await this.fanavaranAuditService.recordStep({ - session: auditSession, - step: FanavaranAuditStep.SUBMIT_CLAIM, - status: FanavaranAuditStatus.FAILURE, - requestUrl: submitUrl, - requestMethod: "POST", - httpStatus: exchange.httpStatus, - requestHeaders: exchange.requestHeaders, - requestBody: fanavaranData, - responseHeaders: exchange.responseHeaders, - responseBody: exchange.responseBody, - errorMessage: this.fanavaranAuditService.extractErrorMessage(error), - errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error), - durationMs: Date.now() - startedAt, - }); - throw error; - } - } - - /** @deprecated Use executeFanavaranV2Submit(claimCaseId, "parsian") */ - private async executeFanavaranParsianV2Submit( - claimCaseId: string, - ): Promise { - return this.executeFanavaranV2Submit(claimCaseId, "parsian"); - } - - /** - * Submit fanavaran data to external API - */ - async submitToFanavaran(claimRequestId: string): Promise { - try { - // First, get the mapped data - this.logger.log( - `[Fanavaran Submit] Starting submission for claimRequestId: ${claimRequestId}`, - ); - const fanavaranData = await this.fanavaranSubmit(claimRequestId); - this.logger.log( - `[Fanavaran Submit] Mapped data prepared:`, - JSON.stringify(fanavaranData, null, 2), - ); - - // Validate required fields before submission - if ( - fanavaranData.AccidentCauseId === undefined || - fanavaranData.AccidentCauseId === null - ) { - this.logger.error( - `[Fanavaran Submit] CRITICAL: AccidentCauseId is missing or null!`, - ); - this.logger.error( - `[Fanavaran Submit] This field is required by the API. Request will likely fail.`, - ); - this.logger.error( - `[Fanavaran Submit] Available fields in result:`, - Object.keys(fanavaranData), - ); - } else { - this.logger.log( - `[Fanavaran Submit] AccidentCauseId validated: ${fanavaranData.AccidentCauseId}`, - ); - } - - // Step 1: Get appToken - this.logger.log(`[Fanavaran Submit] Step 1: Getting appToken`); - const appToken = await this.getAppToken(); - this.logger.log(`[Fanavaran Submit] AppToken obtained: ${appToken}`); - - // Step 2: Login to get authenticationToken - this.logger.log( - `[Fanavaran Submit] Step 2: Logging in to get authenticationToken`, - ); - const authenticationToken = await this.login(appToken); - this.logger.log( - `[Fanavaran Submit] AuthenticationToken obtained: ${authenticationToken}`, - ); - - // Step 3: Submit data to Fanavaran API - this.logger.log( - `[Fanavaran Submit] Step 3: Submitting data to Fanavaran API`, - ); - this.logger.log(`[Fanavaran Submit] URL: ${this.FANAVARAN_SUBMIT_URL}`); - this.logger.log(`[Fanavaran Submit] Request headers:`, { - authenticationToken: authenticationToken, - CorpId: this.CORP_ID, - ContractId: this.CONTRACT_ID, - Location: this.LOCATION, - "Content-Type": "application/json", - }); - this.logger.log( - `[Fanavaran Submit] Request body:`, - JSON.stringify(fanavaranData, null, 2), - ); - - const response = await firstValueFrom( - this.httpService.post(this.FANAVARAN_SUBMIT_URL, fanavaranData, { - headers: { - authenticationToken: authenticationToken, - CorpId: this.CORP_ID, - ContractId: this.CONTRACT_ID, - Location: this.LOCATION, - "Content-Type": "application/json", - }, - }), - ); - - this.logger.log( - `[Fanavaran Submit] API Response Status: ${response.status}`, - ); - this.logger.log( - `[Fanavaran Submit] API Response Headers:`, - JSON.stringify(response.headers, null, 2), - ); - this.logger.log( - `[Fanavaran Submit] API Response Data:`, - JSON.stringify(response.data, null, 2), - ); - this.logger.log("Successfully submitted data to Fanavaran API"); - - // Step 4: Save ClaimNo and Id from response to claim-request-management document - if (response.data) { - const claimNo = response.data.ClaimNo; - const claimId = response.data.Id; - - this.logger.log( - `[Fanavaran Submit] Extracted from response - ClaimNo: ${claimNo}, Id: ${claimId}`, - ); - - if (claimNo !== undefined || claimId !== undefined) { - const updateData: any = { - $set: {}, - }; - if (claimNo !== undefined) { - updateData.$set.claimNo = claimNo; - } - if (claimId !== undefined) { - updateData.$set.claimId = claimId; - } - - this.logger.log( - `[Fanavaran Submit] Updating document with:`, - JSON.stringify(updateData, null, 2), - ); - await this.claimRequestManagementDbService.findAndUpdate( - claimRequestId, - updateData, - ); - - this.logger.log( - `Updated claim-request-management document with claimNo: ${claimNo}, claimId: ${claimId}`, - ); - } else { - this.logger.warn( - `[Fanavaran Submit] No ClaimNo or Id found in response data`, - ); - } - } else { - this.logger.warn(`[Fanavaran Submit] No response data received`); - } - - return response.data; - } catch (error) { - this.logger.error("[Fanavaran Submit] Error submitting to Fanavaran"); - this.logger.error( - "[Fanavaran Submit] Error type:", - error?.constructor?.name, - ); - - if (isAxiosError(error)) { - this.logger.error("[Fanavaran Submit] Axios Error Details:"); - this.logger.error( - "[Fanavaran Submit] Error Status:", - error.response?.status, - ); - this.logger.error( - "[Fanavaran Submit] Error Status Text:", - error.response?.statusText, - ); - this.logger.error( - "[Fanavaran Submit] Error Response Headers:", - JSON.stringify(error.response?.headers, null, 2), - ); - this.logger.error( - "[Fanavaran Submit] Error Response Data:", - JSON.stringify(error.response?.data, null, 2), - ); - this.logger.error("[Fanavaran Submit] Request URL:", error.config?.url); - this.logger.error( - "[Fanavaran Submit] Request Method:", - error.config?.method, - ); - this.logger.error( - "[Fanavaran Submit] Request Headers:", - JSON.stringify(error.config?.headers, null, 2), - ); - this.logger.error( - "[Fanavaran Submit] Request Data:", - JSON.stringify(error.config?.data, null, 2), - ); - - const errorMessage = - error.response?.data?.message || - error.response?.data?.Message || - error.response?.data || - error.message || - "Failed to submit data to Fanavaran API"; - - this.logger.error( - "[Fanavaran Submit] Extracted Error Message:", - errorMessage, - ); - throw new BadGatewayException(errorMessage); - } else { - this.logger.error("[Fanavaran Submit] Non-Axios Error:", error); - throw new BadGatewayException("Failed to submit data to Fanavaran API"); - } - } - } - - /** - * V2: Create claim request from completed blame case - * Only damaged party can create claim after both parties accept expert decision - */ - async createClaimFromBlameV2( - blameRequestId: string, - currentUserId: string, - ): Promise { - try { - // 1. Fetch blame request from new blameCases collection - const blameRequest = - await this.blameRequestDbService.findById(blameRequestId); - if (!blameRequest) { - throw new NotFoundException("Blame request not found"); - } - - // 2. Validate blame status is COMPLETED - // if (blameRequest.status !== BlameCaseStatus.COMPLETED) { - // throw new BadRequestException( - // `Blame request must be COMPLETED. Current status: ${blameRequest.status}`, - // ); - // } - - const parties = blameRequest.parties || []; - const isCarBody = blameRequest.type === BlameRequestType.CAR_BODY; - - if (isCarBody) { - // CAR_BODY: single party, no expert; first party is the damaged one who creates the claim - if (parties.length < 1) { - throw new BadRequestException("Blame request has no party"); - } - const firstParty = parties.find((p) => p.role === "FIRST"); - if ( - !firstParty || - String(firstParty.person?.userId) !== currentUserId - ) { - throw new ForbiddenException( - "Only the first party (damaged) can create a claim from this CAR_BODY blame request", - ); - } - } else { - // THIRD_PARTY: require expert decision and both parties signed - if (!blameRequest.expert?.decision) { - throw new BadRequestException( - "Cannot create claim until expert has made a decision", - ); - } - - const guiltyPartyId = String( - blameRequest.expert.decision.guiltyPartyId, - ); - - if (parties.length < 2) { - throw new BadRequestException( - "Both parties must be present in the blame request", - ); - } - - const allPartiesSigned = parties.every( - (p) => p.confirmation !== undefined && p.confirmation !== null, - ); - - if (!allPartiesSigned) { - throw new BadRequestException( - "Both parties must sign the expert decision before creating a claim", - ); - } - - const allPartiesAccepted = parties.every( - (p) => p.confirmation?.accepted === true, - ); - - if (!allPartiesAccepted) { - throw new BadRequestException( - "Both parties must accept the expert decision. If rejected, in-person resolution is required.", - ); - } - - const guiltyParty = parties.find((p) => { - return String(p.person?.userId) === guiltyPartyId; - }); - - if ( - guiltyParty && - String(guiltyParty.person?.userId) === currentUserId - ) { - throw new ForbiddenException( - "You cannot create a claim as you are the guilty party", - ); - } - } - - // 5. Validate current user is a party (and for THIRD_PARTY not the guilty one) - const currentUserParty = parties.find( - (p) => String(p.person?.userId) === currentUserId, - ); - - if (!currentUserParty) { - throw new ForbiddenException( - "You are not a party in this blame request", - ); - } - - // 6. Validate no existing claim for this blame - const existingClaim = await this.claimCaseDbService.findOne({ - blameRequestId: new Types.ObjectId(blameRequestId), - }); - - if (existingClaim) { - throw new ConflictException( - "A claim request for this blame case already exists", - ); - } - - // 7. Generate claim number - const claimNo = await this.generateUniqueClaimNumber(); - - // 8. Create claim case - const ownerParty = resolveClaimOwnerParty(blameRequest); - if (!ownerParty?.person?.userId) { - throw new BadRequestException( - "Could not resolve claim owner from blame parties", - ); - } - const damagedUserId = (() => { - const oid = String(ownerParty.person.userId); - const dp = (blameRequest.parties || []).find( - (p: any) => p.person?.userId && String(p.person.userId) !== oid, - ); - return dp?.person?.userId ? String(dp.person.userId) : null; - })(); - const newClaim = await this.claimCaseDbService.create({ - requestNo: claimNo, - publicId: blameRequest.publicId, - blameRequestId: new Types.ObjectId(blameRequestId), - blameRequestNo: blameRequest.requestNo, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - claimStatus: ClaimStatus.PENDING, - inquiries: (blameRequest as any).inquiries ?? {}, - workflow: { - currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS, - nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS, - completedSteps: [ClaimWorkflowStep.CLAIM_CREATED], - locked: false, - }, - ...(damagedUserId - ? { damagedPartyUserId: new Types.ObjectId(damagedUserId) } - : {}), - owner: (() => { - const cid = ownerParty.person.clientId; - return { - userId: new Types.ObjectId(String(ownerParty.person.userId)), - userRole: ownerParty.role as any, - fullName: currentUserParty.person?.fullName, - userClientKey: cid ? String(cid) : undefined, - ...(cid ? { clientId: new Types.ObjectId(String(cid)) } : {}), - }; - })(), - history: [ - { - type: "CLAIM_CREATED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: currentUserParty.person?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - blameRequestId, - blamePublicId: blameRequest.publicId, - }, - }, - ], - } as any); - - this.logger.log( - `Claim created: ${newClaim._id} from blame: ${blameRequestId}`, - ); - - const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated( - String(newClaim._id), - ); - const message = this.withFanavaranAutoSubmitMessage( - "Claim request created successfully", - fanavaran, - ); - - return { - claimRequestId: String(newClaim._id), - publicId: blameRequest.publicId, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - message, - fanavaran, - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error( - "createClaimFromBlameV2 failed", - blameRequestId, - error instanceof Error ? error.stack : String(error), - ); - throw new InternalServerErrorException( - error instanceof Error - ? error.message - : "Failed to create claim request", - ); - } - } - - /** - * V2: Field expert creates a claim from an expert-initiated IN_PERSON completed blame. - * Owner: damaged party `userId` (SMS / user actions), guilty party `clientId` (insurer queue). - */ - async createClaimFromBlameForExpertV2( - blameRequestId: string, - expert: { sub: string; firstName?: string; lastName?: string }, - ): Promise { - const blameRequest = - await this.blameRequestDbService.findById(blameRequestId); - if (!blameRequest) { - throw new NotFoundException("Blame request not found"); - } - // if (blameRequest.status !== BlameCaseStatus.COMPLETED) { - // throw new BadRequestException( - // `Blame request must be COMPLETED. Current status: ${blameRequest.status}`, - // ); - // } - if ( - !blameRequest.expertInitiated || - blameRequest.creationMethod !== "IN_PERSON" || - !blameRequest.initiatedByFieldExpertId - ) { - throw new BadRequestException( - "This endpoint is only for expert-initiated IN_PERSON blame files.", - ); - } - if (String(blameRequest.initiatedByFieldExpertId) !== String(expert.sub)) { - throw new ForbiddenException( - "Only the field expert who created this blame file can create the claim.", - ); - } - const ownerFields = resolveClaimOwnerFieldsFromBlame(blameRequest); - if (!ownerFields) { - throw new BadRequestException( - "Could not resolve claim owner (damaged party) from blame", - ); - } - const existingClaim = await this.claimCaseDbService.findOne({ - blameRequestId: new Types.ObjectId(blameRequestId), - }); - if (existingClaim) { - throw new ConflictException("A claim for this blame case already exists"); - } - const claimNo = await this.generateUniqueClaimNumber(); - const newClaim = await this.claimCaseDbService.create({ - requestNo: claimNo, - publicId: blameRequest.publicId, - blameRequestId: new Types.ObjectId(blameRequestId), - blameRequestNo: blameRequest.requestNo, - initiatedByFieldExpertId: new Types.ObjectId(expert.sub), - ...((blameRequest as any).branchId - ? { branchId: new Types.ObjectId(String((blameRequest as any).branchId)) } - : {}), - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - claimStatus: ClaimStatus.PENDING, - inquiries: (blameRequest as any).inquiries ?? {}, - workflow: { - currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS, - nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS, - completedSteps: [ClaimWorkflowStep.CLAIM_CREATED], - locked: false, - }, - damagedPartyUserId: new Types.ObjectId(ownerFields.userId), - owner: { - userId: new Types.ObjectId(ownerFields.userId), - userRole: ownerFields.userRole as any, - ...(ownerFields.clientId - ? { - clientId: new Types.ObjectId(ownerFields.clientId), - userClientKey: ownerFields.clientId, - } - : {}), - }, - history: [ - { - type: "CLAIM_CREATED", - actor: { - actorId: new Types.ObjectId(expert.sub), - actorName: - `${expert.firstName || ""} ${expert.lastName || ""}`.trim(), - actorType: "field_expert", - }, - timestamp: new Date(), - metadata: { - blameRequestId, - blamePublicId: blameRequest.publicId, - createdByExpert: true, - }, - }, - ], - } as any); - this.logger.log( - `Claim created by field expert: ${newClaim._id} from blame: ${blameRequestId}`, - ); - const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated( - String(newClaim._id), - ); - const message = this.withFanavaranAutoSubmitMessage( - "Claim created successfully. You can now fill claim data on behalf of the damaged party.", - fanavaran, - ); - return { - claimRequestId: String(newClaim._id), - publicId: blameRequest.publicId, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - message, - fanavaran, - }; - } - - /** - * True when the actor appears as a non-owner (damaged) party on the claim's - * snapshot.parties. This is the fastest, blame-free fallback: the snapshot is - * written at claim-creation time and always holds the correct user IDs. - * - * Logic: - * - Any party whose person.userId is in linkedUserIds and is NOT the claim - * owner (guilty party) is considered the damaged party. - * - If owner.userId is unknown we accept any matching party (CAR_BODY flows). - */ - private claimSnapshotPartyMatchesAsDamagedParty( - claim: any, - linkedUserIdStrings: string[], - ): boolean { - const parties: any[] = claim?.snapshot?.parties ?? []; - if (!parties.length) return false; - - const ownerIdStr = claim?.owner?.userId ? String(claim.owner.userId) : null; - - for (const party of parties) { - const partyUserId = party?.person?.userId; - if (partyUserId == null) continue; - const partyStr = String(partyUserId); - - // Must be this actor - if (!linkedUserIdStrings.some((id) => id === partyStr)) continue; - - // Must NOT be the guilty-owner (unless owner is unknown — CAR_BODY) - if (ownerIdStr && partyStr === ownerIdStr) continue; - - return true; - } - return false; - } - - private async assertEffectiveUserIsDamagedPartyOnClaim( - claimCase: any, - effectiveUserId: string, - actor?: { username?: string }, - message = "Only the damaged party can perform this action on the claim", - ): Promise { - const linkedUserIds = await resolveLinkedUserIdStrings(this.userDbService, { - sub: effectiveUserId, - username: actor?.username, - }); - const actorCtx = { sub: effectiveUserId, username: actor?.username }; - - // 0. damagedPartyUserId stored directly on the claim (fastest, most reliable) - if (ownerUserIdMatchesActor(claimCase?.damagedPartyUserId, linkedUserIds)) { - return; - } - - // 1. Owner (= guilty party for THIRD_PARTY) — kept for backward compat - // on CAR_BODY where owner IS the damaged party. - if (ownerUserIdMatchesActor(claimCase?.owner?.userId, linkedUserIds)) { - return; - } - - // 2. Blame-based resolution (primary path for THIRD_PARTY) - if (claimCase?.blameRequestId) { - const blame = await this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), - ); - if ( - blame && - blameDamagedPartyMatchesUser(blame, actorCtx, linkedUserIds) - ) { - return; - } - } - - // 3. Snapshot-party fallback: claim.snapshot.parties is written at creation - // and is reliable even when blame lookup fails or userId mapping differs. - if ( - this.claimSnapshotPartyMatchesAsDamagedParty(claimCase, linkedUserIds) - ) { - return; - } - - throw new ForbiddenException(message); - } - - private async assertActorCanViewClaimV2( - claim: any, - currentUserId: string, - actor?: { sub: string; role?: string; username?: string }, - ): Promise { - const linkedUserIds = await resolveLinkedUserIdStrings(this.userDbService, { - sub: currentUserId, - username: actor?.username, - }); - - if (ownerUserIdMatchesActor(claim.owner?.userId, linkedUserIds)) { - return; - } - - // damagedPartyUserId is set at claim-creation time — the most direct check. - if (ownerUserIdMatchesActor(claim.damagedPartyUserId, linkedUserIds)) { - return; - } - - if (!actor?.role || actor.role === RoleEnum.USER) { - const userCtx = { sub: currentUserId, username: actor?.username }; - - // Any party on the linked blame can VIEW the claim. - // (Mutation guards use assertEffectiveUserIsDamagedPartyOnClaim which is - // stricter and only allows the damaged party to act.) - if (claim.blameRequestId) { - const blame = await this.blameRequestDbService.findById( - claim.blameRequestId.toString(), - ); - if (blame) { - const parties: any[] = (blame as any).parties ?? []; - const isParty = parties.some((p: any) => - partyPersonMatchesUser(p?.person, userCtx, linkedUserIds), - ); - if (isParty) return; - } - } - - // Snapshot-party fallback (reliable for claims with snapshot written). - if (this.claimSnapshotPartyMatchesAsDamagedParty(claim, linkedUserIds)) { - return; - } - } - - if (actor?.role === RoleEnum.FIELD_EXPERT) { - const blame = claim.blameRequestId - ? await this.blameRequestDbService.findById( - claim.blameRequestId.toString(), - ) - : null; - if ( - claimCaseInitiatedByFieldExpert(claim, { sub: currentUserId }, blame) - ) { - return; - } - } - - if ( - (actor?.role === RoleEnum.FILE_MAKER || - actor?.role === RoleEnum.FILE_REVIEWER) && - claim.blameRequestId - ) { - const blame = await this.blameRequestDbService.findById( - claim.blameRequestId.toString(), - ); - const isV4OrV5File = - !!(blame as any)?.isMadeByFileMaker && - blame?.expertInitiated && - blame?.creationMethod === "IN_PERSON"; - - if ( - actor.role === RoleEnum.FILE_MAKER && - isV4OrV5File && - claimCaseInitiatedByFieldExpert(claim, { sub: currentUserId }, blame) - ) { - return; - } - - if ( - actor.role === RoleEnum.FILE_REVIEWER && - isV4OrV5File && - String((blame as any)?.assignedFileReviewerId ?? "") === - String(currentUserId) - ) { - return; - } - } - - if (actor?.role === RoleEnum.REGISTRAR && claim.blameRequestId) { - const blame = await this.blameRequestDbService.findById( - claim.blameRequestId.toString(), - ); - if ( - blame?.registrarInitiated && - blame.initiatedByRegistrarId && - String(blame.initiatedByRegistrarId) === currentUserId - ) { - return; - } - } - - throw new ForbiddenException("You do not have access to this claim"); - } - - /** - * Resolve effective user id for claim operations. - * For FIELD_EXPERT acting on expert-initiated IN_PERSON claim, returns the claim owner's id; otherwise returns currentUserId. - */ - private async resolveClaimEffectiveUserId( - claimCase: any, - currentUserId: string, - actorRole?: string, - ): Promise { - const isFieldLikeRole = [ - RoleEnum.FIELD_EXPERT, - RoleEnum.REGISTRAR, - RoleEnum.FILE_MAKER, - RoleEnum.FILE_REVIEWER, - ].includes(actorRole as any); - - if (!isFieldLikeRole || !claimCase?.blameRequestId) { - return currentUserId; - } - const blameRequest = await this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), - ); - if (!blameRequest || blameRequest.creationMethod !== "IN_PERSON") - return currentUserId; - if (actorRole === RoleEnum.FIELD_EXPERT || actorRole === RoleEnum.FILE_MAKER) { - if ( - !blameRequest.expertInitiated || - !blameRequest.initiatedByFieldExpertId || - String(blameRequest.initiatedByFieldExpertId) !== currentUserId - ) { - return currentUserId; - } - } else if (actorRole === RoleEnum.REGISTRAR) { - if ( - !blameRequest.registrarInitiated || - !blameRequest.initiatedByRegistrarId || - String(blameRequest.initiatedByRegistrarId) !== currentUserId - ) { - return currentUserId; - } - } - // FILE_REVIEWER: no initiator-id check — they pick up any IN_PERSON expert - // file after the FileMaker seals it, so we resolve the owner unconditionally. - return ( - resolveDamagedPartyUserId(blameRequest) ?? - (claimCase.owner?.userId ? String(claimCase.owner.userId) : currentUserId) - ); - } - - async createClaimFromBlameForRegistrarV1( - blameRequestId: string, - registrar: { sub: string; firstName?: string; lastName?: string }, - ): Promise { - const blameRequest = - await this.blameRequestDbService.findById(blameRequestId); - if (!blameRequest) throw new NotFoundException("Blame request not found"); - if (blameRequest.status !== BlameCaseStatus.COMPLETED) { - throw new BadRequestException( - `Blame request must be COMPLETED. Current status: ${blameRequest.status}`, - ); - } - if ( - !blameRequest.registrarInitiated || - blameRequest.creationMethod !== "IN_PERSON" || - !blameRequest.initiatedByRegistrarId - ) { - throw new BadRequestException( - "This endpoint is only for registrar-initiated IN_PERSON blame files.", - ); - } - if (String(blameRequest.initiatedByRegistrarId) !== String(registrar.sub)) { - throw new ForbiddenException( - "Only the registrar who created this blame file can create the claim.", - ); - } - const ownerFields = resolveClaimOwnerFieldsFromBlame(blameRequest); - if (!ownerFields) { - throw new BadRequestException( - "Could not resolve claim owner (damaged party) from blame", - ); - } - const existingClaim = await this.claimCaseDbService.findOne({ - blameRequestId: new Types.ObjectId(blameRequestId), - }); - if (existingClaim) - throw new ConflictException("A claim for this blame case already exists"); - const claimNo = await this.generateUniqueClaimNumber(); - const newClaim = await this.claimCaseDbService.create({ - requestNo: claimNo, - publicId: blameRequest.publicId, - blameRequestId: new Types.ObjectId(blameRequestId), - blameRequestNo: blameRequest.requestNo, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - claimStatus: ClaimStatus.PENDING, - inquiries: (blameRequest as any).inquiries ?? {}, - workflow: { - currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS, - nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS, - completedSteps: [ClaimWorkflowStep.CLAIM_CREATED], - locked: false, - }, - damagedPartyUserId: new Types.ObjectId(ownerFields.userId), - owner: { - userId: new Types.ObjectId(ownerFields.userId), - userRole: ownerFields.userRole as any, - ...(ownerFields.clientId - ? { - clientId: new Types.ObjectId(ownerFields.clientId), - userClientKey: ownerFields.clientId, - } - : {}), - }, - createdByRegistrarId: new Types.ObjectId(registrar.sub), - history: [ - { - type: "CLAIM_CREATED", - actor: { - actorId: new Types.ObjectId(registrar.sub), - actorName: - `${registrar.firstName || ""} ${registrar.lastName || ""}`.trim(), - actorType: "registrar", - }, - timestamp: new Date(), - metadata: { - blameRequestId, - blamePublicId: blameRequest.publicId, - createdByRegistrar: true, - }, - }, - ], - } as any); - const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated( - String(newClaim._id), - ); - const message = this.withFanavaranAutoSubmitMessage( - "Claim created successfully. Registrar can now fill claim data.", - fanavaran, - ); - return { - claimRequestId: String(newClaim._id), - publicId: blameRequest.publicId, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - message, - fanavaran, - }; - } - - /** - * V2: Registrar creates a claim from a registrar-initiated IN_PERSON completed blame. - * Mirrors createClaimFromBlameForRegistrarV1 but uses V2 naming conventions. - */ - async createClaimFromBlameForRegistrarV2( - blameRequestId: string, - registrar: { sub: string; firstName?: string; lastName?: string }, - ): Promise { - const blameRequest = - await this.blameRequestDbService.findById(blameRequestId); - if (!blameRequest) throw new NotFoundException("Blame request not found"); - if (blameRequest.status !== BlameCaseStatus.COMPLETED) { - throw new BadRequestException( - `Blame request must be COMPLETED. Current status: ${blameRequest.status}`, - ); - } - if ( - !blameRequest.registrarInitiated || - blameRequest.creationMethod !== "IN_PERSON" || - !blameRequest.initiatedByRegistrarId - ) { - throw new BadRequestException( - "This endpoint is only for registrar-initiated IN_PERSON blame files.", - ); - } - if (String(blameRequest.initiatedByRegistrarId) !== String(registrar.sub)) { - throw new ForbiddenException( - "Only the registrar who created this blame file can create the claim.", - ); - } - const ownerFields = resolveClaimOwnerFieldsFromBlame(blameRequest); - if (!ownerFields) { - throw new BadRequestException( - "Could not resolve claim owner (damaged party) from blame", - ); - } - const existingClaim = await this.claimCaseDbService.findOne({ - blameRequestId: new Types.ObjectId(blameRequestId), - }); - if (existingClaim) - throw new ConflictException("A claim for this blame case already exists"); - const claimNo = await this.generateUniqueClaimNumber(); - const newClaim = await this.claimCaseDbService.create({ - requestNo: claimNo, - publicId: blameRequest.publicId, - blameRequestId: new Types.ObjectId(blameRequestId), - blameRequestNo: blameRequest.requestNo, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - claimStatus: ClaimStatus.PENDING, - inquiries: (blameRequest as any).inquiries ?? {}, - workflow: { - currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS, - nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS, - completedSteps: [ClaimWorkflowStep.CLAIM_CREATED], - locked: false, - }, - damagedPartyUserId: new Types.ObjectId(ownerFields.userId), - owner: { - userId: new Types.ObjectId(ownerFields.userId), - userRole: ownerFields.userRole as any, - ...(ownerFields.clientId - ? { - clientId: new Types.ObjectId(ownerFields.clientId), - userClientKey: ownerFields.clientId, - } - : {}), - }, - createdByRegistrarId: new Types.ObjectId(registrar.sub), - history: [ - { - type: "CLAIM_CREATED", - actor: { - actorId: new Types.ObjectId(registrar.sub), - actorName: - `${registrar.firstName || ""} ${registrar.lastName || ""}`.trim(), - actorType: "registrar", - }, - timestamp: new Date(), - metadata: { - blameRequestId, - blamePublicId: blameRequest.publicId, - createdByRegistrar: true, - }, - }, - ], - } as any); - const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated( - String(newClaim._id), - ); - const message = this.withFanavaranAutoSubmitMessage( - "Claim created successfully. Registrar can now fill claim data on behalf of the damaged party.", - fanavaran, - ); - return { - claimRequestId: String(newClaim._id), - publicId: blameRequest.publicId, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - message, - fanavaran, - }; - } - - /** - * V2 API: Select damaged outer car parts for claim (Step 2 of claim workflow) - * - * @param claimRequestId - The claim case ID - * @param body - Selected outer parts - * @param currentUserId - The current user's ID - * @returns Response with updated claim information - * - * Validations: - * - Claim case must exist - * - User must be the claim owner (damaged party) - * - Current workflow step must be CLAIM_CREATED (step 1) - * - Selected parts array must not be empty - * - Parts must not have been selected previously - */ - async selectOuterPartsV2( - claimRequestId: string, - body: SelectOuterPartsV2Dto, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - try { - // 1. Validate claim exists - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner (damaged party) can select damaged parts", - ); - - // 3. Validate workflow step is correct (should be at SELECT_OUTER_PARTS) - if ( - claimCase.workflow?.currentStep !== ClaimWorkflowStep.SELECT_OUTER_PARTS - ) { - throw new BadRequestException( - `Invalid workflow step. Expected ${ClaimWorkflowStep.SELECT_OUTER_PARTS}, but current step is ${claimCase.workflow?.currentStep}`, - ); - } - - // 4. Validate outer parts haven't been selected yet. - // For FILE_REVIEWER re-reviewing after a FileMaker rejection, the existing - // selection from the prior cycle is intentionally overwritten — skip this - // guard so the reviewer can update the damaged parts list. - const isFileReviewerReselect = - actor?.role === RoleEnum.FILE_REVIEWER; - if ( - !isFileReviewerReselect && - claimCase.damage?.selectedParts && - claimCase.damage.selectedParts.length > 0 - ) { - throw new ConflictException( - "Outer parts have already been selected for this claim", - ); - } - - // 5. Fetch the live Fanavaran catalog and resolve selected parts by ids - const selectedCarType = (body as any)?.carType as - | ClaimVehicleTypeV2 - | undefined; - - const liveCatalog = await this.getLiveFanavaranCatalogItems(); - const byId = new Map( - liveCatalog.map((p) => [p.id, p]), - ); - - const selectedFromIds: OuterPartCatalogItem[] = []; - if ( - Array.isArray((body as any)?.selectedPartIds) && - (body as any).selectedPartIds.length > 0 - ) { - for (const id of (body as any).selectedPartIds as number[]) { - const item = byId.get(id); - if (!item) { - throw new BadRequestException( - `Invalid outer part id: ${id}. Use GET outer-parts-catalog to see valid IDs.`, - ); - } - selectedFromIds.push(item); - } - } - - if (selectedFromIds.length === 0) { - throw new BadRequestException( - "selectedPartIds is required and must contain at least one valid Fanavaran part ID", - ); - } - - const selectedItems = selectedFromIds; - - // DISABLED: At most two non-top sides allowed - // const sideSet = new Set( - // selectedItems - // .map((p) => p.side) - // .filter((s) => s !== "top"), - // ); - // if (sideSet.size > 2) { - // throw new BadRequestException( - // `At most two of left/right/front/back can be selected. Selected: ${[...sideSet].join(", ")}`, - // ); - // } - - const selectedPartDocs = selectedItems.map((p) => - catalogItemToSelectedPart(p, liveCatalog), - ); - const damagedPartsInitial = selectedPartDocs.map((p) => ({ - id: p.id ?? undefined, - name: p.name, - side: p.side, - label_fa: p.label_fa, - ...(p.catalogKey ? { catalogKey: p.catalogKey } : {}), - })); - const selectedPartIds = selectedItems.map((p) => p.id); - - // 6. Update claim case with selected parts and move to next step - const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate( - claimRequestId, - { - "damage.selectedParts": selectedPartDocs, - "media.damagedParts": damagedPartsInitial, - "vehicle.carType": selectedCarType, - status: ClaimCaseStatus.SELECTING_OTHER_PARTS, - "workflow.currentStep": ClaimWorkflowStep.SELECT_OTHER_PARTS, - "workflow.nextStep": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - $unset: { "damage.selectedOuterParts": "" }, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OUTER_PARTS, - history: { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.SELECT_OUTER_PARTS, - selectedParts: selectedPartDocs, - selectedPartIds, - carType: selectedCarType, - partsCount: selectedPartDocs?.length, - description: `User selected ${selectedPartDocs?.length} damaged outer parts`, - }, - }, - }, - }, - ); - - if (!updatedClaim) { - throw new InternalServerErrorException("Failed to update claim case"); - } - - this.logger.log( - `Outer parts selected for claim ${claimRequestId}: ${selectedPartDocs?.length} parts`, - ); - - const fanavaranDamageCase = - await this.autoSubmitFanavaranDamageCaseOnOuterPartsSelected( - claimRequestId, - selectedPartDocs, - ); - - let message = - "Outer parts selected successfully. Please proceed to select other parts and provide bank information."; - if (fanavaranDamageCase.submitted) { - message += " The damage case was sent to Fanavaran successfully."; - } else if (fanavaranDamageCase.warning) { - message += ` ${fanavaranDamageCase.warning}`; - } - - // 7. Return response - return { - claimRequestId: updatedClaim._id.toString(), - publicId: updatedClaim.publicId, - selectedParts: selectedPartDocs, - selectedPartIds, - currentStep: ClaimWorkflowStep.SELECT_OTHER_PARTS, - nextStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - message, - fanavaranDamageCase, - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error( - "selectOuterPartsV2 failed", - claimRequestId, - error instanceof Error ? error.stack : String(error), - ); - throw new InternalServerErrorException( - error instanceof Error ? error.message : "Failed to select outer parts", - ); - } - } - - /** - * V2 API: Select other damaged parts and provide bank information (Step 3 of claim workflow) - * - * @param claimRequestId - The claim case ID - * @param body - Other parts, Sheba number, and national code - * @param currentUserId - The current user's ID - * @returns Response with updated claim information - * - * Validations: - * - Claim case must exist - * - User must be the claim owner (damaged party) - * - Current workflow step must be SELECT_OTHER_PARTS (step 3) - * - Other parts and bank info must not have been submitted previously - */ - async selectOtherPartsV2( - claimRequestId: string, - body: SelectOtherPartsV2Dto, - currentUserId: string, - actor?: { sub: string; role?: string }, - file?: Express.Multer.File, - ): Promise { - try { - // 1. Validate claim exists - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - // 2. Validate user is the damaged party (or field expert for IN_PERSON claim) - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner (damaged party) can submit other parts and bank information", - ); - - // 3. Validate workflow step is correct (should be at SELECT_OTHER_PARTS) - if ( - claimCase.workflow?.currentStep !== - ClaimWorkflowStep.SELECT_OTHER_PARTS && - claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND - ) { - throw new BadRequestException( - `Invalid workflow step. Expected ${ClaimWorkflowStep.SELECT_OTHER_PARTS}, but current step is ${claimCase.workflow?.currentStep}`, - ); - } - - // 4. Validate other parts and bank info haven't been submitted yet - if ( - claimCase.money?.sheba && - claimCase.money?.nationalCodeOfInsurer && - claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND - ) { - throw new ConflictException( - "Bank information has already been submitted for this claim", - ); - } - - // 5. Prepare data - // Backward compatibility aliases: - // - shebaNumber <- sheba - // - nationalCodeOfOwner <- nationalCodeOfInsurer - let otherParts = Array.isArray((body as any)?.otherParts) - ? (body as any).otherParts - : []; - // Multipart clients may send otherParts as JSON string - if ( - !Array.isArray((body as any)?.otherParts) && - typeof (body as any)?.otherParts === "string" - ) { - try { - const parsed = JSON.parse((body as any).otherParts); - otherParts = Array.isArray(parsed) ? parsed : []; - } catch { - otherParts = []; - } - } - const shebaInput = String( - ((body as any).shebaNumber ?? (body as any).sheba ?? "") as string, - ).replace(/\s/g, ""); - - const shebaDigits = shebaInput.replace(/^IR/i, ""); - const shebaNumber = `IR${shebaDigits}`; - const submittedNationalCode = String( - ((body as any).nationalCodeOfOwner ?? - (body as any).nationalCodeOfInsurer ?? - "") as string, - ).replace(/\s/g, ""); - if (!/^[0-9]{24}$/.test(shebaDigits)) { - throw new BadRequestException( - "shebaNumber is required and must be valid (IR + 24 digits or only 24 digits)", - ); - } - const blameRequest = claimCase.blameRequestId - ? await this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), - ) - : null; - const storedOwnerNationalCode = - this.resolveVehicleOwnerNationalCodeForClaim(blameRequest); - if ( - storedOwnerNationalCode && - submittedNationalCode && - submittedNationalCode !== storedOwnerNationalCode - ) { - throw new BadRequestException( - "Submitted national code does not match the vehicle owner saved on the blame case.", - ); - } - const nationalCode = storedOwnerNationalCode ?? submittedNationalCode; - if (!/^[0-9]{10}$/.test(nationalCode)) { - throw new BadRequestException( - "Vehicle owner national code is unavailable; a 10-digit nationalCodeOfOwner is required only for legacy claims.", - ); - } - const ownershipPlate = this.resolveOwnershipPlateForClaim( - claimCase, - blameRequest, - ); - if (!ownershipPlate) { - throw new BadRequestException( - "Could not resolve vehicle plate for ownership validation.", - ); - } - - let step = claimCase.workflow?.currentStep; - - // External inquiry checks before moving workflow: - // 1) ownership check for nationalCode + plate - // await this.sandHubService.getCarOwnershipInfo(ownershipPlate, nationalCode); - // 2) sheba check for nationalCode + sheba - await this.sandHubService.getShebaValidation(nationalCode, shebaNumber); - - const updatePayload: any = { - "damage.otherParts": otherParts.length > 0 ? otherParts : undefined, - "money.sheba": shebaNumber, - "money.nationalCodeOfInsurer": nationalCode, - - status: ClaimCaseStatus.CAPTURING_PART_DAMAGES, - "workflow.currentStep": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "workflow.nextStep": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - - $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OTHER_PARTS, - history: { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.SELECT_OTHER_PARTS, - otherParts, - otherPartsCount: otherParts.length, - hasBankInfo: true, - hasGreenCardUpload: !!file, - description: `User selected ${otherParts.length} other damaged parts and provided bank information`, - }, - }, - }, - }; - - if (file) { - const existingGreen = - (claimCase.requiredDocuments as any)?.get?.( - ClaimRequiredDocumentType.CAR_GREEN_CARD, - ) || - (claimCase.requiredDocuments as any)?.[ - ClaimRequiredDocumentType.CAR_GREEN_CARD - ]; - if (existingGreen?.uploaded) { - throw new ConflictException( - "car_green_card has already been uploaded for this claim", - ); - } - const docRef = await this.claimRequiredDocumentDbService.create({ - path: file.path, - fileName: file.filename, - claimId: new Types.ObjectId(claimRequestId), - documentType: ClaimRequiredDocumentType.CAR_GREEN_CARD, - uploadedAt: new Date(), - }); - updatePayload[ - `requiredDocuments.${ClaimRequiredDocumentType.CAR_GREEN_CARD}` - ] = { - fileId: docRef._id, - filePath: file.path, - fileName: file.filename, - uploaded: true, - uploadedAt: new Date(), - }; - } - - // 6. Update claim case with other parts, bank info and optional green card file - const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate( - claimRequestId, - updatePayload, - ); - - if (!updatedClaim) { - throw new InternalServerErrorException("Failed to update claim case"); - } - - this.logger.log( - `Other parts and bank info submitted for claim ${claimRequestId}: ${otherParts.length} parts`, - ); - - // 7. Mask sensitive data for response - const maskedSheba = `IR${shebaDigits.slice(0, 4)}************${shebaDigits.slice(-4)}`; - const maskedNationalCode = `${nationalCode.slice(0, 2)}******${nationalCode.slice(-2)}`; - - // 8. Return response - return { - claimRequestId: updatedClaim._id.toString(), - publicId: updatedClaim.publicId, - otherParts: otherParts, - shebaNumber: maskedSheba, - nationalCodeOfOwner: maskedNationalCode, - currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - nextStep: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - message: - "Other parts and bank information saved successfully. Please capture car angles and damaged parts, then upload required documents.", - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error( - "selectOtherPartsV2 failed", - claimRequestId, - error instanceof Error ? error.stack : String(error), - ); - throw new InternalServerErrorException( - error instanceof Error ? error.message : "Failed to select other parts", - ); - } - } - - /** - * V2 API: Get capture requirements for claim (documents, angles, parts) - */ - async getCaptureRequirementsV2( - claimRequestId: string, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - try { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can view capture requirements", - ); - - // Build outer-parts lookup for resolving stored DB parts. - // Uses the static snapshot (FANAVARAN_CAR_PARTS_CATALOG) which is keyed - // by numeric id (key === String(id)). This is only needed for legacy - // migration of parts stored before the Fanavaran catalog change. - const catalogByKey = new Map(); - for (const item of FANAVARAN_CAR_PARTS_CATALOG) { - if (!catalogByKey.has(item.key)) catalogByKey.set(item.key, item); - } - - // Required documents vary by claim type. The accident sketch is offered - // in every flow, but is excluded from every completion calculation. - const blameRequest = claimCase.blameRequestId - ? await this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), - ) - : null; - const isCarBody = blameRequest?.type === BlameRequestType.CAR_BODY; - const requiredDocsDefinition = [ - { - key: ClaimRequiredDocumentType.ACCIDENT_SKETCH, - label_fa: "کروکی", - label_en: "Accident Sketch", - category: "general", - required: false, - }, - { - key: "damaged_driving_license_front", - label_fa: "گواهینامه طرف آسیب‌دیده - جلو", - label_en: "Damaged Party License - Front", - category: "damaged_party", - required: true, - }, - { - key: "damaged_driving_license_back", - label_fa: "گواهینامه طرف آسیب‌دیده - پشت", - label_en: "Damaged Party License - Back", - category: "damaged_party", - required: true, - }, - { - key: "damaged_chassis_number", - label_fa: "شماره شاسی", - label_en: "Chassis Number", - category: "damaged_party", - required: true, - }, - { - key: "damaged_engine_photo", - label_fa: "عکس موتور", - label_en: "Engine Photo", - category: "damaged_party", - required: true, - }, - { - key: "damaged_car_card_front", - label_fa: "کارت خودرو آسیب‌دیده - جلو", - label_en: "Damaged Car Card - Front", - category: "damaged_party", - required: true, - }, - { - key: "damaged_car_card_back", - label_fa: "کارت خودرو آسیب‌دیده - پشت", - label_en: "Damaged Car Card - Back", - category: "damaged_party", - required: true, - }, - { - key: "damaged_metal_plate", - label_fa: "پلاک فلزی آسیب‌دیده", - label_en: "Damaged Metal Plate", - category: "damaged_party", - required: true, - }, - { - key: "car_green_card", - label_fa: "کارت سبز خودرو", - label_en: "Car Green Card", - category: "damaged_party", - required: true, - }, - ...(isCarBody - ? [] - : [ - { - key: "guilty_driving_license_front", - label_fa: "گواهینامه طرف مقصر - جلو", - label_en: "Guilty Party License - Front", - category: "guilty_party", - required: true, - }, - { - key: "guilty_driving_license_back", - label_fa: "گواهینامه طرف مقصر - پشت", - label_en: "Guilty Party License - Back", - category: "guilty_party", - required: true, - }, - { - key: "guilty_car_card_front", - label_fa: "کارت خودرو مقصر - جلو", - label_en: "Guilty Car Card - Front", - category: "guilty_party", - required: true, - }, - { - key: "guilty_car_card_back", - label_fa: "کارت خودرو مقصر - پشت", - label_en: "Guilty Car Card - Back", - category: "guilty_party", - required: true, - }, - { - key: "guilty_metal_plate", - label_fa: "پلاک فلزی مقصر", - label_en: "Guilty Metal Plate", - category: "guilty_party", - required: true, - }, - ]), - ]; - - const requiredDocuments = requiredDocsDefinition.map((doc) => { - const docData = (claimCase.requiredDocuments as any)?.get?.(doc.key); - return { - key: doc.key, - label_fa: doc.label_fa, - label_en: doc.label_en, - category: doc.category, - required: doc.required, - uploaded: docData?.uploaded || false, - preferUploadDuringCapture: isCapturePhaseDamagedPartyDocKey(doc.key), - }; - }); - - const hasCapture = (data: any, key: string) => - data && (data instanceof Map ? data.get(key) : data[key]); - - // Car angles - const carAngles = [ - { key: "front", label_fa: "جلوی ماشین", label_en: "Front of the car" }, - { key: "back", label_fa: "عقب ماشین", label_en: "Back of the car" }, - { key: "left", label_fa: "چپ ماشین", label_en: "Left of the car" }, - { key: "right", label_fa: "راست ماشین", label_en: "Right of the car" }, - ].map((angle) => ({ - key: angle.key, - label_fa: angle.label_fa, - label_en: angle.label_en, - captured: hasClaimCarAngleCapture( - claimCase.media?.carAngles as any, - claimCase.media?.damagedParts as any, - angle.key as ClaimCarAngleKey, - ), - })); - - const carType = claimCase.vehicle?.carType as - | ClaimVehicleTypeV2 - | undefined; - const selectedNorm = normalizeDamageSelectedParts( - claimCase.damage?.selectedParts, - carType, - (claimCase.damage as any)?.selectedOuterParts, - ); - - const damagedParts = selectedNorm.map((sp) => { - const catalogMeta = sp.catalogKey - ? catalogByKey.get(sp.catalogKey) - : sp.name - ? catalogByKey.get(catalogLikeKeyFromPart(sp)) - : undefined; - const labelEnName = sp.name - .replace(/([a-z])([A-Z])/g, "$1 $2") - .replace(/_/g, " ") - .trim() - .replace(/\b\w/g, (c) => c.toUpperCase()); - const ck = sp.catalogKey ?? catalogLikeKeyFromPart(sp); - return { - id: sp.id ?? catalogMeta?.id, - key: sp.name, - name: sp.name, - side: sp.side, - label_fa: sp.label_fa, - label_en: labelEnName, - captured: hasDamagedPartCapture( - claimCase.media?.damagedParts as any, - ck, - selectedNorm, - ), - }; - }); - - // Calculate progress - const requiredDocumentItems = requiredDocuments.filter( - (d) => d.required, - ); - const documentsUploaded = requiredDocumentItems.filter( - (d) => d.uploaded, - ).length; - const anglesCaptured = carAngles.filter((a) => a.captured).length; - const partsCaptured = damagedParts.filter((p) => p.captured).length; - - const captureProgress = getClaimCaptureProgress(claimCase); - const capturePhaseDocsRemaining = - captureProgress.capturePhaseDocsRemaining; - const partsRemaining = Math.max( - 0, - captureProgress.partsTotal - captureProgress.partsCaptured, - ); - const anglesRemaining = Math.max( - 0, - captureProgress.anglesTotal - captureProgress.anglesCaptured, - ); - const postCaptureDocsRemaining = requiredDocuments.filter( - (d) => d.required && !d.preferUploadDuringCapture && !d.uploaded, - ).length; - - const totalRemaining = - partsRemaining + anglesRemaining + capturePhaseDocsRemaining; - - return { - claimRequestId: claimCase._id.toString(), - publicId: claimCase.publicId, - currentStep: claimCase.workflow?.currentStep || "", - captureSequencePhase: captureProgress.sequencePhase, - captureSequenceHint: capturePhaseSequenceMessage( - captureProgress.sequencePhase, - ), - requiredDocuments, - carAngles, - damagedParts, - totalRemaining, - progress: { - documentsUploaded, - documentsTotal: requiredDocumentItems.length, - anglesCaptured, - anglesTotal: carAngles.length, - partsCaptured, - partsTotal: damagedParts.length, - capturePhaseDocsRemaining, - postCaptureDocumentsRemaining: postCaptureDocsRemaining, - }, - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("getCaptureRequirementsV2 failed", error); - throw new InternalServerErrorException( - "Failed to get capture requirements", - ); - } - } - - /** - * When the owner has uploaded every expert-requested document/part (or acknowledged description-only resend), - * move the claim back to the damage expert queue (same posture as after initial submission). - */ - private async tryFinalizeExpertResendAfterUserAction( - claimRequestId: string, - actorUserId: string, - ownerDisplayName: string, - ): Promise { - const claim = await this.claimCaseDbService.findById(claimRequestId); - if (!claim || !canFinalizeExpertResend(claim)) { - return; - } - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT, - claimStatus: ClaimStatus.PENDING, - "workflow.currentStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - "workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, - "evaluation.damageExpertResend.fulfilledAt": new Date(), - }, - $push: { - history: { - type: "EXPERT_RESEND_FULFILLED", - actor: { - actorId: new Types.ObjectId(actorUserId), - actorName: ownerDisplayName, - actorType: "user", - }, - timestamp: new Date(), - metadata: {}, - }, - }, - }); - } - - /** - * V2: Owner acknowledges a description-only expert resend (no extra documents or part photos requested). - */ - async acknowledgeExpertResendInstructionsV2( - claimRequestId: string, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise<{ - claimRequestId: string; - status: string; - claimStatus: string; - currentStep: string; - message: string; - }> { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can complete this step", - ); - if ( - claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND - ) { - throw new BadRequestException( - `No expert resend step is active. Current step: ${claimCase.workflow?.currentStep ?? "none"}`, - ); - } - if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) { - throw new BadRequestException( - `Claim is not waiting for resend action. Current status: ${claimCase.status}`, - ); - } - const r = claimCase.evaluation?.damageExpertResend; - if (!r || r.fulfilledAt) { - throw new BadRequestException( - "There is no active expert resend request to acknowledge.", - ); - } - if ( - normalizeResendDocumentKeys(r.resendDocuments).length > 0 || - normalizeResendPartKeys( - r.resendCarParts, - claimCase.vehicle?.carType as ClaimVehicleTypeV2 | undefined, - claimCase.damage?.selectedParts, - ).length > 0 - ) { - throw new BadRequestException( - "Upload all requested documents and part photos before completing the resend step.", - ); - } - await this.tryFinalizeExpertResendAfterUserAction( - claimRequestId, - effectiveUserId, - claimCase.owner?.fullName || "User", - ); - const updated = await this.claimCaseDbService.findById(claimRequestId); - return { - claimRequestId, - status: String(updated?.status ?? ""), - claimStatus: String(updated?.claimStatus ?? ""), - currentStep: String(updated?.workflow?.currentStep ?? ""), - message: "Claim returned to the damage expert queue.", - }; - } - - /** - * V2 API: Upload required document - */ - async uploadRequiredDocumentV2( - claimRequestId: string, - body: UploadRequiredDocumentV2Dto, - file: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string }, - options?: { v3InPersonFlow?: boolean; skipMetalPlate?: boolean; requiresFileMakerApproval?: boolean; includeGuiltyDamageArea?: boolean }, - ): Promise { - try { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can upload documents", - ); - - const step = claimCase.workflow?.currentStep; - const isResendUpload = step === ClaimWorkflowStep.USER_EXPERT_RESEND; - const isOptionalDocument = - body.documentKey === ClaimRequiredDocumentType.ACCIDENT_SKETCH; - const isCapturePhaseDocUpload = - step === ClaimWorkflowStep.CAPTURE_PART_DAMAGES && - (isCapturePhaseDamagedPartyDocKey(body.documentKey) || - (options?.includeGuiltyDamageArea && - (body.documentKey as string) === GUILTY_DAMAGE_AREA_DOC_KEY)); - - if (!isResendUpload) { - if ( - step === ClaimWorkflowStep.CAPTURE_PART_DAMAGES && - !isCapturePhaseDocUpload - ) { - throw new BadRequestException( - `During ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} only chassis, engine, and damaged metal plate photos may be uploaded here (${CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS.join(", ")}), and only after all damaged parts and car angles are captured.`, - ); - } - if (isCapturePhaseDocUpload) { - const captureProgress = getClaimCaptureProgress(claimCase); - if (!captureProgress.partsComplete) { - throw new BadRequestException( - "Upload photos for all selected damaged parts before uploading chassis, engine, or metal plate photos.", - ); - } - if (!captureProgress.anglesComplete) { - throw new BadRequestException( - "Capture all four car angles (front, back, left, right) before uploading chassis, engine, or metal plate photos.", - ); - } - } - const allowedInitialUploadStep = - step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS || - isCapturePhaseDocUpload || - (isOptionalDocument && - step === ClaimWorkflowStep.USER_SUBMISSION_COMPLETE); - if (!allowedInitialUploadStep) { - throw new BadRequestException( - `Invalid workflow step. Expected ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS}, ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} (capture-phase documents only), or ${ClaimWorkflowStep.USER_EXPERT_RESEND}, but current step is ${claimCase.workflow?.currentStep}`, - ); - } - if (options?.v3InPersonFlow) { - if ( - step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && - isCapturePhaseDamagedPartyDocKey(body.documentKey) - ) { - const capturePartDone = ( - claimCase.workflow?.completedSteps ?? [] - ).includes(ClaimWorkflowStep.CAPTURE_PART_DAMAGES); - if (!capturePartDone) { - throw new BadRequestException( - `Complete outer/other part selection and capture-part (damaged parts + car angles) before uploading chassis, engine, and metal plate photos (${CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS.join(", ")}).`, - ); - } - throw new BadRequestException( - `Chassis, engine, and metal plate photos must be uploaded during ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} after parts and angles are captured.`, - ); - } - } - } - - if (isResendUpload) { - if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) { - throw new BadRequestException( - `Claim is not waiting for expert resend uploads. Status: ${claimCase.status}`, - ); - } - if (!documentKeyAllowedForExpertResend(claimCase, body.documentKey)) { - throw new BadRequestException( - `Document "${body.documentKey}" was not requested by the damage expert for this resend.`, - ); - } - } - - // CAR_BODY claims only allow 7 document types (no guilty_*) - const blameForUpload = claimCase.blameRequestId - ? await this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), - ) - : null; - const isCarBodyUpload = - blameForUpload?.type === BlameRequestType.CAR_BODY; - const guiltyKeys = [ - "guilty_driving_license_front", - "guilty_driving_license_back", - "guilty_car_card_front", - "guilty_car_card_back", - "guilty_metal_plate", - ]; - if (isCarBodyUpload && guiltyKeys.includes(body.documentKey)) { - throw new BadRequestException( - `Document type ${body.documentKey} is not required for CAR_BODY claims`, - ); - } - - // Initial flow: each document once. Expert resend and v3 in-person: allow replacement. - if (!isResendUpload && !options?.v3InPersonFlow) { - const existingDoc = - (claimCase.requiredDocuments as any)?.get?.(body.documentKey) ?? - (claimCase.requiredDocuments as any)?.[body.documentKey]; - if (existingDoc?.uploaded) { - throw new ConflictException( - `Document ${body.documentKey} has already been uploaded`, - ); - } - } - - const fileUrl = buildFileLink(file.path); - - const docRef = await this.claimRequiredDocumentDbService.create({ - path: file.path, - fileName: file.filename, - claimId: new Types.ObjectId(claimRequestId), - documentType: body.documentKey, - uploadedAt: new Date(), - }); - - // Base history entry for this upload - const uploadHistoryEntry = { - type: "DOCUMENT_UPLOADED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - documentKey: body.documentKey, - fileName: file.filename, - fileId: docRef._id.toString(), - }, - }; - - // Base $set — always applied - const $set: Record = { - [`requiredDocuments.${body.documentKey}`]: { - fileId: docRef._id, - filePath: file.path, - fileName: file.filename, - uploaded: true, - uploadedAt: new Date(), - }, - }; - - // History entries to push — always at least the upload entry - const historyEntries: unknown[] = [uploadHistoryEntry]; - - // completedSteps entries to push - const completedStepsEntries: string[] = []; - - let allDocumentsUploaded = false; - let remaining = 0; - let captureStepCompletedOnThisUpload = false; - - if (!isResendUpload && !isOptionalDocument) { - if (isCapturePhaseDocUpload) { - const afterThis = (k: string) => - k === body.documentKey || - this.isRequiredDocumentUploadedOnClaim(claimCase, k); - const captureKeysForCount: string[] = [ - ...CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS, - ...(options?.includeGuiltyDamageArea ? [GUILTY_DAMAGE_AREA_DOC_KEY] : []), - ]; - remaining = captureKeysForCount.filter((k) => { - if (options?.skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)) return false; - return !afterThis(k); - }).length; - - if (remaining === 0) { - const progressAfterDoc = getClaimCaptureProgress(claimCase, { - assumeCapturePhaseDocKey: body.documentKey, - skipMetalPlate: options?.skipMetalPlate, - includeGuiltyDamageArea: options?.includeGuiltyDamageArea, - }); - - if ( - progressAfterDoc.partsComplete && - progressAfterDoc.anglesComplete && - progressAfterDoc.capturePhaseDocsComplete - ) { - captureStepCompletedOnThisUpload = true; - - // Advance to walk-around video step (UPLOADING_REQUIRED_DOCUMENTS / - // UPLOAD_REQUIRED_DOCUMENTS). For V4/V5 the claim is finalised in - // setVideoCaptureV3 (car-capture), which is the last FileReviewer - // action before handing off to the damage expert. - $set["status"] = ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS; - $set["workflow.currentStep"] = ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS; - $set["workflow.nextStep"] = ClaimWorkflowStep.USER_SUBMISSION_COMPLETE; - - completedStepsEntries.push( - ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - ); - historyEntries.push({ - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - description: options?.v3InPersonFlow - ? "V4/V5 capture docs complete. Upload walk-around video to finalise." - : "Angles, damaged parts, and capture-phase vehicle evidence are complete.", - }, - }); - } - } - } else { - const v3InitialDocsComplete = - !!options?.v3InPersonFlow && - step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && - this.allV3PreCaptureDocumentsComplete( - claimCase, - isCarBodyUpload, - body.documentKey, - options?.skipMetalPlate, - ); - - allDocumentsUploaded = options?.v3InPersonFlow - ? v3InitialDocsComplete - : this.allV2OwnerDocumentsComplete( - claimCase, - isCarBodyUpload, - body.documentKey, - ); - remaining = options?.v3InPersonFlow - ? this.countRemainingV3PreCaptureDocuments( - claimCase, - isCarBodyUpload, - body.documentKey, - options?.skipMetalPlate, - ) - : this.countRemainingV2OwnerDocuments( - claimCase, - isCarBodyUpload, - body.documentKey, - ); - - if (allDocumentsUploaded) { - if (options?.v3InPersonFlow) { - // V4/V5 split flow: the status transition to WAITING_FOR_FILE_REVIEWER is - // deferred to a post-write re-check (see below) to eliminate the race - // condition where two concurrent uploads each see a stale snapshot and - // neither fires the transition. We skip adding it to $set here. - } else { - $set["status"] = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT; - $set["claimStatus"] = ClaimStatus.PENDING; - $set["workflow.currentStep"] = - ClaimWorkflowStep.USER_SUBMISSION_COMPLETE; - $set["workflow.nextStep"] = - ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT; - - completedStepsEntries.push( - ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - ); - historyEntries.push( - { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - description: "All required documents uploaded", - }, - }, - { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - description: - "User submission complete. Claim ready for damage expert review.", - }, - }, - ); - } - } - } - } - - if (!isResendUpload && isOptionalDocument) { - allDocumentsUploaded = options?.v3InPersonFlow - ? this.allV3PreCaptureDocumentsComplete( - claimCase, - isCarBodyUpload, - undefined, - options?.skipMetalPlate, - ) - : this.allV2OwnerDocumentsComplete(claimCase, isCarBodyUpload); - remaining = options?.v3InPersonFlow - ? this.countRemainingV3PreCaptureDocuments( - claimCase, - isCarBodyUpload, - undefined, - options?.skipMetalPlate, - ) - : this.countRemainingV2OwnerDocuments( - claimCase, - isCarBodyUpload, - ); - } - - // Build the final MongoDB update — all operators explicit and clean - const updatePayload: Record = { $set }; - - const $push: Record = { - history: - historyEntries.length === 1 - ? historyEntries[0] - : { $each: historyEntries }, - }; - if (completedStepsEntries.length === 1) { - $push["workflow.completedSteps"] = completedStepsEntries[0]; - } else if (completedStepsEntries.length > 1) { - $push["workflow.completedSteps"] = { $each: completedStepsEntries }; - } - updatePayload.$push = $push; - - await this.claimCaseDbService.findByIdAndUpdate( - claimRequestId, - updatePayload, - ); - - // ─── V4/V5 in-person flow: post-write race-safe status transition ────── - // After the write we re-read the actual DB state. If all pre-capture - // documents are now present but the status has not yet advanced (i.e. a - // concurrent request uploaded the last doc a split-second before us and - // the stale snapshot we read earlier missed it — or vice-versa), we apply - // WAITING_FOR_FILE_REVIEWER atomically using findOneAndUpdate with a status - // condition, so exactly one writer wins regardless of concurrency. - if (options?.v3InPersonFlow && !isResendUpload && !isCapturePhaseDocUpload) { - const afterWrite = await this.claimCaseDbService.findById(claimRequestId); - if (afterWrite) { - const blameForRecheck = afterWrite.blameRequestId - ? await this.blameRequestDbService.findById( - afterWrite.blameRequestId.toString(), - ) - : null; - const isCarBodyRecheck = blameForRecheck?.type === BlameRequestType.CAR_BODY; - const skipMetalPlateRecheck = !!(blameForRecheck as any)?.isMadeByFileMaker; - const allDoneNow = - afterWrite.status === ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS && - afterWrite.workflow?.currentStep === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && - this.allV3PreCaptureDocumentsComplete(afterWrite, isCarBodyRecheck, undefined, skipMetalPlateRecheck); - - if (allDoneNow) { - // Atomic conditional update: only succeeds when status is still - // UPLOADING_REQUIRED_DOCUMENTS, preventing double-application. - const advanced = await this.claimCaseDbService.findOneAndUpdate( - { - _id: afterWrite._id, - status: ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS, - }, - { - $set: { - status: ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER, - "workflow.nextStep": ClaimWorkflowStep.SELECT_OUTER_PARTS, - }, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - history: { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: afterWrite.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - description: - "FileMaker documents complete. File sealed — awaiting FileReviewer.", - v3InPersonFlow: true, - }, - }, - }, - }, - ); - if (advanced) { - // This request won the race — reflect the final state in the response. - allDocumentsUploaded = true; - // Now that the FileMaker's document phase is complete, promote the - // blame file to WAITING_FOR_FILE_REVIEWER so the frontend shows the - // correct sealed state when the FileMaker returns. - const blameId = (afterWrite as any).blameRequestId; - if (blameId) { - await this.blameRequestDbService.findByIdAndUpdate( - String(blameId), - { $set: { status: BlameCaseStatus.WAITING_FOR_FILE_REVIEWER } }, - ); - } - } - } else if ( - afterWrite.status === ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER || - (afterWrite.workflow?.completedSteps ?? []).includes( - ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - ) - ) { - // Another concurrent request already advanced the status — treat - // this upload as the completing upload for response purposes. - allDocumentsUploaded = true; - } - } - } - - // Auto-submit Fanavaran attachments when all documents are uploaded - if ( - allDocumentsUploaded && - !isOptionalDocument && - !isResendUpload && - !options?.v3InPersonFlow - ) { - this.submitFanavaranAttachmentsV2(claimRequestId, resolveFanavaranClientKey()).catch( - (err) => this.logger.warn(`Fanavaran attachments auto-submit failed: ${err?.message}`), - ); - } - - if (isResendUpload) { - await this.tryFinalizeExpertResendAfterUserAction( - claimRequestId, - currentUserId, - claimCase.owner?.fullName || "User", - ); - const refreshed = - await this.claimCaseDbService.findById(claimRequestId); - const expertResendComplete = - !!refreshed?.evaluation?.damageExpertResend?.fulfilledAt; - const fanavaranAttachment = await this.autoSubmitFanavaranAttachment( - claimRequestId, - { - path: file.path, - fileName: file.filename, - source: `document:${body.documentKey}:resend`, - }, - ); - return { - claimRequestId: claimCase._id.toString(), - documentKey: body.documentKey, - fileUrl, - allDocumentsUploaded: false, - expertResendComplete, - currentStep: - refreshed?.workflow?.currentStep || - ClaimWorkflowStep.USER_EXPERT_RESEND, - message: expertResendComplete - ? "Expert resend requirements are complete. Your claim is back in the damage expert queue." - : "Document uploaded for expert resend.", - fanavaranAttachment, - }; - } - - const message = isOptionalDocument - ? "Optional accident sketch uploaded successfully." - : isCapturePhaseDocUpload - ? captureStepCompletedOnThisUpload - ? options?.v3InPersonFlow - ? "Capture-phase documents and all damage captures are complete. Upload the walk-around video (car-capture) to finalise." - : "Capture-phase documents and all damage captures are complete. Please proceed to upload the remaining required documents." - : remaining > 0 - ? `Document saved. ${remaining} capture-phase document(s) still required (chassis, engine, metal plate).` - : capturePhaseSequenceMessage( - getClaimCaptureProgress(claimCase, { - assumeCapturePhaseDocKey: body.documentKey, - }).sequencePhase, - ) - : allDocumentsUploaded - ? options?.v3InPersonFlow - ? "All FileMaker documents uploaded. File is sealed and ready for FileReviewer pickup." - : "All documents uploaded successfully. Your claim is now ready for damage expert review." - : `Document uploaded successfully. ${remaining} documents remaining.`; - - return { - claimRequestId: claimCase._id.toString(), - documentKey: body.documentKey, - fileUrl, - allDocumentsUploaded, - currentStep: isOptionalDocument - ? step || ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - : isCapturePhaseDocUpload - ? captureStepCompletedOnThisUpload - ? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - : ClaimWorkflowStep.CAPTURE_PART_DAMAGES - : allDocumentsUploaded - ? options?.v3InPersonFlow - ? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - : ClaimWorkflowStep.USER_SUBMISSION_COMPLETE - : ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - message, - fanavaranAttachment: await this.autoSubmitFanavaranAttachment( - claimRequestId, - { - path: file.path, - fileName: file.filename, - source: `document:${body.documentKey}`, - }, - ), - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("uploadRequiredDocumentV2 failed", error); - throw new InternalServerErrorException("Failed to upload document"); - } - } - - /** - * V2 API: Capture car angle or damaged part - */ - async capturePartV2( - claimRequestId: string, - body: CapturePartV2Dto, - file: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - try { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can capture parts", - ); - - const capStep = claimCase.workflow?.currentStep; - const isResendCapture = capStep === ClaimWorkflowStep.USER_EXPERT_RESEND; - if ( - !isResendCapture && - capStep !== ClaimWorkflowStep.CAPTURE_PART_DAMAGES - ) { - throw new BadRequestException( - `Invalid workflow step. Expected ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} or ${ClaimWorkflowStep.USER_EXPERT_RESEND}, but current step is ${claimCase.workflow?.currentStep}`, - ); - } - if (isResendCapture) { - if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) { - throw new BadRequestException( - `Claim is not waiting for expert resend uploads. Status: ${claimCase.status}`, - ); - } - if (body.captureType !== "part") { - throw new BadRequestException( - "During expert resend only damaged-part photos can be uploaded (not car angles).", - ); - } - if (!partKeyAllowedForExpertResend(claimCase, body.captureKey)) { - throw new BadRequestException( - `Part "${body.captureKey}" was not requested by the damage expert for this resend.`, - ); - } - if (canonicalizeClaimCarAngleKey(body.captureKey)) { - throw new BadRequestException( - "During expert resend only damaged-part photos are allowed, not car angles (front/back/left/right).", - ); - } - } - - if (!isResendCapture) { - const captureProgressBefore = getClaimCaptureProgress(claimCase); - const willBeAngle = - body.captureType === "angle" || - (body.captureType === "part" && - canonicalizeClaimCarAngleKey(body.captureKey) !== null); - if (willBeAngle && !captureProgressBefore.partsComplete) { - throw new BadRequestException( - "Upload photos for all selected damaged parts before capturing car angles.", - ); - } - } - - const angleCanon = canonicalizeClaimCarAngleKey(body.captureKey); - if (body.captureType === "angle" && !angleCanon) { - throw new BadRequestException( - `Invalid angle captureKey "${body.captureKey}". Use one of: front, back, left, right.`, - ); - } - const treatAsAngle = - !isResendCapture && - (body.captureType === "angle" || - (body.captureType === "part" && angleCanon !== null)); - - const fileUrl = buildFileLink(file.path); - const captureData = { - path: file.path, - fileName: file.filename, - url: fileUrl, - capturedAt: new Date(), - }; - - const updateData: any = { - $push: { - history: { - type: treatAsAngle ? "ANGLE_CAPTURED" : "PART_CAPTURED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - captureType: body.captureType, - captureKey: body.captureKey, - ...(treatAsAngle && angleCanon - ? { resolvedCarAngleKey: angleCanon } - : {}), - fileName: file.filename, - }, - }, - }, - }; - - const carType = claimCase.vehicle?.carType as - | ClaimVehicleTypeV2 - | undefined; - const selectedOuterLegacy = (claimCase.damage as any)?.selectedOuterParts; - const selectedBeforeNorm = normalizeDamageSelectedParts( - claimCase.damage?.selectedParts, - carType, - selectedOuterLegacy, - ); - let nextSelected = [...selectedBeforeNorm]; - let nextMedia = coerceDamagedPartsMediaToArray( - claimCase.media?.damagedParts, - nextSelected, - ); - - if (treatAsAngle && angleCanon) { - updateData[`media.carAngles.${angleCanon}`] = captureData; - if (!Array.isArray(claimCase.media?.damagedParts)) { - const unsetFieldKeys = legacyAngleDamagedPartFieldKeysToUnset( - angleCanon, - body.captureKey, - claimCase.damage?.selectedParts, - carType, - selectedOuterLegacy, - ); - if (unsetFieldKeys.length) { - updateData.$unset = {}; - for (const k of unsetFieldKeys) { - updateData.$unset[`media.damagedParts.${k}`] = ""; - } - } - } - } else { - let idx = resolvePartCaptureIndex( - body.captureKey, - nextSelected, - nextMedia, - ); - if (isResendCapture && body.captureType === "part" && idx < 0) { - const added = normalizeDamageSelectedParts( - [body.captureKey], - carType, - undefined, - ); - const row = added[0] || { - id: null, - name: body.captureKey, - side: "", - label_fa: body.captureKey, - catalogKey: body.captureKey, - }; - nextSelected.push(row); - idx = nextSelected.length - 1; - nextMedia.push({}); - } - if (idx < 0) { - throw new BadRequestException( - `Unknown damaged-part captureKey "${body.captureKey}". Use catalog id, 0-based index, or catalog key.`, - ); - } - while (nextMedia.length <= idx) { - nextMedia.push({}); - } - const base = nextSelected[idx] || { - id: null, - name: String(body.captureKey), - side: "", - label_fa: String(body.captureKey), - }; - nextMedia[idx] = { - ...(base.id != null ? { id: base.id } : {}), - name: base.name, - side: base.side, - label_fa: base.label_fa, - ...(base.catalogKey ? { catalogKey: base.catalogKey } : {}), - ...nextMedia[idx], - ...captureData, - }; - // Per-index $set avoids lost updates when clients upload multiple parts - // in parallel (whole-array replace raced with Fanavaran-awaited requests). - // Legacy object maps still need a full write to migrate to array shape. - if (!Array.isArray(claimCase.media?.damagedParts)) { - updateData["media.damagedParts"] = nextMedia; - } else { - updateData[`media.damagedParts.${idx}`] = nextMedia[idx]; - } - if ( - isResendCapture && - nextSelected.length !== selectedBeforeNorm.length - ) { - updateData["damage.selectedParts"] = nextSelected; - } - } - - await this.claimCaseDbService.findByIdAndUpdate( - claimRequestId, - updateData, - ); - // Re-read so capture-progress sees sibling concurrent part/angle writes. - const updatedClaim = - (await this.claimCaseDbService.findById(claimRequestId)) ?? - claimCase; - - if (isResendCapture) { - await this.tryFinalizeExpertResendAfterUserAction( - claimRequestId, - currentUserId, - claimCase.owner?.fullName || "User", - ); - const refreshed = - await this.claimCaseDbService.findById(claimRequestId); - const expertResendComplete = - !!refreshed?.evaluation?.damageExpertResend?.fulfilledAt; - const fanavaranAttachment = await this.autoSubmitFanavaranAttachment( - claimRequestId, - { - path: file.path, - fileName: file.filename, - source: `capture:${body.captureType}:${body.captureKey}:resend`, - }, - ); - return { - claimRequestId: claimCase._id.toString(), - captureType: body.captureType, - captureKey: body.captureKey, - fileUrl, - allCapturesComplete: expertResendComplete, - expertResendComplete, - currentStep: - refreshed?.workflow?.currentStep || - ClaimWorkflowStep.USER_EXPERT_RESEND, - message: expertResendComplete - ? "Expert resend requirements are complete. Your claim is back in the damage expert queue." - : "Part photo uploaded for expert resend.", - fanavaranAttachment, - }; - } - - const captureProgress = getClaimCaptureProgress(updatedClaim); - const allCapturesComplete = isClaimCaptureStepComplete(updatedClaim); - - if (allCapturesComplete) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - status: ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS, - "workflow.currentStep": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - "workflow.nextStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - history: { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - description: - "Angles, damaged parts, and capture-phase vehicle evidence (chassis, engine, metal plate) are complete. Please upload remaining required documents.", - }, - }, - }, - }); - } - - const partsRemaining = Math.max( - 0, - captureProgress.partsTotal - captureProgress.partsCaptured, - ); - const anglesRemaining = Math.max( - 0, - captureProgress.anglesTotal - captureProgress.anglesCaptured, - ); - const remaining = - partsRemaining + - anglesRemaining + - captureProgress.capturePhaseDocsRemaining; - const message = allCapturesComplete - ? "All captures complete. Please proceed to upload the remaining required documents." - : `${body.captureType === "angle" ? "Angle" : "Part"} captured successfully. ${capturePhaseSequenceMessage(captureProgress.sequencePhase)} (${remaining} item(s) left in this step).`; - - return { - claimRequestId: claimCase._id.toString(), - captureType: body.captureType, - captureKey: body.captureKey, - fileUrl, - allCapturesComplete, - currentStep: allCapturesComplete - ? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - : ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - message, - fanavaranAttachment: await this.autoSubmitFanavaranAttachment( - claimRequestId, - { - path: file.path, - fileName: file.filename, - source: `capture:${body.captureType}:${body.captureKey}`, - }, - ), - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("capturePartV2 failed", error); - throw new InternalServerErrorException("Failed to capture part"); - } - } - - /** - * V2 API: Upload car walk-around video (same storage as v1: claim-video-capture + ClaimCase.media.videoCaptureId). - */ - async setVideoCaptureV2( - claimRequestId: string, - fileDetail: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - try { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can upload car capture video", - ); - - if (!fileDetail) { - throw new BadRequestException("Video file is required."); - } - - if ( - claimCase.workflow?.currentStep !== - ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - ) { - throw new BadRequestException( - `Invalid workflow step. Expected ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS}, but current step is ${claimCase.workflow?.currentStep}`, - ); - } - - const captureProgress = getClaimCaptureProgress(claimCase); - if (!captureProgress.partsComplete) { - throw new BadRequestException( - "Upload photos for all selected damaged parts before uploading the walk-around video.", - ); - } - if (!captureProgress.anglesComplete) { - throw new BadRequestException( - "Capture all four car angles (front, back, left, right) before uploading the walk-around video.", - ); - } - - if (claimCase.media?.videoCaptureId) { - throw new ConflictException( - "A video has already been uploaded for this claim.", - ); - } - - const videoDoc = await this.createVideoCapture( - fileDetail, - claimRequestId, - ); - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { "media.videoCaptureId": videoDoc._id }, - $push: { - history: { - type: "VIDEO_CAPTURE_UPLOADED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - videoId: videoDoc._id.toString(), - fileName: fileDetail.filename, - }, - }, - }, - }); - - return { - claimRequestId: claimCase._id.toString(), - videoId: videoDoc._id.toString(), - message: "Video capture uploaded successfully.", - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("setVideoCaptureV2 failed", error); - throw new InternalServerErrorException("Failed to upload video capture"); - } - } - - /** - * Whether an expert resend request exists (user is expected to respond). - */ - private claimCaseHasExpertResend(claimCase: any): boolean { - const r = claimCase?.evaluation?.damageExpertResend; - if (!r) return false; - if ( - typeof r.resendDescription === "string" && - r.resendDescription.trim() !== "" - ) { - return true; - } - if (Array.isArray(r.resendDocuments) && r.resendDocuments.length > 0) - return true; - if (Array.isArray(r.resendCarParts) && r.resendCarParts.length > 0) - return true; - return false; - } - - /** - * V2 API: User objection (ClaimCase + evaluation.objection payload). - * - * Priced-flow: insurer-review post-expert statuses (`INSURER_REVIEW_AWAITING_OWNER_SIGN`, `INSURER_REVIEW_MIXED_FACTORS_PENDING`, or legacy `WAITING_FOR_INSURER_APPROVAL`) @ `INSURER_REVIEW` — either NEEDS_REVISION (mixed-priced gate before factor upload) - * or APPROVED (final totals after pricing / factor validation); never while uploading factors or while expert validates. - * Legacy: objection during unpaid expert resend (`WAITING_FOR_USER_RESEND` @ `USER_EXPERT_RESEND`). - * Post: resets owner signatures when applicable and returns claim to WAITING_FOR_DAMAGE_EXPERT. - */ - async handleUserObjectionV2( - claimRequestId: string, - body: UserObjectionV2Dto, - currentUserId: string, - actor?: { sub: string; role?: string }, - invoiceFiles?: Express.Multer.File[], - ) { - try { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can submit an objection", - ); - - if (claimCase.evaluation?.objection?.submittedAt) { - throw new ConflictException( - "An objection has already been submitted for this claim.", - ); - } - - const hasExpertResend = this.claimCaseHasExpertResend(claimCase); - const pendingResendGate = - hasExpertResend && - claimCase.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND && - claimCase.workflow?.currentStep === - ClaimWorkflowStep.USER_EXPERT_RESEND; - - if (claimCase.evaluation?.damageExpertReplyFinal) { - throw new ConflictException( - "The expert already submitted the final reply after objection; submit accept/reject via the owner signer.", - ); - } - - const activeExpert = getActiveV2ExpertReply( - claimCase as unknown as { evaluation?: Record }, - ); - - const partsIn = body.objectionParts ?? []; - const newPartsIn = body.newParts ?? []; - if (partsIn.length === 0 && newPartsIn.length === 0) { - throw new BadRequestException( - "Provide at least one entry in objectionParts and/or newParts.", - ); - } - - let pricingObjectionEligible = false; - if ( - claimCaseStatusAllowsOwnerInsurerSignStep(claimCase.status) && - claimCase.workflow?.currentStep === ClaimWorkflowStep.INSURER_REVIEW && - !claimCase.evaluation?.ownerInsurerApproval?.signedAt - ) { - if (objectionDisallowedDueToOutstandingFactorWorkflow(claimCase)) { - throw new BadRequestException( - "Objections are paused while factor files are uploading or the expert is validating repair factors.", - ); - } - - const shape = classifyV2ExpertPricingParts(activeExpert?.parts ?? []); - const atMixedPartialGate = - claimCase.claimStatus === ClaimStatus.NEEDS_REVISION && - shape.mixedFactorAndPrice && - !claimCase.evaluation?.ownerPricedPartsApproval?.signedAt; - const atFinalPricingGate = - claimCase.claimStatus === ClaimStatus.APPROVED; - pricingObjectionEligible = atMixedPartialGate || atFinalPricingGate; - } - - if (!(pendingResendGate || pricingObjectionEligible)) { - throw new BadRequestException( - "No open objection window. Use this after a priced insurer-review step without a recorded final approval, " + - "or while completing an unpaid expert resend.", - ); - } - - if ( - !pendingResendGate && - pricingObjectionEligible && - !activeExpert?.parts?.length - ) { - throw new BadRequestException( - "A priced assessment is required before you can object.", - ); - } - - const pricedCatalogIds = activeExpert?.parts?.length - ? new Set( - activeExpert.parts - .filter((p) => p.factorNeeded !== true) - .map((p) => parseCatalogPartIdInput(p.partId)) - .filter((id): id is number => id != null), - ) - : new Set(); - - if (partsIn.length && pricingObjectionEligible) { - for (const op of partsIn) { - const catalogId = parseCatalogPartIdInput(op.partId); - if (catalogId == null || !pricedCatalogIds.has(catalogId)) { - throw new BadRequestException( - `Only priced repair lines can be disputed (${String(op.partId)} is factor-only or unknown).`, - ); - } - } - } - - const objectionParts = partsIn.map((p) => ({ - partId: parseCatalogPartIdInput(p.partId)!, - reason: p.reason?.trim() || undefined, - partPrice: - p.partPrice != null && String(p.partPrice).trim() !== "" - ? normalizeMoneyAmountString(String(p.partPrice)) - : undefined, - partSalary: - p.partSalary != null && String(p.partSalary).trim() !== "" - ? normalizeMoneyAmountString(String(p.partSalary)) - : undefined, - typeOfDamage: - p.typeOfDamage != null ? String(p.typeOfDamage) : undefined, - carPartDamage: p.carPartDamage?.trim() || undefined, - side: p.side?.trim() || undefined, - })); - - const newParts = newPartsIn.map((p) => ({ - partId: - p.partId != null && parseCatalogPartIdInput(p.partId) != null - ? parseCatalogPartIdInput(p.partId)! - : new Types.ObjectId().toString(), - partName: p.partName.trim(), - side: p.side?.trim() || undefined, - })); - - const objectionCarType = claimCase.vehicle?.carType as - | ClaimVehicleTypeV2 - | undefined; - const mergedNorm = normalizeDamageSelectedParts( - claimCase.damage?.selectedParts, - objectionCarType, - (claimCase.damage as any)?.selectedOuterParts, - ); - const mergedKeys = new Set(mergedNorm.map((p) => partLookupKey(p))); - for (const np of newParts) { - const name = np.partName?.trim(); - if (!name) continue; - const side = String(np.side ?? "").trim(); - const row = { - id: null as number | null, - name, - side, - label_fa: name, - }; - const k = partLookupKey(row); - if (!mergedKeys.has(k)) { - mergedNorm.push(row); - mergedKeys.add(k); - } - } - - const invoices = (invoiceFiles ?? []).map((f) => ({ - fileId: new Types.ObjectId(), - path: f.path, - fileName: f.filename, - uploadedAt: new Date(), - })); - - const objectionPayload = { - objectionParts, - newParts, - submittedAt: new Date(), - ...(invoices.length > 0 && { invoices }), - }; - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT, - claimStatus: ClaimStatus.PENDING, - "workflow.locked": false, - "workflow.currentStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, - "workflow.nextStep": ClaimWorkflowStep.EXPERT_COST_EVALUATION, - "evaluation.objection": objectionPayload, - "damage.selectedParts": mergedNorm, - ...(pendingResendGate && { - "evaluation.damageExpertResend.fulfilledAt": new Date(), - }), - }, - $unset: { - "evaluation.ownerPricedPartsApproval": "", - "evaluation.ownerInsurerApproval": "", - }, - $push: { - history: { - type: "USER_OBJECTION_SUBMITTED", - actor: { - actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: { - objectionPartCount: objectionParts.length, - newPartCount: newParts.length, - invoiceCount: invoices.length, - }, - }, - }, - }); - - return objectionPayload; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("handleUserObjectionV2 failed", error); - throw new InternalServerErrorException("Failed to submit objection"); - } - } - - /** - * V2 API: User satisfaction rating for a completed claim case (same intent as v1 PUT …/request/:id/user-rating). - */ - async addUserRatingV2( - claimRequestId: string, - ratingDto: UserRatingDto, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner can submit a satisfaction rating.", - ); - - if (claimCase.status !== ClaimCaseStatus.COMPLETED) { - throw new BadRequestException( - "You can only rate a claim after it has been completed.", - ); - } - - if (claimCase.userRating?.createdAt) { - throw new ConflictException( - "A rating has already been submitted for this claim.", - ); - } - - const score = (n: number) => Number(n); - for (const [key, label] of [ - [ratingDto.progressSpeed, "progressSpeed"], - [ratingDto.registrationEase, "registrationEase"], - [ratingDto.overallEvaluation, "overallEvaluation"], - ] as const) { - const v = score(key); - if (Number.isNaN(v) || v < 0 || v > 5) { - throw new BadRequestException( - `${label} must be a number between 0 and 5.`, - ); - } - } - - const userRating: UserClaimRating = { - progressSpeed: ratingDto.progressSpeed, - registrationEase: ratingDto.registrationEase, - overallEvaluation: ratingDto.overallEvaluation, - comment: ratingDto.comment, - createdAt: new Date(), - }; - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { userRating }, - $push: { - history: { - type: "USER_RATING_SUBMITTED", - actor: { - actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }, - timestamp: new Date(), - metadata: {}, - }, - }, - }); - - return userRating; - } - - /** - * V2: Claim owner signature on expert pricing. - * - * Phase 1 (mixed priced + factor-needed lines): `INSURER_REVIEW_MIXED_FACTORS_PENDING` (or legacy `WAITING_FOR_INSURER_APPROVAL`), NEEDS_REVISION, INSURER_REVIEW, - * owner has not yet accepted priced lines — agreeing records `evaluation.ownerPricedPartsApproval` and moves the - * workflow to OWNER_UPLOAD_FACTOR_DOCUMENTS. Rejecting rejects the whole case. - * - * Phase 2 (final): INSURER_REVIEW_AWAITING_OWNER_SIGN (or legacy WAITING_FOR_INSURER_APPROVAL), APPROVED, INSURER_REVIEW — full accept/reject completes the case. - */ - async submitOwnerInsurerApprovalSignV2( - claimRequestId: string, - agree: boolean, - signFile: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string; fullName?: string }, - ): Promise<{ - message: string; - claimRequestId: string; - status: ClaimCaseStatus; - claimStatus: ClaimStatus; - currentStep?: ClaimWorkflowStep; - accepted: boolean; - phase?: "PRICED_PARTS_FOR_FACTORS" | "FINAL_APPROVAL"; - fanavaran?: FanavaranAutoSubmitResult; - fanavaranExpertise?: FanavaranExpertiseSubmitResult; - }> { - if (!Types.ObjectId.isValid(claimRequestId)) { - throw new BadRequestException("Invalid claim request id"); - } - if (!signFile) { - throw new BadRequestException("A signature file is required"); - } - - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException("Claim request not found"); - } - - const effectiveUserId = await this.resolveClaimEffectiveUserId( - claimCase, - currentUserId, - actor?.role, - ); - await this.assertEffectiveUserIsDamagedPartyOnClaim( - claimCase, - effectiveUserId, - actor as { username?: string }, - "Only the claim owner (damaged party) can sign at this step.", - ); - - if (!claimCaseStatusAllowsOwnerInsurerSignStep(claimCase.status)) { - throw new BadRequestException( - `Claim is not waiting for your insurer-approval signature. Current status: ${String(claimCase.status)}`, - ); - } - if (claimCase.workflow?.currentStep !== ClaimWorkflowStep.INSURER_REVIEW) { - throw new BadRequestException( - `Signing is only allowed at workflow step ${ClaimWorkflowStep.INSURER_REVIEW}. Current: ${String(claimCase.workflow?.currentStep ?? "")}`, - ); - } - - const active = - claimCase.evaluation?.damageExpertReplyFinal || - claimCase.evaluation?.damageExpertReply; - if (!active?.submittedAt) { - throw new BadRequestException( - "No expert reply is available to sign off on yet.", - ); - } - - const shape = classifyV2ExpertPricingParts(active.parts ?? []); - const isMixedPartialGate = - shape.mixedFactorAndPrice && - claimCase.claimStatus === ClaimStatus.NEEDS_REVISION && - !claimCase.evaluation?.ownerPricedPartsApproval?.signedAt; - - const isFinalApprovalGate = - claimCase.claimStatus === ClaimStatus.APPROVED && - !claimCase.evaluation?.ownerInsurerApproval?.signedAt; - - if (!isMixedPartialGate && !isFinalApprovalGate) { - throw new BadRequestException( - "No owner signature action is available at this state. " + - "If repair factors are pending upload, complete the priced-line signature first (when claimStatus is NEEDS_REVISION). " + - "If you already completed the final approval signature, refresh the claim.", - ); - } - - if ( - isMixedPartialGate && - claimCase.evaluation?.ownerInsurerApproval?.signedAt - ) { - throw new ConflictException( - "Claim already has a final approval record; refresh the claim state.", - ); - } - if ( - isFinalApprovalGate && - claimCase.evaluation?.ownerInsurerApproval?.signedAt - ) { - throw new ConflictException( - "You have already submitted a signature for this claim.", - ); - } - - const signDoc = await this.claimSignDbService.create({ - fileName: signFile.filename, - userId: effectiveUserId, - path: signFile.path, - requestId: new Types.ObjectId(claimRequestId), - } as any); - const signId = new Types.ObjectId(String((signDoc as any)._id)); - const signedAt = new Date(); - const scopedApprovalPayload = { - agree, - signDetailId: signId, - signedAt, - }; - - const historyActor = { - actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", - }; - - /** Mixed reply: priced lines acceptance before factor uploads */ - if (isMixedPartialGate) { - if (!agree) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - "evaluation.ownerPricedPartsApproval": scopedApprovalPayload, - "workflow.nextStep": null, - }, - $push: { - history: { - type: "OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS", - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - return { - message: - "Your rejection has been recorded. This claim is marked rejected and will not proceed.", - claimRequestId, - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - currentStep: claimCase.workflow?.currentStep, - accepted: false, - phase: "PRICED_PARTS_FOR_FACTORS", - }; - } - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - claimStatus: ClaimStatus.NEEDS_REVISION, - "evaluation.ownerPricedPartsApproval": scopedApprovalPayload, - "workflow.currentStep": - ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS, - "workflow.nextStep": ClaimWorkflowStep.EXPERT_COST_EVALUATION, - }, - $push: { - history: { - type: "OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD", - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - - return { - message: - "Priced repair lines accepted. Upload repair factor files for each factor-needed part; the claim will return to the damage expert for cost validation.", - claimRequestId, - status: claimCase.status, - claimStatus: ClaimStatus.NEEDS_REVISION, - currentStep: ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS, - accepted: true, - phase: "PRICED_PARTS_FOR_FACTORS", - }; - } - - /** Final accept / reject (no outstanding factor gate at this step) */ - if (!agree) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - "evaluation.ownerInsurerApproval": scopedApprovalPayload, - "workflow.nextStep": null, - }, - $push: { - history: { - type: "OWNER_REJECTED_INSURER_APPROVAL_PRICING", - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - return { - message: - "Your rejection has been recorded. This claim is marked rejected and will not proceed.", - claimRequestId, - status: ClaimCaseStatus.REJECTED, - claimStatus: ClaimStatus.REJECTED, - currentStep: claimCase.workflow?.currentStep, - accepted: false, - phase: "FINAL_APPROVAL", - }; - } - - // Submit Fanavaran expertise when owner accepts the expert reply - const fanavaranExpertise = - await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId); - - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.COMPLETED, - claimStatus: ClaimStatus.APPROVED, - "evaluation.ownerInsurerApproval": scopedApprovalPayload, - "workflow.currentStep": ClaimWorkflowStep.CLAIM_COMPLETED, - "workflow.nextStep": ClaimWorkflowStep.CLAIM_COMPLETED, - }, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.INSURER_REVIEW, - history: { - type: "OWNER_SIGNED_INSURER_APPROVAL", - actor: historyActor, - timestamp: signedAt, - metadata: {}, - }, - }, - }); - - const fanavaran = - await this.autoSubmitToFanavaranV2OnClaimCompleted(claimRequestId); - - let message = "Your signature has been recorded. The claim is completed."; - if (fanavaran.submitted) { - message += " The claim was sent to Fanavaran successfully."; - } else if (fanavaran.warning) { - message += ` ${fanavaran.warning}`; - } - - return { - message, - claimRequestId, - status: ClaimCaseStatus.COMPLETED, - claimStatus: ClaimStatus.APPROVED, - currentStep: ClaimWorkflowStep.CLAIM_COMPLETED, - accepted: true, - phase: "FINAL_APPROVAL", - fanavaran, - fanavaranExpertise, - }; - } - - /** - * V2 API: Get list of claims for current user (or for FIELD_EXPERT: claims from their expert-initiated IN_PERSON blame files). - */ - async getMyClaimsV2( - currentUserId: string, - actor?: { sub: string; role?: string }, - query: ListQueryV2Dto = {}, - ): Promise { - try { - let claims: any[]; - if (actor?.role === RoleEnum.FIELD_EXPERT) { - const expertOid = new Types.ObjectId(currentUserId); - const expertBlameIds = await this.blameRequestDbService - .find( - { - expertInitiated: true, - initiatedByFieldExpertId: expertOid, - }, - { select: "_id", lean: true }, - ) - .then((docs) => docs.map((d) => (d as any)._id)); - const claimOr: Record[] = [ - { initiatedByFieldExpertId: expertOid }, - ]; - if (expertBlameIds.length > 0) { - claimOr.push({ blameRequestId: { $in: expertBlameIds } }); - } - claims = await this.claimCaseDbService.find( - { $or: claimOr }, - { lean: true }, - ); - } else if (actor?.role === RoleEnum.REGISTRAR) { - const registrarBlameIds = await this.blameRequestDbService - .find( - { - registrarInitiated: true, - creationMethod: "IN_PERSON", - initiatedByRegistrarId: new Types.ObjectId(currentUserId), - }, - { select: "_id", lean: true }, - ) - .then((docs) => docs.map((d) => (d as any)._id)); - claims = await this.claimCaseDbService.find( - { - $or: [ - { "owner.userId": new Types.ObjectId(currentUserId) }, - ...(registrarBlameIds.length - ? [{ blameRequestId: { $in: registrarBlameIds } }] - : []), - ], - }, - { lean: true }, - ); - } else { - const linkedUserIds = await resolveLinkedUserIdStrings( - this.userDbService, - { - sub: currentUserId, - username: (actor as { username?: string })?.username, - }, - ); - const actorCtx = { - sub: currentUserId, - username: (actor as { username?: string })?.username, - }; - const partyBlameOr = buildBlamePartyAccessOrConditions( - actorCtx, - linkedUserIds, - ); - - const idVariants = collectUserIdVariants(...linkedUserIds); - - const ownerOr = buildOwnerUserIdAccessFilter(idVariants); - - // damagedPartyUserId filter — direct match without blame lookup - const damagedOr = - idVariants.length === 1 - ? { damagedPartyUserId: idVariants[0] } - : idVariants.length > 1 - ? { damagedPartyUserId: { $in: idVariants } } - : null; - - // Build snapshot-party query: claim.snapshot.parties.person.userId - // is the most direct and reliable path — it's copied from the blame - // at claim-creation time and always has the correct damaged-party userId. - const snapshotPartyFilter = - idVariants.length === 1 - ? { "snapshot.parties.person.userId": idVariants[0] } - : idVariants.length > 1 - ? { "snapshot.parties.person.userId": { $in: idVariants } } - : null; - - const [ - ownerClaims, - damagedDirectClaims, - snapshotClaims, - candidateBlames, - ] = await Promise.all([ - ownerOr - ? this.claimCaseDbService.find(ownerOr as any, { lean: true }) - : Promise.resolve([]), - damagedOr - ? this.claimCaseDbService.find(damagedOr as any, { lean: true }) - : Promise.resolve([]), - snapshotPartyFilter - ? this.claimCaseDbService.find(snapshotPartyFilter as any, { - lean: true, - }) - : Promise.resolve([]), - partyBlameOr.length - ? this.blameRequestDbService.find( - partyBlameOr.length === 1 - ? (partyBlameOr[0] as any) - : ({ $or: partyBlameOr } as any), - { - lean: true, - select: "type parties expert.decision blameStatus", - }, - ) - : Promise.resolve([]), - ]); - - // Any blame where the user is a party (not just damaged) surfaces - // the linked claim. Mutation guards protect against acting as the - // wrong party; viewing is intentionally open to all parties. - const partyBlameIds = (candidateBlames as any[]).map((b) => b._id); - - const damagedClaims = - partyBlameIds.length > 0 - ? await this.claimCaseDbService.find( - { blameRequestId: { $in: partyBlameIds } }, - { lean: true }, - ) - : []; - - // Merge: owner claims + blame-resolved damaged claims + snapshot-party claims - // snapshotClaims may include guilty-owner claims too — filter them out here. - const snapshotDamagedClaims = (snapshotClaims as any[]).filter((c) => { - if (!c?.owner?.userId) return true; // unknown owner: allow - const ownerStr = String(c.owner.userId); - // Exclude if the user IS the owner (already in ownerClaims) - return !linkedUserIds.some((id) => id === ownerStr); - }); - - const byId = new Map(); - for (const c of [ - ...(ownerClaims as any[]), - ...(damagedDirectClaims as any[]), - ...(damagedClaims as any[]), - ...snapshotDamagedClaims, - ]) { - byId.set(String(c._id), c); - } - claims = [...byId.values()]; - } - const blameIdsForList = [ - ...new Set( - (claims as any[]) - .map((c) => c.blameRequestId?.toString()) - .filter((id): id is string => !!id), - ), - ]; - const blamesForList = - blameIdsForList.length > 0 - ? ((await this.blameRequestDbService.find( - { _id: { $in: blameIdsForList.map((id) => new Types.ObjectId(id)) } }, - { lean: true, select: "type creationMethod status" }, - )) as any[]) - : []; - const blameByIdForList = new Map( - blamesForList.map((b) => [String(b._id), b]), - ); - - const list = (claims as any[]).map((c) => { - const blameForItem = c.blameRequestId - ? blameByIdForList.get(c.blameRequestId.toString()) - : undefined; - return { - claimRequestId: c._id.toString(), - publicId: c.publicId, - requestNo: c.requestNo, - status: c.status, - claimStatus: c.claimStatus || "PENDING", - currentStep: c.workflow?.currentStep || "", - createdAt: c.createdAt, - blameRequestId: c.blameRequestId?.toString(), - partyIdentities: c.parties ?? c.snapshot?.parties, - blameType: blameForItem?.type ?? undefined, - creationMethod: blameForItem?.creationMethod ?? undefined, - unifiedFileStatus: resolveUnifiedFileStatus({ - blameStatus: blameForItem?.status, - claimStatus: c.status, - }), - }; - }) as ClaimListItemV2Dto[]; - - let filtered = list; - if (query.unifiedStatus) { - filtered = filtered.filter( - (row) => row.unifiedFileStatus === query.unifiedStatus, - ); - } - const { fromDate, toDate } = parseListDateRange( - query.startDate, - query.endDate, - ); - if (fromDate || toDate) { - filtered = filtered.filter((row) => - isInListDateRange(row.createdAt, fromDate, toDate), - ); - } - - const paged = applyListQueryV2( - filtered, - { - publicId: (r) => r.publicId, - createdAt: (r) => r.createdAt, - requestNo: (r) => r.requestNo, - status: (r) => r.unifiedFileStatus ?? r.status, - fileType: (r) => r.blameType, - searchExtras: (r) => - [ - r.claimRequestId, - r.claimStatus, - r.currentStep, - r.blameRequestId, - ].filter(Boolean) as string[], - }, - query, - ); - - return { - list: paged.list, - total: paged.total, - page: paged.page, - limit: paged.limit, - totalPages: paged.totalPages, - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("getMyClaimsV2 failed", error); - throw new InternalServerErrorException("Failed to get claims list"); - } - } - - /** - * V2 API: Get claim details by ID (owner — or FIELD_EXPERT with enriched money/rating fields). - * Owners receive `ownerGuidance` computed from workflow state. - */ - async getClaimDetailsV2( - claimRequestId: string, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - try { - const claim = await this.claimCaseDbService.findById(claimRequestId); - if (!claim) { - throw new NotFoundException("Claim request not found"); - } - await this.assertActorCanViewClaimV2(claim, currentUserId, actor); - - const blameForDetail = claim.blameRequestId - ? (( - await this.blameRequestDbService.find( - { _id: new Types.ObjectId(claim.blameRequestId.toString()) }, - { lean: true, select: "type creationMethod" }, - ) - )[0] ?? null) - : null; - - const hasCapture = (data: any, key: string) => - data && (data instanceof Map ? data.get(key) : data[key]); - - const requiredDocs = claim.requiredDocuments as any; - const requiredDocumentsStatus: Record< - string, - { uploaded: boolean; fileUrl?: string } - > = {}; - if (requiredDocs) { - const keys = - requiredDocs instanceof Map - ? Array.from(requiredDocs.keys()) - : Object.keys(requiredDocs); - for (const k of keys) { - const doc = - requiredDocs instanceof Map ? requiredDocs.get(k) : requiredDocs[k]; - requiredDocumentsStatus[k] = { - uploaded: !!doc?.uploaded, - fileUrl: doc?.filePath ? buildFileLink(doc.filePath) : undefined, - }; - } - } - - const carAnglesData = claim.media?.carAngles as any; - const damagedPartsForAngles = claim.media?.damagedParts as any; - const carAngles: Record = {}; - for (const k of ["front", "back", "left", "right"]) { - const cap = getClaimCarAngleCaptureBlob( - carAnglesData, - damagedPartsForAngles, - k as ClaimCarAngleKey, - ) as { url?: string; path?: string } | undefined; - carAngles[k] = { - captured: !!cap, - url: resolveStoredFileUrl(cap), - }; - } - - const carTypeDetails = claim.vehicle?.carType as - | ClaimVehicleTypeV2 - | undefined; - const selectedNormDetails = normalizeDamageSelectedParts( - claim.damage?.selectedParts, - carTypeDetails, - (claim.damage as any)?.selectedOuterParts, - ); - const damagedPartsData = claim.media?.damagedParts as any; - const resendPartKeys = normalizeResendPartKeys( - claim.evaluation?.damageExpertResend?.resendCarParts, - carTypeDetails, - claim.damage?.selectedParts, - ); - const displayParts = [...selectedNormDetails]; - const seenDetailKeys = new Set( - selectedNormDetails.map((p) => partLookupKey(p)), - ); - for (const rk of resendPartKeys) { - const extra = normalizeDamageSelectedParts( - [rk], - carTypeDetails, - undefined, - )[0] || { - id: null, - name: rk, - side: "", - label_fa: rk, - catalogKey: rk, - }; - const k = partLookupKey(extra); - if (!seenDetailKeys.has(k)) { - displayParts.push(extra); - seenDetailKeys.add(k); - } - } - - const damagedParts = buildEnrichedDamagedParts({ - selectedParts: displayParts, - damagedPartsData: damagedPartsData, - evaluationBlock: (claim as any).evaluation, - expertAddedParts: (claim.damage as any)?.expertAddedParts ?? [], - getDamagedPartCaptureBlob, - hasDamagedPartCapture, - catalogLikeKeyFromPart, - buildFileLink, - }); - const damagedPartsHistory = serializeDamagedPartSelectionHistory({ - history: (claim.damage as any)?.partSelectionHistory, - currentSelectedParts: selectedNormDetails, - }); - - const er = claim.evaluation?.damageExpertResend; - const expertResend = - er && - (er.resendDescription || - (er.resendDocuments?.length ?? 0) > 0 || - (er.resendCarParts?.length ?? 0) > 0) - ? { - resendDescription: er.resendDescription, - resendDocuments: normalizeResendDocumentKeys(er.resendDocuments), - resendCarParts: mapExpertResendCarPartsForClient( - er.resendCarParts, - { - carType: carTypeDetails, - selectedParts: claim.damage?.selectedParts, - damagedPartsData: claim.media?.damagedParts, - buildUrl: (path) => buildFileLink(path), - }, - ), - fulfilledAt: er.fulfilledAt, - } - : undefined; - - const maskSheba = (s?: string) => - s ? s.replace(/^(.{4})(.*)(.{4})$/, "IR$1************$3") : undefined; - const maskNationalCode = (s?: string) => - s ? s.replace(/^(.{2})(.*)(.{2})$/, "$1******$3") : undefined; - const isExpertViewer = - actor?.role === RoleEnum.FIELD_EXPERT || - actor?.role === RoleEnum.REGISTRAR; - const ownerData = claim.owner - ? { - userId: claim.owner.userId?.toString(), - clientId: claim.owner.clientId?.toString(), - ...(claim.owner.userClientKey - ? { userClientKey: claim.owner.userClientKey.toString() } - : {}), - fullName: claim.owner.fullName, - } - : undefined; - const moneyForUser = claim.money - ? { - sheba: maskSheba(claim.money.sheba), - nationalCodeOfOwner: maskNationalCode( - claim.money.nationalCodeOfInsurer, - ), - } - : undefined; - const moneyForExpert = claim.money - ? { - sheba: claim.money.sheba, - nationalCodeOfOwner: claim.money.nationalCodeOfInsurer, - } - : undefined; - - const mappedEvaluation = await this.mapEvaluationForClient( - claim.evaluation, - claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined, - ); - - return { - claimRequestId: claim._id.toString(), - publicId: claim.publicId, - requestNo: claim.requestNo, - status: claim.status, - claimStatus: claim.claimStatus || "PENDING", - currentStep: claim.workflow?.currentStep || "", - nextStep: claim.workflow?.nextStep, - blameRequestId: claim.blameRequestId?.toString(), - blameRequestNo: claim.blameRequestNo, - blameType: (blameForDetail as any)?.type ?? undefined, - creationMethod: (blameForDetail as any)?.creationMethod ?? undefined, - ...(ownerData ? { owner: ownerData } : {}), - vehicle: claim.vehicle, - selectedParts: selectedNormDetails, - otherParts: claim.damage?.otherParts, - money: isExpertViewer ? moneyForExpert : moneyForUser, - requiredDocuments: - Object.keys(requiredDocumentsStatus).length > 0 - ? requiredDocumentsStatus - : undefined, - carAngles, - damagedParts, - damagedPartsHistory, - expertResend, - fanavaran: fanavaranClaimReferences(claim), - evaluation: mappedEvaluation - ? { - damageExpertReply: mappedEvaluation.damageExpertReply, - damageExpertReplyFinal: mappedEvaluation.damageExpertReplyFinal, - } - : undefined, - ...(!isExpertViewer - ? { - ownerGuidance: buildClaimDetailsV2OwnerGuidance( - claim, - claim._id.toString(), - ), - } - : {}), - ...(isExpertViewer - ? { - userRating: claim.userRating - ? { - progressSpeed: claim.userRating.progressSpeed, - registrationEase: claim.userRating.registrationEase, - overallEvaluation: claim.userRating.overallEvaluation, - comment: claim.userRating.comment, - createdAt: claim.userRating.createdAt, - } - : undefined, - } - : {}), - createdAt: (claim as any).createdAt, - updatedAt: (claim as any).updatedAt, - }; - } catch (error) { - if (error instanceof HttpException) throw error; - this.logger.error("getClaimDetailsV2 failed", error); - throw new InternalServerErrorException("Failed to get claim details"); - } - } - - private async generateUniqueClaimNumber(): Promise { - const prefix = "CL"; - const randomPart = Math.floor(10000 + Math.random() * 90000); // 5 digits - return `${prefix}${randomPart}`; - } - - private async loadBlameForV3Claim(claimCase: any) { - if (!claimCase?.blameRequestId) return null; - return this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), - ); - } - - private hasPartyInquiriesOnBlame( - blame: any, - role: "FIRST" | "SECOND", - ): boolean { - const step = - role === "FIRST" - ? WorkflowStep.FIRST_INITIAL_FORM - : WorkflowStep.SECOND_INITIAL_FORM; - return (blame.workflow?.completedSteps ?? []).includes(step); - } - - private partyHasSignedOnBlame(blame: any, role: "FIRST" | "SECOND"): boolean { - const party = (blame.parties ?? []).find((p: any) => p?.role === role); - return !!party?.confirmation; - } - - private assertV3ClaimDocumentsPhase( - blame: any, - options?: { skipAccidentFieldsCheck?: boolean }, - ): void { - if ( - !options?.skipAccidentFieldsCheck && - !(blame.expert?.decision as any)?.fields?.accidentWay - ) { - throw new BadRequestException( - "Submit accident fields before uploading required documents.", - ); - } - const isCarBody = - blame?.type === BlameRequestType.CAR_BODY || blame?.type === "CAR_BODY"; - if (isCarBody) { - if (!this.partyHasSignedOnBlame(blame, "FIRST")) { - throw new BadRequestException( - "Upload documents after the party has signed.", - ); - } - return; - } - if ( - !this.partyHasSignedOnBlame(blame, "FIRST") || - !this.partyHasSignedOnBlame(blame, "SECOND") - ) { - throw new BadRequestException( - "Both parties must sign before uploading required documents.", - ); - } - } - - private assertV3ClaimPartsPhase(blame: any): void { - if (!(blame.expert?.decision as any)?.fields?.accidentWay) { - throw new BadRequestException( - "Submit accident fields before part selection.", - ); - } - const isCarBody = - blame?.type === BlameRequestType.CAR_BODY || blame?.type === "CAR_BODY"; - if (isCarBody) { - if (!this.partyHasSignedOnBlame(blame, "FIRST")) { - throw new BadRequestException( - "Part selection requires the party signature.", - ); - } - return; - } - if ( - !this.partyHasSignedOnBlame(blame, "FIRST") || - !this.partyHasSignedOnBlame(blame, "SECOND") - ) { - throw new BadRequestException( - "Both parties must sign before part selection.", - ); - } - } - - private claimV3StepCompleted( - claimCase: any, - step: ClaimWorkflowStep, - ): boolean { - return (claimCase.workflow?.completedSteps ?? []).includes(step); - } - - private assertV3ClaimWorkflowStep( - claimCase: any, - expected: ClaimWorkflowStep | ClaimWorkflowStep[], - hint?: string, - ): void { - const allowed = Array.isArray(expected) ? expected : [expected]; - const current = claimCase.workflow?.currentStep; - if (!allowed.includes(current)) { - throw new BadRequestException( - hint ?? - `Invalid workflow step. Expected ${allowed.join(" or ")}, but current step is ${current}`, - ); - } - } - - private async advanceV3ClaimToOuterPartsIfReady( - claimCase: any, - blame: any, - ): Promise { - if ( - claimCase.workflow?.currentStep === ClaimWorkflowStep.SELECT_OUTER_PARTS - ) { - return; - } - - const step = claimCase.workflow?.currentStep; - // UPLOAD_REQUIRED_DOCUMENTS: normal V3/V4 path after FileMaker docs. - // WAITING_FOR_FILE_REVIEWER (claim status): same DB step but with the new - // V4 claim status — FileReviewer is picking up the sealed file. - // USER_SUBMISSION_COMPLETE: can occur when documents were uploaded via a - // non-V3 path (e.g. generic v2 endpoint). Safe to advance as long as - // accident fields are set (checked just below). - // EXPERT_REVIEWING + EXPERT_DAMAGE_ASSESSMENT: FileReviewer re-entering - // after a FileMaker rejection. The claim was locked back to - // EXPERT_REVIEWING by the reviewer's lock call; the document phase was - // already completed in the prior cycle so it's safe to advance directly - // to part selection. - const isFileReviewerReentry = - claimCase.status === ClaimCaseStatus.EXPERT_REVIEWING && - step === ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT && - (blame as any)?.isMadeByFileMaker === true; - - const canAdvance = - step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS || - step === ClaimWorkflowStep.USER_SUBMISSION_COMPLETE || - claimCase.status === ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER || - isFileReviewerReentry; - - if (!canAdvance) { - throw new BadRequestException( - `Complete required documents before selecting outer parts. Current step: ${step}`, - ); - } - if (!(blame.expert?.decision as any)?.fields?.accidentWay) { - throw new BadRequestException( - "Submit accident fields before selecting outer parts.", - ); - } - - await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), { - $set: { - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - claimStatus: ClaimStatus.PENDING, - "workflow.currentStep": ClaimWorkflowStep.SELECT_OUTER_PARTS, - "workflow.nextStep": ClaimWorkflowStep.SELECT_OTHER_PARTS, - }, - }); - } - - private async assertV3InPersonClaim(claimCase: any) { - const blame = await this.loadBlameForV3Claim(claimCase); - if (!blame) { - throw new BadRequestException( - "V3 claim flow requires a linked blame file.", - ); - } - if (blame.creationMethod !== CreationMethod.IN_PERSON) { - throw new BadRequestException( - "V3 claim flow is only for IN_PERSON blame files.", - ); - } - if (!blame.expertInitiated) { - throw new BadRequestException( - "V3 claim flow requires an expert-initiated blame file.", - ); - } - return blame; - } - - private isV3InitialDocumentsPhase(claimCase: any): boolean { - const step = claimCase.workflow?.currentStep; - const capturePartDone = this.claimV3StepCompleted( - claimCase, - ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - ); - return ( - step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && !capturePartDone - ); - } - - private shapeCaptureRequirementsForV3( - claimCase: any, - blame: any, - base: GetCaptureRequirementsV2ResponseDto, - ): GetCaptureRequirementsV2ResponseDto { - const skipMetalPlate = !!(blame as any)?.isMadeByFileMaker; - // V4 = FileMaker flow without a secondary FileMaker approval step - const isV4 = - !!(blame as any)?.isMadeByFileMaker && - !(claimCase as any)?.requiresFileMakerApproval; - const isCarBody = - blame?.type === BlameRequestType.CAR_BODY || - (blame as any)?.type === "CAR_BODY"; - - // For V4/V5 files strip metal-plate keys from the base response entirely - // so they never appear in any phase — the front-end should not show them. - if (skipMetalPlate) { - base = { - ...base, - requiredDocuments: base.requiredDocuments.filter( - (d) => !OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(d.key as any), - ), - }; - } - - const step = claimCase.workflow?.currentStep; - const capturePartDone = this.claimV3StepCompleted( - claimCase, - ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - ); - - if (this.isV3InitialDocumentsPhase(claimCase)) { - const preCaptureDocs = base.requiredDocuments.filter( - (d) => !d.preferUploadDuringCapture, - ); - const requiredPreCaptureDocs = preCaptureDocs.filter((d) => d.required); - const remaining = requiredPreCaptureDocs.filter( - (d) => !d.uploaded, - ).length; - return { - ...base, - requiredDocuments: preCaptureDocs, - captureSequencePhase: "parts", - captureSequenceHint: - "Upload initial required documents (licenses and car cards). Chassis, engine, and metal plate photos come after part selection, damaged-part photos, and car angles.", - damagedParts: [], - carAngles: base.carAngles.map((a) => ({ ...a, captured: false })), - totalRemaining: remaining, - progress: { - ...base.progress, - documentsTotal: requiredPreCaptureDocs.length, - documentsUploaded: requiredPreCaptureDocs.filter((d) => d.uploaded) - .length, - partsCaptured: 0, - partsTotal: 0, - anglesCaptured: 0, - capturePhaseDocsRemaining: 0, - postCaptureDocumentsRemaining: remaining, - }, - }; - } - - if (step === ClaimWorkflowStep.SELECT_OUTER_PARTS) { - return { - ...base, - requiredDocuments: base.requiredDocuments.filter( - (d) => !d.preferUploadDuringCapture, - ), - captureSequencePhase: "parts", - captureSequenceHint: "Select outer damaged parts before capture.", - totalRemaining: base.damagedParts.filter((p) => !p.captured).length, - }; - } - - if (step === ClaimWorkflowStep.SELECT_OTHER_PARTS) { - return { - ...base, - requiredDocuments: base.requiredDocuments.filter( - (d) => !d.preferUploadDuringCapture, - ), - captureSequencePhase: "parts", - captureSequenceHint: - "Select other damaged parts (and car green card when required) before capture.", - }; - } - - if (step === ClaimWorkflowStep.CAPTURE_PART_DAMAGES) { - const capturePhaseDocs = base.requiredDocuments.filter( - (d) => - d.preferUploadDuringCapture && - !(skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(d.key as any)), - ); - - // V4 THIRD_PARTY only: guilty_damage_area is uploaded via upload-document - // after all car angles are captured (last item in the documents phase). - // It also appears in damagedParts so the expert sees it labelled as a - // damaged-part capture. - if (isV4 && !isCarBody) { - const guiltyAreaUploaded = this.isRequiredDocumentUploadedOnClaim( - claimCase, - GUILTY_DAMAGE_AREA_DOC_KEY, - ); - const guiltyAreaDoc = { - key: GUILTY_DAMAGE_AREA_DOC_KEY, - label_fa: "تصویر نقطه آسیب‌دیده مقصر", - label_en: "Guilty Car Damaged Area", - category: "guilty_party", - required: true, - uploaded: guiltyAreaUploaded, - preferUploadDuringCapture: true, - }; - const captureProgress = getClaimCaptureProgress(claimCase, { - skipMetalPlate, - includeGuiltyDamageArea: true, - }); - - return { - ...base, - requiredDocuments: [...capturePhaseDocs, guiltyAreaDoc], - totalRemaining: captureProgress.capturePhaseDocsRemaining, - progress: { - ...base.progress, - capturePhaseDocsRemaining: captureProgress.capturePhaseDocsRemaining, - }, - }; - } - - return { - ...base, - requiredDocuments: capturePhaseDocs, - totalRemaining: base.progress.capturePhaseDocsRemaining, - }; - } - - if ( - step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && - capturePartDone - ) { - // car-capture not yet uploaded: next step is the walk-around video. - return { - ...base, - requiredDocuments: [], - captureSequencePhase: "complete", - captureSequenceHint: - "Upload the walk-around car video (car-capture), then the blame accident video.", - totalRemaining: claimCase.media?.videoCaptureId ? 0 : 1, - }; - } - - // V3 FIELD_EXPERT only: car-capture is done (step advanced to USER_SUBMISSION_COMPLETE - // in setVideoCaptureV3). The one remaining action is the blame accident video. - if ( - step === ClaimWorkflowStep.USER_SUBMISSION_COMPLETE && - !(blame as any).isMadeByFileMaker - ) { - return { - ...base, - requiredDocuments: [], - captureSequencePhase: "complete", - captureSequenceHint: - "Walk-around video uploaded. Upload the blame accident video to finalise.", - totalRemaining: 0, - }; - } - - return base; - } - - async uploadRequiredDocumentV3( - claimRequestId: string, - body: UploadRequiredDocumentV2Dto, - file: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const blame = await this.assertV3InPersonClaim(claimCase); - const skipMetalPlate = !!(blame as any).isMadeByFileMaker; - const isV4FileMaker = - !!(blame as any)?.isMadeByFileMaker && - !(claimCase as any)?.requiresFileMakerApproval; - const isCarBodyBlame = - blame?.type === BlameRequestType.CAR_BODY || - (blame as any)?.type === "CAR_BODY"; - - // guilty_damage_area is an extra capture-phase doc key for V4 THIRD_PARTY - const isGuiltyDamageAreaDoc = - (body.documentKey as string) === GUILTY_DAMAGE_AREA_DOC_KEY && - isV4FileMaker && - !isCarBodyBlame; - - const isCaptureDoc = - isCapturePhaseDamagedPartyDocKey(body.documentKey) || isGuiltyDamageAreaDoc; - - if (isCaptureDoc) { - this.assertV3ClaimPartsPhase(blame); - this.assertV3ClaimWorkflowStep( - claimCase, - ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "Upload chassis and engine photos during capture after damaged-part photos and car angles.", - ); - if ( - !this.claimV3StepCompleted( - claimCase, - ClaimWorkflowStep.SELECT_OTHER_PARTS, - ) - ) { - throw new BadRequestException( - "Complete outer and other part selection before capture-phase vehicle documents.", - ); - } - const captureProgress = getClaimCaptureProgress(claimCase, { - skipMetalPlate, - includeGuiltyDamageArea: isGuiltyDamageAreaDoc, - }); - if (!captureProgress.partsComplete) { - throw new BadRequestException( - "Upload photos for all selected damaged parts before chassis or engine photos.", - ); - } - if (!captureProgress.anglesComplete) { - throw new BadRequestException( - "Capture all four car angles before chassis or engine photos.", - ); - } - } else { - this.assertV3ClaimDocumentsPhase(blame, { - skipAccidentFieldsCheck: actor?.role === "file_maker", - }); - if (!this.isV3InitialDocumentsPhase(claimCase)) { - throw new BadRequestException( - `Upload initial required documents during ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS} before part selection. Current step: ${claimCase.workflow?.currentStep}`, - ); - } - } - - // For V4 THIRD_PARTY files, guilty_damage_area must be counted in the - // capture-phase doc total for ALL capture uploads (not just the guilty_damage_area - // upload itself) so that the CAPTURE_PART_DAMAGES step is not marked complete - // until all three standard docs AND the guilty area photo are uploaded. - const includeGuiltyDamageArea = isV4FileMaker && !isCarBodyBlame; - - return this.uploadRequiredDocumentV2( - claimRequestId, - body, - file, - currentUserId, - actor, - { - v3InPersonFlow: true, - skipMetalPlate, - requiresFileMakerApproval: !!(claimCase as any).requiresFileMakerApproval, - includeGuiltyDamageArea, - }, - ); - } - - async getCaptureRequirementsV3( - claimRequestId: string, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const blame = await this.assertV3InPersonClaim(claimCase); - - if (this.isV3InitialDocumentsPhase(claimCase)) { - this.assertV3ClaimDocumentsPhase(blame, { - skipAccidentFieldsCheck: actor?.role === "file_maker", - }); - } else if ( - claimCase.workflow?.currentStep === ClaimWorkflowStep.CAPTURE_PART_DAMAGES - ) { - this.assertV3ClaimPartsPhase(blame); - } - - const base = await this.getCaptureRequirementsV2( - claimRequestId, - currentUserId, - actor, - ); - return this.shapeCaptureRequirementsForV3(claimCase, blame, base); - } - - async selectOuterPartsV3( - claimRequestId: string, - body: SelectOuterPartsV2Dto, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const blame = await this.assertV3InPersonClaim(claimCase); - this.assertV3ClaimPartsPhase(blame); - await this.advanceV3ClaimToOuterPartsIfReady(claimCase, blame); - - const refreshed = await this.claimCaseDbService.findById(claimRequestId); - this.assertV3ClaimWorkflowStep( - refreshed, - ClaimWorkflowStep.SELECT_OUTER_PARTS, - "Select outer parts after accident fields and required documents.", - ); - - const result = await this.selectOuterPartsV2(claimRequestId, body, currentUserId, actor); - - return result; - } - - async selectOtherPartsV3( - claimRequestId: string, - body: SelectOtherPartsV3Dto, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const blame = await this.assertV3InPersonClaim(claimCase); - this.assertV3ClaimPartsPhase(blame); - this.assertV3ClaimWorkflowStep( - claimCase, - ClaimWorkflowStep.SELECT_OTHER_PARTS, - "Select outer parts before other parts.", - ); - if ( - !this.claimV3StepCompleted( - claimCase, - ClaimWorkflowStep.SELECT_OUTER_PARTS, - ) - ) { - throw new BadRequestException( - "Complete outer part selection before selecting other parts.", - ); - } - - let otherParts = Array.isArray((body as any)?.otherParts) - ? (body as any).otherParts - : []; - if ( - !Array.isArray((body as any)?.otherParts) && - typeof (body as any)?.otherParts === "string" - ) { - try { - const parsed = JSON.parse((body as any).otherParts); - otherParts = Array.isArray(parsed) ? parsed : []; - } catch { - otherParts = []; - } - } - - const shebaNumber = claimCase.money?.sheba; - const nationalCode = claimCase.money?.nationalCodeOfInsurer; - - const updatePayload: any = { - "damage.otherParts": otherParts.length > 0 ? otherParts : undefined, - status: ClaimCaseStatus.CAPTURING_PART_DAMAGES, - "workflow.currentStep": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "workflow.nextStep": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OTHER_PARTS, - history: { - type: "V3_STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "Actor", - actorType: - actor?.role === RoleEnum.REGISTRAR ? "registrar" : "field_expert", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.SELECT_OTHER_PARTS, - otherParts, - v3SelectionOnly: true, - }, - }, - }, - }; - - const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate( - claimRequestId, - updatePayload, - ); - if (!updatedClaim) { - throw new InternalServerErrorException("Failed to update claim case"); - } - - return { - claimRequestId: updatedClaim._id.toString(), - publicId: updatedClaim.publicId, - otherParts, - ...(shebaNumber - ? { - shebaNumber: String(shebaNumber).replace( - /^(.{4})(.*)(.{4})$/, - "IR$1************$3", - ), - } - : {}), - ...(nationalCode - ? { - nationalCodeOfOwner: String(nationalCode).replace( - /^(.{2})(.*)(.{2})$/, - "$1******$3", - ), - } - : {}), - currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - nextStep: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - message: - "Other parts saved. Proceed to damaged-part photos and car angles (capture-part).", - }; - } - - async setVideoCaptureV3( - claimRequestId: string, - fileDetail: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const blame = await this.assertV3InPersonClaim(claimCase); - const skipMetalPlate = !!(blame as any).isMadeByFileMaker; - - if (!fileDetail) { - throw new BadRequestException("Video file is required."); - } - if (claimCase.media?.videoCaptureId) { - // FILE_REVIEWER re-reviewing after a FileMaker rejection: allow replacing - // the previous walk-around video by clearing the stale id first so that - // setVideoCaptureV2's own conflict check doesn't block the upload. - if (actor?.role === RoleEnum.FILE_REVIEWER) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $unset: { "media.videoCaptureId": "" }, - }); - claimCase.media = { ...(claimCase.media ?? {}), videoCaptureId: undefined } as any; - } else { - throw new ConflictException( - "A walk-around video has already been uploaded for this claim.", - ); - } - } - - if ( - claimCase.workflow?.currentStep !== - ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - ) { - throw new BadRequestException( - `Complete capture-phase documents (chassis/engine) first. Expected ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS}, but current step is ${claimCase.workflow?.currentStep}`, - ); - } - - const captureProgress = getClaimCaptureProgress(claimCase, { skipMetalPlate }); - if (!captureProgress.partsComplete) { - throw new BadRequestException( - "Upload photos for all selected damaged parts before the walk-around video.", - ); - } - if (!captureProgress.anglesComplete) { - throw new BadRequestException( - "Capture all four car angles before the walk-around video.", - ); - } - if (!isClaimCaptureStepComplete(claimCase, { skipMetalPlate })) { - throw new BadRequestException( - skipMetalPlate - ? "Upload capture-phase vehicle documents (chassis and engine) before the walk-around video." - : "Upload capture-phase vehicle documents (chassis, engine, metal plate) before the walk-around video.", - ); - } - - // Store the walk-around video (shared V2 logic). - const result = await this.setVideoCaptureV2( - claimRequestId, - fileDetail, - currentUserId, - actor, - ); - - // V4/V5 only (isMadeByFileMaker): car-capture is the FINAL FileReviewer step. - // For the v3 mirror (FIELD_EXPERT IN_PERSON), car-capture is penultimate — - // expertUploadBlameVideoV3 finalises the blame with the accident video next. - // Advance the workflow step so that if the expert exits and reopens the claim - // the system correctly resumes at upload-video rather than replaying car-capture. - if (!(blame as any).isMadeByFileMaker) { - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - "workflow.currentStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - "workflow.nextStep": undefined, - }, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - history: { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "field_expert", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - description: - "V3 walk-around video uploaded. Upload blame accident video to finalise.", - v3InPersonFlow: true, - }, - }, - }, - }); - } else if ((blame as any).isMadeByFileMaker) { - // Both V4 and V5 land at WAITING_FOR_DAMAGE_EXPERT here. - // For V5 (requiresFileMakerApproval=true), autoSubmitToFanavaranV2OnClaimCompleted - // intercepts COMPLETED → WAITING_FOR_FILE_MAKER_APPROVAL after expert review. - await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { - status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT, - claimStatus: ClaimStatus.PENDING, - "workflow.currentStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - "workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, - }, - $push: { - "workflow.completedSteps": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - history: { - type: "STEP_COMPLETED", - actor: { - actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: actor?.role === RoleEnum.FILE_REVIEWER ? "file_reviewer" : "user", - }, - timestamp: new Date(), - metadata: { - stepKey: ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - description: "V4/V5 walk-around video uploaded. Claim ready for damage expert review.", - v3InPersonFlow: true, - }, - }, - }, - }); - - // Mark the linked blame file as COMPLETED. - if (claimCase.blameRequestId) { - await this.blameRequestDbService.findByIdAndUpdate( - String(claimCase.blameRequestId), - { $set: { status: BlameCaseStatus.COMPLETED } }, - ); - } - } - - return result; - } - - async capturePartV3( - claimRequestId: string, - body: CapturePartV2Dto, - file: Express.Multer.File, - currentUserId: string, - actor?: { sub: string; role?: string }, - ): Promise { - const claimCase = await this.claimCaseDbService.findById(claimRequestId); - if (!claimCase) { - throw new NotFoundException( - `Claim case with ID ${claimRequestId} not found`, - ); - } - const blame = await this.assertV3InPersonClaim(claimCase); - this.assertV3ClaimPartsPhase(blame); - this.assertV3ClaimWorkflowStep( - claimCase, - ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "Select other parts before capturing damaged parts and angles.", - ); - if ( - !this.claimV3StepCompleted( - claimCase, - ClaimWorkflowStep.SELECT_OTHER_PARTS, - ) - ) { - throw new BadRequestException( - "Complete other part selection before capture.", - ); - } - - return this.capturePartV2(claimRequestId, body, file, currentUserId, actor); - } -}