diff --git a/.gitignore b/.gitignore index 4def0e3..75478d8 100644 --- a/.gitignore +++ b/.gitignore @@ -186,3 +186,20 @@ dist *.sh !scripts/fanavaran-flow-test.sh !scripts/fanavaran-auth.sh + +# --- local WIP (do not track) --- +.agents/ +.cursor/ +.mimocode/ +.vscode/ +A00191.json +test.json +skills-lock.json +docs/fanavaran/car-body-stage-fields.html +docs/fanavaran/third-party-stage-fields.html +docs/fanavaran/stage1-hull-body.json +docs/fanavaran/stage4-hull-expertise-body.json +# scripts/fanavaran-flow-ui-server.js +# scripts/data/fanavaran-flow-ui.html +scripts/data/fanavaran-flow-cases/ +scripts/data/offline-plate-seeds.json diff --git a/Dockerfile b/Dockerfile index 50d7cbe..1e7f66d 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -# Use the official Node.js image as the base image +# Use the official Node.js image as the base image FROM node:20-alpine # Set the working directory inside the container @@ -16,8 +16,12 @@ RUN npm i --force # Copy the rest of the application code to the working directory COPY . . +# Compile once at image build time — do not compile with `nest start` at container boot +RUN npm run build + # Expose the port on which your NestJS application will run EXPOSE 3002 -# Start the NestJS application -CMD ["npm", "start"] +# Run the prebuilt app (avoids TypeScript compile OOM on restart) +ENV NODE_OPTIONS=--max-old-space-size=1024 +CMD ["npm", "run", "start:prod"] diff --git a/docs/fanavaran/README.md b/docs/fanavaran/README.md index 36e2d58..e6421ba 100644 --- a/docs/fanavaran/README.md +++ b/docs/fanavaran/README.md @@ -23,7 +23,7 @@ source: fanavaran-module-docs | # | Document | Covers | |---|----------|--------| -| 1 | [01-write-apis.md](./01-write-apis.md) | Auth + GEN.03 / GEN.12 / GEN.07 / GEN.08 write APIs | +| 1 | [01-write-apis.md](./01-write-apis.md) | Auth + GEN.03 / GEN.12 / GEN.44 / GEN.07 / GEN.08 write APIs | | 2 | [02-read-apis-lookups.md](./02-read-apis-lookups.md) | Policy inquiry, driver inquiry, lookups | | 3 | [03-constants.md](./03-constants.md) | Shared vs tenant constants | | 4 | [04-tenant-matrix.md](./04-tenant-matrix.md) | Shared ✅ / tenant-specific ✅ matrix | @@ -34,6 +34,10 @@ source: fanavaran-module-docs | 9 | [09-error-handling.md](./09-error-handling.md) | Errors, retry, backoff, logging | | 10 | [10-testing.md](./10-testing.md) | Test scenarios, **manual flow-test script**, proven case | | 11 | [11-onboard-new-client.md](./11-onboard-new-client.md) | Checklist to add a new insurer | +| — | [car-body-curl-flow.md](./car-body-curl-flow.md) | **Car-body (بدنه)** manual curl: auth + stages 1, 3, 4 (no dmg-cases) | +| — | [third-party-stage-fields.md](./third-party-stage-fields.md) | ثالث: each stage body, null vs required, lookup/inquiry vs user | +| — | [car-body-stage-fields.md](./car-body-stage-fields.md) | بدنه: each stage body, null vs required, lookup/inquiry vs user | +| — | [flow-design-user-vs-inquiry.md](./flow-design-user-vs-inquiry.md) | Proposed intake: user vs inquiry, Persian titles + types | ## Related sources (code) @@ -75,8 +79,9 @@ Fanavaran API Manager |-------|---------------|------------------| | Auth | EITAuthentication | token cache (`fanavaranAuthTokens`) | | Policy inquiry | inquiry-my-policies | `fanavaranSync.baseClaim.policyId` | +| Other people | GEN.44 | `driverId` / `otherPersonId` when inquiry misses | | Base claim | GEN.03 | `claimId`, `claimNo` | -| Damage case | GEN.12 | `dmgCaseId`, `driverId`, … | +| Damage case | GEN.12 | `dmgCaseId`, `driverId`, `otherPersonId`, … | | Attachments | GEN.07 | `fanavaranSync.attachments.files[]` | | Expertise | GEN.08 | `expertiseId` | diff --git a/docs/fanavaran/third-party-stage-fields.md b/docs/fanavaran/third-party-stage-fields.md index 798456c..78a5291 100644 --- a/docs/fanavaran/third-party-stage-fields.md +++ b/docs/fanavaran/third-party-stage-fields.md @@ -2,11 +2,6 @@ Snapshot of **what `ClaimRequestManagementService` actually sends** for `THIRD_PARTY` as of this version. -TejaratNo additionally sends expert-reviewed `NotifierTypeId` and `NotifierRelationId` on the base claim, using the tenant-supplied codebooks. Both are required before initial submission; see [expert field review](../fanavaran-stage-field-review.md#tejaratno-notifier-review). Other tenants' bodies are unchanged. - - -Experts can now override address, city, report type, damage history and inspection place before their sending stage. See [expert field review](../fanavaran-stage-field-review.md); defaults below remain fallbacks for unreviewed records. - - Base: `POST /car/third-party-car-financial-claims` (GEN.03) - Damage case: `POST …/{claimId}/dmg-cases` (GEN.12) - Attachments: `POST …/{claimId}/files` (GEN.07, multipart) @@ -43,12 +38,12 @@ Parsian tenant defaults used below: `ClaimExpertId=154`, `ExpertiseClaimExpertId | AnnouncementDate | تاریخ اعلام | string Jalali | **no** | **derived** = AccidentDate | | | DocReceivedDate | تاریخ وصول مدارک | string Jalali | **no** | **derived** = AccidentDate | Third-party only (not on hull whitelist) | | AccidentTime | ساعت حادثه | string `HH:mm` | **no** | **user** / **derived** from createdAt | | -| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **user** expert review, else **system** `"استان تهران شهر تهران"` | | +| AccidentLocationAddress | نشانی محل حادثه | string | **no** | **system** `"استان تهران شهر تهران"` | Should later be **user** | | AccidentCauseId | علت حادثه | number | **no** | **system** `6` | Lookup: `GET /lookups/accident-causes`. Expert `accidentReason.fanavaran` exists but is not yet wired as the sent id | -| AccidentCityId | شهر محل حادثه | number | **no** | **user** expert review, else **system** `701` تهران | Lookup: `GET /lookups/cities` | -| AccidentReportTypeId | نحوه اعلام حادثه | number | **no** | **user** expert review, else **system** `155` | Lookup: `GET /lookups/accident-report-type` | +| AccidentCityId | شهر محل حادثه | number | **no** | **system** `701` تهران | Lookup: `GET /lookups/cities` | +| AccidentReportTypeId | نحوه اعلام حادثه | number | **no** | **system** `155` | Lookup: `GET /lookups/accident-report-type` | | AccidentVehicleUsedId | نوع کاربری خودرو | number | **no** | **inquiry** VIN / policy vehicle `UsedId`, else tenant `1` | Lookup: `GET /lookups/vehicle-use-types` | -| CulpritTypeId | نوع مقصر | number | **no** | **system** `337` | Lookup: `GET /lookups/accident-culprit-type` (ثالث, not hull) | +| CulpritTypeId | نوع مقصر | number | **no** | **derived** from guilty party: driver = insurer → `337` (بیمه‌گذار), else `338` (راننده غير از بيمه گذار). Never `728` | Lookup: `GET /lookups/accident-culprit-type` (ثالث, not hull) | | CulpritLicenceTypeId | نوع گواهینامه مقصر | number | **no** | **system** `2` | Lookup: `GET /lookups/driving-licence-types` | | CulpritLicenceNo | شماره گواهینامه مقصر | string | **no** | **user** party licence if stored, else dummy `9705463515` | Must never be empty | | CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **system** `"1394/10/13"` | Should later be **user** | @@ -109,8 +104,8 @@ If `DriverId` is missing, **submit** (not preview) registers GEN.44 `POST /commo | Field | Persian | Type | Null? | Current source | |-------|---------|------|-------|----------------| -| DriverId | شناسه راننده زیان‌دیده در فناوران | number | **no** on submit | **inquiry** `GET /lookups/inquiry-by-unique-identifier` (national code + Jalali birthday). Fallback **GEN.44** create | -| OwnerId | شناسه مالک | number | yes | currently `null` | +| DriverId | شناسه راننده زیان‌دیده در فناوران | number | **no** on submit | **inquiry** `GET /lookups/inquiry-by-unique-identifier` — only RoleId **161** or **166**. If missing / only e.g. 162 → **GEN.44** create on submit | +| OwnerId | شناسه مالک | number | preferred | **inquiry** same RoleId **161**/**166** rule as DriverId; else **GEN.44** on submit (reuse DriverId when same national code) | | VehicleKindId | نوع خودرو | number | **no** | **inquiry** VIN vehicle `VehicleKindId`, else **lookup** `GET /lookups/vehicle-kinds` matched to `claim.vehicle.carType` | | AccidentVehicleUsedId | کاربری | number | **no** | **inquiry** vehicle `UsedId` / use-types, else tenant | | VIN | شماره شاسی ۱۷ رقمی | string | preferred | **inquiry** plate/VIN inquiry | @@ -132,7 +127,7 @@ If `DriverId` is missing, **submit** (not preview) registers GEN.44 `POST /commo | PreviousPolicyEndDate | پایان بیمه‌نامه قبلی | string | empty ok | **derived** from EndDate | | InsuranceCorpId | شرکت بیمه زیان‌دیده | number | **no** | **lookup** insurance-corp for tenant | | DmgCaseTypeId | نوع مورد خسارت | number | **no** | **system** `175` · lookup `dmg-case-type` | -| DmgHistoryStatus | وضعیت سابقه خسارت | number | **no** | **user** expert review, else **system** `5214` · lookup `dmg-history-status` | +| DmgHistoryStatus | وضعیت سابقه خسارت | number | **no** | **system** `5214` · lookup `dmg-history-status` | | FaultPercent | درصد تقصیر | number | **no** | **system** `100` | | DriverIsOwner | راننده همان مالک؟ | number | **no** | **user** `driverIsInsurer` → 1/0 | | LicenceNo | شماره گواهینامه زیان‌دیده | string | **no** | **user**, else dummy | @@ -174,7 +169,7 @@ Requires local `dmgCaseId`. `ClaimExpertId` here is the **assessor** role (Parsi | ClaimExpertId | کارشناس ارزیاب | number | **no** | **staff** / tenant `ExpertiseClaimExpertId` | | DmgAssessmentDate | تاریخ بازدید | string Jalali | **no** | **derived** expert reply `submittedAt` | | InspectionTime | ساعت بازدید | string `HH:mm` | **no** | **derived** | -| InspectionPlaceId | محل بازدید | number | **no** | **user** expert review, else **system** `282` · lookup `GET /lookups/inspection-place` | +| InspectionPlaceId | محل بازدید | number | **no** | **system** `282` · lookup `GET /lookups/inspection-place` | | RepairWage | اجرت کل | number | **no** | **user** sum of part `salary` | | ComponentReplacementCost | قطعه کل | number | **no** | **user** sum of part `price` | | WasteValue | داغی کل | number | **no** | **user** daghi prices | diff --git a/package-lock.json b/package-lock.json index abcfbc6..2c63388 100644 --- a/package-lock.json +++ b/package-lock.json @@ -30,6 +30,7 @@ "reflect-metadata": "^0.2.2", "rxjs": "^7.8.1", "socks-proxy-agent": "^8.0.4", + "socks-proxy-agent": "^8.0.4", "svg-captcha": "^1.4.0" }, "devDependencies": { diff --git a/scripts/data/fanavaran-flow-ui.html b/scripts/data/fanavaran-flow-ui.html index 710e2ce..ec64dbe 100644 --- a/scripts/data/fanavaran-flow-ui.html +++ b/scripts/data/fanavaran-flow-ui.html @@ -3,7 +3,7 @@ - Fanavaran ثالث — تست ۴ مرحله + Fanavaran Claims — Third Party / Car Body @@ -146,6 +146,8 @@ border: 1px solid var(--line); border-radius: var(--radius); padding: 1.05rem 1.1rem 1.15rem; margin-bottom: 0.9rem; box-shadow: var(--shadow); } + .car-body-only { display: none; } + body[data-product="CAR_BODY"] .car-body-only { display: flex; } .card h2 { margin: 0 0 0.9rem; font-size: 0.9rem; font-weight: 650; display: flex; align-items: center; gap: 0.55rem; color: var(--ink); @@ -534,7 +536,7 @@
-

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

+

Fanavaran — تست ثالث و بدنه

v14 — قرارداد فعلی. GEN.03 با AnnouncementDate.
@@ -703,6 +705,8 @@

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

+ + @@ -874,8 +878,33 @@ + + + + + + + + + + + + + + + + + + + + + + + + +
@@ -951,7 +980,7 @@

۱ — GEN.03 Base

-

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

+

Policy inquiry + پرونده

@@ -968,8 +997,8 @@
-

۲ — GEN.12 Damage

-

Driver inquiry / GEN.44 + dmg-case

+

۲ — GEN.12 Damage

+

Driver inquiry / GEN.44 + dmg-case

@@ -977,7 +1006,7 @@
-

۳ — GEN.07 Attachments

+

۳ — GEN.07 Attachments

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

@@ -986,8 +1015,8 @@
-

۴ — GEN.08 Expertise

-

ثبت کارشناسی

+

۴ — GEN.08 Expertise

+

ثبت کارشناسی

@@ -1067,6 +1096,7 @@ node scripts/fanavaran-flow-ui-server.js /** Cleared when starting a new Fanavaran submit; person/lookup ids like ACCIDENT_CULPRIT_ID stay. */ const FANAVARAN_CASE_ID_KEYS = ["POLICY_ID","CLAIM_ID","CLAIM_NO","DRIVER_ID","DMG_CASE_ID","EXPERTISE_ID","DMG_NOTIFICATION_ID","INSURANCE_CORP_ID_NUM"]; const stateIds = Object.fromEntries(ID_KEYS.map((k) => [k, ""])); + let lookupResults = {}; let busy = false; const culpritOptions = []; const comboTimers = {}; @@ -1383,7 +1413,35 @@ node scripts/fanavaran-flow-ui-server.js input.hidden = sel.value !== "__manual__"; } - function fillIdSelect(id, rows, preferred) { + function enableLookupSearch(sel) { + if (!sel) return; + let search = $(sel.id + "_lookup_search"); + if (!search) { + search = document.createElement("input"); + search.type = "search"; + search.id = sel.id + "_lookup_search"; + search.className = "lookup-search"; + search.placeholder = "جستجو در شناسه یا عنوان لوکاپ…"; + search.setAttribute("aria-label", "جستجوی گزینه‌های لوکاپ"); + sel.parentNode.insertBefore(search, sel); + search.addEventListener("input", () => { + const query = search.value.trim().toLocaleLowerCase(); + const selected = sel.value; + const options = [...sel._lookupOptions]; + sel.innerHTML = ""; + options.forEach((option) => { + const matches = !query || option.textContent.toLocaleLowerCase().includes(query) || option.value === selected || option.value === "" || option.value === "__manual__"; + if (!matches) return; + sel.appendChild(option.cloneNode(true)); + }); + if ([...sel.options].some((option) => option.value === selected)) sel.value = selected; + }); + } + sel._lookupOptions = [...sel.options].map((option) => option.cloneNode(true)); + search.value = ""; + } + + function fillIdSelect(id, rows, preferred, allowManual = true) { const sel = $(id); if (!sel) return; const saved = sel.dataset.saved || ""; @@ -1406,29 +1464,123 @@ node scripts/fanavaran-flow-ui-server.js } sel.appendChild(o); }); - const manual = document.createElement("option"); - manual.value = "__manual__"; - manual.textContent = "ورود دستی"; - sel.appendChild(manual); + if (allowManual) { + const manual = document.createElement("option"); + manual.value = "__manual__"; + manual.textContent = "ورود دستی"; + sel.appendChild(manual); + } const manualInput = $(id + "_manual"); - if (current && !matched) { + if (allowManual && current && !matched) { sel.value = "__manual__"; if (manualInput) manualInput.value = current; + } else if (!matched) { + sel.value = ""; } + enableLookupSearch(sel); syncManualLookup(id); } + function isActiveLookupSelection(lookupName, fieldId) { + const selected = lookupValue(fieldId); + const lookup = lookupResults[lookupName]; + return Boolean( + selected && + lookup?.source === "remote" && + (lookup.options || []).some((row) => row.id === selected), + ); + } + async function refreshTenantLookups() { const client = q("FANAVARAN_CLIENT") || "tejaratno"; const hint = $("lookupHint"); hint.style.display = "block"; hint.textContent = "در حال دریافت لوکاپ " + client + " از فناوران…"; setStatus("دریافت لوکاپ " + client + "…"); - const data = await api("/api/lookups/refresh?client=" + encodeURIComponent(client)); + const policyId = stateIds.POLICY_ID || ""; + const data = await api("/api/lookups/refresh?client=" + encodeURIComponent(client) + (policyId ? "&policyId=" + encodeURIComponent(policyId) : "")); fillIdSelect("CLAIM_FILE_TYPE_ID", data.fileTypes, lookupValue("CLAIM_FILE_TYPE_ID")); fillIdSelect("INSURANCE_CORP_ID", data.insuranceCorps, lookupValue("INSURANCE_CORP_ID")); fillIdSelect("NOTIFIER_TYPE_ID", data.notifierTypes, lookupValue("NOTIFIER_TYPE_ID")); fillIdSelect("NOTIFIER_RELATION_ID", data.notifierRelations, lookupValue("NOTIFIER_RELATION_ID")); + lookupResults = data.lookups || {}; + const hullVehicle = data.hullVehicle || null; + lookupResults["hull-policy-vehicle"] = { + ...(hullVehicle || {}), + source: hullVehicle?.usedId ? "remote" : "unavailable", + error: data.failures?.["hull-policy-vehicle"] || "", + }; + const hullLookupFields = { + "accident-causes": "ACCIDENT_CAUSE_ID", + cities: "ACCIDENT_CITY_ID", + "accident-report-type": "ACCIDENT_REPORT_TYPE_ID", + "vehicle-hull-accident-types": "HULL_ACCIDENT_TYPE_ID", + "vehicle-hull-accident-culprit-type": "HULL_CULPRIT_TYPE_ID", + "detection-accident-culprits": "HULL_AUTHORITY_CULPRIT_ID", + "driving-licence-types": "CULPRIT_LICENCE_TYPE_ID", + "police-officers": "POLICE_OFFICER_ID", + ans: "HULL_COST_SEPARATION,HULL_IS_OWNER_CHANGED,HULL_IS_ACCIDENT_OUT_OF_BORDER,HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW", + "glass-break-reason": "HULL_GLASS_BREAK_REASON_ID", + colors: "COLOR_ID", + "plaque-design": "PLAQUE_DESIGN_ID", + "accident-percent": "ACCIDENT_PERCENT", + "vehicle-hull-dmg-kind": "HULL_DMG_KIND_ID", + "vehicle-hull-dmg-cost-kinds": "HULL_DMG_COST_KIND_ID", + "vehicle-hull-accessories": "VEHICLE_HULL_ACCESSORY_ID", + }; + const policyVehicleSelections = { + "vehicle-hull-dmg-kind": "", + "vehicle-hull-dmg-cost-kinds": "", + "vehicle-hull-accessories": "", + colors: hullVehicle?.colorId || "", + "plaque-design": hullVehicle?.plaqueDesignId || "", + "plaque-city": hullVehicle?.plaqueCityId || "", + "accident-percent": hullVehicle?.accidentPercent || "", + }; + for (const [lookupName, fields] of Object.entries(hullLookupFields)) { + const options = data.lookups?.[lookupName]?.options || []; + for (const id of fields.split(",")) { + fillIdSelect(id, options, policyVehicleSelections[lookupName] || lookupValue(id), false); + } + } + const kindRows = data.lookups?.["vehicle-kinds"]?.options || []; + const policyVehicleKind = kindRows.find((row) => row.id === String(hullVehicle?.vehicleKindId || "")); + if (policyVehicleKind) setComboValue("VEHICLE_KIND_ID", policyVehicleKind.id, policyVehicleKind); + const vehicleKind = policyVehicleKind || kindRows.find((row) => row.id === q("VEHICLE_KIND_ID")); + const useLookup = data.lookups?.["vehicle-use-types"] || { options: [], error: "vehicle kind is not selected", source: "unavailable" }; + const matchingUseTypes = vehicleKind?.vehicleGroupId + ? (useLookup.options || []).filter((row) => row.vehicleGroupId === vehicleKind.vehicleGroupId) + : []; + lookupResults["vehicle-use-types"] = { + ...useLookup, + options: matchingUseTypes, + vehicleGroupId: vehicleKind?.vehicleGroupId || "", + error: vehicleKind?.vehicleGroupId ? useLookup.error : "select the insured vehicle kind to filter use types by VehicleGroupId", + source: vehicleKind?.vehicleGroupId ? useLookup.source : "unavailable", + }; + const policyUsedId = String(hullVehicle?.usedId || ""); + fillIdSelect("ACCIDENT_VEHICLE_USED_ID", matchingUseTypes, policyUsedId || lookupValue("ACCIDENT_VEHICLE_USED_ID"), false); + if (policyUsedId && !matchingUseTypes.some((row) => row.id === policyUsedId)) { + lookupResults["hull-policy-vehicle"].error = + "PolicyId " + hullVehicle.policyId + " returned UsedId " + policyUsedId + + " for VehicleKindId " + (hullVehicle.vehicleKindId || "unknown") + + ", but that value is absent from the active vehicle-use-types lookup for this vehicle group."; + } + const vehicleTextFields = { + VEHICLE_CURRENT_VALUE: hullVehicle?.vehicleValue, + BUILT_YEAR: hullVehicle?.builtYear, + VIN: hullVehicle?.vin, + MOTOR_NO: hullVehicle?.motorNo, + CHASSIS_NO: hullVehicle?.chassisNo, + PLAQUE_NO: hullVehicle?.plaqueNo, + PLAQUE_SERIAL: hullVehicle?.plaqueSerial, + POLICY_NO: hullVehicle?.policyNo, + BEGIN_DATE: hullVehicle?.beginDate, + END_DATE: hullVehicle?.endDate, + }; + for (const [id, value] of Object.entries(vehicleTextFields)) { + if (value != null && String(value).trim() !== "" && $(id)) $(id).value = String(value); + } const counts = data.counts || {}; const fromFile = data.fromFile || []; hint.textContent = @@ -1439,6 +1591,12 @@ node scripts/fanavaran-flow-ui-server.js " · notifier-relation " + (counts["notifier-relation"] || 0) + " · vehicle-kinds " + (counts["vehicle-kinds"] || 0) + " · car-components " + (counts["car-components"] || 0) + + " · hull-accident-types " + (counts["vehicle-hull-accident-types"] || 0) + + " · hull vehicle-use-types " + (counts["vehicle-use-types"] || 0) + + " · hull accessories " + (counts["vehicle-hull-accessories"] || 0) + + " · policy vehicle use " + (policyUsedId || "unavailable") + + " · failed lookups " + Object.keys(data.failures || {}).length + + ((Object.keys(data.failures || {}).length) ? " · unavailable: " + Object.keys(data.failures).join(", ") : "") + (fromFile.length ? " · از فایل: " + fromFile.join(", ") : ""); setStatus("لوکاپ " + client + " دریافت شد", "ok"); } @@ -1446,6 +1604,10 @@ node scripts/fanavaran-flow-ui-server.js function syncGuilty() { const mode=$("guiltyRoleMode").value; $("guiltyOwnerBox").style.display = (mode==="1"||mode==="2a") ? "none" : "block"; + if (q("FANAVARAN_PRODUCT") === "CAR_BODY") { + $("guiltyHint").textContent = "بدنه: شناسه راننده خودروی بیمه‌شده را در ACCIDENT_CULPRIT_ID انتخاب کنید؛ این مقدار برای GEN.03 حفظ می‌شود."; + return; + } if (mode==="1") { $("guiltyHint").textContent="CulpritTypeId=337 — AccidentCulpritId لازم نیست."; $("CULPRIT_TYPE_ID").value="337"; @@ -1484,6 +1646,8 @@ node scripts/fanavaran-flow-ui-server.js const bd=splitBd(q("damagedDriverBd")); return { FANAVARAN_CLIENT:q("FANAVARAN_CLIENT"), + FANAVARAN_PRODUCT:q("FANAVARAN_PRODUCT"), + HULL_CONTRACT_ID:q("HULL_CONTRACT_ID"), FANAVARAN_API_VERSION: q("FANAVARAN_API_VERSION") === "v15" ? "v15" : "v14", CLAIM_NOTIFICATION_DATE:q("CLAIM_NOTIFICATION_DATE"), NOTIFY_LETTER_NO:q("NOTIFY_LETTER_NO"), @@ -1564,8 +1728,34 @@ node scripts/fanavaran-flow-ui-server.js INSPECTION_TIME:q("INSPECTION_TIME"), ESTIMATE_AMOUNT:q("ESTIMATE_AMOUNT"), REPAIR_WAGE:q("REPAIR_WAGE"), + REPAIR_DURATION:q("REPAIR_DURATION"), COMPONENT_REPLACEMENT_COST:q("COMPONENT_REPLACEMENT_COST"), WASTE_VALUE:q("WASTE_VALUE"), + CAR_BODY_POLICYHOLDER_NC:q("CAR_BODY_POLICYHOLDER_NC"), + ACCIDENT_CAUSE_ID:lookupValue("ACCIDENT_CAUSE_ID"), + ACCIDENT_CITY_ID:lookupValue("ACCIDENT_CITY_ID"), + ACCIDENT_REPORT_TYPE_ID:lookupValue("ACCIDENT_REPORT_TYPE_ID"), + HULL_ACCIDENT_TYPE_ID:lookupValue("HULL_ACCIDENT_TYPE_ID"), + HULL_CULPRIT_TYPE_ID:lookupValue("HULL_CULPRIT_TYPE_ID"), + HULL_AUTHORITY_CULPRIT_ID:lookupValue("HULL_AUTHORITY_CULPRIT_ID"), + CULPRIT_LICENCE_TYPE_ID:lookupValue("CULPRIT_LICENCE_TYPE_ID"), + ACCIDENT_VEHICLE_USED_ID:lookupValue("ACCIDENT_VEHICLE_USED_ID"), + POLICE_OFFICER_ID:lookupValue("POLICE_OFFICER_ID"), + HULL_IS_ACCIDENT_OUT_OF_BORDER:lookupValue("HULL_IS_ACCIDENT_OUT_OF_BORDER"), + HULL_CUSTOMER_FAULT_PERCENT:q("HULL_CUSTOMER_FAULT_PERCENT"), + HULL_COST_SEPARATION:lookupValue("HULL_COST_SEPARATION"), + HULL_IS_OWNER_CHANGED:lookupValue("HULL_IS_OWNER_CHANGED"), + HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW:lookupValue("HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW"), + HULL_GLASS_BREAK_REASON_ID:lookupValue("HULL_GLASS_BREAK_REASON_ID"), + VEHICLE_CURRENT_VALUE:q("VEHICLE_CURRENT_VALUE"), + HULL_DMG_KIND_ID:lookupValue("HULL_DMG_KIND_ID"), + HULL_DMG_COST_KIND_ID:lookupValue("HULL_DMG_COST_KIND_ID"), + ACCESSORY_KIND_ID:q("DMG_SECTION_ID"), + VEHICLE_HULL_ACCESSORY_ID:q("VEHICLE_HULL_ACCESSORY_ID"), + COLOR_ID:lookupValue("COLOR_ID"), + PLAQUE_DESIGN_ID:lookupValue("PLAQUE_DESIGN_ID"), + PLAQUE_CITY_ID:lookupValue("PLAQUE_CITY_ID"), + ACCIDENT_PERCENT:lookupValue("ACCIDENT_PERCENT"), POLICY_ID:stateIds.POLICY_ID||"", CLAIM_ID:stateIds.CLAIM_ID||"", CLAIM_NO:stateIds.CLAIM_NO||"", @@ -1609,9 +1799,37 @@ node scripts/fanavaran-flow-ui-server.js if (!q("notifierNc") && q("guiltyInsurerNc")) $("notifierNc").value = q("guiltyInsurerNc"); if (!q("notifierBd") && q("guiltyInsurerBd")) $("notifierBd").value = q("guiltyInsurerBd"); } + if (typeof syncProduct === "function") syncProduct(); + } + + function syncProduct() { + const hull = q("FANAVARAN_PRODUCT") === "CAR_BODY"; + document.body.dataset.product = hull ? "CAR_BODY" : "THIRD_PARTY"; + $("baseStageHint").textContent = hull + ? "استعلام بیمه‌نامه بدنه (InsuranceLineId=4) + پرونده GEN.03" + : "Policy inquiry + پرونده ثالث"; + $("damageStageTitle").textContent = hull ? "۲ — بدون مرحله خسارت" : "۲ — GEN.12 Damage"; + $("damageStageHint").textContent = hull + ? "برای بدنه API پرونده خسارت جداگانه وجود ندارد؛ این مرحله رد می‌شود." + : "Driver inquiry / GEN.44 + dmg-case"; + $("attachmentStageTitle").textContent = hull ? "۳ — GEN.05 Attachments" : "۳ — GEN.07 Attachments"; + $("expertiseStageTitle").textContent = hull ? "۴ — GEN.06 Expertise" : "۴ — GEN.08 Expertise"; + $("expertiseStageHint").textContent = hull + ? "کارشناسی بدنه با Wage و DmgSections، بدون DmgCaseId" + : "ثبت کارشناسی"; + $("comboVehicleKind").closest("label").querySelector("b").textContent = hull + ? "VEHICLE_KIND_ID خودرو بیمه‌شده (برای فیلتر کاربری خودرو)" + : "VEHICLE_KIND_ID"; + $("EXPERTISE_CLAIM_EXPERT_ID").closest("label").querySelector("b").textContent = hull ? "GEN.06 ClaimExpertId" : "GEN.08 ExpertiseClaimExpertId"; + $("stageNotification").hidden = hull || q("FANAVARAN_API_VERSION") !== "v15"; + $("formTabNotify").hidden = hull || (q("FANAVARAN_API_VERSION") !== "v15" && q("FANAVARAN_CLIENT") !== "moallem"); + document.querySelector('[data-form-panel="person"]').hidden = hull; + document.querySelector('[data-form-tab="person"]').hidden = hull; + if (hull && document.querySelector('[data-form-tab="person"]')?.classList.contains("active")) showFormTab("cars"); } function missingRequiredNotifier(stage) { + if (q("FANAVARAN_PRODUCT") === "CAR_BODY") return ""; const v15 = q("FANAVARAN_API_VERSION") === "v15"; const moallemV14 = q("FANAVARAN_CLIENT") === "moallem" && !v15; if (!v15 && !moallemV14) return ""; @@ -1751,6 +1969,8 @@ node scripts/fanavaran-flow-ui-server.js if (!env) return; const set = (id, key) => { if (env[key] != null && $(id)) $(id).value = env[key]; }; set("FANAVARAN_CLIENT","FANAVARAN_CLIENT"); + set("FANAVARAN_PRODUCT","FANAVARAN_PRODUCT"); + set("HULL_CONTRACT_ID","HULL_CONTRACT_ID"); $("FANAVARAN_API_VERSION").value = env.FANAVARAN_API_VERSION === "v15" ? "v15" : "v14"; set("CLAIM_NOTIFICATION_DATE","CLAIM_NOTIFICATION_DATE"); set("NOTIFY_LETTER_NO","NOTIFY_LETTER_NO"); @@ -1760,7 +1980,7 @@ node scripts/fanavaran-flow-ui-server.js set("NOTIFY_DESC","NOTIFY_DESC"); set("NOTIFIER_TYPE_ID","NOTIFIER_TYPE_ID"); set("NOTIFIER_RELATION_ID","NOTIFIER_RELATION_ID"); - ["NOTIFIER_TYPE_ID","NOTIFIER_RELATION_ID","CLAIM_FILE_TYPE_ID","INSURANCE_CORP_ID"].forEach((id) => { + ["NOTIFIER_TYPE_ID","NOTIFIER_RELATION_ID","CLAIM_FILE_TYPE_ID","INSURANCE_CORP_ID","ACCIDENT_CAUSE_ID","ACCIDENT_CITY_ID","ACCIDENT_REPORT_TYPE_ID","HULL_ACCIDENT_TYPE_ID","HULL_CULPRIT_TYPE_ID","HULL_AUTHORITY_CULPRIT_ID","CULPRIT_LICENCE_TYPE_ID","ACCIDENT_VEHICLE_USED_ID","POLICE_OFFICER_ID","HULL_IS_ACCIDENT_OUT_OF_BORDER","HULL_COST_SEPARATION","HULL_IS_OWNER_CHANGED","HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW","HULL_GLASS_BREAK_REASON_ID","HULL_DMG_KIND_ID","HULL_DMG_COST_KIND_ID","COLOR_ID","PLAQUE_DESIGN_ID","PLAQUE_CITY_ID","ACCIDENT_PERCENT"].forEach((id) => { const sel = $(id); if (!sel || env[id] == null || env[id] === "") return; sel.dataset.saved = String(env[id]); @@ -1852,8 +2072,11 @@ node scripts/fanavaran-flow-ui-server.js set("INSPECTION_TIME","INSPECTION_TIME"); set("ESTIMATE_AMOUNT","ESTIMATE_AMOUNT"); set("REPAIR_WAGE","REPAIR_WAGE"); + set("REPAIR_DURATION","REPAIR_DURATION"); set("COMPONENT_REPLACEMENT_COST","COMPONENT_REPLACEMENT_COST"); set("WASTE_VALUE","WASTE_VALUE"); + ["CAR_BODY_POLICYHOLDER_NC","ACCIDENT_CAUSE_ID","ACCIDENT_CITY_ID","ACCIDENT_REPORT_TYPE_ID","HULL_ACCIDENT_TYPE_ID","HULL_CULPRIT_TYPE_ID","HULL_AUTHORITY_CULPRIT_ID","CULPRIT_LICENCE_TYPE_ID","ACCIDENT_VEHICLE_USED_ID","POLICE_OFFICER_ID","HULL_IS_ACCIDENT_OUT_OF_BORDER","HULL_CUSTOMER_FAULT_PERCENT","HULL_COST_SEPARATION","HULL_IS_OWNER_CHANGED","HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW","HULL_GLASS_BREAK_REASON_ID","VEHICLE_CURRENT_VALUE","HULL_DMG_KIND_ID","HULL_DMG_COST_KIND_ID","VEHICLE_HULL_ACCESSORY_ID","COLOR_ID","PLAQUE_DESIGN_ID","PLAQUE_CITY_ID","ACCIDENT_PERCENT"].forEach((id) => set(id,id)); + syncProduct(); ID_KEYS.forEach((k) => { stateIds[k] = env[k] || ""; }); if (env.CULPRIT_TYPE_ID === "337") $("guiltyRoleMode").value = "1"; else if (!$("guiltyRoleMode").value) $("guiltyRoleMode").value = "2a"; @@ -2104,10 +2327,68 @@ node scripts/fanavaran-flow-ui-server.js setStatus("سرور UI روشن نیست.", "err"); return; } - if (q("CULPRIT_TYPE_ID")==="338" && !q("ACCIDENT_CULPRIT_ID") && (stage==="base"||stage==="all")) { + if (q("FANAVARAN_PRODUCT") !== "CAR_BODY" && q("CULPRIT_TYPE_ID")==="338" && !q("ACCIDENT_CULPRIT_ID") && (stage==="base"||stage==="all")) { setStatus("ACCIDENT_CULPRIT_ID برای CulpritTypeId=338 لازم است.", "err"); return; } + const hullTypeId = lookupValue("HULL_ACCIDENT_TYPE_ID"); + const hullTypeIsEnabled = [...$("HULL_ACCIDENT_TYPE_ID").options].some((option) => option.value === hullTypeId && option.value !== "" && option.value !== "__manual__"); + if (q("FANAVARAN_PRODUCT") === "CAR_BODY" && (stage === "base" || stage === "all") && !hullTypeIsEnabled) { + setStatus("از لوکاپ فعال AccidentTypeId همین تنانت یک مقدار انتخاب کنید.", "err"); + showFormTab("accident"); + return; + } + if (q("FANAVARAN_PRODUCT") === "CAR_BODY" && (stage === "base" || stage === "all")) { + const requiredLookups = [ + ["accident-causes", "ACCIDENT_CAUSE_ID"], + ["cities", "ACCIDENT_CITY_ID"], + ["accident-report-type", "ACCIDENT_REPORT_TYPE_ID"], + ["vehicle-hull-accident-types", "HULL_ACCIDENT_TYPE_ID"], + ["vehicle-hull-accident-culprit-type", "HULL_CULPRIT_TYPE_ID"], + ["detection-accident-culprits", "HULL_AUTHORITY_CULPRIT_ID"], + ["driving-licence-types", "CULPRIT_LICENCE_TYPE_ID"], + ["ans", "HULL_COST_SEPARATION"], + ["ans", "HULL_IS_OWNER_CHANGED"], + ["ans", "HULL_IS_ACCIDENT_OUT_OF_BORDER"], + ]; + const missing = requiredLookups.filter(([name, id]) => !isActiveLookupSelection(name, id)); + const policyUsedId = String(lookupResults["hull-policy-vehicle"]?.usedId || ""); + const selectedUsedId = lookupValue("ACCIDENT_VEHICLE_USED_ID"); + const hasPolicyId = Boolean(stateIds.POLICY_ID); + const policyUsedMismatch = hasPolicyId && (!policyUsedId || selectedUsedId !== policyUsedId || !isActiveLookupSelection("vehicle-use-types", "ACCIDENT_VEHICLE_USED_ID")); + if (missing.length || !q("ACCIDENT_CULPRIT_ID") || policyUsedMismatch) { + const failed = [...new Set(missing.map(([name]) => name).filter((name) => lookupResults[name]?.source !== "remote"))]; + if (policyUsedMismatch) failed.push("hull-policy-vehicle"); + setStatus(failed.length + ? "لوکاپ‌ها یا دادهٔ وابسته کامل نیست: " + failed.map((name) => name + " (" + (lookupResults[name]?.error || (name === "hull-policy-vehicle" && policyUsedId ? "select the policy vehicle's UsedId " + policyUsedId : "lookup unavailable")) + ")").join("؛ ") + " — داده را تکمیل و لوکاپ‌ها را دوباره بگیرید." + : "AccidentVehicleUsedId باید با UsedId خودروی متصل به PolicyId یکی باشد؛ مشخصات بیمه‌نامه را دوباره از لوکاپ بگیرید.", "err"); + showFormTab("accident"); + return; + } + } + if (q("FANAVARAN_PRODUCT") === "CAR_BODY" && (stage === "expertise" || stage === "all")) { + const repairDuration = Number(q("REPAIR_DURATION")); + if (!Number.isInteger(repairDuration) || repairDuration < 1 || repairDuration > 255) { + setStatus("RepairDuration الزامی است؛ مدت تعمیر را بین 1 تا 255 روز وارد کنید.", "err"); + showFormTab("accident"); + return; + } + const requiredLookups = [ + ["vehicle-hull-dmg-kind", "HULL_DMG_KIND_ID"], + ["vehicle-hull-dmg-cost-kinds", "HULL_DMG_COST_KIND_ID"], + ["vehicle-hull-accessories", "VEHICLE_HULL_ACCESSORY_ID"], + ["car-components", "DMG_SECTION_ID"], + ]; + const missing = requiredLookups.filter(([name, id]) => !isActiveLookupSelection(name, id)); + if (missing.length) { + const dependentAccessoryMissing = missing.some(([name]) => name === "vehicle-hull-accessories"); + setStatus(dependentAccessoryMissing + ? "پس از ثبت پایه، با PolicyId پرونده لوکاپ لوازم بدنه را دوباره دریافت کنید؛ سپس مقادیر آسیب و هزینه را انتخاب کنید." + : "مقادیر فعال نوع آسیب، نوع هزینه و قطعه را از لوکاپ‌های فناوران انتخاب کنید.", "err"); + showFormTab(dependentAccessoryMissing ? "accident" : "tenant"); + return; + } + } const notifierGap = missingRequiredNotifier(stage); if (notifierGap) { setStatus(notifierGap, "err"); @@ -2146,6 +2427,12 @@ node scripts/fanavaran-flow-ui-server.js const errors = extractFanavaranErrors(stdout, stderr); renderFanavaranErrors(errors.length ? errors : [{ message: err.message, rule: "" }]); showSideTab("errors"); + if (q("FANAVARAN_PRODUCT") === "CAR_BODY" && d.ids?.POLICY_ID) { + try { + await refreshTenantLookups(); + $("envOut").value = envToText(collectEnv()); + } catch { /* the failed submit already contains the primary error */ } + } setStatus(err.message, "err"); } finally { setBusy(false); @@ -2153,6 +2440,10 @@ node scripts/fanavaran-flow-ui-server.js } $("LOCATION").addEventListener("change", () => refreshExperts()); + $("FANAVARAN_PRODUCT").addEventListener("change", () => { + syncProduct(); + $("envOut").value = envToText(collectEnv()); + }); ["CLAIM_EXPERT_ID", "EXPERTISE_CLAIM_EXPERT_ID"].forEach((id) => { const manual = $(id + "_manual"); $(id).addEventListener("change", () => { @@ -2532,6 +2823,7 @@ node scripts/fanavaran-flow-ui-server.js syncDamaged(); renderIds(); syncApiVersion(false); + syncProduct(); $("envOut").value = envToText(collectEnv()); $("LOCATION").addEventListener("change", () => refreshExperts()); $("FANAVARAN_API_VERSION").addEventListener("change", () => { diff --git a/scripts/data/fanavaran-flow.env.example b/scripts/data/fanavaran-flow.env.example index ed17bc9..bf04fe3 100644 --- a/scripts/data/fanavaran-flow.env.example +++ b/scripts/data/fanavaran-flow.env.example @@ -1,7 +1,7 @@ # Fanavaran flow test — copy this file, fill section A, then run: # # cp scripts/data/fanavaran-flow.env.example scripts/data/fanavaran-flow.moallem.env -# ./scripts/fanavaran-flow-test.sh --env scripts/data/fanavaran-flow.moallem.env +# FANAVARAN_FLOW_ENV=scripts/data/fanavaran-flow.moallem.env node scripts/fanavaran-flow-ui-server.js # # Section A = you fill before (or when the script asks). # Section B = leave empty. The script writes Fanavaran ids here after each stage @@ -16,6 +16,10 @@ # --- tenant --- FANAVARAN_CLIENT=moallem +# Moallem uses the V14 GEN.03 body and requires an embedded claimant notification. +FANAVARAN_API_VERSION=v14 +FANAVARAN_BASE_URL=https://api.inssw.ir/BimeApiManager/api + # Localhost only: route curl through Termius SOCKS (Dynamic Port Forwarding). # Example: CURL_PROXY=socks5h://127.0.0.1:1080 # Or run the script on the Moallem server (no proxy needed). @@ -50,6 +54,20 @@ GUILTY_NATIONAL_CODE= ACCIDENT_DATE=1404/05/20 ACCIDENT_TIME=12:00 +# --- Moallem V14 GEN.03 embedded claimant notification --- +# IDs must come from Moallem's own Fanavaran code lists / party inquiry. +CLAIM_NOTIFICATION_DATE= +NOTIFY_LETTER_DATE= +NOTIFIER_TYPE_ID= +NOTIFIER_RELATION_ID= +NOTIFIER_PARTY_ID= +NOTIFY_LETTER_NO= +NOTIFY_DESC= +INJURED_COUNT= +DEATH_COUNT= +IS_INJURED_PARTY_IDENTIFIED= +INJURED_PARTY_ID= + # --- GEN.12 case --- DRIVER_NATIONAL_CODE= DRIVER_BIRTH_YEAR=1370 diff --git a/scripts/fanavaran-auth.sh b/scripts/fanavaran-auth.sh index 5435ff9..72e3134 100755 --- a/scripts/fanavaran-auth.sh +++ b/scripts/fanavaran-auth.sh @@ -4,7 +4,7 @@ set -euo pipefail usage() { cat <<'USAGE' Usage: - scripts/fanavaran-auth.sh + scripts/fanavaran-auth.sh Calls Fanavaran GetAppToken, then Login with the returned appToken. Outputs the appToken and authenticationToken, and writes raw responses to: @@ -40,6 +40,15 @@ case "$client" in contract_id='28' location='210050' ;; + moallem) + app_name='ItTalie' + app_secret='itT@l!3@api' + fanavaran_username='itTalieUser' + fanavaran_password='itT@l!3@user' + corp_id='5650' + contract_id='304' + location='30900' + ;; *) printf 'Unknown Fanavaran client: %s\n\n' "$client" >&2 usage >&2 @@ -51,6 +60,13 @@ base_url="${FANAVARAN_BASE_URL:-https://apimanager.iraneit.com/BimeApiManager/ap auth_dir="files/fanavaran-auth/$client" mkdir -p "$auth_dir" +curl_proxy_args() { + local proxy="${CURL_PROXY:-${ALL_PROXY:-}}" + if [[ -n "$proxy" ]]; then + printf '%s' "--proxy $proxy" + fi +} + app_token_headers="$auth_dir/get-app-token.headers" app_token_body="$auth_dir/get-app-token.body.json" login_headers="$auth_dir/login.headers" @@ -88,7 +104,9 @@ printf 'Fanavaran client: %s\n' "$client" printf 'Base URL: %s\n\n' "$base_url" printf '1. Calling GetAppToken...\n' +# shellcheck disable=SC2046 curl -sS -D "$app_token_headers" -o "$app_token_body" \ + $(curl_proxy_args) \ -X POST "$base_url/EITAuthentication/GetAppToken" \ -H "appname: $app_name" \ -H "secret: $app_secret" \ @@ -102,7 +120,9 @@ if [[ -z "$app_token" ]]; then fi printf '2. Calling Login...\n' +# shellcheck disable=SC2046 curl -sS -D "$login_headers" -o "$login_body" \ + $(curl_proxy_args) \ -X POST "$base_url/EITAuthentication/Login" \ -H "appToken: $app_token" \ -H "userName: $fanavaran_username" \ diff --git a/scripts/fanavaran-flow-test.sh b/scripts/fanavaran-flow-test.sh index fc2e80e..a0fc64a 100755 --- a/scripts/fanavaran-flow-test.sh +++ b/scripts/fanavaran-flow-test.sh @@ -5,10 +5,16 @@ # 1) Auth (GetAppToken → Login) # 2) Policy inquiry → PolicyId # 3) GEN.03 base claim -# 4) Driver inquiry → DriverId + resolve InsuranceCorpId from Persian caption -# 5) GEN.12 damage case -# 6) GEN.07 attachments (one multipart request per file) -# 7) GEN.08 expertise +# 4) Embedded GEN.03 damage notification for V15 and Moallem V14 +# 5) Driver inquiry → DriverId + resolve InsuranceCorpId from Persian caption +# 6) GEN.12 damage case +# 7) GEN.07 attachments (one multipart request per file) +# 8) GEN.08 expertise +# +# FANAVARAN_API_VERSION=v14 (default) keeps AnnouncementDate. Moallem V14 also +# embeds DmgNotifications in GEN.03 because Moallem requires a claim notifier. +# Other V14 clients keep their current GEN.03 body. V15 drops AnnouncementDate +# and embeds DmgNotifications; this flow does not call GEN.30. # # Plate / chassis / VIN / policy document fields are NOT inquired here — # put them in the env file (Tejarat/ESG may be unavailable on the host). @@ -46,8 +52,9 @@ Fanavaran-only multi-stage submit. No YARA / no plate-provider inquiry. Options: --env Required. Copy scripts/data/fanavaran-flow.env.example and fill section A. Section B (CLAIM_ID, …) is written back into this file as stages succeed. - --stages all | base | damage | attachments | expertise - or comma list (default: all). + --stages all | auth | base | notification | person | damage | attachments | expertise + or comma list (default: all). auth = GetAppToken + Login only. + notification = V15 GEN.30; Moallem V14 uses GEN.03 embed. --yes Submit without confirmation prompts --preview-only Build payloads + run inquiries; do not POST creates/uploads --force-login Ignore cached authenticationToken and call GetAppToken+Login @@ -58,10 +65,33 @@ Auth token is cached in files/fanavaran-auth//tokens.env until Asia/Tehr midnight (same as the Nest app). Re-runs reuse it; do not Login every invocation. Stage sequence matches the app (soft-skip when id already present): - auth → policy → GEN.03 → driver+corp resolve → GEN.12 → GEN.07 → GEN.08 + auth → policy → GEN.03 (+ notifier for V15 / Moallem V14) + → driver+corp resolve → GEN.12 → GEN.07 → GEN.08 + +FANAVARAN_API_VERSION=v14 is the default and does not send GEN.30. Moallem +V14 still embeds the required notifier on the GEN.03 create. USAGE } +api_is_v15() { + local v="${FANAVARAN_API_VERSION:-v14}" + v="${v,,}" + [[ "$v" == "v15" || "$v" == "15" ]] +} + +is_car_body() { [[ "${FANAVARAN_PRODUCT:-THIRD_PARTY}" == "CAR_BODY" ]]; } +claim_collection() { + if is_car_body; then printf '%s' 'vehicle-hull-claims'; else printf '%s' 'third-party-car-financial-claims'; fi +} + +moallem_v14_needs_notifier() { + [[ "${FANAVARAN_CLIENT:-}" == "moallem" ]] && ! api_is_v15 +} + +base_claim_needs_notifier() { + api_is_v15 || moallem_v14_needs_notifier +} + die() { printf 'ERROR: %s\n' "$*" >&2; exit 1; } info() { printf '\n==> %s\n' "$*"; } ok() { printf 'OK: %s\n' "$*"; } @@ -187,7 +217,16 @@ confirm_submit() { stage_wanted() { local name="$1" - [[ "$STAGES" == "all" ]] && return 0 + if [[ "$STAGES" == "all" ]]; then + # GEN.30 is not part of the v14 flow. Person register is a manual stage. + if [[ "$name" == "notification" ]] && ! api_is_v15; then + return 1 + fi + if [[ "$name" == "person" ]]; then + return 1 + fi + return 0 + fi local p IFS=',' read -r -a parts <<< "$STAGES" for p in "${parts[@]}"; do @@ -247,6 +286,53 @@ try { ' "$file" } +# Print Fanavaran Message/RuleName from a submit body, then die. +fanavaran_die() { + local label="$1" + local body_file="$2" + local msg rule html_title + msg="$(json_get "$body_file" 'data.Message ?? data.message ?? ""' 2>/dev/null || true)" + rule="$(json_get "$body_file" 'data.RuleName ?? data.ruleName ?? ""' 2>/dev/null || true)" + if [[ -z "$msg" ]]; then + msg="$( + node -e ' +const fs = require("fs"); +const raw = fs.readFileSync(process.argv[1], "utf8"); +try { + const d = JSON.parse(raw); + const m = d.Message || d.message || ""; + process.stdout.write(String(m)); +} catch { + const t = raw.match(/

([^<]+)<\/h3>/i); + process.stdout.write(t ? t[1] : raw.slice(0, 240).replace(/\s+/g, " ")); +} +' "$body_file" 2>/dev/null || true + )" + fi + if [[ -z "$rule" ]]; then + rule="$( + node -e ' +const fs = require("fs"); +try { + const d = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); + process.stdout.write(String(d.RuleName || d.ruleName || "")); +} catch { process.stdout.write(""); } +' "$body_file" 2>/dev/null || true + )" + fi + msg="${msg//$'\r'/}" + msg="${msg//$'\n'/ | }" + printf 'ERROR: %s failed\n' "$label" >&2 + if [[ -n "$msg" ]]; then + printf 'Fanavaran Message: %s\n' "$msg" >&2 + fi + if [[ -n "$rule" ]]; then + printf 'Fanavaran RuleName: %s\n' "$rule" >&2 + fi + printf 'See: %s\n' "$body_file" >&2 + exit 1 +} + save_ids() { mkdir -p "$OUT_DIR" cat > "$OUT_DIR/ids.env" </dev/null || true)" + printf -- '----- RESPONSE HTTP %s -----\n' "${code:-?}" + if [[ -s "$body_file" ]]; then + cat "$body_file" + tail -c 1 "$body_file" | grep -q $'\n' || printf '\n' + else + printf '(empty body)\n' + fi + printf 'saved body: %s\n' "$body_file" + printf 'saved headers: %s\n' "$headers_file" +} + fv_curl_json() { local method="$1" local url="$2" local out_body="$3" local data_file="${4:-}" local headers_file="${out_body%.json}.headers" + local -a extra_headers=( + "authenticationToken: ${AUTHENTICATION_TOKEN}" + "CorpId: ${CORP_ID}" + "ContractId: ${CONTRACT_ID}" + "Location: ${LOCATION}" + "Content-Type: application/json" + ) + print_http_request "$method" "$url" "$data_file" "${extra_headers[@]}" if [[ -n "$data_file" ]]; then # shellcheck disable=SC2046 curl -sS -D "$headers_file" -o "$out_body" \ @@ -561,9 +725,7 @@ fv_curl_json() { -H "Content-Type: application/json" fi pretty_json_file "$out_body" || true - local code - code="$(awk 'NR==1 {print $2}' "$headers_file")" - printf 'HTTP %s → %s\n' "$code" "$out_body" + print_http_response "$headers_file" "$out_body" } # ---------- inquiries ---------- @@ -572,12 +734,16 @@ inquire_policy_id() { ok "Using POLICY_ID=$POLICY_ID from env (skip inquiry)" return 0 fi - ask_var GUILTY_NATIONAL_CODE "Guilty insurer national code (policy inquiry)" + local policy_nc="${GUILTY_NATIONAL_CODE:-}" + if is_car_body; then policy_nc="${CAR_BODY_POLICYHOLDER_NC:-$policy_nc}"; fi + [[ -n "$policy_nc" ]] || { if is_car_body; then ask_var CAR_BODY_POLICYHOLDER_NC "Car-body policyholder national code"; policy_nc="$CAR_BODY_POLICYHOLDER_NC"; else ask_var GUILTY_NATIONAL_CODE "Guilty insurer national code (policy inquiry)"; policy_nc="$GUILTY_NATIONAL_CODE"; fi; } local out="$OUT_DIR/policy-inquiry.json" - info "2) Policy inquiry — NationalCode=$GUILTY_NATIONAL_CODE" + local insurance_line=5 + if is_car_body; then insurance_line=4; fi + info "2) Policy inquiry (InsuranceLineId=$insurance_line) — NationalCode=$policy_nc" fv_curl_json GET \ - "$FANAVARAN_BIME_URL/common/Policies/inquiry-my-policies?InsuranceLineId=5&NationalCode=${GUILTY_NATIONAL_CODE}" \ + "$FANAVARAN_BIME_URL/common/Policies/inquiry-my-policies?InsuranceLineId=${insurance_line}&NationalCode=${policy_nc}" \ "$out" POLICY_ID="$(node -e ' @@ -599,6 +765,52 @@ console.log(String(withId[0].id)); save_ids } +inquire_hull_policy_vehicle() { + is_car_body || return 0 + require_var POLICY_ID + + local policy_out="$OUT_DIR/hull-policy.json" + local vehicle_out="$OUT_DIR/hull-policy-vehicle.json" + info "2b) Read car-body policy vehicle (PolicyId=$POLICY_ID)" + fv_curl_json GET \ + "$FANAVARAN_BIME_URL/car/vehicle-hull-policies/${POLICY_ID}" \ + "$policy_out" + + local vehicle_id version_no version_query + vehicle_id="$(json_get "$policy_out" 'data?.VehicleId ?? data?.vehicleId ?? data?.data?.VehicleId ?? data?.data?.vehicleId ?? ""')" + version_no="$(json_get "$policy_out" 'data?.VehicleVersionNo ?? data?.vehicleVersionNo ?? data?.data?.VehicleVersionNo ?? data?.data?.vehicleVersionNo ?? ""')" + [[ "$vehicle_id" =~ ^[0-9]+$ ]] || die "Hull policy $POLICY_ID did not return a numeric VehicleId. Inspect $policy_out." + version_query="" + if [[ "$version_no" =~ ^[0-9]+$ ]]; then version_query="?versionno=$version_no"; fi + + fv_curl_json GET \ + "$FANAVARAN_BIME_URL/car/vehicles/${vehicle_id}${version_query}" \ + "$vehicle_out" + + local used_id vehicle_kind_id vehicle_value color_id built_year vin motor_no chassis_no + used_id="$(json_get "$vehicle_out" 'data?.UsedId ?? data?.usedId ?? data?.data?.UsedId ?? data?.data?.usedId ?? ""')" + vehicle_kind_id="$(json_get "$vehicle_out" 'data?.VehicleKindId ?? data?.vehicleKindId ?? data?.data?.VehicleKindId ?? data?.data?.vehicleKindId ?? ""')" + vehicle_value="$(json_get "$policy_out" 'data?.VehicleValue ?? data?.vehicleValue ?? data?.data?.VehicleValue ?? data?.data?.vehicleValue ?? ""')" + color_id="$(json_get "$vehicle_out" 'data?.ColorId ?? data?.colorId ?? data?.data?.ColorId ?? data?.data?.colorId ?? ""')" + built_year="$(json_get "$vehicle_out" 'data?.BuiltYear ?? data?.builtYear ?? data?.ManufactureYear ?? data?.manufactureYear ?? data?.data?.BuiltYear ?? data?.data?.ManufactureYear ?? ""')" + vin="$(json_get "$vehicle_out" 'data?.VIN ?? data?.Vin ?? data?.vin ?? data?.data?.VIN ?? data?.data?.Vin ?? ""')" + motor_no="$(json_get "$vehicle_out" 'data?.MotorNo ?? data?.motorNo ?? data?.data?.MotorNo ?? data?.data?.motorNo ?? ""')" + chassis_no="$(json_get "$vehicle_out" 'data?.ChassisNo ?? data?.chassisNo ?? data?.data?.ChassisNo ?? data?.data?.chassisNo ?? ""')" + [[ "$used_id" =~ ^[0-9]+$ && "$used_id" != "0" ]] || die "Vehicle $vehicle_id did not return a valid UsedId. Inspect $vehicle_out; refusing the car-body default." + + persist_env ACCIDENT_VEHICLE_USED_ID "$used_id" + persist_env VEHICLE_ID "$vehicle_id" + [[ -z "$vehicle_kind_id" ]] || persist_env VEHICLE_KIND_ID "$vehicle_kind_id" + [[ -z "$vehicle_value" ]] || persist_env VEHICLE_CURRENT_VALUE "$vehicle_value" + [[ -z "$color_id" ]] || persist_env COLOR_ID "$color_id" + [[ -z "$built_year" ]] || persist_env BUILT_YEAR "$built_year" + [[ -z "$vin" ]] || persist_env VIN "$vin" + [[ -z "$motor_no" ]] || persist_env MOTOR_NO "$motor_no" + [[ -z "$chassis_no" ]] || persist_env CHASSIS_NO "$chassis_no" + save_ids + ok "Policy vehicle resolved: VehicleId=$vehicle_id UsedId=$used_id VehicleKindId=${vehicle_kind_id:-?}" +} + inquire_driver_id() { if [[ -n "${DRIVER_ID:-}" ]]; then ok "Using DRIVER_ID=$DRIVER_ID from env (skip inquiry)" @@ -625,21 +837,144 @@ inquire_driver_id() { DRIVER_ID="$(node -e ' const fs = require("fs"); const target = Number(process.argv[2]); +const ACCEPTED = new Set([161, 166]); const data = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); const rows = Array.isArray(data) ? data : (data?.value || data?.data || []); if (!Array.isArray(rows) || !rows.length) { console.log(""); process.exit(0); } -const match = rows.find(r => Number(r.RoleId) === target); -if (match) console.log(String(match.Id)); -else { - console.error("No RoleId=" + target + "; rows: " + rows.map(r => "Id=" + r.Id + "/RoleId=" + r.RoleId).join(", ")); - console.log(""); -} +const match = rows.find(r => Number(r.RoleId) === target && ACCEPTED.has(Number(r.RoleId))); +if (match && Number(match.Id) > 0) { console.log(String(match.Id)); process.exit(0); } +const accepted = rows.find(r => ACCEPTED.has(Number(r.RoleId)) && Number(r.Id) > 0); +if (accepted) console.log(String(accepted.Id)); +else console.log(""); ' "$out" "$target_role")" - [[ -n "$DRIVER_ID" ]] || die "Driver inquiry failed. Inspect $out or set DRIVER_ID in env." - ok "DriverId=$DRIVER_ID (RoleId=$target_role)" + if [[ -n "$DRIVER_ID" ]]; then + ok "DriverId=$DRIVER_ID (inquiry RoleId=$target_role or accepted 161/166)" + persist_env DRIVER_ID + save_ids + return 0 + fi + + warn "Driver inquiry has no RoleId 161/166 for $DRIVER_NATIONAL_CODE — GEN.44 other-people create" + create_other_person +} + +create_other_person() { + require_var DRIVER_NATIONAL_CODE + require_var DRIVER_BIRTH_YEAR + require_var DRIVER_BIRTH_MONTH + require_var DRIVER_BIRTH_DAY + + export DRIVER_NATIONAL_CODE DRIVER_BIRTH_YEAR DRIVER_BIRTH_MONTH DRIVER_BIRTH_DAY + export DRIVER_MOBILE="${DRIVER_MOBILE:-}" + export DRIVER_TEL="${DRIVER_TEL:-}" + export DRIVER_ADDRESS="${DRIVER_ADDRESS:-}" + export DRIVER_POSTAL_CODE="${DRIVER_POSTAL_CODE:-}" + export DRIVER_EMAIL="${DRIVER_EMAIL:-}" + export DRIVER_JOB_ADDRESS="${DRIVER_JOB_ADDRESS:-}" + export DRIVER_CITY_ID="${DRIVER_CITY_ID:-}" + export DRIVER_PERSON_KIND_ID="${DRIVER_PERSON_KIND_ID:-}" + export IS_IRANIAN="${IS_IRANIAN:-}" + export DRIVER_IDENTITY_ISSU_PLACE="${DRIVER_IDENTITY_ISSU_PLACE:-}" + export DRIVER_MARITAL_STATUS="${DRIVER_MARITAL_STATUS:-}" + export DRIVER_NATIONALITY_ID="${DRIVER_NATIONALITY_ID:-}" + export DRIVER_PASSPORT_NO="${DRIVER_PASSPORT_NO:-}" + export DRIVER_NATURALIZED_CODE="${DRIVER_NATURALIZED_CODE:-}" + export DRIVER_ECONOMIC_CODE="${DRIVER_ECONOMIC_CODE:-}" + export DRIVER_AD_BIRTH_YEAR="${DRIVER_AD_BIRTH_YEAR:-}" + export DRIVER_AD_BIRTH_MONTH="${DRIVER_AD_BIRTH_MONTH:-}" + export DRIVER_AD_BIRTH_DAY="${DRIVER_AD_BIRTH_DAY:-}" + + node <<'NODE' >"$OUT_DIR/other-people-payload.json" +const e = process.env; +const numOrNull = (v) => { + if (v === undefined || v === null) return null; + const s = String(v).trim(); + if (s === "" || s.toLowerCase() === "null") return null; + const x = Number(s); + return Number.isFinite(x) ? x : null; +}; +const strOrNull = (v) => { + if (v === undefined || v === null) return null; + const s = String(v).trim(); + if (s === "" || s.toLowerCase() === "null") return null; + return s; +}; +const payload = { + NationalCode: e.DRIVER_NATIONAL_CODE, + BirthYear: numOrNull(e.DRIVER_BIRTH_YEAR), + BirthMonth: numOrNull(e.DRIVER_BIRTH_MONTH), + BirthDay: numOrNull(e.DRIVER_BIRTH_DAY), + ADBirthYear: numOrNull(e.DRIVER_AD_BIRTH_YEAR), + ADBirthMonth: numOrNull(e.DRIVER_AD_BIRTH_MONTH), + ADBirthDay: numOrNull(e.DRIVER_AD_BIRTH_DAY), + IdentityNoIssuPlace: strOrNull(e.DRIVER_IDENTITY_ISSU_PLACE), + CityId: numOrNull(e.DRIVER_CITY_ID), + PersonKindId: numOrNull(e.DRIVER_PERSON_KIND_ID), + Address: strOrNull(e.DRIVER_ADDRESS), + PostalCode: strOrNull(e.DRIVER_POSTAL_CODE), + Tel: strOrNull(e.DRIVER_TEL), + Mobile: strOrNull(e.DRIVER_MOBILE), + Email: strOrNull(e.DRIVER_EMAIL), + JobAddress: strOrNull(e.DRIVER_JOB_ADDRESS), + MaritalStatus: numOrNull(e.DRIVER_MARITAL_STATUS), + NationalityId: numOrNull(e.DRIVER_NATIONALITY_ID), + PassportNo: strOrNull(e.DRIVER_PASSPORT_NO), + NaturalizedCode: strOrNull(e.DRIVER_NATURALIZED_CODE), + EconomicCode: strOrNull(e.DRIVER_ECONOMIC_CODE), + IsIranian: strOrNull(e.IS_IRANIAN), +}; +process.stdout.write(JSON.stringify(payload, null, 2) + "\n"); +NODE + + if [[ "$PREVIEW_ONLY" -eq 1 ]]; then + warn "Preview-only: other-people payload written, not POSTed" + return 0 + fi + + info "4b) POST GEN.44 other-people" + fv_curl_json POST \ + "$FANAVARAN_BIME_URL/common/other-people" \ + "$OUT_DIR/other-people-submit.json" \ + "$OUT_DIR/other-people-payload.json" + + OTHER_PERSON_ID="$(json_get "$OUT_DIR/other-people-submit.json" 'data.Id ?? data.id ?? data.ID ?? ""')" + if [[ -z "$OTHER_PERSON_ID" ]]; then + warn "GEN.44 create returned no Id — re-inquiring parties" + else + persist_env OTHER_PERSON_ID + persist_env OTHER_PERSON_CREATED 1 + ok "GEN.44 otherPersonId=$OTHER_PERSON_ID" + fi + + local retry="$OUT_DIR/driver-inquiry-after-create.json" + local url="$FANAVARAN_BIME_URL/common/parties/inquiry-by-unique-identifier" + url+="?NationalCode=${DRIVER_NATIONAL_CODE}" + url+="&BirthYear=${DRIVER_BIRTH_YEAR}&BirthMonth=${DRIVER_BIRTH_MONTH}&BirthDay=${DRIVER_BIRTH_DAY}" + info "4c) Driver inquiry after GEN.44" + fv_curl_json GET "$url" "$retry" + + DRIVER_ID="$(node -e ' +const fs = require("fs"); +const ACCEPTED = new Set([161, 166]); +const data = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); +const rows = Array.isArray(data) ? data : (data?.value || data?.data || []); +const accepted = Array.isArray(rows) + ? rows.find(r => ACCEPTED.has(Number(r.RoleId)) && Number(r.Id) > 0) + : null; +if (accepted) console.log(String(accepted.Id)); +else console.log(""); +' "$retry")" + + if [[ -z "$DRIVER_ID" && -n "${OTHER_PERSON_ID:-}" ]]; then + DRIVER_ID="$OTHER_PERSON_ID" + warn "Re-inquiry still empty — using GEN.44 Id as DriverId=$DRIVER_ID" + fi + + [[ -n "$DRIVER_ID" ]] || fanavaran_die "GEN.44 other-people" "$OUT_DIR/other-people-submit.json" persist_env DRIVER_ID save_ids + ok "DriverId=$DRIVER_ID (GEN.44 fallback)" } resolve_insurance_corp_id() { @@ -702,12 +1037,63 @@ build_base_payload() { ask_var ACCIDENT_DATE "AccidentDate Jalali YYYY/MM/DD" ask_var ACCIDENT_TIME "AccidentTime HH:mm" require_var POLICY_ID + export TRACKING_CODE="${TRACKING_CODE:-}" + if is_car_body; then + for lookup_field in ACCIDENT_CAUSE_ID ACCIDENT_CITY_ID ACCIDENT_REPORT_TYPE_ID \ + HULL_ACCIDENT_TYPE_ID HULL_CULPRIT_TYPE_ID HULL_AUTHORITY_CULPRIT_ID \ + CULPRIT_LICENCE_TYPE_ID ACCIDENT_VEHICLE_USED_ID HULL_COST_SEPARATION \ + HULL_IS_OWNER_CHANGED HULL_IS_ACCIDENT_OUT_OF_BORDER; do + require_var "$lookup_field" "select an active value from this tenant's Fanavaran lookup" + done + export HULL_CUSTOMER_FAULT_PERCENT="${HULL_CUSTOMER_FAULT_PERCENT:-100}" + node <<'NODE' >"$OUT_DIR/base-payload.json" +const e=process.env, n=(k)=>Number(e[k]), nullable=(v)=>v===""?null:Number(v); +const payload={AccidentCauseId:n("ACCIDENT_CAUSE_ID"),AccidentCityId:n("ACCIDENT_CITY_ID"),AccidentCulpritId:nullable(e.ACCIDENT_CULPRIT_ID),AccidentDate:e.ACCIDENT_DATE,AccidentLocationAddress:e.ACCIDENT_LOCATION_ADDRESS,AccidentReportTypeId:n("ACCIDENT_REPORT_TYPE_ID"),AccidentTime:e.ACCIDENT_TIME,AccidentTypeId:n("HULL_ACCIDENT_TYPE_ID"),AccidentVehicleUsedId:n("ACCIDENT_VEHICLE_USED_ID"),AuthorityCulpritId:n("HULL_AUTHORITY_CULPRIT_ID"),ClaimExpertId:n("CLAIM_EXPERT_ID"),CostSeparationToDmgSections:n("HULL_COST_SEPARATION"),CulpritLicenceIssuDate:e.CULPRIT_LICENCE_ISSU_DATE,CulpritLicenceNo:e.CULPRIT_LICENCE_NO,CulpritLicenceTypeId:n("CULPRIT_LICENCE_TYPE_ID"),CulpritTypeId:n("HULL_CULPRIT_TYPE_ID"),CustomerFaultPercent:n("HULL_CUSTOMER_FAULT_PERCENT"),EstimateAmount:n("ESTIMATE_AMOUNT"),GlassBreakReasonId:nullable(e.HULL_GLASS_BREAK_REASON_ID),IsAccidentOutOfBorder:n("HULL_IS_ACCIDENT_OUT_OF_BORDER"),IsLicenseReplaced:null,IsOwnerChanged:n("HULL_IS_OWNER_CHANGED"),IsSurplusArticleEighthLaw:nullable(e.HULL_IS_SURPLUS_ARTICLE_EIGHTH_LAW),PolicyId:n("POLICY_ID"),PoliceOfficerId:nullable(e.POLICE_OFFICER_ID),PoliceReportDesc:e.POLICE_REPORT_DESC||null,TrackingCode:e.TRACKING_CODE||null}; +process.stdout.write(JSON.stringify(payload,null,2)+"\n"); +NODE + ok "Wrote hull GEN.03 payload (no third-party-only fields)" + return + fi + export POLICE_REPORT_DESC="${POLICE_REPORT_DESC:-YARA TEST CASE — GEN.44 — please delete from Fanavaran}" + + if ! is_car_body && base_claim_needs_notifier; then + CLAIM_NOTIFICATION_DATE="${CLAIM_NOTIFICATION_DATE:-$ACCIDENT_DATE}" + NOTIFY_LETTER_DATE="${NOTIFY_LETTER_DATE:-$CLAIM_NOTIFICATION_DATE}" + INJURED_COUNT="${INJURED_COUNT:-}" + DEATH_COUNT="${DEATH_COUNT:-}" + NOTIFY_LETTER_NO="${NOTIFY_LETTER_NO:-}" + NOTIFY_DESC="${NOTIFY_DESC:-}" + IS_INJURED_PARTY_IDENTIFIED="${IS_INJURED_PARTY_IDENTIFIED:-}" + INJURED_PARTY_ID="${INJURED_PARTY_ID:-}" + export CLAIM_NOTIFICATION_DATE NOTIFY_LETTER_DATE INJURED_COUNT DEATH_COUNT \ + NOTIFY_LETTER_NO NOTIFY_DESC NOTIFIER_TYPE_ID NOTIFIER_RELATION_ID \ + NOTIFIER_PARTY_ID IS_INJURED_PARTY_IDENTIFIED INJURED_PARTY_ID + require_var CLAIM_NOTIFICATION_DATE "تاریخ اعلام خسارت (CLAIM_NOTIFICATION_DATE)" + require_var NOTIFIER_TYPE_ID "NotifierTypeId — نوع اعلام‌کننده" + require_var NOTIFIER_RELATION_ID "NotifierRelationId — نسبت اعلام‌کننده" + require_var NOTIFIER_PARTY_ID "NotifierPartyId — شخص اعلام‌کننده را در پنل استعلام کنید" + BASE_INCLUDED_NOTIFICATION=1 + fi node <<'NODE' >"$OUT_DIR/base-payload.json" -const fs = require("fs"); const e = process.env; const n = (k) => Number(e[k]); -const payload = { +const numOrNull = (v) => { + if (v === undefined || v === null) return null; + const s = String(v).trim(); + if (s === "" || s.toLowerCase() === "null") return null; + const x = Number(s); + return Number.isFinite(x) ? x : null; +}; +const strOrNull = (v) => { + if (v === undefined || v === null || String(v).trim() === "") return null; + return String(v); +}; +const version = String(e.FANAVARAN_API_VERSION || "v14").toLowerCase(); +const v15 = version === "v15" || version === "15"; +const includeNotifier = + v15 || String(e.FANAVARAN_CLIENT || "").toLowerCase() === "moallem"; +const v14Payload = { AccidentCityId: n("ACCIDENT_CITY_ID"), AccidentReportTypeId: n("ACCIDENT_REPORT_TYPE_ID"), AccidentVehicleUsedId: n("ACCIDENT_VEHICLE_USED_ID"), @@ -725,7 +1111,7 @@ const payload = { ActualPremium: null, ArchiveNo: null, AuthorityCulpritId: null, - AccidentCulpritId: null, + AccidentCulpritId: n("ACCIDENT_CULPRIT_ID") || null, ClaimCompletionDate: null, CostSeparationToDmgSections: null, CouponNo: null, @@ -756,19 +1142,124 @@ const payload = { PlaqueSampleId: null, PlaqueSerial: null, PoliceOfficerId: 1, - PoliceReportDesc: null, + PoliceReportDesc: e.POLICE_REPORT_DESC || null, PoliceReportSeri: null, PoliceReportSerial: null, PolicyId: n("POLICY_ID"), PreviousPolicyEndDate: "", StatusChangeDate: null, - TrackingCode: null, + TrackingCode: e.TRACKING_CODE || null, IsLicenseReplacement: 0, UnknownCulpritCauseId: null, }; +let payload = v14Payload; +if (v15) { + payload = { + AccidentCityId: v14Payload.AccidentCityId, + AccidentReportTypeId: v14Payload.AccidentReportTypeId, + AccidentVehicleUsedId: v14Payload.AccidentVehicleUsedId, + ClaimExpertId: v14Payload.ClaimExpertId, + CompensationReferenceId: v14Payload.CompensationReferenceId, + CulpritLicenceTypeId: v14Payload.CulpritLicenceTypeId, + CulpritTypeId: v14Payload.CulpritTypeId, + AccidentCauseId: v14Payload.AccidentCauseId, + AccidentDate: v14Payload.AccidentDate, + DocReceivedDate: v14Payload.DocReceivedDate, + AccidentTime: v14Payload.AccidentTime, + AccidentLocationAddress: v14Payload.AccidentLocationAddress, + EstimateAmount: v14Payload.EstimateAmount, + AccidentCulpritId: v14Payload.AccidentCulpritId, + CouponNo: null, + CourtArchiveNo: null, + CulpritLicenceCityId: null, + CulpritLicenceCountryId: null, + CulpritLicenceForeignCityName: null, + CulpritLicenceIssuDate: v14Payload.CulpritLicenceIssuDate, + CulpritLicenceNo: v14Payload.CulpritLicenceNo, + DamagedCount: 1, + DmgAssessorFirstCreationTime: null, + EntryDate: null, + IsLicenseMatchWithVehicleKind: 1, + HasOtherCulprit: 0, + IsAccidentOutOfBorder: 0, + IsFatalAccident: 0, + IsPlaqueChanged: 0, + PlaqueCityId: null, + PlaqueKindId: null, + PlaqueLeftNo: null, + PlaqueMiddleCodeId: null, + PlaqueNo: null, + PlaqueRightNo: null, + PlaqueSampleId: null, + PlaqueSerial: null, + PoliceOfficerId: 1, + PoliceReportDesc: v14Payload.PoliceReportDesc, + PoliceReportSeri: null, + PoliceReportSerial: null, + PolicyId: v14Payload.PolicyId, + PreviousPolicyEndDate: "", + TrackingCode: v14Payload.TrackingCode, + IsLicenseReplacement: 0, + UnknownCulpritCauseId: null, + }; +} +if (includeNotifier) { + payload.DmgNotifications = [{ + LetterNo: strOrNull(e.NOTIFY_LETTER_NO), + ClaimNotificationDate: strOrNull(e.CLAIM_NOTIFICATION_DATE), + LetterDate: strOrNull(e.NOTIFY_LETTER_DATE) || strOrNull(e.CLAIM_NOTIFICATION_DATE), + InjuredCount: numOrNull(e.INJURED_COUNT), + DeathCount: numOrNull(e.DEATH_COUNT), + Desc: strOrNull(e.NOTIFY_DESC), + NotifierTypeId: numOrNull(e.NOTIFIER_TYPE_ID), + NotifierRelationId: numOrNull(e.NOTIFIER_RELATION_ID), + NotifierPartyId: numOrNull(e.NOTIFIER_PARTY_ID), + IsInjuredPartyIdentified: numOrNull(e.IS_INJURED_PARTY_IDENTIFIED), + InjuredPartyId: numOrNull(e.INJURED_PARTY_ID), + }]; +} process.stdout.write(JSON.stringify(payload, null, 2) + "\n"); NODE - ok "Wrote $OUT_DIR/base-payload.json" + if api_is_v15; then + ok "Wrote $OUT_DIR/base-payload.json (v15 — DmgNotifications included, AnnouncementDate omitted)" + elif moallem_v14_needs_notifier; then + ok "Wrote $OUT_DIR/base-payload.json (Moallem V14 — AnnouncementDate and DmgNotifications included)" + else + ok "Wrote $OUT_DIR/base-payload.json (v14)" + fi +} + +build_notification_payload() { + require_var CLAIM_NOTIFICATION_DATE "GEN.30 ClaimNotificationDate Jalali YYYY/MM/DD" + node <<'NODE' >"$OUT_DIR/notification-payload.json" +const e = process.env; +const numOrNull = (v) => { + if (v === undefined || v === null) return null; + const s = String(v).trim(); + if (s === "" || s.toLowerCase() === "null") return null; + const x = Number(s); + return Number.isFinite(x) ? x : null; +}; +const strOrNull = (v) => { + if (v === undefined || v === null || String(v).trim() === "") return null; + return String(v); +}; +const payload = { + LetterNo: strOrNull(e.NOTIFY_LETTER_NO), + ClaimNotificationDate: strOrNull(e.CLAIM_NOTIFICATION_DATE), + LetterDate: strOrNull(e.NOTIFY_LETTER_DATE), + InjuredCount: numOrNull(e.INJURED_COUNT), + DeathCount: numOrNull(e.DEATH_COUNT), + Desc: strOrNull(e.NOTIFY_DESC), + NotifierTypeId: numOrNull(e.NOTIFIER_TYPE_ID), + NotifierRelationId: numOrNull(e.NOTIFIER_RELATION_ID), + NotifierPartyId: numOrNull(e.NOTIFIER_PARTY_ID), + IsInjuredPartyIdentified: numOrNull(e.IS_INJURED_PARTY_IDENTIFIED), + InjuredPartyId: numOrNull(e.INJURED_PARTY_ID), +}; +process.stdout.write(JSON.stringify(payload, null, 2) + "\n"); +NODE + ok "Wrote $OUT_DIR/notification-payload.json" } build_damage_payload() { @@ -849,6 +1340,28 @@ NODE } build_expertise_payload() { + if is_car_body; then + ask_var EXPERTISE_CLAIM_EXPERT_ID "GEN.06 ClaimExpertId (ارزیاب بدنه)" + ask_var DMG_ASSESSMENT_DATE "GEN.06 DmgAssessmentDate Jalali YYYY/MM/DD" + ask_var INSPECTION_TIME "GEN.06 InspectionTime HH:mm" + require_var REPAIR_DURATION "estimated repair duration in days (1-255)" + [[ "$REPAIR_DURATION" =~ ^[0-9]{1,3}$ ]] || die "REPAIR_DURATION must be an integer from 1 to 255." + local repair_duration_decimal=$((10#$REPAIR_DURATION)) + (( repair_duration_decimal >= 1 && repair_duration_decimal <= 255 )) || die "REPAIR_DURATION must be an integer from 1 to 255." + require_var HULL_DMG_KIND_ID "select from vehicle-hull-dmg-kind lookup" + require_var HULL_DMG_COST_KIND_ID "select from vehicle-hull-dmg-cost-kinds lookup" + require_var VEHICLE_HULL_ACCESSORY_ID "select from the policy's hull accessories lookup" + require_var DMG_SECTION_ID "select the damaged component from car-components lookup" + export WAGE="${WAGE:-${REPAIR_WAGE:-0}}" VEHICLE_CURRENT_VALUE="${VEHICLE_CURRENT_VALUE:-0}" + node <<'NODE' >"$OUT_DIR/expertise-payload.json" +const e=process.env, n=(v)=>v===""?null:Number(v), s=(v)=>v||null; +const section={Count:1,DmgKindId:n(e.HULL_DMG_KIND_ID),VehicleHullAccessoryId:n(e.VEHICLE_HULL_ACCESSORY_ID),AccessoryKindId:n(e.ACCESSORY_KIND_ID||e.DMG_SECTION_ID),Desc:e.DESC||"",WasteValue:n(e.WASTE_VALUE),DmgSectionCosts:[{Caption:e.DESC||"خسارت بدنه",DmgCostKindId:n(e.HULL_DMG_COST_KIND_ID),Amount:n(e.COMPONENT_REPLACEMENT_COST)}]}; +const p={ClaimExpertId:n(e.EXPERTISE_CLAIM_EXPERT_ID),DmgAssessmentDate:e.DMG_ASSESSMENT_DATE,InspectionTime:e.INSPECTION_TIME,MotorNo:s(e.MOTOR_NO),ChassisNo:s(e.CHASSIS_NO),BuiltYear:n(e.BUILT_YEAR),VIN:s(e.VIN),PlaqueNo:s(e.PLAQUE_NO),PlaqueSerial:s(e.PLAQUE_SERIAL),ColorId:n(e.COLOR_ID),PlaqueDesignId:n(e.PLAQUE_DESIGN_ID),PlaqueCityId:n(e.PLAQUE_CITY_ID),AccidentPercent:n(e.ACCIDENT_PERCENT),Wage:n(e.WAGE),ComponentReplacementCost:n(e.COMPONENT_REPLACEMENT_COST),WasteValue:n(e.WASTE_VALUE),CarryAndRescueCost:null,RepairDuration:n(e.REPAIR_DURATION),VehicleCurrentValue:n(e.VEHICLE_CURRENT_VALUE),WreckHighestValue:null,InspectionDeduction:null,DmgAndWasteDesc:null,WentDistanceByExpert:null,IsDestruction:null,DropAmount:n(e.DROP_AMOUNT||"0"),TheftCases:[],DmgSections:[section]}; +process.stdout.write(JSON.stringify(p,null,2)+"\n"); +NODE + ok "Wrote hull GEN.06 expertise payload" + return + fi ask_var EXPERTISE_CLAIM_EXPERT_ID "GEN.08 ExpertiseClaimExpertId (ارزیاب)" ask_var DMG_SECTION_ID "DmgSectionId (car-components Id)" ask_var DMG_ASSESSMENT_DATE "DmgAssessmentDate Jalali YYYY/MM/DD" @@ -898,16 +1411,17 @@ run_base() { return 0 fi inquire_policy_id + inquire_hull_policy_vehicle build_base_payload if confirm_submit "GEN.03 base claim"; then info "3) POST GEN.03 base claim" fv_curl_json POST \ - "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims" \ + "$FANAVARAN_BIME_URL/car/$(claim_collection)" \ "$OUT_DIR/base-submit.json" \ "$OUT_DIR/base-payload.json" - CLAIM_ID="$(json_get "$OUT_DIR/base-submit.json" 'data.Id ?? data.id ?? ""')" - CLAIM_NO="$(json_get "$OUT_DIR/base-submit.json" 'data.ClaimNo ?? data.claimNo ?? ""')" - [[ -n "$CLAIM_ID" ]] || die "GEN.03 response missing Id — see $OUT_DIR/base-submit.json" + CLAIM_ID="$(json_get "$OUT_DIR/base-submit.json" 'data?.data?.Id ?? data?.data?.id ?? data?.Id ?? data?.id ?? ""')" + CLAIM_NO="$(json_get "$OUT_DIR/base-submit.json" 'data?.data?.ClaimNo ?? data?.data?.claimNo ?? data?.ClaimNo ?? data?.claimNo ?? ""')" + [[ -n "$CLAIM_ID" ]] || fanavaran_die "GEN.03 base claim" "$OUT_DIR/base-submit.json" ok "claimId=$CLAIM_ID claimNo=${CLAIM_NO:-?}" persist_env CLAIM_ID persist_env CLAIM_NO @@ -919,6 +1433,34 @@ run_base() { fi } +run_notification() { + if ! api_is_v15; then + die "GEN.30 is V15 only. Set FANAVARAN_API_VERSION=v15." + fi + require_var CLAIM_ID "from GEN.03 or set in env to resume" + if [[ -n "${DMG_NOTIFICATION_ID:-}" ]]; then + ok "DMG_NOTIFICATION_ID=$DMG_NOTIFICATION_ID already set — skip GEN.30" + return 0 + fi + build_notification_payload + if confirm_submit "GEN.30 damage notification"; then + info "3b) POST GEN.30 dmg-notifications" + fv_curl_json POST \ + "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims/${CLAIM_ID}/dmg-notifications" \ + "$OUT_DIR/notification-submit.json" \ + "$OUT_DIR/notification-payload.json" + DMG_NOTIFICATION_ID="$(json_get "$OUT_DIR/notification-submit.json" 'data.Id ?? data.id ?? ""')" + [[ -n "$DMG_NOTIFICATION_ID" ]] || fanavaran_die "GEN.30 damage notification" "$OUT_DIR/notification-submit.json" + ok "dmgNotificationId=$DMG_NOTIFICATION_ID" + persist_env DMG_NOTIFICATION_ID + save_ids + elif [[ "$PREVIEW_ONLY" -eq 1 ]]; then + ok "Preview-only: notification payload ready (no DMG_NOTIFICATION_ID)" + else + die "GEN.30 not submitted and DMG_NOTIFICATION_ID unset." + fi +} + run_damage() { require_var CLAIM_ID "from GEN.03 or set in env to resume" if [[ -n "${DMG_CASE_ID:-}" ]]; then @@ -935,7 +1477,7 @@ run_damage() { "$OUT_DIR/damage-submit.json" \ "$OUT_DIR/damage-payload.json" DMG_CASE_ID="$(json_get "$OUT_DIR/damage-submit.json" 'data.Id ?? data.id ?? ""')" - [[ -n "$DMG_CASE_ID" ]] || die "GEN.12 response missing Id — see $OUT_DIR/damage-submit.json" + [[ -n "$DMG_CASE_ID" ]] || fanavaran_die "GEN.12 damage case" "$OUT_DIR/damage-submit.json" ok "dmgCaseId=$DMG_CASE_ID" persist_env DMG_CASE_ID save_ids @@ -984,7 +1526,9 @@ run_attachments() { out="$OUT_DIR/attachment-${idx}-submit.json" headers="${out%.json}.headers" - node -e ' + if is_car_body; then + node -e 'const fs=require("fs");fs.writeFileSync(process.argv[3],JSON.stringify({FileName:process.argv[1],FileTypeId:Number(process.argv[2]),ClaimId:Number(process.argv[4])})+"\n")' "$fname" "$CLAIM_FILE_TYPE_ID" "$meta" "$CLAIM_ID" + else node -e ' const fs = require("fs"); fs.writeFileSync(process.argv[3], JSON.stringify({ FileName: process.argv[1], @@ -992,40 +1536,56 @@ fs.writeFileSync(process.argv[3], JSON.stringify({ Files: [{ FileName: process.argv[1], FileTypeId: Number(process.argv[2]) }], }) + "\n"); ' "$fname" "$CLAIM_FILE_TYPE_ID" "$meta" + fi if confirm_submit "GEN.07 attachment #$idx ($fname)"; then info "6) POST GEN.07 files — $fname (FileTypeId=$CLAIM_FILE_TYPE_ID)" - # Let curl set multipart boundary; do not set Content-Type manually. - # shellcheck disable=SC2046 + print_http_request POST \ + "$FANAVARAN_BIME_URL/car/$(claim_collection)/${CLAIM_ID}/files" \ + "$meta" \ + "authenticationToken: ${AUTHENTICATION_TOKEN}" \ + "CorpId: ${CORP_ID}" \ + "ContractId: ${CONTRACT_ID}" \ + "Location: ${LOCATION}" \ + "multipart file: ${path}" + # Let curl set multipart boundary; hull GEN.05 uses Param/Param1. + local -a multipart_args + if is_car_body; then + multipart_args=(-F "Param=$(cat "$meta");type=application/json" -F "Param1=@${path};filename=${fname}") + else + multipart_args=(-F "content=$(cat "$meta");type=application/json" -F "files=@${path}") + fi curl -sS -D "$headers" -o "$out" \ $(curl_proxy_args) \ - -X POST "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims/${CLAIM_ID}/files" \ + -X POST "$FANAVARAN_BIME_URL/car/$(claim_collection)/${CLAIM_ID}/files" \ -H "authenticationToken: $AUTHENTICATION_TOKEN" \ -H "CorpId: $CORP_ID" \ -H "ContractId: $CONTRACT_ID" \ -H "Location: $LOCATION" \ - -F "content=$(cat "$meta");type=application/json" \ - -F "files=@${path}" + "${multipart_args[@]}" pretty_json_file "$out" || true + print_http_response "$headers" "$out" local code code="$(awk 'NR==1 {print $2}' "$headers")" - printf 'HTTP %s → %s\n' "$code" "$out" + if [[ "$code" != "200" && "$code" != "201" ]]; then + fanavaran_die "GEN.07 attachment #$idx ($fname)" "$out" + fi fi done } run_expertise() { require_var CLAIM_ID - require_var DMG_CASE_ID + if ! is_car_body; then require_var DMG_CASE_ID; fi build_expertise_payload if confirm_submit "GEN.08 expertise"; then - info "7) POST GEN.08 expertise" + if is_car_body; then info "7) POST hull GEN.06 expertise"; else info "7) POST GEN.08 expertise"; fi fv_curl_json POST \ - "$FANAVARAN_BIME_URL/car/third-party-car-financial-claims/${CLAIM_ID}/expertise" \ + "$FANAVARAN_BIME_URL/car/$(claim_collection)/${CLAIM_ID}/expertise" \ "$OUT_DIR/expertise-submit.json" \ "$OUT_DIR/expertise-payload.json" - EXPERTISE_ID="$(json_get "$OUT_DIR/expertise-submit.json" 'data.Id ?? data.id ?? ""')" - [[ -n "$EXPERTISE_ID" ]] || warn "Could not parse Expertise Id — see $OUT_DIR/expertise-submit.json" + EXPERTISE_ID="$(json_get "$OUT_DIR/expertise-submit.json" 'data?.data?.Id ?? data?.data?.id ?? data?.Id ?? data?.id ?? ""')" + [[ -n "$EXPERTISE_ID" ]] || fanavaran_die "GEN.08 expertise" "$OUT_DIR/expertise-submit.json" ok "expertiseId=${EXPERTISE_ID:-?}" persist_env EXPERTISE_ID save_ids @@ -1065,7 +1625,12 @@ FANAVARAN_CLIENT="${FANAVARAN_CLIENT,,}" apply_client_auth_defaults apply_client_endpoint_defaults +FANAVARAN_PRODUCT="${FANAVARAN_PRODUCT:-THIRD_PARTY}" +FANAVARAN_PRODUCT="${FANAVARAN_PRODUCT^^}" +export FANAVARAN_PRODUCT +[[ "$FANAVARAN_PRODUCT" == "THIRD_PARTY" || "$FANAVARAN_PRODUCT" == "CAR_BODY" ]] || die "FANAVARAN_PRODUCT must be THIRD_PARTY or CAR_BODY" apply_shared_defaults +if is_car_body && [[ -n "${HULL_CONTRACT_ID:-}" ]]; then CONTRACT_ID="$HULL_CONTRACT_ID"; fi STAGES="$(echo "$STAGES" | tr '[:upper:]' '[:lower:]' | tr -d ' ')" TS="$(date +%Y%m%d-%H%M%S)" @@ -1073,16 +1638,22 @@ OUT_DIR="${OUT_DIR:-$ROOT_DIR/files/fanavaran-flow/$FANAVARAN_CLIENT/$TS}" mkdir -p "$OUT_DIR" cp "$ENV_FILE" "$OUT_DIR/input.env" 2>/dev/null || true -info "Fanavaran-only flow | client=$FANAVARAN_CLIENT | stages=$STAGES" +API_VERSION_LABEL="v14" +if api_is_v15; then API_VERSION_LABEL="v15"; fi +info "Fanavaran-only flow | client=$FANAVARAN_CLIENT | api=$API_VERSION_LABEL | stages=$STAGES" info "Env file (section B will be updated in-place): $ENV_FILE" info "Output: $OUT_DIR" fanavaran_login +if stage_wanted person && ! is_car_body; then + inquire_driver_id +fi + # Soft-ensure order like the app: later stages create earlier ones if ids missing if stage_wanted base; then run_base -elif stage_wanted damage || stage_wanted attachments || stage_wanted expertise; then +elif stage_wanted damage || stage_wanted attachments || stage_wanted expertise || stage_wanted notification; then if [[ -z "${CLAIM_ID:-}" ]]; then if [[ "$PREVIEW_ONLY" -eq 1 ]]; then warn "CLAIM_ID missing — preview-only cannot soft-ensure GEN.03 submit; set CLAIM_ID to preview later stages" @@ -1093,7 +1664,27 @@ elif stage_wanted damage || stage_wanted attachments || stage_wanted expertise; fi fi -if stage_wanted damage; then +if stage_wanted notification && ! is_car_body; then + if ! api_is_v15; then + warn "GEN.30 skipped — FANAVARAN_API_VERSION is not v15" + elif [[ "${BASE_INCLUDED_NOTIFICATION:-0}" == "1" ]]; then + ok "GEN.30 جدا رد شد — اعلام‌کننده داخل GEN.03 همین اجرا رفت" + elif [[ -z "${CLAIM_NOTIFICATION_DATE:-}" ]]; then + if [[ "$STAGES" == "all" ]]; then + warn "V15 GEN.30 skipped — fill CLAIM_NOTIFICATION_DATE to send اعلام خسارت" + else + die "CLAIM_NOTIFICATION_DATE is required for GEN.30" + fi + elif [[ -n "${CLAIM_ID:-}" || "$PREVIEW_ONLY" -eq 0 ]]; then + run_notification + else + warn "Skip GEN.30: CLAIM_ID required" + fi +fi + +if is_car_body; then + if stage_wanted damage; then warn "GEN.12 damage-case skipped: vehicle hull has no dmg-cases endpoint"; fi +elif stage_wanted damage; then if [[ -n "${CLAIM_ID:-}" || "$PREVIEW_ONLY" -eq 0 ]]; then run_damage fi @@ -1117,7 +1708,9 @@ if stage_wanted attachments; then fi if stage_wanted expertise; then - if [[ -n "${CLAIM_ID:-}" && -n "${DMG_CASE_ID:-}" ]]; then + if is_car_body && [[ -n "${CLAIM_ID:-}" ]]; then + run_expertise + elif [[ -n "${CLAIM_ID:-}" && -n "${DMG_CASE_ID:-}" ]]; then run_expertise elif [[ "$PREVIEW_ONLY" -eq 1 && -n "${DMG_CASE_ID:-}" ]]; then run_expertise diff --git a/scripts/fanavaran-flow-ui-server.js b/scripts/fanavaran-flow-ui-server.js index 69ee2e2..4336726 100755 --- a/scripts/fanavaran-flow-ui-server.js +++ b/scripts/fanavaran-flow-ui-server.js @@ -1,6 +1,6 @@ #!/usr/bin/env node /** - * Local UI server for Fanavaran third-party flow test. + * Local UI server for Fanavaran third-party and car-body staged claim flows. * * node scripts/fanavaran-flow-ui-server.js * open http://127.0.0.1:17824 @@ -320,12 +320,28 @@ async function inquirePlate(input) { const LOOKUP_CACHE = {}; const LOOKUP_PATHS = { + "accident-causes": "car/base-info/accident-causes", + cities: "common/base-info/cities", + "accident-report-type": "car/code-list/accident-report-type", + "vehicle-use-types": "car/base-info/vehicle-use-types", + "driving-licence-types": "car/base-info/driving-licence-types", + "police-officers": "car/base-info/police-officers", + ans: "common/code-list/ans", + "glass-break-reason": "car/code-list/glass-break-reason", + "vehicle-hull-accident-culprit-type": "car/code-list/vehicle-hull-accident-culprit-type", + "detection-accident-culprits": "car/base-info/detection-accident-culprits", "vehicle-kinds": "car/base-info/vehicle-kinds", "car-components": "car/base-info/car-components", + colors: "common/base-info/colors", + "plaque-design": "car/code-list/plaque-design", + "accident-percent": "car/code-list/accident-percent", + "vehicle-hull-dmg-kind": "car/code-list/vehicle-hull-dmg-kind", + "vehicle-hull-dmg-cost-kinds": "car/base-info/vehicle-hull-dmg-cost-kinds", "file-types": "common/base-info/file-types", "insurance-corp": "common/code-list/insurance-corp", "notifier-type": "car/code-list/notifier-type", "notifier-relation": "car/code-list/notifier-relation", + "vehicle-hull-accident-types": "car/base-info/vehicle-hull-accident-types", }; function defaultFanavaranBimeBase(client) { @@ -376,6 +392,7 @@ function mapLookupRows(name, rows) { id: String(r.Id), caption: String(r.Caption || r.Name || ""), system: String(r.VehicleSystemCaption || ""), + vehicleGroupId: r.VehicleGroupId == null ? "" : String(r.VehicleGroupId), active: r.IsActive == null ? true : Number(r.IsActive) === 1, })); } @@ -420,6 +437,104 @@ async function fetchRemoteLookup(client, name) { return mapped; } +async function fetchHullAccessories(client, policyId) { + if (!/^\d+$/.test(String(policyId || ""))) throw new Error("valid hull PolicyId is required"); + const env = loadEnv(); + const tokens = loadAuthTokens(client); + if (!tokens || !tokens.AUTHENTICATION_TOKEN) throw new Error("Fanavaran authentication token is missing"); + const base = fanavaranBimeBaseForToken(client, tokens); + const result = await curlJson( + "GET", + `${base}/car/vehicle-hull-policies/${policyId}/dmg-accessories`, + { + authenticationToken: tokens.AUTHENTICATION_TOKEN, + CorpId: tokens.CORP_ID || "", + ContractId: env.HULL_CONTRACT_ID || tokens.CONTRACT_ID || "", + Location: env.LOCATION || tokens.LOCATION || "", + }, + env.CURL_PROXY || process.env.CURL_PROXY || "", + ); + const rows = rowsFromLookupBody(result.json); + if (!rows) throw new Error(String(result.json?.Message || result.stderr || "hull accessories lookup failed")); + const dir = path.join(ROOT, "files", "fanavaran-lookups", client); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, `vehicle-hull-accessories-${policyId}.json`), JSON.stringify(rows)); + return mapLookupRows("vehicle-hull-accessories", rows); +} + +function unwrapFanavaranObject(value) { + let current = value; + for (let depth = 0; depth < 4 && current && typeof current === "object"; depth++) { + if (Array.isArray(current)) return null; + const nested = current.data ?? current.Data ?? current.value ?? current.Value ?? current.result ?? current.Result; + if (!nested || typeof nested !== "object" || Array.isArray(nested)) return current; + current = nested; + } + return current && typeof current === "object" && !Array.isArray(current) ? current : null; +} + +async function fetchHullPolicyVehicle(client, policyId) { + if (!/^\d+$/.test(String(policyId || ""))) throw new Error("valid hull PolicyId is required"); + const env = loadEnv(); + const tokens = loadAuthTokens(client); + if (!tokens || !tokens.AUTHENTICATION_TOKEN) throw new Error("Fanavaran authentication token is missing"); + const base = fanavaranBimeBaseForToken(client, tokens); + const headers = { + authenticationToken: tokens.AUTHENTICATION_TOKEN, + CorpId: tokens.CORP_ID || "", + ContractId: env.HULL_CONTRACT_ID || tokens.CONTRACT_ID || "", + Location: env.LOCATION || tokens.LOCATION || "", + Accept: "application/json", + }; + const proxy = env.CURL_PROXY || process.env.CURL_PROXY || ""; + const policyResult = await curlJson( + "GET", + `${base}/car/vehicle-hull-policies/${policyId}`, + headers, + proxy, + ); + const policy = unwrapFanavaranObject(policyResult.json); + const vehicleId = policy?.VehicleId ?? policy?.vehicleId; + if (!policy || !/^\d+$/.test(String(vehicleId || ""))) { + throw new Error(String(policyResult.json?.Message || policyResult.stderr || "hull policy response did not include VehicleId")); + } + const versionNo = policy.VehicleVersionNo ?? policy.vehicleVersionNo; + const versionQuery = versionNo == null || versionNo === "" + ? "" + : `?versionno=${encodeURIComponent(String(versionNo))}`; + const vehicleResult = await curlJson( + "GET", + `${base}/car/vehicles/${vehicleId}${versionQuery}`, + headers, + proxy, + ); + const vehicle = unwrapFanavaranObject(vehicleResult.json); + if (!vehicle) { + throw new Error(String(vehicleResult.json?.Message || vehicleResult.stderr || "hull vehicle response was empty")); + } + const pick = (...values) => values.find((value) => value != null && String(value).trim() !== "") ?? ""; + return { + policyId: String(policyId), + vehicleId: String(vehicleId), + usedId: String(pick(vehicle.UsedId, vehicle.usedId)), + vehicleKindId: String(pick(vehicle.VehicleKindId, vehicle.vehicleKindId)), + vehicleValue: pick(policy.VehicleValue, policy.vehicleValue, vehicle.VehicleValue, vehicle.vehicleValue), + colorId: String(pick(vehicle.ColorId, vehicle.colorId)), + plaqueDesignId: String(pick(vehicle.PlaqueDesignId, vehicle.plaqueDesignId)), + plaqueCityId: String(pick(vehicle.PlaqueCityId, vehicle.plaqueCityId)), + accidentPercent: String(pick(vehicle.AccidentPercent, vehicle.accidentPercent)), + builtYear: String(pick(vehicle.BuiltYear, vehicle.builtYear, vehicle.ManufactureYear, vehicle.manufactureYear)), + vin: String(pick(vehicle.VIN, vehicle.Vin, vehicle.vin)), + motorNo: String(pick(vehicle.MotorNo, vehicle.motorNo)), + chassisNo: String(pick(vehicle.ChassisNo, vehicle.chassisNo)), + plaqueNo: String(pick(vehicle.PlaqueNo, vehicle.plaqueNo)), + plaqueSerial: String(pick(vehicle.PlaqueSerial, vehicle.plaqueSerial)), + policyNo: String(pick(policy.PolicyNo, policy.policyNo)), + beginDate: String(pick(policy.BeginDate, policy.beginDate)), + endDate: String(pick(policy.EndDate, policy.endDate)), + }; +} + async function getLookup(client, name, refresh) { const key = lookupCacheKey(client, name); if (!refresh) { @@ -800,6 +915,8 @@ function listCaseSnapshots() { /** Auth keys from the flow env file override the API .env inherited by this process. */ const FLOW_AUTH_KEYS = [ "FANAVARAN_CLIENT", + "FANAVARAN_PRODUCT", + "HULL_CONTRACT_ID", "APP_NAME", "APP_SECRET", "FANAVARAN_USERNAME", @@ -946,27 +1063,67 @@ const server = http.createServer(async (req, res) => { if (req.method === "GET" && url.pathname === "/api/lookups/refresh") { const client = url.searchParams.get("client") || loadEnv().FANAVARAN_CLIENT || "tejaratno"; - const names = ["file-types", "insurance-corp", "vehicle-kinds", "car-components", "notifier-type", "notifier-relation"]; - const out = { ok: true, client, counts: {}, fromFile: [] }; - for (const name of names) { - if (readLookupFile(client, name)) out.fromFile.push(name); - const rows = await getLookup(client, name, true); - out.counts[name] = rows.length; - if (name === "file-types") out.fileTypes = rows.filter((r) => r.active); - if (name === "insurance-corp") out.insuranceCorps = rows.filter((r) => r.active); - if (name === "notifier-type") out.notifierTypes = rows.filter((r) => r.active); - if (name === "notifier-relation") out.notifierRelations = rows.filter((r) => r.active); + const names = Object.keys(LOOKUP_PATHS); + const out = { ok: true, client, counts: {}, fromFile: [], failures: {}, lookups: {} }; + const policyId = url.searchParams.get("policyId") || ""; + const results = await Promise.allSettled(names.map(async (name) => ({ name, rows: await getLookup(client, name, true) }))); + for (let i = 0; i < results.length; i++) { + const name = names[i]; + const result = results[i]; + let rows; + if (result.status === "fulfilled") { + rows = result.value.rows; + } else { + const message = String(result.reason?.message || result.reason || "lookup failed"); + out.failures[name] = message; + rows = readLookupFile(client, name) || []; + if (rows.length) out.fromFile.push(name + " (cached)"); + } + const active = rows.filter((r) => r.active); + out.counts[name] = active.length; + out.lookups[name] = { options: active, error: out.failures[name] || "", source: out.failures[name] ? (active.length ? "cache" : "unavailable") : "remote" }; + const keys = { + "file-types": "fileTypes", + "insurance-corp": "insuranceCorps", + "notifier-type": "notifierTypes", + "notifier-relation": "notifierRelations", + "vehicle-hull-accident-types": "hullAccidentTypes", + }; + if (keys[name]) out[keys[name]] = active; + } + if (policyId) { + try { + out.hullVehicle = await fetchHullPolicyVehicle(client, policyId); + } catch (error) { + out.hullVehicle = null; + out.failures["hull-policy-vehicle"] = String(error?.message || error); + } + try { + const options = (await fetchHullAccessories(client, policyId)).filter((row) => row.active); + out.lookups["vehicle-hull-accessories"] = { options, error: "", source: "remote" }; + out.hullAccessories = options; + out.counts["vehicle-hull-accessories"] = options.length; + } catch (error) { + out.lookups["vehicle-hull-accessories"] = { + options: [], + error: String(error?.message || error), + source: "unavailable", + }; + out.failures["vehicle-hull-accessories"] = String(error?.message || error); + out.hullAccessories = []; + out.counts["vehicle-hull-accessories"] = 0; + } } send(res, 200, out); return; } - if ( - req.method === "GET" && - (url.pathname === "/api/lookups/vehicle-kinds" || - url.pathname === "/api/lookups/car-components") - ) { - const name = url.pathname.endsWith("vehicle-kinds") ? "vehicle-kinds" : "car-components"; + if (req.method === "GET" && url.pathname.startsWith("/api/lookups/")) { + const name = url.pathname.slice("/api/lookups/".length); + if (!LOOKUP_PATHS[name]) { + send(res, 404, { ok: false, error: "unknown lookup " + name }); + return; + } const client = url.searchParams.get("client") || loadEnv().FANAVARAN_CLIENT || "tejaratno"; const q = url.searchParams.get("q") || ""; const id = url.searchParams.get("id") || "";