update the IsLicenseReplaced and for the accessories

This commit is contained in:
2026-11-11 17:20:02 +03:30
parent 54459877a2
commit 90bdc51715
13 changed files with 693 additions and 124 deletions
@@ -188,7 +188,8 @@ import {
actualPremiumFromHullPolicyRecord,
authorityCulpritIdFromDetectionRows,
customerIdFromHullPolicyRecord,
FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID,
FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION,
FANAVARAN_HULL_CULPRIT_TYPE_CAPTION,
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload,
@@ -205,13 +206,16 @@ import {
vehicleCurrentValueFromHullPolicyRecord,
} from './fanavaran-hull-expertise';
import {
FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID,
FANAVARAN_DEFAULT_HULL_DMG_KIND_ID,
FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID,
FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
FANAVARAN_HULL_DMG_KIND_CAPTION,
findLookupIdByCaption,
asHullDmgAccessoryRows,
resolveVehicleHullAccessoryId,
} from './fanavaran-hull-expertise-lookups';
import {
validateFanavaranHullLookupIds,
type HullLookupStage,
} from './fanavaran-hull-lookup-validation';
import {
activeStageLookupRows,
applyFanavaranStageFieldReview,
@@ -2636,23 +2640,15 @@ export class ClaimRequestManagementService {
input.payload.CustomerFaultPercent =
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT;
if (parseFanavaranId(input.payload.AuthorityCulpritId) == null) {
try {
const authorityRows = await this.getFanavaranLookupRows(
input.clientKey,
'detection-accident-culprits',
);
input.payload.AuthorityCulpritId =
authorityCulpritIdFromDetectionRows(authorityRows);
} catch (error) {
this.logger.warn(
`${input.logPrefix} detection-accident-culprits lookup failed; using default AuthorityCulpritId=${FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID}`,
error,
);
input.payload.AuthorityCulpritId =
FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID;
}
}
const [accidentTypes, culpritTypes, authorities] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-types', true),
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-culprit-type', true),
this.getFanavaranLookupRows(input.clientKey, 'detection-accident-culprits', true),
]);
input.payload.AccidentTypeId ??= findLookupIdByCaption(accidentTypes, FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION);
if (input.payload.CulpritTypeId == null || input.payload.CulpritTypeId === 337)
input.payload.CulpritTypeId = findLookupIdByCaption(culpritTypes, FANAVARAN_HULL_CULPRIT_TYPE_CAPTION);
input.payload.AuthorityCulpritId ??= authorityCulpritIdFromDetectionRows(authorities);
}
/** GEN.06: VehicleCurrentValue from hull policy when price-drop / frontend value is missing. */
@@ -2728,11 +2724,12 @@ export class ClaimRequestManagementService {
),
};
const [dmgKindRows, dmgCostKindRows, policyRecord] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind'),
const [dmgKindRows, dmgCostKindRows, policyRecord, componentRows] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind', true),
this.getFanavaranLookupRows(
input.clientKey,
'vehicle-hull-dmg-cost-kinds',
true,
),
policyId != null
? this.fanavaranLookupService.bodyPolicyById(
@@ -2741,16 +2738,34 @@ export class ClaimRequestManagementService {
contractOptions,
)
: Promise.resolve(null),
input.parts.length ? this.getFanavaranLookupRows(input.clientKey, 'car-components', true) : Promise.resolve([]),
]);
const dmgKindId =
findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION) ??
FANAVARAN_DEFAULT_HULL_DMG_KIND_ID;
findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION);
const dmgCostKindId =
findLookupIdByCaption(
dmgCostKindRows,
FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
) ?? FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID;
);
let accessories = asHullDmgAccessoryRows([]);
if (policyId == null && input.parts.length > 0) input.warnings.push('VehicleHullAccessoryId cannot be resolved: missing PolicyId.');
if (policyId != null && input.parts.length > 0) {
try {
accessories = asHullDmgAccessoryRows(
await this.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId(
input.clientKey,
policyId,
contractOptions,
),
);
} catch (error) {
this.logger.warn(
`[buildCarBodyFanavaranExpertisePayload] policy ${policyId} dmg-accessories lookup failed: ${error instanceof Error ? error.message : error}`,
);
}
}
let vehicle = pickHullVehicleIdentity(input.blame);
let colorId: number | null = null;
@@ -2795,6 +2810,10 @@ export class ClaimRequestManagementService {
);
const hullSections = input.parts.map((part: any) => {
const vehicleHullAccessoryId = resolveVehicleHullAccessoryId(
accessories,
parseFanavaranId(part?.partId),
);
return toFanavaranHullExpertiseDmgSection({
partId: part?.partId,
desc: this.fanavaranPartLabel(part),
@@ -2804,7 +2823,7 @@ export class ClaimRequestManagementService {
this.parseFanavaranMoney(part?.salary),
dmgKindId,
dmgCostKindId,
vehicleHullAccessoryId: FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID,
vehicleHullAccessoryId,
});
});
@@ -2824,23 +2843,27 @@ export class ClaimRequestManagementService {
input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ??
FANAVARAN_DEFAULT_HULL_REPAIR_DURATION;
const payload = toFanavaranHullExpertisePayload({
claimExpertId: input.claimExpertId,
dmgAssessmentDate: this.convertToPersianDate(input.submittedAt),
inspectionTime: this.getTime24Hour(input.submittedAt),
wage, componentReplacementCost, wasteValue,
dropAmount: input.priceDropTotal || 0,
vehicleCurrentValue, vehicle, colorId, repairDuration,
dmgSections: hullSections,
});
const sources = {
'vehicle-hull-dmg-kind': dmgKindRows,
'vehicle-hull-dmg-cost-kinds': dmgCostKindRows,
'car-components': componentRows,
'policy-dmg-accessories': accessories,
};
input.warnings.push(...await validateFanavaranHullLookupIds(payload, 'expertise', async lookup => sources[lookup] ?? []));
return {
replyKey: input.replyKey,
warnings: input.warnings,
payload: toFanavaranHullExpertisePayload({
claimExpertId: input.claimExpertId,
dmgAssessmentDate: this.convertToPersianDate(input.submittedAt),
inspectionTime: this.getTime24Hour(input.submittedAt),
wage,
componentReplacementCost,
wasteValue,
dropAmount: input.priceDropTotal || 0,
vehicleCurrentValue,
vehicle,
colorId,
repairDuration,
dmgSections: hullSections,
}),
payload,
};
}
@@ -4775,6 +4798,18 @@ export class ClaimRequestManagementService {
const hull = toFanavaranHullBaseClaimPayload(payload, clientKey);
for (const key of Object.keys(payload)) delete payload[key];
Object.assign(payload, hull);
try {
await this.assertFanavaranHullApiValues(
`${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims`,
payload, clientKey, claimCaseId,
);
} catch (error) {
if (requirePolicyId) throw error;
previewWarnings.push({
code: 'FANAVARAN_HULL_LOOKUP_INVALID', field: 'lookups',
message: error instanceof Error ? error.message : String(error),
});
}
}
if (
@@ -5655,8 +5690,8 @@ export class ClaimRequestManagementService {
AccidentReportTypeId: defaults.AccidentReportTypeId,
DmgHistoryStatus: defaults.DmgHistoryStatus,
InspectionPlaceId: 282,
AccidentTypeId: 2,
CulpritTypeId: 300,
AccidentTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-types') ?? [], FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION),
CulpritTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-culprit-type') ?? [], FANAVARAN_HULL_CULPRIT_TYPE_CAPTION),
AuthorityCulpritId: authorityCulpritIdFromDetectionRows(
options.get('detection-accident-culprits') ?? [],
),
@@ -5715,11 +5750,65 @@ export class ClaimRequestManagementService {
};
}
private async assertFanavaranHullApiValues(
url: string,
payload: Record<string, unknown>,
clientKey: FanavaranClientKey,
claimCaseId?: string,
): Promise<void> {
if (!/\/car\/vehicle-hull-claims(?:\/|$)/.test(url)) return;
const stage: HullLookupStage = url.endsWith('/expertise')
? 'expertise'
: url.endsWith('/files') ? 'files' : 'baseClaim';
const warnings = await validateFanavaranHullLookupIds(
payload, stage, async (lookup) => {
if (lookup !== 'policy-dmg-accessories') {
return this.getFanavaranLookupRows(clientKey, lookup, true);
}
const claim = claimCaseId
? await this.claimCaseDbService.findById(claimCaseId)
: null;
const policyId = this.parseHullClaimPolicyId(claim);
if (policyId == null) return [];
return this.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId(
clientKey, policyId, {
contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
},
);
},
);
if (stage === 'baseClaim') {
const policyId = parseFanavaranId(payload.PolicyId);
try {
const policy = policyId == null ? null : asObjectRecord(
await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId, {
contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
}),
);
const premium = actualPremiumFromHullPolicyRecord(policy);
if (premium == null) warnings.push('ActualPremium could not be resolved from the current hull policy API response.');
else payload.ActualPremium = premium;
} catch {
warnings.push('Hull policy API is unavailable; policy values could not be verified.');
}
}
if (warnings.length) {
throw new BadRequestException({
code: 'FANAVARAN_HULL_LOOKUP_INVALID',
message: 'Hull submission requires valid values from the current Fanavaran API responses.',
warnings,
});
}
}
private async getFanavaranLookupRows(
clientKey: FanavaranClientKey,
name: string,
requireRemote = false,
): Promise<unknown[]> {
if (clientKey === 'tejaratno' && isTejaratNotifierLookup(name)) {
if (
!requireRemote && clientKey === 'tejaratno' && isTejaratNotifierLookup(name)
) {
const stored = await this.fanavaranLookupService.readStoredLookup(name);
let rows: unknown = stored;
for (
@@ -5733,11 +5822,15 @@ export class ClaimRequestManagementService {
}
const definition = this.fanavaranLookupDefinition(name);
try {
const data = await this.fanavaranLookupService.getRemoteLookup(
clientKey,
definition.url,
definition.cacheFile,
);
const data = requireRemote
? await this.fanavaranLookupService.fetchFromFanavaran(clientKey, definition.url, {
contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
})
: await this.fanavaranLookupService.getRemoteLookup(
clientKey,
definition.url,
definition.cacheFile,
);
let rows: unknown = data;
for (
let level = 0;
@@ -5890,13 +5983,26 @@ export class ClaimRequestManagementService {
warnings.push('No submit-ready expert pricing lines exist yet.');
}
const priceDrop = input.claimCase.evaluation?.priceDrop ?? {};
const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total);
const submittedAt = reply?.submittedAt ?? new Date();
const product = await this.resolveFanavaranClaimProduct(
input.claimCase?._id ? String(input.claimCase._id) : undefined,
);
if (product === 'car-body') {
return this.buildCarBodyFanavaranExpertisePayload({
clientKey: input.clientKey, claimCase: input.claimCase,
blame: blameForExpertIds, profile, parts, claimExpertId,
submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice,
warnings, replyKey: active?.replyKey,
});
}
const [inspectionPlaces, dropAmountStatuses] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'inspection-place'),
this.getFanavaranLookupRows(input.clientKey, 'drop-amount-status'),
]);
const priceDrop = input.claimCase.evaluation?.priceDrop ?? {};
const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total);
const inspectionPlaceId =
input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282;
const dropAmountStatus = 5458;
@@ -5920,28 +6026,6 @@ export class ClaimRequestManagementService {
(sum, section) => sum + this.parseFanavaranMoney(section.WasteValue),
0,
);
const submittedAt = reply?.submittedAt ?? new Date();
const product = await this.resolveFanavaranClaimProduct(
input.claimCase?._id ? String(input.claimCase._id) : undefined,
);
if (product === 'car-body') {
const blame = blameForExpertIds;
return this.buildCarBodyFanavaranExpertisePayload({
clientKey: input.clientKey,
claimCase: input.claimCase,
blame,
profile,
parts,
claimExpertId,
submittedAt,
priceDropTotal,
priceDropCarPrice: priceDrop?.carPrice,
warnings,
replyKey: active?.replyKey,
});
}
const payload: Record<string, unknown> = {
ClaimExpertId: claimExpertId,
ComponentReplacementCost: componentReplacementCost,
@@ -6510,6 +6594,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
@@ -6541,6 +6626,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
@@ -6618,6 +6704,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, content, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
@@ -7507,6 +7594,7 @@ export class ClaimRequestManagementService {
claimCaseId,
);
const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId);
await this.assertFanavaranHullApiValues(submitUrl, fanavaranData, clientKey, claimCaseId);
const requestHeaders = {
...headers,
@@ -0,0 +1,138 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
function setup(accessories: unknown) {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { warn: jest.fn(), log: jest.fn() };
service.getFanavaranLookupRows = jest.fn().mockImplementation(
async (_client: string, name: string) =>
({
"vehicle-hull-dmg-kind": [{ Id: 8001, Caption: "تخريب", IsActive: 1 }],
"vehicle-hull-dmg-cost-kinds": [
{ Id: 8002, Caption: "مجموع لوازم", IsActive: 1 },
],
"car-components": [{ Id: 9 }, { Id: 13 }],
})[name] ?? [],
);
service.fanavaranLookupService = {
bodyPolicyById: jest.fn().mockResolvedValue({ VehicleValue: 15000000000 }),
vehicleHullDmgAccessoriesByPolicyId: jest
.fn()
.mockResolvedValue(accessories),
};
const build = (policyId = 123) =>
service.buildCarBodyFanavaranExpertisePayload({
clientKey: "parsian",
claimCase: { fanavaranSync: { baseClaim: { policyId } } },
blame: { parties: [] },
profile: {},
parts: [
{ partId: 9, partName: "سپر جلو", price: 50000000, salary: 25000000 },
{ partId: 13, partName: "چراغ جلو چپ", price: 0, salary: 2000000 },
],
claimExpertId: 4044,
submittedAt: new Date("2026-11-11T09:09:00Z"),
priceDropTotal: 0,
priceDropCarPrice: null,
warnings: [],
});
return { service, build };
}
describe("hull expertise policy accessory mapping", () => {
it("uses the current policy accessory IDs for the bumper and headlamp", async () => {
const { service, build } = setup([
{ Id: 900001, AccessoryKindId: 9, AccessoryDesc: "سپر جلو" },
{ Id: 900002, AccessoryKindId: 13, AccessoryDesc: "چراغ جلو چپ" },
]);
const { payload, warnings } = await build();
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([900001, 900002]);
expect(warnings).toEqual([]);
expect(payload.DmgSections[0]).toMatchObject({
DmgKindId: 8001,
DmgSectionCosts: [
{
DmgCostKindId: 8002,
Caption: expect.any(String),
Amount: expect.any(Number),
},
],
});
expect(
service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId,
).toHaveBeenCalledWith(
"parsian",
123,
expect.objectContaining({ contractIdOverride: expect.any(String) }),
);
});
it("uses a factory bundle only when it belongs to the current policy", async () => {
const { build } = setup([
{ Id: 900003, AccessoryDesc: "کليه قطعات فابريک" },
]);
const { payload } = await build();
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([900003, 900003]);
});
it("does not replace unavailable lookup values with 5485 or 1", async () => {
const { service, build } = setup([
{ Id: 2810613, AccessoryDesc: "کليه قطعات فابريک" },
]);
service.getFanavaranLookupRows.mockResolvedValue([]);
const { payload, warnings } = await build();
expect(payload.DmgSections[0]).toMatchObject({ DmgKindId: null });
expect(payload.DmgSections[0].DmgSectionCosts[0].DmgCostKindId).toBeNull();
expect(warnings).toEqual(
expect.arrayContaining([
expect.stringContaining("DmgKindId"),
expect.stringContaining("DmgCostKindId"),
]),
);
});
it("reports unavailable lookup data without reusing the old hardcoded ID", async () => {
const { service, build } = setup([]);
service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId.mockRejectedValue(
new Error("lookup unavailable"),
);
const { payload, warnings } = await build();
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([null, null]);
expect(warnings).toHaveLength(2);
});
it("reports a missing hull PolicyId instead of using the claim ID as a policy", async () => {
const { service, build } = setup([]);
const { warnings } = await build(null);
expect(
service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId,
).not.toHaveBeenCalled();
expect(warnings).toEqual(
expect.arrayContaining([expect.stringContaining("missing PolicyId")]),
);
});
it.each([
{ rows: [] },
{ rows: [{ Id: 900004, AccessoryKindId: 99, AccessoryDesc: "unrelated" }] },
])(
"reports unmapped accessories instead of guessing an ID: %j",
async ({ rows }) => {
const { build } = setup(rows);
const { payload, warnings } = await build();
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([null, null]);
expect(warnings).toEqual(
expect.arrayContaining([
expect.stringContaining("VehicleHullAccessoryId"),
]),
);
},
);
});
@@ -1,7 +1,7 @@
import {
actualPremiumFromHullPolicyRecord,
customerIdFromHullPolicyRecord,
FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID,
authorityCulpritIdFromDetectionRows,
fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload,
} from "./fanavaran-hull-base-claim";
@@ -34,12 +34,13 @@ describe("fanavaran hull base claim", () => {
expect(fanavaranHullNestedClaimId({ ClaimNo: 2268 })).toBeNull();
});
it("keeps IsLicenseReplaced null even when ثالث IsLicenseReplacement is 0", () => {
it("sends IsLicenseReplaced as 0 using the hull field name", () => {
const hull = toFanavaranHullBaseClaimPayload({
PolicyId: 1,
IsLicenseReplacement: 0,
});
expect(hull.IsLicenseReplaced).toBeNull();
expect(hull.IsLicenseReplaced).toBe(0);
expect(hull).not.toHaveProperty("IsLicenseReplacement");
});
it("strips ثالث-only fields from a live hull create echo", () => {
@@ -72,11 +73,12 @@ describe("fanavaran hull base claim", () => {
});
expect(hull.PolicyId).toBe(13764408);
expect(hull.AccidentTypeId).toBe(FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID);
expect(hull.IsLicenseReplaced).toBeNull();
expect(hull.AccidentTypeId).toBeNull();
expect(hull.IsLicenseReplaced).toBe(0);
expect(hull.CostSeparationToDmgSections).toBe(0);
expect(hull.IsOwnerChanged).toBe(0);
expect(hull.CulpritTypeId).toBe(300);
expect(hull.CulpritTypeId).toBeNull();
expect(hull.AuthorityCulpritId).toBeNull();
expect(hull.DamagedCount).toBeUndefined();
expect(hull.HasOtherCulprit).toBeUndefined();
expect(hull.CompensationReferenceId).toBeUndefined();
@@ -84,4 +86,10 @@ describe("fanavaran hull base claim", () => {
expect(hull.Id).toBeUndefined();
expect(hull.ClaimNo).toBeUndefined();
});
it("selects the authority from the response without inventing an ID when absent", () => {
expect(authorityCulpritIdFromDetectionRows([{ Id: 888, Caption: "بیمه گذار" }])).toBe(888);
expect(authorityCulpritIdFromDetectionRows([])).toBeNull();
expect(actualPremiumFromHullPolicyRecord({})).toBeNull();
});
});
@@ -47,14 +47,13 @@ export const FANAVARAN_HULL_BASE_CLAIM_KEYS = [
"CostSeparationToDmgSections",
] as const;
/** GEN.03 default: تصادف(حادثه). Lookup: GET /lookups/vehicle-hull-accident-types */
export const FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID = 2;
/** Select the current API row for the default collision scenario. */
export const FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION = "تصادف(حادثه)";
/** GEN.03 ans (0=خیر). Used for CostSeparationToDmgSections, IsOwnerChanged, IsLicenseReplaced. */
export const FANAVARAN_HULL_ANS_NO = 0;
/** GEN.03 hull culprit type when third-party is at fault. Lookup: vehicle-hull-accident-culprit-type */
export const FANAVARAN_DEFAULT_HULL_CULPRIT_TYPE_ID = 300;
export const FANAVARAN_HULL_CULPRIT_TYPE_CAPTION = "بيمه گذار";
/** GEN.03 required: درصد تقصير بيمه گذار. Proven Parsian submit uses 100. */
export const FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT = 100;
@@ -63,7 +62,6 @@ export const FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT = 100;
* GEN.03 required: مرجع تعيين مقصر.
* Lookup: GET /lookups/detection-accident-culprits. Fallback is بیمه‌گذار.
*/
export const FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID = 1;
export const FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION = "بيمه گذار";
/** GEN.03 ActualPremium from GET car/vehicle-hull-policies/{PolicyId} → TotalPremium. */
@@ -72,6 +70,7 @@ export function actualPremiumFromHullPolicyRecord(
): number | null {
if (!policy) return null;
const raw = policy.TotalPremium ?? policy.totalPremium;
if (raw == null || raw === "") return null;
const n = typeof raw === "number" ? raw : Number(raw);
return Number.isFinite(n) && n >= 0 ? n : null;
}
@@ -80,6 +79,7 @@ function normalizeHullCaption(value: unknown): string {
return String(value ?? "")
.replace(/ي/g, "ی")
.replace(/ك/g, "ک")
.replace(/\u200c/g, " ")
.replace(/\s+/g, " ")
.trim();
}
@@ -87,13 +87,15 @@ function normalizeHullCaption(value: unknown): string {
/** AuthorityCulpritId from GET /lookups/detection-accident-culprits. */
export function authorityCulpritIdFromDetectionRows(
rows: unknown,
): number {
): number | null {
const list = Array.isArray(rows) ? rows : [];
const wanted = normalizeHullCaption(
FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION,
);
for (const row of list) {
if (!row || typeof row !== "object") continue;
const active = (row as { IsActive?: unknown }).IsActive;
if (active === false || (active != null && Number(active) === 0)) continue;
const caption = normalizeHullCaption(
(row as { Caption?: unknown }).Caption,
);
@@ -102,13 +104,7 @@ export function authorityCulpritIdFromDetectionRows(
const n = typeof raw === "number" ? raw : Number(raw);
if (Number.isFinite(n) && n > 0) return n;
}
for (const row of list) {
if (!row || typeof row !== "object") continue;
const raw = (row as { Id?: unknown }).Id;
const n = typeof raw === "number" ? raw : Number(raw);
if (Number.isFinite(n) && n > 0) return n;
}
return FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID;
return null;
}
/** Fallback AccidentCulpritId when parties inquiry is unavailable. */
@@ -128,13 +124,12 @@ export function toFanavaranHullBaseClaimPayload(
const next: Record<string, unknown> = {};
for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) {
if (key === "IsLicenseReplaced") {
// GEN.03: must be empty/null. Do not map ثالث IsLicenseReplacement (default 0).
next[key] = null;
// Hull GEN.03: explicitly send خیر. Keep the hull field name.
next[key] = FANAVARAN_HULL_ANS_NO;
continue;
}
if (key === "AccidentTypeId") {
next[key] =
built.AccidentTypeId ?? FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID;
next[key] = built.AccidentTypeId ?? null;
continue;
}
if (key === "CostSeparationToDmgSections") {
@@ -150,7 +145,7 @@ export function toFanavaranHullBaseClaimPayload(
const raw = built.CulpritTypeId;
// ثالث profile default 337 is not in vehicle-hull-accident-culprit-type.
if (raw == null || raw === 337) {
next[key] = FANAVARAN_DEFAULT_HULL_CULPRIT_TYPE_ID;
next[key] = null;
} else {
next[key] = raw;
}
@@ -163,8 +158,12 @@ export function toFanavaranHullBaseClaimPayload(
continue;
}
if (key === "AuthorityCulpritId") {
next[key] =
built.AuthorityCulpritId ?? FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID;
next[key] = built.AuthorityCulpritId ?? null;
continue;
}
if (key === "PoliceOfficerId") {
// The shared third-party builder supplies a sample 1; hull has no officer source.
next[key] = null;
continue;
}
next[key] = Object.prototype.hasOwnProperty.call(built, key)
@@ -3,13 +3,6 @@ import { parseFanavaranId } from "src/lookups/fanavaran-last-car-policy";
export const FANAVARAN_HULL_DMG_KIND_CAPTION = "تخریب";
export const FANAVARAN_HULL_DMG_COST_KIND_CAPTION = "مجموع لوازم";
/** Fallback when lookup fetch fails (Parsian `vehicle-hull-dmg-kind`). */
export const FANAVARAN_DEFAULT_HULL_DMG_KIND_ID = 5485;
/** Fallback when lookup fetch fails (`vehicle-hull-dmg-cost-kinds` Id). */
export const FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID = 1;
/** GEN.06 factory (فابریک) accessory row. Used for every hull DmgSection. */
export const FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID = 3043330;
export type FanavaranHullDmgAccessoryRow = {
Id?: unknown;
AccessoryKindId?: unknown;
@@ -17,6 +10,14 @@ export type FanavaranHullDmgAccessoryRow = {
};
export function asLookupRows(value: unknown): Record<string, unknown>[] {
for (
let depth = 0;
depth < 4 && value && !Array.isArray(value) && typeof value === "object";
depth++
) {
const record = value as Record<string, unknown>;
value = record.data ?? record.Data;
}
if (!Array.isArray(value)) return [];
return value.filter(
(row): row is Record<string, unknown> =>
@@ -24,7 +25,9 @@ export function asLookupRows(value: unknown): Record<string, unknown>[] {
);
}
export function asHullDmgAccessoryRows(value: unknown): FanavaranHullDmgAccessoryRow[] {
export function asHullDmgAccessoryRows(
value: unknown,
): FanavaranHullDmgAccessoryRow[] {
return asLookupRows(value) as FanavaranHullDmgAccessoryRow[];
}
@@ -32,16 +35,31 @@ export function findLookupIdByCaption(
rows: unknown,
caption: string,
): number | null {
const target = caption.trim();
const normalize = (raw: unknown) =>
String(raw ?? "")
.replace(/ي/g, "ی")
.replace(/ك/g, "ک")
.replace(/\u200c/g, " ")
.replace(/\s*([()])\s*/g, "$1")
.replace(/\s+/g, " ")
.trim();
const target = normalize(caption);
for (const row of asLookupRows(rows)) {
if (String(row.Caption ?? "").trim() !== target) continue;
if (
row.IsActive === false ||
(row.IsActive != null && Number(row.IsActive) === 0)
)
continue;
if (normalize(row.Caption) !== target) continue;
const id = parseFanavaranId(row.Id);
if (id != null) return id;
}
return null;
}
function isFactoryDefaultAccessoryRow(row: FanavaranHullDmgAccessoryRow): boolean {
function isFactoryDefaultAccessoryRow(
row: FanavaranHullDmgAccessoryRow,
): boolean {
const desc = String(row.AccessoryDesc ?? "").trim();
return (
desc.includes("کليه قطعات فابريک") ||
@@ -74,5 +92,5 @@ export function resolveVehicleHullAccessoryId(
const factoryId = parseFanavaranId(factory?.Id);
if (factoryId != null) return factoryId;
return parseFanavaranId(accessories[0]?.Id);
return null;
}
@@ -72,8 +72,6 @@ function text(value: unknown): string | null {
}
export {
FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID,
FANAVARAN_DEFAULT_HULL_DMG_KIND_ID,
FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
FANAVARAN_HULL_DMG_KIND_CAPTION,
} from "./fanavaran-hull-expertise-lookups";
@@ -0,0 +1,190 @@
import { of } from "rxjs";
import { ClaimRequestManagementService } from "./claim-request-management.service";
function setup() {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { warn: jest.fn() };
service.fanavaranLookupService = {
fetchFromFanavaran: jest
.fn()
.mockResolvedValue([{ Id: 63, Caption: "File" }]),
getRemoteLookup: jest.fn().mockResolvedValue([{ Id: 999 }]),
};
service.fanavaranAuthService = {
assertNotInBackoff: jest.fn(),
clearBackoff: jest.fn(),
};
service.getFanavaranAuthHeaders = jest.fn().mockResolvedValue({});
service.httpService = { post: jest.fn().mockReturnValue(of({ data: {} })) };
return service;
}
describe("hull live lookup submission checks", () => {
it("bypasses file/database lookup caches when fresh responses are required", async () => {
const service = setup();
expect(
await service.getFanavaranLookupRows("parsian", "file-types", true),
).toEqual([{ Id: 63, Caption: "File" }]);
expect(
service.fanavaranLookupService.fetchFromFanavaran,
).toHaveBeenCalled();
expect(
service.fanavaranLookupService.getRemoteLookup,
).not.toHaveBeenCalled();
});
it("prevents a hull write with an attachment ID absent from the API response", async () => {
const service = setup();
await expect(
service.postFanavaranJson(
"https://example.test/car/vehicle-hull-claims/123/files",
{ FileTypeId: 999 },
"parsian",
),
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_HULL_LOOKUP_INVALID",
}),
});
expect(service.httpService.post).not.toHaveBeenCalled();
});
it("sends a valid attachment ID obtained from the current API response", async () => {
const service = setup();
const url = "https://example.test/car/vehicle-hull-claims/123/files";
await service.postFanavaranJson(url, { FileTypeId: 63 }, "parsian");
expect(
service.fanavaranLookupService.fetchFromFanavaran,
).toHaveBeenCalled();
expect(service.httpService.post).toHaveBeenCalledWith(
url,
{ FileTypeId: 63 },
expect.anything(),
);
});
it("validates base-claim selections against live responses and refreshes the premium from the policy", async () => {
const service = setup();
const rows = {
cities: 801,
"accident-report-type": 802,
"accident-causes": 803,
"vehicle-hull-accident-types": 804,
"vehicle-hull-accident-culprit-type": 805,
"detection-accident-culprits": 806,
"driving-licence-types": 807,
"vehicle-use-types": 808,
ans: 0,
};
service.fanavaranLookupService.fetchFromFanavaran.mockImplementation(
async (_client: string, url: string) => ({
data: [
{ Id: rows[url.split("/").at(-1)], Caption: "Valid", IsActive: 1 },
],
}),
);
service.fanavaranLookupService.bodyPolicyById = jest
.fn()
.mockResolvedValue({ TotalPremium: 123456 });
const payload = {
PolicyId: 14231020,
ActualPremium: 111,
AccidentCityId: 801,
AccidentReportTypeId: 802,
AccidentCauseId: 803,
AccidentTypeId: 804,
CulpritTypeId: 805,
AuthorityCulpritId: 806,
CulpritLicenceTypeId: 807,
AccidentVehicleUsedId: 808,
IsLicenseReplaced: 0,
};
const url = "https://example.test/car/vehicle-hull-claims";
await service.postFanavaranJson(url, payload, "parsian");
expect(payload.ActualPremium).toBe(123456);
expect(
service.fanavaranLookupService.getRemoteLookup,
).not.toHaveBeenCalled();
service.httpService.post.mockClear();
await expect(
service.postFanavaranJson(
url,
{ ...payload, AccidentTypeId: 2 },
"parsian",
),
).rejects.toMatchObject({
response: expect.objectContaining({
warnings: expect.arrayContaining([
expect.stringContaining("AccidentTypeId=2"),
]),
}),
});
expect(service.httpService.post).not.toHaveBeenCalled();
});
it("rejects inactive attachment types even when their IDs match", async () => {
const service = setup();
service.fanavaranLookupService.fetchFromFanavaran.mockResolvedValue([
{ Id: 63, IsActive: 0 },
]);
await expect(
service.postFanavaranJson(
"https://example.test/car/vehicle-hull-claims/123/files",
{ FileTypeId: 63 },
"parsian",
),
).rejects.toThrow();
expect(service.httpService.post).not.toHaveBeenCalled();
});
it("blocks invalid lookup values on hull PUTs and multipart uploads too", async () => {
const service = setup();
service.httpService.put = jest.fn();
service.fanavaranLookupService.fetchFromFanavaran.mockResolvedValue([]);
const url = "https://example.test/car/vehicle-hull-claims/123/files";
await expect(
service.putFanavaranJson(url, { FileTypeId: 63 }, "parsian"),
).rejects.toThrow();
await expect(
service.postFanavaranMultipart(url, { FileTypeId: 63 }, [], "parsian"),
).rejects.toThrow();
expect(service.httpService.post).not.toHaveBeenCalled();
expect(service.httpService.put).not.toHaveBeenCalled();
});
it("resolves default hull base selections from changed lookup IDs", async () => {
const service = setup();
service.logger.log = jest.fn();
service.getFanavaranLookupRows = jest.fn().mockImplementation(
async (_client: string, name: string) =>
({
"vehicle-hull-accident-types": [
{ Id: 804, Caption: "تصادف (حادثه)" },
],
"vehicle-hull-accident-culprit-type": [
{ Id: 805, Caption: "بیمه گذار" },
],
"detection-accident-culprits": [{ Id: 806, Caption: "بیمه گذار" }],
})[name],
);
service.fanavaranLookupService.bodyPolicyById = jest
.fn()
.mockResolvedValue({ TotalPremium: 123456 });
const payload: Record<string, unknown> = {
PolicyId: 14231020,
CulpritTypeId: 337,
};
await service.enrichCarBodyHullBaseClaimPayload({
clientKey: "parsian",
payload,
blameCase: {},
logPrefix: "test",
});
expect(payload).toMatchObject({
AccidentTypeId: 804,
CulpritTypeId: 805,
AuthorityCulpritId: 806,
ActualPremium: 123456,
});
});
});
@@ -0,0 +1,113 @@
import { asLookupRows } from "./fanavaran-hull-expertise-lookups";
export type HullLookupStage = "baseClaim" | "expertise" | "files";
type LookupField = {
row: Record<string, unknown>;
key: string;
lookup: string;
path: string;
};
/** Validate outbound IDs against responses for this tenant, never a sample ID. */
export async function validateFanavaranHullLookupIds(
payload: Record<string, unknown>,
stage: HullLookupStage,
fetchRows: (lookup: string) => Promise<unknown>,
): Promise<string[]> {
const fields: LookupField[] = [];
const add = (
row: Record<string, unknown>,
key: string,
lookup: string,
path = key,
required = true,
) => {
if (required || row[key] != null) fields.push({ row, key, lookup, path });
};
if (stage === "baseClaim") {
for (const [key, lookup] of Object.entries({
AccidentCityId: "cities",
AccidentReportTypeId: "accident-report-type",
AccidentCauseId: "accident-causes",
AccidentTypeId: "vehicle-hull-accident-types",
CulpritTypeId: "vehicle-hull-accident-culprit-type",
AuthorityCulpritId: "detection-accident-culprits",
CulpritLicenceTypeId: "driving-licence-types",
AccidentVehicleUsedId: "vehicle-use-types",
}))
add(payload, key, lookup);
for (const key of [
"IsLicenseReplaced",
"IsOwnerChanged",
"CostSeparationToDmgSections",
"IsAccidentOutOfBorder",
"IsSurplusArticleEighthLaw",
])
add(payload, key, "ans", key, false);
add(payload, "CulpritLicenceCountryId", "countries", undefined, false);
add(payload, "CulpritLicenceCityId", "cities", undefined, false);
add(payload, "NotifierTypeId", "notifier-type", undefined, false);
add(payload, "NotifierRelationId", "notifier-relation", undefined, false);
} else if (stage === "files") {
add(payload, "FileTypeId", "file-types");
for (const [i, row] of asLookupRows(payload.Files).entries())
add(row, "FileTypeId", "file-types", `Files[${i}].FileTypeId`);
} else {
for (const [i, row] of asLookupRows(payload.DmgSections).entries()) {
const prefix = `DmgSections[${i}]`;
add(
row,
"AccessoryKindId",
"car-components",
`${prefix}.AccessoryKindId`,
);
add(
row,
"VehicleHullAccessoryId",
"policy-dmg-accessories",
`${prefix}.VehicleHullAccessoryId`,
);
add(row, "DmgKindId", "vehicle-hull-dmg-kind", `${prefix}.DmgKindId`);
for (const [j, cost] of asLookupRows(row.DmgSectionCosts).entries())
add(
cost,
"DmgCostKindId",
"vehicle-hull-dmg-cost-kinds",
`${prefix}.DmgSectionCosts[${j}].DmgCostKindId`,
);
}
}
const sources = new Map<string, Record<string, unknown>[]>();
await Promise.all(
[...new Set(fields.map((field) => field.lookup))].map(async (lookup) => {
try {
sources.set(lookup, asLookupRows(await fetchRows(lookup)));
} catch {
sources.set(lookup, []);
}
}),
);
const warnings: string[] = [];
for (const field of fields) {
const raw = field.row[field.key];
const id = raw == null || String(raw).trim() === "" ? NaN : Number(raw);
const matched =
Number.isSafeInteger(id) && id >= 0
? sources
.get(field.lookup)
?.find(
(row) =>
row.Id != null &&
Number(row.Id) === id &&
row.IsActive !== false &&
(row.IsActive == null || Number(row.IsActive) !== 0),
)
: undefined;
if (!matched)
warnings.push(
`${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response.`,
);
else field.row[field.key] = Number(matched.Id);
}
return warnings;
}