fix(fanavaran): honor supplied submission payload fields

Apply every supplied JSON field over generated defaults, preserving IDs, nested values and explicit nulls across base, damage and expertise submits. Validate manual hull payloads without rewriting their values or premium, and derive an empty replacement flag for old hull licences.
This commit is contained in:
2026-11-21 13:33:41 +03:30
parent 83d7351310
commit 99e6fa0850
10 changed files with 334 additions and 90 deletions
+15 -5
View File
@@ -20,6 +20,15 @@ A PUT to `/vehicle-hull-claims/{Id}` may run before files/expertise; Parsian oft
**Send rule:** send the **hull whitelist only**. Do not send ثالث-only keys (`DamagedCount`, `HasOtherCulprit`, `CompensationReferenceId`, `DocReceivedDate`, `IsLicenseReplacement`, plaque block on base, …).
**Manual submit body:** every supplied top-level field overrides its generated
value, including IDs, arrays, nested objects, `false`, `0` and JSON `null`.
Omitted fields retain generated defaults. Arrays and nested objects replace the
corresponding value; they are not merged element by element. Lookup validation
checks a copy of manual payloads and does not refresh their supplied premium or
rewrite their values. Automatic submission without overrides keeps its existing
inquiry, normalization and validation behavior. This also applies to third-party
base/damage submits and both products' expertise submits.
**Source tags:** same as `third-party-stage-fields.md` (`system` / `lookup` / `inquiry` / `user` / `staff` / `derived`).
---
@@ -32,10 +41,11 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
`CustomerFaultPercent`, `AuthorityCulpritId`, `AccidentTypeId`, `CostSeparationToDmgSections`, `IsOwnerChanged`, `PolicyId`, `ClaimExpertId`, dates/time, `CulpritTypeId`.
**IsLicenseReplaced:** derived on the server from `CulpritLicenceIssuDate` and
`AccidentDate`: `0` through the third anniversary, `null` after three years
through the tenth anniversary, and `1` after ten years. Intake accepts valid past
issue dates older than ten years; no expiry-date or replacement-checkbox input
is required. The existing missing-date fallback is `1400/01/01`.
`AccidentDate`: default `0` through the third anniversary and `null` afterward.
Do not infer replacement from licence age exceeding ten years: Parsian rejects
that `1` with «باید خالی باشد». The hull base-claim submit body may explicitly
override `IsLicenseReplaced` with `0`, `1`, or JSON `null`; omitted fields keep
the derived default. Intake accepts valid past issue dates older than ten years. The existing missing-date fallback is `1400/01/01`.
| Field | Persian | Type | Null? | Current value / source |
|-------|---------|------|-------|------------------------|
@@ -55,7 +65,7 @@ is required. The existing missing-date fallback is `1400/01/01`.
| CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` |
| CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` |
| IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` |
| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | often null | **derived** `1` if issue date >10y before accident, else `null` (hull name; ثالث uses `IsLicenseReplacement`) |
| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | often null | **derived** `0` through three years, otherwise `null`; explicit hull submit answer is preserved (ثالث uses `IsLicenseReplacement`) |
| ActualPremium | حق بیمه واقعی | number | preferred | **inquiry** hull policy `TotalPremium` via `GET /lookups/body-policy/{PolicyId}` |
| EstimateAmount | برآورد | number | **no** | **user** expert prices / provisional |
| CulpritLicenceNo | شماره گواهینامه | string | **no** | dummy / **user** |
@@ -198,6 +198,7 @@ import {
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload,
resolveFanavaranHullIsLicenseReplaced,
} from './fanavaran-hull-base-claim';
import { toTejaratV15ThirdPartyBasePayload } from './fanavaran-v15-third-party-base';
import {
@@ -268,9 +269,6 @@ import {
asVehicleInquiryRows,
collectPartyVinCandidates,
completePlaqueParts,
FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS,
FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS,
FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS,
fanavaranVehicleMatchesDamagedIdentity,
normalizeVin,
parseFanavaranId,
@@ -2739,7 +2737,7 @@ export class ClaimRequestManagementService {
);
input.payload.CulpritLicenceIssuDate =
resolveFanavaranLicenceIssuDate(driverIdentity);
const licenseReplaced = resolveFanavaranIsLicenseReplaced(
const licenseReplaced = resolveFanavaranHullIsLicenseReplaced(
input.payload.CulpritLicenceIssuDate,
input.payload.AccidentDate,
);
@@ -4642,6 +4640,8 @@ export class ClaimRequestManagementService {
requirePolicyId?: boolean;
/** Only submission may register the hull driver through GEN.44. */
registerMissingHullDriver?: boolean;
/** Internal manual-submit default source; the final body retains its exact value. */
policyIdOverride?: unknown;
/**
* When false (HTTP preview), missing staff ClaimExpertId stays null and is
* reported in previewWarnings instead of throwing.
@@ -4792,6 +4792,11 @@ export class ClaimRequestManagementService {
logPrefix,
requirePolicyId,
resolvePolicyId: async () => {
if (
Object.prototype.hasOwnProperty.call(options ?? {}, 'policyIdOverride')
) {
return options.policyIdOverride as number;
}
const product = fanavaranClaimProductFromBlameType(blameCase.type);
if (cachedPolicyId != null && !forceRefreshPolicy) {
@@ -6086,8 +6091,10 @@ export class ClaimRequestManagementService {
payload: Record<string, unknown>,
clientKey: FanavaranClientKey,
claimCaseId?: string,
preservePayload = false,
): Promise<void> {
if (!/\/car\/vehicle-hull-claims(?:\/|$)/.test(url)) return;
if (preservePayload) payload = JSON.parse(JSON.stringify(payload));
const stage: HullLookupStage = url.endsWith('/expertise')
? 'expertise'
: url.endsWith('/files') ? 'files' : 'baseClaim';
@@ -6108,7 +6115,7 @@ export class ClaimRequestManagementService {
);
},
);
if (stage === 'baseClaim') {
if (stage === 'baseClaim' && !preservePayload) {
const policyId = parseFanavaranId(payload.PolicyId);
try {
const policy = policyId == null ? null : asObjectRecord(
@@ -6543,6 +6550,8 @@ export class ClaimRequestManagementService {
bodyOverride?: Record<string, unknown>,
): Promise<any> {
try {
const manualSubmission =
bodyOverride != null && Object.keys(bodyOverride).length > 0;
await this.completeFanavaranExpertisePrerequisites(
claimCaseId,
clientKey,
@@ -6557,20 +6566,23 @@ export class ClaimRequestManagementService {
const built = await this.buildFanavaranExpertisePayload({
claimCase,
clientKey,
requireClaimExpertId: !manualSubmission,
});
const payload = applyFanavaranManualPayloadOverrides(
built.payload,
bodyOverride,
FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS,
);
this.assertFanavaranExpertisePayloadReady(payload, built.warnings, {
...hullExpertiseAssertFields(product),
});
this.assertFanavaranExpertisePayloadReady(
payload,
manualSubmission ? [] : built.warnings,
{ ...hullExpertiseAssertFields(product) },
);
const result = await this.executeFanavaranExpertiseSubmit(
claimCaseId,
clientKey,
payload,
FanavaranAuditSource.SUBMIT,
manualSubmission,
);
// Surface infoWarnings (e.g. factory-bundle fallbacks) on the success
// response so callers are informed, without ever blocking the submit.
@@ -6593,6 +6605,7 @@ export class ClaimRequestManagementService {
clientKey: FanavaranClientKey,
payload: Record<string, unknown>,
auditSource: FanavaranAuditSource,
preservePayload = false,
): Promise<any> {
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) throw new NotFoundException('Claim case not found');
@@ -6659,6 +6672,8 @@ export class ClaimRequestManagementService {
payload,
clientKey,
auditSession,
claimCaseId,
preservePayload,
);
const expertiseId = response.data?.Id;
const exchange =
@@ -7024,9 +7039,16 @@ export class ClaimRequestManagementService {
clientKey: FanavaranClientKey,
auditSession?: FanavaranAuditSession,
claimCaseId?: string,
preservePayload = false,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
await this.assertFanavaranHullApiValues(
url,
payload,
clientKey,
claimCaseId ?? auditSession?.claimCaseId,
preservePayload,
);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
@@ -7365,18 +7387,19 @@ export class ClaimRequestManagementService {
selectedParts: selectedParts ?? claimCase.damage?.selectedParts ?? [],
clientKey,
defaults: profile.defaults,
registerMissingPerson: true,
registerMissingPerson:
bodyOverride == null || Object.keys(bodyOverride).length === 0,
});
const payload = applyFanavaranManualPayloadOverrides(
builtPayload,
bodyOverride,
FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS,
);
// Guardrail: never send empty/null licence fields even if manual overrides arrive.
if (!Object.prototype.hasOwnProperty.call(bodyOverride ?? {}, 'LicenceNo')) {
payload.LicenceNo = this.ensureFanavaranNonEmptyLicenceNo(
payload.LicenceNo,
);
}
this.logger.log(
`[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? 'NULL'} payload keys=${Object.keys(payload).join(', ')}`,
@@ -7405,6 +7428,8 @@ export class ClaimRequestManagementService {
payload,
clientKey,
auditSession,
claimCaseId,
bodyOverride != null && Object.keys(bodyOverride).length > 0,
);
const dmgCaseId = response.data?.Id;
const exchange =
@@ -8033,6 +8058,8 @@ export class ClaimRequestManagementService {
`${logPrefix} Starting submission for claimCaseId: ${claimCaseId}`,
);
const manualSubmission =
bodyOverride != null && Object.keys(bodyOverride).length > 0;
const existing = await this.claimCaseDbService.findById(claimCaseId);
if (existing?.claimId != null) {
this.logger.log(
@@ -8052,6 +8079,7 @@ export class ClaimRequestManagementService {
? await this.tejaratNotifierAllowedIds(clientKey)
: undefined;
if (
!manualSubmission &&
!hasReviewedTejaratNotifier(
existing.fanavaranFieldReview?.values,
clientKey,
@@ -8073,23 +8101,45 @@ export class ClaimRequestManagementService {
};
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true,
registerMissingHullDriver: true,
requirePolicyId: !manualSubmission,
requireClaimExpertId: !manualSubmission,
registerMissingHullDriver: !Object.prototype.hasOwnProperty.call(
bodyOverride ?? {},
'AccidentCulpritId',
),
auditSession,
persistPayload: true,
forceRefreshPolicy: true,
forceRefreshUsedId: true,
...(Object.prototype.hasOwnProperty.call(bodyOverride ?? {}, 'PolicyId')
? { policyIdOverride: bodyOverride.PolicyId }
: {}),
});
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
const generated =
built && typeof built === 'object' && 'payload' in built
? built.payload
: built;
const fanavaranData = applyFanavaranManualPayloadOverrides(
built,
generated,
bodyOverride,
FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS,
);
// Guardrail: never send empty/null licence fields even if manual overrides arrive.
if (
product === 'car-body' &&
!Object.prototype.hasOwnProperty.call(bodyOverride ?? {}, 'IsLicenseReplaced')
) {
fanavaranData.IsLicenseReplaced = resolveFanavaranHullIsLicenseReplaced(
fanavaranData.CulpritLicenceIssuDate,
fanavaranData.AccidentDate,
);
}
if (!Object.prototype.hasOwnProperty.call(bodyOverride ?? {}, 'CulpritLicenceNo')) {
fanavaranData.CulpritLicenceNo = this.ensureFanavaranNonEmptyLicenceNo(
fanavaranData.CulpritLicenceNo,
);
}
this.logger.log(
`${logPrefix} Mapped data prepared:`,
@@ -8116,7 +8166,13 @@ export class ClaimRequestManagementService {
claimCaseId,
);
const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId);
await this.assertFanavaranHullApiValues(submitUrl, fanavaranData, clientKey, claimCaseId);
await this.assertFanavaranHullApiValues(
submitUrl,
fanavaranData,
clientKey,
claimCaseId,
manualSubmission,
);
const requestHeaders = {
...headers,
@@ -223,4 +223,13 @@ describe("expertise submit completes earlier Fanavaran stages", () => {
"expertise",
]);
});
it("applies arbitrary expertise fields and replaces supplied damage sections", async () => {
const { service } = setup("car-body");
const body = { ClaimExpertId: 999, DmgSections: [{ AccessoryKindId: 42 }], CustomField: null };
await service.submitFanavaranExpertiseV2("claim-1", "parsian", body);
expect(service.executeFanavaranExpertiseSubmit).toHaveBeenCalledWith(
"claim-1", "parsian", expect.objectContaining(body), expect.anything(), true,
);
});
});
@@ -34,17 +34,17 @@ describe("fanavaran hull base claim", () => {
expect(fanavaranHullNestedClaimId({ ClaimNo: 2268 })).toBeNull();
});
it("sets IsLicenseReplaced to 1 when licence issue is more than 10 years before accident", () => {
it("leaves IsLicenseReplaced empty when licence issue is more than 10 years before accident", () => {
const hull = toFanavaranHullBaseClaimPayload({
PolicyId: 1,
AccidentDate: "1405/08/20",
CulpritLicenceIssuDate: "1394/10/13",
});
expect(hull.IsLicenseReplaced).toBe(1);
expect(hull.IsLicenseReplaced).toBeNull();
expect(hull).not.toHaveProperty("IsLicenseReplacement");
});
it("sets IsLicenseReplaced to null when licence issue is within 10 years", () => {
it("sets IsLicenseReplaced to null when licence issue is more than three years before accident", () => {
const hull = toFanavaranHullBaseClaimPayload({
PolicyId: 1,
AccidentDate: "1405/08/20",
@@ -1,6 +1,7 @@
import type { FanavaranClientKey } from "src/core/config/fanavaran-client.config";
import { TEJARAT_NOTIFIER_FIELDS } from "src/fanavaran/tejarat-notifier";
import { resolveFanavaranIsLicenseReplaced } from "./fanavaran-party-roles";
import { isJalaliDateOlderThanYears } from "./fanavaran-party-roles";
import { parseJalaliDateParts } from "./fanavaran-driver-inquiry";
/** GEN.03 VHUD input fields. Do not send ثالث-only keys (DamagedCount, HasOtherCulprit, plaques, …). */
export const FANAVARAN_HULL_BASE_CLAIM_KEYS = [
@@ -118,6 +119,17 @@ export function customerIdFromHullPolicyRecord(
return Number.isFinite(n) && n > 0 ? n : null;
}
/** Hull requires an empty replacement flag for licences older than three years. */
export function resolveFanavaranHullIsLicenseReplaced(
licenceIssuDate: unknown,
accidentDate: unknown,
): 0 | null {
if (!parseJalaliDateParts(licenceIssuDate) || !parseJalaliDateParts(accidentDate)) {
return null;
}
return isJalaliDateOlderThanYears(licenceIssuDate, accidentDate, 3) ? null : 0;
}
export function toFanavaranHullBaseClaimPayload(
built: Record<string, unknown>,
clientKey?: FanavaranClientKey,
@@ -125,14 +137,14 @@ export function toFanavaranHullBaseClaimPayload(
const next: Record<string, unknown> = {};
for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) {
if (key === "IsLicenseReplaced") {
// Preserve the server's conditional 0 / null / 1 mapping for licence age.
// Preserve explicit answers; otherwise derive the hull-specific default.
if (
Object.prototype.hasOwnProperty.call(built, key) &&
(built[key] === 1 || built[key] === 0 || built[key] === null)
) {
next[key] = built[key];
} else {
next[key] = resolveFanavaranIsLicenseReplaced(
next[key] = resolveFanavaranHullIsLicenseReplaced(
built.CulpritLicenceIssuDate,
built.AccidentDate,
);
@@ -187,4 +187,28 @@ describe("hull live lookup submission checks", () => {
ActualPremium: 123456,
});
});
it("validates a manual payload without normalizing values or refreshing the supplied premium", async () => {
const service = setup();
const ids = {
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,
};
service.fanavaranLookupService.fetchFromFanavaran.mockImplementation(async (_client, url) => [
{ Id: ids[url.split("/").at(-1)], IsActive: 1 },
]);
service.fanavaranLookupService.bodyPolicyById = jest.fn().mockResolvedValue({ TotalPremium: 123456 });
const payload = {
PolicyId: 1, ActualPremium: 12, AccidentCityId: "801", AccidentReportTypeId: 802,
AccidentCauseId: 803, AccidentTypeId: 804, CulpritTypeId: 805,
AuthorityCulpritId: 806, CulpritLicenceTypeId: 807, AccidentVehicleUsedId: 808,
IsLicenseReplaced: null,
};
const original = JSON.parse(JSON.stringify(payload));
await service.postFanavaranJson("https://example.test/car/vehicle-hull-claims", payload, "parsian", undefined, undefined, true);
expect(payload).toEqual(original);
expect(service.httpService.post).toHaveBeenCalledWith(expect.any(String), original, expect.any(Object));
expect(service.fanavaranLookupService.bodyPolicyById).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,176 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
import { toFanavaranHullBaseClaimPayload } from "./fanavaran-hull-base-claim";
function setup(product = "car-body") {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
service.claimCaseDbService = { findById: jest.fn().mockResolvedValue({}) };
service.fanavaranAuditService = { generateTrackingCode: () => "test" };
service.fanavaranAuthService = { assertNotInBackoff: jest.fn() };
service.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
PolicyId: 1,
AccidentVehicleUsedId: 1,
AccidentCauseId: 6,
CulpritLicenceNo: "1234567890",
IsLicenseReplaced: 1,
});
service.resolveFanavaranClaimProduct = jest.fn().mockResolvedValue(product);
service.getFanavaranAuthHeaders = jest.fn().mockResolvedValue({});
service.fanavaranClaimsUrlForClaim = jest
.fn()
.mockResolvedValue("https://example.test/car/vehicle-hull-claims");
const stop = new Error("Captured before HTTP POST");
service.assertFanavaranHullApiValues = jest.fn().mockRejectedValue(stop);
return { service, stop };
}
describe("hull licence replacement at submit", () => {
it("honours explicit null from the submit body before validating the outgoing hull payload", async () => {
const { service, stop } = setup();
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
IsLicenseReplaced: null,
PolicyId: 999,
AccidentVehicleUsedId: 999,
}),
).rejects.toBe(stop);
const outgoing = service.assertFanavaranHullApiValues.mock.calls[0][1];
expect(outgoing.IsLicenseReplaced).toBeNull();
expect(outgoing.PolicyId).toBe(999);
expect(outgoing.AccidentVehicleUsedId).toBe(999);
});
it("applies all supplied fields on third-party submissions too", async () => {
const { service, stop } = setup("third-party");
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
IsLicenseReplaced: null,
}),
).rejects.toBe(stop);
expect(
service.assertFanavaranHullApiValues.mock.calls[0][1].IsLicenseReplaced,
).toBeNull();
});
it("builds null for the old licence and accident dates from the rejected request", () => {
expect(
toFanavaranHullBaseClaimPayload({
CulpritLicenceIssuDate: "1381/03/26",
AccidentDate: "1405/08/30",
}).IsLicenseReplaced,
).toBeNull();
});
it.each([0, 1, null])(
"preserves the explicit hull answer %s",
async (answer) => {
const { service, stop } = setup();
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
IsLicenseReplaced: answer,
}),
).rejects.toBe(stop);
expect(
service.assertFanavaranHullApiValues.mock.calls[0][1].IsLicenseReplaced,
).toBe(answer);
},
);
it.each([
["1381/03/26", null],
["1404/08/30", 0],
])(
"derives an omitted hull answer from the final overridden licence date %s",
async (date, answer) => {
const { service, stop } = setup();
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
CulpritLicenceIssuDate: date,
AccidentDate: "1405/08/30",
}),
).rejects.toBe(stop);
expect(
service.assertFanavaranHullApiValues.mock.calls[0][1].IsLicenseReplaced,
).toBe(answer);
},
);
it("preserves null licence numbers, arbitrary fields and nested arrays in the final payload", async () => {
const { service, stop } = setup();
const body = {
CulpritLicenceNo: null,
ActualPremium: 12,
ClaimExpertId: 888,
CustomField: { nested: [1, null, { value: false }] },
DmgSections: [{ AccessoryKindId: 42 }],
};
await expect(
service.executeFanavaranV2Submit("claim", "parsian", body),
).rejects.toBe(stop);
expect(service.assertFanavaranHullApiValues.mock.calls[0][1]).toMatchObject(
body,
);
expect(service.assertFanavaranHullApiValues.mock.calls[0][4]).toBe(true);
});
it("merges against the generated payload rather than forwarding a preview warning envelope", async () => {
const { service, stop } = setup();
service.previewFanavaranSubmitV2.mockResolvedValue({
payload: { PolicyId: null, ActualPremium: null },
previewWarnings: [{ field: "PolicyId" }],
});
await expect(
service.executeFanavaranV2Submit("claim", "parsian", {
PolicyId: 999,
ActualPremium: 12,
}),
).rejects.toBe(stop);
const outgoing = service.assertFanavaranHullApiValues.mock.calls[0][1];
expect(outgoing.PolicyId).toBe(999);
expect(outgoing).not.toHaveProperty("payload");
expect(outgoing).not.toHaveProperty("previewWarnings");
expect(service.previewFanavaranSubmitV2).toHaveBeenCalledWith(
"claim",
"parsian",
expect.objectContaining({
policyIdOverride: 999,
requirePolicyId: false,
requireClaimExpertId: false,
}),
);
});
it("sends every supplied value to the HTTP client without replacing null licence numbers", async () => {
const { service, stop } = setup();
service.assertFanavaranHullApiValues.mockResolvedValue(undefined);
service.fanavaranAuthService.registerFailure = jest.fn();
service.fanavaranAuditService.recordStep = jest.fn();
service.fanavaranAuditService.captureAxiosExchange = jest
.fn()
.mockReturnValue({});
service.fanavaranAuditService.extractErrorMessage = jest
.fn()
.mockReturnValue(stop.message);
service.fanavaranAuditService.sanitizeErrorDetails = jest
.fn()
.mockReturnValue({});
service.httpService = {
post: jest.fn().mockImplementation(() => {
throw stop;
}),
};
const body = {
PolicyId: 999,
ActualPremium: 12,
AccidentVehicleUsedId: 42,
CulpritLicenceNo: null,
IsLicenseReplaced: null,
ArbitraryField: false,
};
await expect(
service.executeFanavaranV2Submit("claim", "parsian", body),
).rejects.toBe(stop);
expect(service.httpService.post).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining(body),
expect.any(Object),
);
});
});
+6 -6
View File
@@ -111,7 +111,7 @@ export class FanavaranController {
@ApiOperation({
summary: "Submit Fanavaran base claim create request",
description:
"Swagger JSON body is optional. Always rebuilds GEN.03 from live inquiries, then POSTs that rebuilt payload. Pasting a previous preview JSON does not skip inquiry. Only user-entry keys are applied from the body (EstimateAmount, licence, dates, address, police report). PolicyId and AccidentVehicleUsedId in pasted JSON are ignored.",
"Optional JSON overrides the generated GEN.03 defaults. Every supplied field takes precedence, including lookup IDs, nested objects, arrays and explicit null. Omitted fields retain generated defaults. Validation checks the final payload without rewriting supplied values.",
})
@ApiParam({
name: "client",
@@ -125,7 +125,7 @@ export class FanavaranController {
@ApiBody({
required: false,
description:
"Optional. Paste previous preview JSON if you want to tweak user-entry fields. Lookup ids in that JSON are ignored.",
"Optional JSON payload overrides. All supplied fields are applied as-is; arrays and nested objects replace their generated counterparts. Explicit null is preserved.",
schema: { type: "object", additionalProperties: true, example: {} },
})
async submit(
@@ -171,7 +171,7 @@ export class FanavaranController {
@ApiOperation({
summary: "Submit Fanavaran damage-case request",
description:
"Swagger JSON body is optional. Always rebuilds GEN.12 from live VIN/vehicle/driver inquiries, then POSTs that rebuilt payload. Pasting a previous preview JSON does not skip inquiry. Only Desc, EstimateAmount, LicenceNo, LicenceIssuDate, DriverIsOwner are taken from the body. PlaqueKindId, PlaqueSampleId, VehicleKindId, DriverId, InsuranceCorpId in pasted JSON are ignored.",
"Optional JSON overrides the generated GEN.12 defaults. Every supplied field takes precedence, including DriverId, plaque/vehicle IDs, nested objects, arrays and null. Omitted fields retain generated defaults.",
})
@ApiParam({
name: "client",
@@ -185,7 +185,7 @@ export class FanavaranController {
@ApiBody({
required: false,
description:
"Optional. Paste previous preview JSON if you want to tweak Desc / licence / estimate. Lookup-filter ids in that JSON are ignored.",
"Optional JSON overrides. Every supplied field is applied as-is, including IDs and explicit null.",
schema: { type: "object", additionalProperties: true, example: {} },
})
async submitDamageCase(
@@ -283,7 +283,7 @@ export class FanavaranController {
@ApiOperation({
summary: "Submit Fanavaran expertise request",
description:
"Completes missing prerequisite stages in order before expertise: base claim, third-party damage case when applicable, then all pending attachments. Skipped images are retried; any image without a saved Fanavaran file ID blocks expertise with stage and pendingFiles details. Existing IDs/receipts are reused; existing expertise is not duplicated. Optional JSON overrides only allowed money/date fields; the GEN.08 third-party or GEN.06 hull payload is rebuilt from the expert reply and live lookups.",
"Completes missing prerequisite stages in order before expertise: base claim, third-party damage case when applicable, then all pending attachments. Skipped images are retried; any image without a saved Fanavaran file ID blocks expertise with stage and pendingFiles details. Existing IDs/receipts are reused; existing expertise is not duplicated. Optional JSON overrides every supplied GEN.08 third-party or GEN.06 hull field, including DmgCaseId, ClaimExpertId, DmgSections and explicit null. Omitted fields retain generated defaults.",
})
@ApiParam({
name: "client",
@@ -297,7 +297,7 @@ export class FanavaranController {
@ApiBody({
required: false,
description:
"Optional. Paste previous preview JSON if you want to tweak money/date fields. DmgCaseId / ClaimExpertId / DmgSections in that JSON are ignored.",
"Optional JSON overrides every supplied field. IDs, arrays, nested objects and explicit null take precedence over generated defaults.",
schema: { type: "object", additionalProperties: true, example: {} },
})
async submitExpertise(
@@ -476,7 +476,7 @@ describe("fanavaran last car policy", () => {
});
});
it("keeps live PlaqueKindId 8 when Swagger body still has stale 15", () => {
it("applies all submitted fields while keeping omitted generated defaults", () => {
expect(
applyFanavaranManualPayloadOverrides(
{
@@ -491,11 +491,10 @@ describe("fanavaran last car policy", () => {
PlaqueSampleId: 24,
Desc: "سپر جلو (edited)",
},
["Desc", "EstimateAmount", "LicenceNo"],
),
).toEqual({
PlaqueKindId: 8,
PlaqueSampleId: 10,
PlaqueKindId: 15,
PlaqueSampleId: 24,
VehicleKindId: 6704,
AccidentVehicleUsedId: 1,
Desc: "سپر جلو (edited)",
+2 -44
View File
@@ -408,55 +408,13 @@ export function canReuseCachedFanavaranVehicleIds(source: unknown): boolean {
export const FANAVARAN_NATIONAL_PLAQUE_KIND_ID = 8;
export const FANAVARAN_NATIONAL_PLAQUE_SAMPLE_ID = 10;
export const FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS = [
"Desc",
"EstimateAmount",
"LicenceNo",
"LicenceIssuDate",
"DriverIsOwner",
] as const;
export const FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS = [
"RepairWage",
"ComponentReplacementCost",
"WasteValue",
"DmgAssessmentDate",
"InspectionTime",
"DamagedVehicleCurrentPrice",
"DropAmountAdditionsDeductions",
] as const;
export const FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS = [
"EstimateAmount",
"CulpritLicenceNo",
"CulpritLicenceIssuDate",
"AccidentLocationAddress",
"AccidentDate",
"AnnouncementDate",
"DocReceivedDate",
"AccidentTime",
"PoliceReportDesc",
"PoliceReportSeri",
"PoliceReportSerial",
] as const;
/**
* Swagger POST body is optional user-entry tweaks only.
* Inquiry / lookup-filter ids always come from the live rebuilt payload.
*/
/** Supplied JSON fields win, including null, arrays, nested objects and lookup IDs. */
export function applyFanavaranManualPayloadOverrides(
built: Record<string, unknown>,
body: Record<string, unknown> | null | undefined,
keys: readonly string[],
): Record<string, unknown> {
if (!body) return built;
const next = { ...built };
for (const key of keys) {
if (!Object.prototype.hasOwnProperty.call(body, key)) continue;
if (body[key] === undefined) continue;
next[key] = body[key];
}
return next;
return { ...built, ...body };
}
/**