feat: support Fanavaran car-body flow in UI

This commit is contained in:
2026-10-31 14:45:26 +03:30
parent 82d204bd66
commit c185145394
10 changed files with 1210 additions and 108 deletions
+174 -17
View File
@@ -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") || "";