Compare commits

..
3 Commits
Author SHA1 Message Date
s.hajizadeh 83d7351310 merge upstream 2026-11-21 12:48:06 +03:30
s.hajizadeh ab3ae53ec0 new person registration + car body matching accident date with endDate 2026-11-21 12:47:50 +03:30
s.hajizadeh 5c6e21dd14 fix(car-body): validate policy coverage on accident date
Validate hull coverage against the accident date, select the covering renewal, and defer validation until that date is collected.
2026-11-21 12:04:09 +03:30
20 changed files with 961 additions and 83 deletions
+1 -1
View File
@@ -156,7 +156,7 @@ Example hull-only GEN.03 body (proven Parsian case): [`stage1-hull-body.json`](.
| Field | Source | | Field | Source |
|-------|--------| |-------|--------|
| `ActualPremium` | `GET /lookups/body-policy/{PolicyId}` → `TotalPremium` | | `ActualPremium` | `GET /lookups/body-policy/{PolicyId}` → `TotalPremium` |
| `AccidentCulpritId` | `GET /lookups/inquiry-by-unique-identifier?nationalCode=…&birthday=…` → `driverId` (fallback: policy `CustomerId`) | | `AccidentCulpritId` | `GET /lookups/inquiry-by-unique-identifier?nationalCode=…&birthday=…` → inspect `parties` for RoleId **166**. Hull submit registers GEN.44 when missing and re-inquires to verify; preview stays read-only. The wrapper `driverId` may fall back to role 161 and is insufficient for this check. |
| `CustomerFaultPercent` | **100** (required; درصد تقصير بيمه گذار) | | `CustomerFaultPercent` | **100** (required; درصد تقصير بيمه گذار) |
| `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` → بیمه‌گذار (required; مرجع تعيين مقصر) | | `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` → بیمه‌گذار (required; مرجع تعيين مقصر) |
+14 -1
View File
@@ -51,7 +51,7 @@ is required. The existing missing-date fallback is `1400/01/01`.
| AccidentTypeId | نوع حادثه بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-types` row caption تصادف(حادثه); no numeric fallback | | AccidentTypeId | نوع حادثه بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-types` row caption تصادف(حادثه); no numeric fallback |
| CulpritTypeId | نوع مقصر بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-culprit-type` row caption بیمه‌گذار; never reuse third-party `337` | | CulpritTypeId | نوع مقصر بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-culprit-type` row caption بیمه‌گذار; never reuse third-party `337` |
| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | Reviewed choice, else current `detection-accident-culprits` row caption بیمه‌گذار; no numeric fallback | | AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | Reviewed choice, else current `detection-accident-culprits` row caption بیمه‌گذار; no numeric fallback |
| AccidentCulpritId | شناسه مقصر فناوران | number | preferred | **inquiry** parties `inquiry-by-unique-identifier`, fallback hull policy `CustomerId` | | AccidentCulpritId | شناسه مقصر فناوران | number | **no** | Actual driver from parties inquiry with RoleId **166**; submit registers GEN.44 if missing, then verifies the role. Preview warns without creating a person. |
| CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` | | CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` |
| CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` | | CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` |
| IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` | | IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` |
@@ -161,3 +161,16 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
Same routes as ثالث (`/base-claim`, `/attachments`, `/expertise`). Same routes as ثالث (`/base-claim`, `/attachments`, `/expertise`).
`/damage-case` preview/submit **skips** for `CAR_BODY`. `/damage-case` preview/submit **skips** for `CAR_BODY`.
### Hull driver registration
A policyholder-only (`RoleId=161`) inquiry does not satisfy the hull driver role.
Before base-claim submission or hull synchronization, YARA checks the actual driver
for `RoleId=166` (سایر) and registers `common/other-people` when missing, using
national code, birthday and person details. The policyholder role is preserved.
The returned create ID is used only after a subsequent inquiry verifies role 166.
A successful registration is cached with national code and birthday so retries
wait for verification rather than creating the same role again. Missing identity,
lookup failures or unverified registration block the external hull write with
`FANAVARAN_HULL_DRIVER_ROLE_REQUIRED`; local claim creation remains best-effort.
Third-party driver/owner resolution continues to accept roles 161 or 166.
+17
View File
@@ -77,3 +77,20 @@ test("flow UI includes every seed expert in each assigned branch and both Kazemi
assert.equal(kazemi.tp, "3992"); assert.equal(kazemi.tp, "3992");
assert.equal(kazemi.body, "3991"); assert.equal(kazemi.body, "3991");
}); });
test("hull flow derives all three licence replacement states from dates", () => {
const script = fs.readFileSync(path.join(__dirname, "fanavaran-flow-test.sh"), "utf8");
const start = script.indexOf('const e=process.env, n=(k)=>Number(e[k]), nullable=');
const builder = script.slice(start, script.indexOf('\nNODE', start));
for (const [issue, expected] of [
["1404/08/24", 0], ["1401/08/24", null], ["1394/08/24", 1],
["1402/08/24", 0], ["1395/08/24", null],
]) {
let output = "";
vm.runInNewContext(builder, { process: {
env: { POLICE_REPORT_DESC: "شرح حادثه", CULPRIT_LICENCE_ISSU_DATE: issue, ACCIDENT_DATE: "1405/08/24" },
stdout: { write: text => { output += text; } },
} });
assert.equal(JSON.parse(output).IsLicenseReplaced, expected, issue);
}
});
@@ -193,7 +193,6 @@ import { fanavaranAttachmentStatus } from './fanavaran-attachment-status';
import { import {
actualPremiumFromHullPolicyRecord, actualPremiumFromHullPolicyRecord,
authorityCulpritIdFromDetectionRows, authorityCulpritIdFromDetectionRows,
customerIdFromHullPolicyRecord,
FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION, FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION,
FANAVARAN_HULL_CULPRIT_TYPE_CAPTION, FANAVARAN_HULL_CULPRIT_TYPE_CAPTION,
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
@@ -295,6 +294,7 @@ import {
pickPersonBirthday, pickPersonBirthday,
pickPersonNationalCode, pickPersonNationalCode,
selectFanavaranDriverId, selectFanavaranDriverId,
selectFanavaranOtherPersonId,
selectFanavaranOwnerId, selectFanavaranOwnerId,
} from './fanavaran-driver-inquiry'; } from './fanavaran-driver-inquiry';
import { import {
@@ -312,7 +312,10 @@ import {
resolvePolicyholderFromParty, resolvePolicyholderFromParty,
resolveThirdPartyCulpritTypeId, resolveThirdPartyCulpritTypeId,
} from './fanavaran-party-roles'; } from './fanavaran-party-roles';
import { selectLatestActiveFanavaranPolicy } from './fanavaran-policy-selection'; import {
selectLatestActiveFanavaranPolicy,
selectFanavaranPolicyForAccident,
} from './fanavaran-policy-selection';
export interface FanavaranAutoSubmitResult { export interface FanavaranAutoSubmitResult {
attempted: boolean; attempted: boolean;
@@ -2567,6 +2570,79 @@ export class ClaimRequestManagementService {
} }
} }
/** Resolve the actual hull driver as سایر; policyholder membership alone is insufficient. */
private async resolveHullDriverFanavaranId(input: {
clientKey: FanavaranClientKey;
person: any;
claimCaseId?: string;
registerMissingDriver?: boolean;
cachedRegistration?: {
otherPersonId?: number;
otherPersonNationalCode?: string;
otherPersonBirthday?: string;
};
}): Promise<number | null> {
const nationalCode = pickPersonNationalCode(input.person);
const birthday = pickPersonBirthday(input.person);
const parsed = parseJalaliDateParts(birthday);
if (!nationalCode || !parsed) return null;
const birthdayKey = `${parsed.year}/${parsed.month}/${parsed.day}`;
const inquire = () =>
this.fanavaranLookupService.inquiryByUniqueIdentifier(input.clientKey, {
nationalCode,
birthYear: parsed.year,
birthMonth: parsed.month,
birthDay: parsed.day,
});
// Failed inquiry is not evidence that a role is missing: never create blindly.
let rows: unknown;
try {
rows = await inquire();
} catch (error) {
this.logger.warn(
`[hull driver] Person inquiry unavailable: ${error instanceof Error ? error.message : String(error)}`,
);
return null;
}
const existingId = selectFanavaranOtherPersonId(rows);
if (existingId != null) return existingId;
if (!input.registerMissingDriver) return null;
const cached = input.cachedRegistration;
if (
cached?.otherPersonId &&
cached.otherPersonNationalCode === nationalCode &&
cached.otherPersonBirthday === birthdayKey
) {
// GEN.44 already succeeded. Wait for the role to become visible instead of duplicating it.
return null;
}
const registeredId = await this.registerFanavaranOtherPerson({
clientKey: input.clientKey,
person: input.person,
claimCaseId: input.claimCaseId,
requiredRoleId: 166,
});
if (registeredId == null) return null;
if (input.claimCaseId) {
await this.claimCaseDbService.findByIdAndUpdate(input.claimCaseId, {
$set: {
'fanavaranSync.baseClaim.otherPersonId': registeredId,
'fanavaranSync.baseClaim.otherPersonNationalCode': nationalCode,
'fanavaranSync.baseClaim.otherPersonBirthday': birthdayKey,
},
});
}
try {
return selectFanavaranOtherPersonId(await inquire());
} catch (error) {
this.logger.warn(
`[hull driver] Registration awaits role-166 verification: ${error instanceof Error ? error.message : String(error)}`,
);
return null;
}
}
/** GEN.03 hull: TotalPremium + parties inquiry (AccidentCulpritId) before hull field whitelist. */ /** GEN.03 hull: TotalPremium + parties inquiry (AccidentCulpritId) before hull field whitelist. */
private async enrichCarBodyHullBaseClaimPayload(input: { private async enrichCarBodyHullBaseClaimPayload(input: {
clientKey: FanavaranClientKey; clientKey: FanavaranClientKey;
@@ -2576,6 +2652,12 @@ export class ClaimRequestManagementService {
firstParty?: { person?: unknown }; firstParty?: { person?: unknown };
logPrefix: string; logPrefix: string;
claimCaseId?: string; claimCaseId?: string;
registerMissingDriver?: boolean;
cachedRegistration?: {
otherPersonId?: number;
otherPersonNationalCode?: string;
otherPersonBirthday?: string;
};
}): Promise<void> { }): Promise<void> {
const policyId = parseFanavaranId(input.payload.PolicyId); const policyId = parseFanavaranId(input.payload.PolicyId);
if (policyId == null) return; if (policyId == null) return;
@@ -2629,30 +2711,27 @@ export class ClaimRequestManagementService {
const driverIdentity = resolveDriverFromParty(input.firstParty as any); const driverIdentity = resolveDriverFromParty(input.firstParty as any);
const nationalCode = const nationalCode =
driverIdentity.nationalCode ?? driverIdentity.nationalCode ??
pickPersonNationalCode(person) ?? (person?.driverIsInsurer ? pickPersonNationalCode(person) : null);
pickCarBodyPolicyNationalCode(input.blameCase as { parties?: unknown[] }); const birthday =
const birthday = driverIdentity.birthday ?? pickPersonBirthday(person); driverIdentity.birthday ??
(person?.driverIsInsurer ? pickPersonBirthday(person) : null);
let accidentCulpritId: number | null = null; // Always use the actual driver identity; CustomerId identifies the policyholder.
if (nationalCode && birthday) { input.payload.AccidentCulpritId = await this.resolveHullDriverFanavaranId({
accidentCulpritId = await this.resolveDriverFanavaranId( clientKey: input.clientKey,
input.clientKey, person: {
...person,
nationalCodeOfDriver: nationalCode,
nationalCodeOfInsurer: undefined,
nationalCode, nationalCode,
driverBirthday: birthday,
insurerBirthday: undefined,
birthday, birthday,
false, driverIsInsurer: false,
); },
} claimCaseId: input.claimCaseId,
if (accidentCulpritId == null) { registerMissingDriver: input.registerMissingDriver,
accidentCulpritId = customerIdFromHullPolicyRecord(policyRecord); cachedRegistration: input.cachedRegistration,
if (accidentCulpritId != null) { });
this.logger.log(
`${input.logPrefix} AccidentCulpritId from policy CustomerId=${accidentCulpritId}`,
);
}
}
if (accidentCulpritId != null) {
input.payload.AccidentCulpritId = accidentCulpritId;
}
input.payload.CulpritLicenceNo = resolveFanavaranLicenceNo( input.payload.CulpritLicenceNo = resolveFanavaranLicenceNo(
driverIdentity, driverIdentity,
@@ -3959,6 +4038,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string; claimCaseId?: string;
product?: FanavaranClaimProduct; product?: FanavaranClaimProduct;
insuranceLineId?: number; insuranceLineId?: number;
accidentDate?: Date | string;
}, },
): Promise<number | null> { ): Promise<number | null> {
const clientKey = const clientKey =
@@ -4024,7 +4104,10 @@ export class ClaimRequestManagementService {
this.logger.log( this.logger.log(
`${logPrefix} Policy inquiry response status=${response.status} count=${policyCount}`, `${logPrefix} Policy inquiry response status=${response.status} count=${policyCount}`,
); );
const selectedPolicy = selectLatestActiveFanavaranPolicy(response.data); const selectedPolicy =
product === 'car-body'
? selectFanavaranPolicyForAccident(response.data, options?.accidentDate)
: selectLatestActiveFanavaranPolicy(response.data);
this.logger.log( this.logger.log(
`${logPrefix} Selected latest active policy PolicyId=${selectedPolicy.policyId} EndDate=${selectedPolicy.endDate}`, `${logPrefix} Selected latest active policy PolicyId=${selectedPolicy.policyId} EndDate=${selectedPolicy.endDate}`,
); );
@@ -4229,6 +4312,7 @@ export class ClaimRequestManagementService {
clientKey: FanavaranClientKey; clientKey: FanavaranClientKey;
person: any; person: any;
claimCaseId?: string; claimCaseId?: string;
requiredRoleId?: 166;
}): Promise<number | null> { }): Promise<number | null> {
const nationalCode = pickPersonNationalCode(input.person); const nationalCode = pickPersonNationalCode(input.person);
const birthday = pickPersonBirthday(input.person); const birthday = pickPersonBirthday(input.person);
@@ -4281,6 +4365,10 @@ export class ClaimRequestManagementService {
birthDay: parsedBirthday.day, birthDay: parsedBirthday.day,
}, },
); );
if (input.requiredRoleId === 166) {
const existingId = selectFanavaranOtherPersonId(inquiryRows);
if (existingId != null) return existingId;
}
const parties = asPartyInquiryRows(inquiryRows); const parties = asPartyInquiryRows(inquiryRows);
const seedRow = const seedRow =
parties.find( parties.find(
@@ -4313,10 +4401,11 @@ export class ClaimRequestManagementService {
} }
} catch (error) { } catch (error) {
this.logger.warn( this.logger.warn(
`[registerFanavaranOtherPerson] pre-create inquiry failed (continuing with local data): ${ `[registerFanavaranOtherPerson] pre-create inquiry failed (${input.requiredRoleId === 166 ? 'registration deferred' : 'continuing with local data'}): ${
error instanceof Error ? error.message : error error instanceof Error ? error.message : error
}`, }`,
); );
if (input.requiredRoleId === 166) return null;
} }
const lookups = await this.loadFanavaranOtherPeopleLookups(input.clientKey); const lookups = await this.loadFanavaranOtherPeopleLookups(input.clientKey);
@@ -4410,6 +4499,23 @@ export class ClaimRequestManagementService {
); );
} }
if (input.requiredRoleId === 166) {
try {
return selectFanavaranOtherPersonId(
await this.fanavaranLookupService.inquiryByUniqueIdentifier(
input.clientKey,
{
nationalCode,
birthYear: parsedBirthday.year,
birthMonth: parsedBirthday.month,
birthDay: parsedBirthday.day,
},
),
);
} catch {
return null;
}
}
return this.resolveDriverFanavaranId( return this.resolveDriverFanavaranId(
input.clientKey, input.clientKey,
nationalCode, nationalCode,
@@ -4534,6 +4640,8 @@ export class ClaimRequestManagementService {
resolvePolicy?: boolean; resolvePolicy?: boolean;
/** When true (submit), missing PolicyId throws. Preview keeps payload even if inquiry fails. */ /** When true (submit), missing PolicyId throws. Preview keeps payload even if inquiry fails. */
requirePolicyId?: boolean; requirePolicyId?: boolean;
/** Only submission may register the hull driver through GEN.44. */
registerMissingHullDriver?: boolean;
/** /**
* When false (HTTP preview), missing staff ClaimExpertId stays null and is * When false (HTTP preview), missing staff ClaimExpertId stays null and is
* reported in previewWarnings instead of throwing. * reported in previewWarnings instead of throwing.
@@ -4719,7 +4827,12 @@ export class ClaimRequestManagementService {
profile.auth, profile.auth,
logPrefix, logPrefix,
auditSession, auditSession,
{ clientKey, claimCaseId, product: 'car-body' }, {
clientKey,
claimCaseId,
product: 'car-body',
accidentDate: firstParty?.statement?.accidentDate,
},
); );
debug.values.policyId = policyId; debug.values.policyId = policyId;
debug.steps.policyInquirySucceeded = policyId !== null; debug.steps.policyInquirySucceeded = policyId !== null;
@@ -4922,7 +5035,19 @@ export class ClaimRequestManagementService {
firstParty, firstParty,
logPrefix, logPrefix,
claimCaseId, claimCaseId,
registerMissingDriver: options?.registerMissingHullDriver === true,
cachedRegistration: claimCase.fanavaranSync?.baseClaim,
}); });
if (payload.AccidentCulpritId == null) {
const warning = {
code: 'FANAVARAN_HULL_DRIVER_ROLE_REQUIRED',
field: 'AccidentCulpritId',
message:
'راننده بیمه بدنه باید در فناوران با نقش سایر (166) ثبت و تأیید شود. ثبت شخص هنگام ارسال انجام می‌شود.',
};
if (requirePolicyId) throw new BadRequestException(warning);
previewWarnings.push(warning);
}
applyFanavaranStageFieldReview( applyFanavaranStageFieldReview(
payload, payload,
claimCase, claimCase,
@@ -6976,6 +7101,7 @@ export class ClaimRequestManagementService {
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, { const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true, requirePolicyId: true,
registerMissingHullDriver: true,
persistPayload: true, persistPayload: true,
}); });
const hull = toFanavaranHullBaseClaimPayload( const hull = toFanavaranHullBaseClaimPayload(
@@ -7948,6 +8074,7 @@ export class ClaimRequestManagementService {
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, { const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true, requirePolicyId: true,
registerMissingHullDriver: true,
auditSession, auditSession,
persistPayload: true, persistPayload: true,
forceRefreshPolicy: true, forceRefreshPolicy: true,
@@ -90,10 +90,17 @@ export class FanavaranSyncStage {
@Prop({ type: Number }) @Prop({ type: Number })
driverId?: number; driverId?: number;
/** Cached GEN.44 other-people Id when the person was created because inquiry missed. */ /** Cached GEN.44 other-people Id when registration was required. */
@Prop({ type: Number }) @Prop({ type: Number })
otherPersonId?: number; otherPersonId?: number;
/** Identity associated with a hull GEN.44 registration, including pending role verification. */
@Prop({ type: String })
otherPersonNationalCode?: string;
@Prop({ type: String })
otherPersonBirthday?: string;
/** Cached Fanavaran VehicleKindId. */ /** Cached Fanavaran VehicleKindId. */
@Prop({ type: Number }) @Prop({ type: Number })
vehicleKindId?: number; vehicleKindId?: number;
@@ -87,6 +87,13 @@ export function selectFanavaranDriverId(
}); });
} }
/** Hull driver registration must resolve specifically to GEN.44's سایر role. */
export function selectFanavaranOtherPersonId(rows: unknown): number | null {
return selectFanavaranIdByRoles(rows, [FANAVARAN_DRIVER_ROLE_ID], {
allowFallbackToFirst: false,
});
}
/** /**
* OwnerId for GEN.12: same accepted roles as DriverId (161 / 166 only). * OwnerId for GEN.12: same accepted roles as DriverId (161 / 166 only).
* Prefer بیمه‌گذار then سایر. RoleId 162/163/… → null → GEN.44 on submit. * Prefer بیمه‌گذار then سایر. RoleId 162/163/… → null → GEN.44 on submit.
@@ -0,0 +1,244 @@
import { ClaimRequestManagementService } from "./claim-request-management.service";
const insurer = {
Id: 41,
RoleId: 161,
NationalCode: "0012345678",
Name: "تست",
LastName: "راننده",
};
const driver = { ...insurer, RoleId: 166 };
function setup() {
const service = Object.create(ClaimRequestManagementService.prototype) as any;
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
service.fanavaranLookupService = {
bodyPolicyById: jest
.fn()
.mockResolvedValue({ CustomerId: insurer.Id, TotalPremium: 76391920 }),
inquiryByUniqueIdentifier: jest.fn().mockResolvedValue([insurer]),
};
service.getFanavaranLookupRows = jest.fn().mockResolvedValue([]);
service.resolveDriverFanavaranId = jest.fn().mockResolvedValue(insurer.Id);
service.loadFanavaranOtherPeopleLookups = jest.fn().mockResolvedValue({});
service.postFanavaranJson = jest
.fn()
.mockResolvedValue({ data: { Id: insurer.Id } });
service.fanavaranAuditService = {
generateTrackingCode: jest.fn().mockReturnValue("test"),
recordStep: jest.fn(),
};
service.claimCaseDbService = {
findByIdAndUpdate: jest.fn().mockResolvedValue({}),
};
const input = {
clientKey: "parsian",
payload: { PolicyId: 15708843 } as Record<string, unknown>,
blameCase: {},
firstParty: {
person: {
nationalCodeOfDriver: "0012345678",
driverBirthday: "1360/01/02",
driverIsInsurer: true,
},
},
claimCaseId: "case-1",
logPrefix: "test",
registerMissingDriver: true,
};
return { service, input };
}
describe("hull role-166 registration", () => {
it("registers a policyholder-only driver through GEN.44 before filling the hull person reference", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier
.mockResolvedValueOnce([insurer])
.mockResolvedValueOnce([insurer])
.mockResolvedValue([insurer, driver]);
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(service.postFanavaranJson).toHaveBeenCalledWith(
expect.stringContaining("/common/other-people"),
expect.objectContaining({
NationalCode: "0012345678",
BirthYear: 1360,
BirthMonth: 1,
BirthDay: 2,
PersonKindId: 46,
}),
"parsian",
expect.anything(),
"case-1",
);
expect(input.payload.AccidentCulpritId).toBe(insurer.Id);
});
it("keeps a policyholder-only preview read-only and leaves the driver unresolved", async () => {
const { service, input } = setup();
input.registerMissingDriver = false;
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(service.postFanavaranJson).not.toHaveBeenCalled();
expect(input.payload.AccidentCulpritId).toBeNull();
});
it("reuses an existing role-166 person without a registration POST", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockResolvedValue([
insurer,
{ ...driver, Id: 42 },
]);
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(input.payload.AccidentCulpritId).toBe(42);
expect(service.postFanavaranJson).not.toHaveBeenCalled();
});
it("does not use the returned create ID until role 166 is verified", async () => {
const { service, input } = setup();
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
expect(input.payload.AccidentCulpritId).toBeNull();
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
"case-1",
{
$set: {
"fanavaranSync.baseClaim.otherPersonId": 41,
"fanavaranSync.baseClaim.otherPersonNationalCode": "0012345678",
"fanavaranSync.baseClaim.otherPersonBirthday": "1360/1/2",
},
},
);
const retry = {
...input,
cachedRegistration: {
otherPersonId: 41,
otherPersonNationalCode: "0012345678",
otherPersonBirthday: "1360/1/2",
},
};
await service.enrichCarBodyHullBaseClaimPayload(retry);
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockResolvedValue([
insurer,
driver,
]);
await service.enrichCarBodyHullBaseClaimPayload(retry);
expect(input.payload.AccidentCulpritId).toBe(41);
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
});
it("keeps a registration cached when the verification request fails", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier
.mockResolvedValueOnce([insurer])
.mockResolvedValueOnce([insurer])
.mockRejectedValue(new Error("ECONNRESET"));
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(input.payload.AccidentCulpritId).toBeNull();
expect(service.claimCaseDbService.findByIdAndUpdate).toHaveBeenCalledWith(
"case-1",
expect.objectContaining({
$set: expect.objectContaining({
"fanavaranSync.baseClaim.otherPersonId": 41,
}),
}),
);
});
it("does not create a person when initial inquiry fails", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockRejectedValue(
new Error("ECONNRESET"),
);
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(service.postFanavaranJson).not.toHaveBeenCalled();
expect(input.payload.AccidentCulpritId).toBeNull();
});
it("does not replace failed registration with the policy customer's role 161", async () => {
const { service, input } = setup();
service.postFanavaranJson.mockRejectedValue(
new Error("Registration failed"),
);
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(input.payload.AccidentCulpritId).toBeNull();
expect(service.resolveDriverFanavaranId).not.toHaveBeenCalled();
});
it("rechecks the role before POST to avoid registering a role that already appeared", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier
.mockResolvedValueOnce([insurer])
.mockResolvedValue([insurer, driver]);
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(input.payload.AccidentCulpritId).toBe(41);
expect(service.postFanavaranJson).not.toHaveBeenCalled();
});
it("does not use a pending registration for a different driver", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier
.mockResolvedValueOnce([insurer])
.mockResolvedValueOnce([insurer])
.mockResolvedValue([driver]);
await service.enrichCarBodyHullBaseClaimPayload({
...input,
cachedRegistration: {
otherPersonId: 999,
otherPersonNationalCode: "9999999999",
otherPersonBirthday: "1360/1/2",
},
});
expect(service.postFanavaranJson).toHaveBeenCalledTimes(1);
expect(input.payload.AccidentCulpritId).toBe(41);
});
it("recovers from a duplicate-create response only after the role-166 inquiry succeeds", async () => {
const { service, input } = setup();
service.postFanavaranJson.mockRejectedValue(
new Error("Duplicate national code"),
);
service.fanavaranLookupService.inquiryByUniqueIdentifier
.mockResolvedValueOnce([insurer])
.mockResolvedValueOnce([insurer])
.mockResolvedValue([insurer, driver]);
await service.enrichCarBodyHullBaseClaimPayload(input);
expect(input.payload.AccidentCulpritId).toBe(41);
expect(service.resolveDriverFanavaranId).not.toHaveBeenCalled();
});
it("does not substitute the policyholder when the actual driver identity is missing", async () => {
const { service, input } = setup();
await service.enrichCarBodyHullBaseClaimPayload({
...input,
firstParty: {
person: {
nationalCodeOfInsurer: "0012345678",
insurerBirthday: "1360/01/02",
driverIsInsurer: false,
},
},
});
expect(input.payload.AccidentCulpritId).toBeNull();
expect(service.postFanavaranJson).not.toHaveBeenCalled();
expect(
service.fanavaranLookupService.inquiryByUniqueIdentifier,
).not.toHaveBeenCalled();
});
it("uses the explicitly shared identity for legacy driver-is-policyholder cases", async () => {
const { service, input } = setup();
service.fanavaranLookupService.inquiryByUniqueIdentifier.mockResolvedValue([
driver,
]);
await service.enrichCarBodyHullBaseClaimPayload({
...input,
firstParty: {
person: {
nationalCodeOfInsurer: "0012345678",
insurerBirthday: "1360/01/02",
driverIsInsurer: true,
},
},
});
expect(input.payload.AccidentCulpritId).toBe(41);
expect(service.postFanavaranJson).not.toHaveBeenCalled();
});
});
@@ -153,3 +153,35 @@ describe("Hull base-claim vehicle use from policy inquiry", () => {
}); });
}); });
}); });
describe("Hull preview and submission driver-role gate", () => {
it("reports unresolved role 166 in preview without enabling registration", async () => {
const service = previewSetup({ UsedId: 42, VehicleKindId: 8671 });
const result = await service.previewFanavaranSubmitV2("claim", "moallem", {
debug: true,
});
expect(service.enrichCarBodyHullBaseClaimPayload).toHaveBeenCalledWith(
expect.objectContaining({ registerMissingDriver: false }),
);
expect(result.previewWarnings).toContainEqual(
expect.objectContaining({ code: "FANAVARAN_HULL_DRIVER_ROLE_REQUIRED" }),
);
});
it("blocks submission when the driver's role remains unresolved after registration", async () => {
const service = previewSetup({ UsedId: 42, VehicleKindId: 8671 });
await expect(
service.previewFanavaranSubmitV2("claim", "moallem", {
requirePolicyId: true,
registerMissingHullDriver: true,
}),
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_HULL_DRIVER_ROLE_REQUIRED",
}),
});
expect(service.enrichCarBodyHullBaseClaimPayload).toHaveBeenCalledWith(
expect.objectContaining({ registerMissingDriver: true }),
);
});
});
@@ -1,5 +1,8 @@
import { BadRequestException } from "@nestjs/common"; import { BadRequestException } from "@nestjs/common";
import { selectLatestActiveFanavaranPolicy } from "./fanavaran-policy-selection"; import {
selectLatestActiveFanavaranPolicy,
selectFanavaranPolicyForAccident,
} from "./fanavaran-policy-selection";
describe("selectLatestActiveFanavaranPolicy", () => { describe("selectLatestActiveFanavaranPolicy", () => {
const today = "2026-06-30"; const today = "2026-06-30";
@@ -61,3 +64,29 @@ describe("selectLatestActiveFanavaranPolicy", () => {
).toThrow(BadRequestException); ).toThrow(BadRequestException);
}); });
}); });
describe("car-body accident policy selection", () => {
const policies = [
{ PolicyId: 2, BeginDate: "1401/01/02", EndDate: "1402/01/02" },
{ PolicyId: 1, BeginDate: "1400/01/01", EndDate: "1401/01/01" },
];
it("selects the previous renewal covering the accident, even when both expired today", () => {
expect(
selectFanavaranPolicyForAccident(policies, "1400/12/28").policyId,
).toBe(1);
});
it.each(["1400/01/01", "1401/01/01"])(
"includes the coverage boundary %s",
(date) => {
expect(selectFanavaranPolicyForAccident(policies, date).policyId).toBe(1);
},
);
it.each(["1399/12/29", "1402/01/03", "invalid", undefined])(
"rejects an uncovered or missing accident date %s",
(date) => {
expect(() => selectFanavaranPolicyForAccident(policies, date)).toThrow(
BadRequestException,
);
},
);
});
@@ -1,3 +1,8 @@
import {
isPolicyActiveOn,
policyAccidentDate,
selectLastAmongCarMatches,
} from "src/lookups/fanavaran-last-car-policy";
import { BadRequestException } from "@nestjs/common"; import { BadRequestException } from "@nestjs/common";
import { jalaliToGregorianDate } from "src/helpers/date-jalali"; import { jalaliToGregorianDate } from "src/helpers/date-jalali";
import { gregorianDateInIran } from "src/helpers/iran-datetime"; import { gregorianDateInIran } from "src/helpers/iran-datetime";
@@ -93,3 +98,34 @@ export function selectLatestActiveFanavaranPolicy(
return { ...latest, policyId }; return { ...latest, policyId };
} }
/** Hull renewals must be selected for the loss date, regardless of submission date. */
export function selectFanavaranPolicyForAccident(
policies: unknown,
accidentDate: unknown,
): SelectedFanavaranPolicy {
const date = policyAccidentDate(accidentDate);
if (!date)
throw new BadRequestException(
"A valid accidentDate is required for car-body policy selection.",
);
if (!Array.isArray(policies) || policies.length === 0) {
throw new BadRequestException(NO_POLICY_MESSAGE);
}
const matches = policies
.filter((row) => row && typeof row === "object")
.map((row) => ({
policyId: parsePolicyId(row.PolicyId) ?? 0,
beginDate: row.BeginDate,
endDate: row.EndDate,
policy: row,
vehicle: null,
}));
const selected = selectLastAmongCarMatches(matches, date);
if (!selected || !isPolicyActiveOn(selected, date)) {
throw new BadRequestException(
"No Fanavaran car-body policy covers the accident date.",
);
}
return selectLatestActiveFanavaranPolicy([selected.policy], date);
}
+18 -1
View File
@@ -1,5 +1,8 @@
import { jalaliToGregorianDate } from "src/helpers/date-jalali"; import { jalaliToGregorianDate } from "src/helpers/date-jalali";
import { gregorianDateInIran } from "src/helpers/iran-datetime"; import {
gregorianDateInIran,
parseIranLocalDateTime,
} from "src/helpers/iran-datetime";
import { normalizePlateText } from "src/utils/plate-normalizer/plate-normalizer.service"; import { normalizePlateText } from "src/utils/plate-normalizer/plate-normalizer.service";
export const FANAVARAN_THIRD_PARTY_LINE_ID = 5; export const FANAVARAN_THIRD_PARTY_LINE_ID = 5;
@@ -222,6 +225,20 @@ export function toGregorianDate(value: unknown): string | null {
return jalaliToGregorianDate(toEnglishDigits(value).trim() || null); return jalaliToGregorianDate(toEnglishDigits(value).trim() || null);
} }
/** Accident calendar date; timestamps are interpreted in Iran, like claim dates. */
export function policyAccidentDate(value: unknown): string | null {
if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? null : gregorianDateInIran(value);
}
const raw = toEnglishDigits(value).trim();
if (!raw) return null;
if (/^\d{4}-\d{2}-\d{2}T/.test(raw)) {
const date = parseIranLocalDateTime(raw);
return date ? gregorianDateInIran(date) : null;
}
return toGregorianDate(raw);
}
export function pickVehicleVin(vehicle: Record<string, unknown> | null): string { export function pickVehicleVin(vehicle: Record<string, unknown> | null): string {
if (!vehicle) return ""; if (!vehicle) return "";
for (const key of ["VIN", "Vin", "VinNo", "vin", "ChassisNo", "chassisNo"]) { for (const key of ["VIN", "Vin", "VinNo", "vin", "ChassisNo", "chassisNo"]) {
+9
View File
@@ -874,6 +874,13 @@ export class LookupsController {
@ApiQuery({ name: "plaqueLetter", required: false, example: "ب" }) @ApiQuery({ name: "plaqueLetter", required: false, example: "ب" })
@ApiQuery({ name: "plaqueRight", required: false, example: "345" }) @ApiQuery({ name: "plaqueRight", required: false, example: "345" })
@ApiQuery({ name: "plaqueSerial", required: false, example: "67" }) @ApiQuery({ name: "plaqueSerial", required: false, example: "67" })
@ApiQuery({
name: "accidentDate",
required: false,
example: "1405/05/18",
description:
"Coverage date (Jalali or Gregorian). Without it, coverage validation is deferred.",
})
@ApiOkResponse({ @ApiOkResponse({
description: "Mapped last body policy plus vehicle", description: "Mapped last body policy plus vehicle",
schema: { type: "object" }, schema: { type: "object" },
@@ -885,9 +892,11 @@ export class LookupsController {
@Query("plaqueLetter") plaqueLetter?: string, @Query("plaqueLetter") plaqueLetter?: string,
@Query("plaqueRight") plaqueRight?: string, @Query("plaqueRight") plaqueRight?: string,
@Query("plaqueSerial") plaqueSerial?: string, @Query("plaqueSerial") plaqueSerial?: string,
@Query("accidentDate") accidentDate?: string,
) { ) {
return this.lookupsService.findLastProcessedCarPolicy("car-body", { return this.lookupsService.findLastProcessedCarPolicy("car-body", {
nationalCode, nationalCode,
accidentDate,
vin, vin,
plaqueLeft, plaqueLeft,
plaqueLetter, plaqueLetter,
@@ -13,13 +13,17 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
}); });
function createService(lookup: Record<string, jest.Mock>) { function createService(lookup: Record<string, jest.Mock>) {
return new LookupsService({} as any, lookup as any, { return new LookupsService(
countDocuments: jest.fn().mockResolvedValue(1), {} as any,
getLatestSyncedAt: jest.fn().mockResolvedValue(new Date()), lookup as any,
findAllPublic: jest.fn().mockResolvedValue([]), {
searchActiveByCaption: jest.fn().mockResolvedValue([]), countDocuments: jest.fn().mockResolvedValue(1),
replaceAllFromFanavaran: jest.fn().mockResolvedValue(0), getLatestSyncedAt: jest.fn().mockResolvedValue(new Date()),
} as any); findAllPublic: jest.fn().mockResolvedValue([]),
searchActiveByCaption: jest.fn().mockResolvedValue([]),
replaceAllFromFanavaran: jest.fn().mockResolvedValue(0),
} as any,
);
} }
it("returns the last matching third-party policy and its vehicle", async () => { it("returns the last matching third-party policy and its vehicle", async () => {
@@ -44,7 +48,9 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
EndDate: "1406/01/01", EndDate: "1406/01/01",
}, },
]), ]),
inquiryByVin: jest.fn().mockResolvedValue([{ Id: 500, VIN: "IRNKAEK4150012345" }]), inquiryByVin: jest
.fn()
.mockResolvedValue([{ Id: 500, VIN: "IRNKAEK4150012345" }]),
thirdPartyPolicyById: jest.fn().mockImplementation((_key, policyId) => thirdPartyPolicyById: jest.fn().mockImplementation((_key, policyId) =>
Promise.resolve({ Promise.resolve({
PolicyId: policyId, PolicyId: policyId,
@@ -138,45 +144,124 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
expect(lookup.inquiryByVin).not.toHaveBeenCalled(); expect(lookup.inquiryByVin).not.toHaveBeenCalled();
}); });
it("rejects an expired car-body policy instead of treating it as active coverage", async () => { it.each(["1400/12/28", "1400/01/01", "1401/01/01", undefined])(
const lookup = { "allows a covered accident date %s or defers an undated inquiry",
myPolicies: jest.fn().mockResolvedValue([ async (accidentDate) => {
{ const lookup = {
myPolicies: jest.fn().mockResolvedValue([
{
PolicyId: 44,
InsuranceLineId: 4,
BeginDate: "1400/01/01",
EndDate: "1401/01/01",
},
]),
bodyPolicyById: jest.fn().mockResolvedValue({
PolicyId: 44, PolicyId: 44,
InsuranceLineId: 4, VehicleId: 8,
BeginDate: "1400/01/01", BeginDate: "1400/01/01",
EndDate: "1401/01/01", EndDate: "1401/01/01",
}, }),
]), vehicleById: jest
inquiryByVin: jest.fn(), .fn()
bodyPolicyById: jest.fn().mockResolvedValue({ .mockResolvedValue({ Id: 8, VIN: "IRNKAEK4150012345" }),
PolicyId: 44, inquiryByVin: jest.fn().mockResolvedValue([{ Id: 8 }]),
getRemoteLookup: jest.fn().mockResolvedValue([]),
customerById: jest.fn().mockResolvedValue(null),
};
await expect(
createService(lookup).findLastProcessedCarPolicy("car-body", {
nationalCode: "0012345678",
vin: "IRNKAEK4150012345",
accidentDate,
}),
).resolves.toMatchObject({ policyId: 44 });
},
);
it("selects the earlier renewal that covered the accident for the matching car", async () => {
const policies = [
{
PolicyId: 45,
InsuranceLineId: 4,
BeginDate: "1401/01/02",
EndDate: "1402/01/02",
VehicleId: 8, VehicleId: 8,
},
{
PolicyId: 44,
InsuranceLineId: 4,
BeginDate: "1400/01/01", BeginDate: "1400/01/01",
EndDate: "1401/01/01", EndDate: "1401/01/01",
}), VehicleId: 8,
vehicleById: jest.fn().mockResolvedValue({ },
Id: 8, ];
PlaqueLeftNo: "12", const lookup = {
PlaqueMiddleCodeId: 2, myPolicies: jest.fn().mockResolvedValue(policies),
PlaqueRightNo: "345", bodyPolicyById: jest
PlaqueSerial: "67", .fn()
}), .mockImplementation((_key, id) =>
Promise.resolve(policies.find((p) => p.PolicyId === id)),
),
vehicleById: jest
.fn()
.mockResolvedValue({ Id: 8, VIN: "IRNKAEK4150012345" }),
inquiryByVin: jest.fn().mockResolvedValue([{ Id: 8 }]),
getRemoteLookup: jest.fn().mockResolvedValue([]), getRemoteLookup: jest.fn().mockResolvedValue([]),
customerById: jest.fn().mockResolvedValue(null), customerById: jest.fn().mockResolvedValue(null),
}; };
await expect( await expect(
createService(lookup).findLastProcessedCarPolicy("car-body", { createService(lookup).findLastProcessedCarPolicy("car-body", {
nationalCode: "0012345678", nationalCode: "0012345678",
plaqueLeft: "12", vin: "IRNKAEK4150012345",
plaqueLetter: "ب", accidentDate: "1400/12/28",
plaqueRight: "345",
plaqueSerial: "67",
}), }),
).rejects.toBeInstanceOf(NotFoundException); ).resolves.toMatchObject({ policyId: 44 });
}); });
it.each(["1401/01/02", "1399/12/29"])(
"rejects a policy outside the accident date %s",
async (accidentDate) => {
const lookup = {
myPolicies: jest.fn().mockResolvedValue([
{
PolicyId: 44,
InsuranceLineId: 4,
BeginDate: "1400/01/01",
EndDate: "1401/01/01",
},
]),
inquiryByVin: jest.fn(),
bodyPolicyById: jest.fn().mockResolvedValue({
PolicyId: 44,
VehicleId: 8,
BeginDate: "1400/01/01",
EndDate: "1401/01/01",
}),
vehicleById: jest.fn().mockResolvedValue({
Id: 8,
PlaqueLeftNo: "12",
PlaqueMiddleCodeId: 2,
PlaqueRightNo: "345",
PlaqueSerial: "67",
}),
getRemoteLookup: jest.fn().mockResolvedValue([]),
customerById: jest.fn().mockResolvedValue(null),
};
await expect(
createService(lookup).findLastProcessedCarPolicy("car-body", {
nationalCode: "0012345678",
accidentDate,
plaqueLeft: "12",
plaqueLetter: "ب",
plaqueRight: "345",
plaqueSerial: "67",
}),
).rejects.toBeInstanceOf(NotFoundException);
},
);
it("accepts the policy when VIN inquiry VehicleId matches and GEN.15 VIN is empty", async () => { it("accepts the policy when VIN inquiry VehicleId matches and GEN.15 VIN is empty", async () => {
const lookup = { const lookup = {
myPolicies: jest.fn().mockResolvedValue([ myPolicies: jest.fn().mockResolvedValue([
@@ -187,9 +272,9 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
EndDate: "1406/01/01", EndDate: "1406/01/01",
}, },
]), ]),
inquiryByVin: jest.fn().mockResolvedValue([ inquiryByVin: jest
{ Id: 4118289, VIN: "NAAR03HFFRDE07024" }, .fn()
]), .mockResolvedValue([{ Id: 4118289, VIN: "NAAR03HFFRDE07024" }]),
bodyPolicyById: jest.fn().mockResolvedValue({ bodyPolicyById: jest.fn().mockResolvedValue({
PolicyId: 15292336, PolicyId: 15292336,
VehicleId: 4118289, VehicleId: 4118289,
@@ -226,7 +311,9 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
EndDate: "1406/01/01", EndDate: "1406/01/01",
}, },
]), ]),
inquiryByVin: jest.fn().mockResolvedValue([{ Id: 99, VIN: "IRNKAEK4150012345" }]), inquiryByVin: jest
.fn()
.mockResolvedValue([{ Id: 99, VIN: "IRNKAEK4150012345" }]),
thirdPartyPolicyById: jest.fn().mockResolvedValue({ thirdPartyPolicyById: jest.fn().mockResolvedValue({
PolicyId: 10, PolicyId: 10,
VehicleId: 1, VehicleId: 1,
+13 -7
View File
@@ -30,6 +30,7 @@ import {
insuranceLineIdForProduct, insuranceLineIdForProduct,
insuranceLineLabel, insuranceLineLabel,
isPolicyActiveOn, isPolicyActiveOn,
policyAccidentDate,
parseFanavaranId, parseFanavaranId,
parseLastCarPolicyInput, parseLastCarPolicyInput,
pickVehicleId, pickVehicleId,
@@ -45,7 +46,6 @@ import {
isVehicleKindsSyncStale, isVehicleKindsSyncStale,
VEHICLE_KINDS_REFRESH_MS, VEHICLE_KINDS_REFRESH_MS,
} from "./vehicle-kind-search"; } from "./vehicle-kind-search";
import { gregorianDateInIran } from "src/helpers/iran-datetime";
import { normalizeDrivingLicenceTypes, type DrivingLicenceType } from "./driving-licence-types"; import { normalizeDrivingLicenceTypes, type DrivingLicenceType } from "./driving-licence-types";
type TejaratAccidentReasonRow = { type TejaratAccidentReasonRow = {
@@ -612,6 +612,7 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
product: FanavaranCarPolicyProduct, product: FanavaranCarPolicyProduct,
query: { query: {
nationalCode?: string; nationalCode?: string;
accidentDate?: Date | string;
vin?: string; vin?: string;
plaqueLeft?: string; plaqueLeft?: string;
plaqueLetter?: string; plaqueLetter?: string;
@@ -632,6 +633,11 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
throw new BadRequestException(parsed.error); throw new BadRequestException(parsed.error);
} }
const accidentDate =
query.accidentDate == null ? null : policyAccidentDate(query.accidentDate);
if (query.accidentDate != null && !accidentDate) {
throw new BadRequestException("Invalid accidentDate");
}
const clientKey = this.activeClientKey(); const clientKey = this.activeClientKey();
const insuranceLineId = insuranceLineIdForProduct(product); const insuranceLineId = insuranceLineIdForProduct(product);
const contractIdOverride = resolveFanavaranProductContractId( const contractIdOverride = resolveFanavaranProductContractId(
@@ -755,7 +761,7 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
}); });
} }
const selected = selectLastAmongCarMatches(matches); const selected = selectLastAmongCarMatches(matches, accidentDate ?? undefined);
if (!selected) { if (!selected) {
if (candidates.length === 0) { if (candidates.length === 0) {
throw new NotFoundException( throw new NotFoundException(
@@ -772,15 +778,15 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
); );
} }
// A CAR_BODY case is payable only with current hull coverage. The generic // Before the description step the accident date may not be known yet.
// selector may intentionally return the latest expired policy for history; // Retrieve the policy now; validate coverage when that date is supplied.
// that fallback is not valid for a new CAR_BODY case.
if ( if (
product === "car-body" && product === "car-body" &&
!isPolicyActiveOn(selected, gregorianDateInIran(new Date())) accidentDate &&
!isPolicyActiveOn(selected, accidentDate)
) { ) {
throw new NotFoundException( throw new NotFoundException(
"No active Fanavaran car-body policy was found for this car.", "No Fanavaran car-body policy covering the accident date was found for this car.",
); );
} }
@@ -0,0 +1,67 @@
import { BadRequestException } from "@nestjs/common";
import { RequestManagementService } from "./request-management.service";
describe("car-body coverage when the accident date is collected after inquiry", () => {
function setup(startDate = "1400/01/01", endDate = "1401/01/01") {
const party = {
person: { nationalCodeOfInsurer: "0012345678" },
vehicle: {
vin: "IRNKAEK4150012345",
inquiry: {
carBody: { mapped: { StartDate: startDate, EndDate: endDate } },
},
},
insurance: { carBodyInsurance: { policyId: 2 } },
};
const service = Object.create(RequestManagementService.prototype) as any;
service.sandHubService = { getCarBodyInquiry: jest.fn() };
return {
service,
party,
inquiry: service.sandHubService.getCarBodyInquiry,
};
}
it("accepts a policy that has expired today but covered the accident", async () => {
const { service, party, inquiry } = setup();
await expect(
service.validateCarBodyAccidentCoverage(party, "1400/12/28"),
).resolves.toBeUndefined();
expect(inquiry).not.toHaveBeenCalled();
});
it("reselects and stores the earlier renewal for the supplied accident date", async () => {
const { service, party, inquiry } = setup("1401/01/02", "1402/01/02");
inquiry.mockResolvedValue({
source: "ESG_CAR_BODY_INQUIRY",
mapped: {
policyId: 1,
StartDate: "1400/01/01",
EndDate: "1401/01/01",
vehicleValue: 1000,
},
});
await service.validateCarBodyAccidentCoverage(party, "1400/12/28");
expect(inquiry).toHaveBeenCalledWith({
nationalCodeOfInsurer: "0012345678",
plate: "IRNKAEK4150012345",
accidentDate: "1400/12/28",
});
expect(party.insurance.carBodyInsurance).toMatchObject({
policyId: 1,
startDate: "1400/01/01",
endDate: "1401/01/01",
vehicleValue: 1000,
});
expect(party.vehicle.inquiry.carBody.mapped).toMatchObject({ policyId: 1 });
});
it("rejects an uncovered accident even if re-inquiry returns the expired policy", async () => {
const { service, party, inquiry } = setup();
inquiry.mockResolvedValue({ mapped: party.vehicle.inquiry.carBody.mapped });
await expect(
service.validateCarBodyAccidentCoverage(party, "1401/01/02"),
).rejects.toBeInstanceOf(BadRequestException);
expect(party.insurance.carBodyInsurance.policyId).toBe(2);
});
});
@@ -6,6 +6,7 @@ import {
} from "src/common/dto/inquiry-participants.dto"; } from "src/common/dto/inquiry-participants.dto";
import { import {
isMappedPolicyCurrent, isMappedPolicyCurrent,
isMappedBodyPolicyCovered,
normalizeInquirySubmission, normalizeInquirySubmission,
participantForRole, participantForRole,
participantForStoredPartyRole, participantForStoredPartyRole,
@@ -619,3 +620,30 @@ describe("inquiry participant resolver", () => {
]); ]);
}); });
}); });
describe("car-body mapped policy coverage", () => {
const mapped = { StartDate: "1400/01/01", EndDate: "1401/01/01" };
it.each(["1400/12/28", "1400/01/01", "1401/01/01"])(
"allows historical coverage for %s",
(date) => {
expect(isMappedBodyPolicyCovered(mapped, date)).toBe(true);
},
);
it.each(["1399/12/29", "1401/01/02", "bad-date"])(
"rejects an invalid coverage date %s",
(date) => {
expect(isMappedBodyPolicyCovered(mapped, date)).toBe(false);
},
);
it("defers until the accident date is collected", () => {
expect(isMappedBodyPolicyCovered(mapped)).toBe(true);
});
it("uses the Iran calendar date for timestamp inputs", () => {
expect(
isMappedBodyPolicyCovered(
{ EndDate: "2026-11-20" },
new Date("2026-11-20T22:00:00Z"),
),
).toBe(false);
});
});
@@ -1,3 +1,7 @@
import {
isPolicyActiveOn,
policyAccidentDate,
} from "src/lookups/fanavaran-last-car-policy";
import { BadRequestException } from "@nestjs/common"; import { BadRequestException } from "@nestjs/common";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { jalaliToGregorianDate } from "src/helpers/date-jalali"; import { jalaliToGregorianDate } from "src/helpers/date-jalali";
@@ -456,6 +460,27 @@ export function isMappedPolicyCurrent(
return endDate != null && endDate >= todayGregorian; return endDate != null && endDate >= todayGregorian;
} }
/** Hull inquiry precedes the description in some flows: defer until accidentDate exists. */
export function isMappedBodyPolicyCovered(
mapped: Record<string, any>,
accidentDate?: Date | string | null,
): boolean {
if (accidentDate == null) return true;
const date = policyAccidentDate(accidentDate);
if (!date) return false;
return isPolicyActiveOn(
{
beginDate: mapped?.BeginDate ?? mapped?.StartDate ?? mapped?.startDate,
endDate:
mapped?.EndDate ??
mapped?.HEndDte ??
mapped?.persianEndDate ??
mapped?.endDate,
},
date,
);
}
const LEGACY_INQUIRY_FIELDS = [ const LEGACY_INQUIRY_FIELDS = [
"nationalCodeOfDriver", "nationalCodeOfDriver",
"driverBirthday", "driverBirthday",
@@ -141,6 +141,7 @@ import {
import { import {
InquirySubjects, InquirySubjects,
isMappedPolicyCurrent, isMappedPolicyCurrent,
isMappedBodyPolicyCovered,
NormalizedInquirySubmission, NormalizedInquirySubmission,
normalizeInquirySubmission, normalizeInquirySubmission,
resolveInquirySubjects, resolveInquirySubjects,
@@ -447,8 +448,86 @@ export class RequestManagementService {
}; };
} }
private async validateCarBodyAccidentCoverage(
party: any,
accidentDate: Date | string,
): Promise<void> {
const inquiry = party.vehicle?.inquiry?.carBody;
const mapped = inquiry?.mapped ?? party.insurance?.carBodyInsurance;
if (!mapped) return; // No hull inquiry has been performed yet.
if (isMappedBodyPolicyCovered(mapped, accidentDate)) return;
const policyholderId = party.participantRoles?.carBodyPolicyholder;
const nationalCode =
party.participants?.find(
(participant: any) => participant.participantId === policyholderId,
)?.nationalCode ?? party.person?.nationalCodeOfInsurer;
const plate = {
leftDigits: mapped.platePartOne,
centerAlphabet: mapped.plateLetterTitle,
centerDigits: mapped.platePartThree,
ir: mapped.plateSerialNumber,
};
const vin = party.vehicle?.vin ?? mapped.VinNumberField ?? mapped.vin;
const hasPlate = Object.values(plate).every(
(value) => value != null && value !== "",
);
if (!nationalCode || (!hasPlate && !vin)) {
throw new BadRequestException("بیمه‌نامه بدنه در تاریخ حادثه معتبر نیست.");
}
const refreshed = await this.sandHubService.getCarBodyInquiry({
nationalCodeOfInsurer: nationalCode,
plate: hasPlate ? plate : vin,
accidentDate,
});
if (!isMappedBodyPolicyCovered(refreshed.mapped, accidentDate)) {
throw new BadRequestException("بیمه‌نامه بدنه در تاریخ حادثه معتبر نیست.");
}
party.vehicle ??= {};
party.vehicle.inquiry ??= {};
party.insurance ??= {};
party.vehicle.inquiry.carBody = refreshed;
const m = refreshed.mapped;
party.insurance.carBodyInsurance = {
policyNumber: m.policyNumber ?? null,
policyId: m.policyId ?? null,
contractId: m.contractId ?? null,
companyId: m.companyId ?? null,
companyName: m.CompanyName ?? null,
insurerName: m.insurerName ?? null,
insurerNationalCode: m.insurerNationalCode ?? null,
ownerNationalCode: m.ownerNationalCode ?? null,
ownerName: m.ownerName ?? null,
customerName: m.customerName ?? null,
customerLastName: m.customerLastName ?? null,
customerFatherName: m.customerFatherName ?? null,
customerMobile: m.customerMobile ?? null,
customerAddress: m.customerAddress ?? null,
customerPostalCode: m.customerPostalCode ?? null,
chassisNumber: m.ChassisNumberField ?? null,
vin: m.VinNumberField ?? null,
motorNumber: m.EngineNumberField ?? null,
vehicleGroup: m.vehicleGroupTitle ?? null,
vehicleSystem: m.vehicleSystemTitle ?? null,
vehicleKind: m.vehicleKind ?? null,
builtYear: m.builtYear ?? null,
cylinderCount: m.cylinderCount ?? null,
passengerCount: m.passengerCount ?? null,
usage: m.usage ?? null,
startDate: m.StartDate ?? null,
endDate: m.EndDate ?? null,
issueDate: m.IssueDate ?? null,
vehicleValue: m.vehicleValue ?? null,
totalPremium: m.totalPremium ?? null,
noLossYearsCount: m.noLossYearsCount ?? null,
lossDocuments: m.lossDocuments ?? [],
hasEndorsement: m.hasEndorsement ?? null,
};
}
private async getCarBodyPlateInquiry( private async getCarBodyPlateInquiry(
submission: NormalizedInquirySubmission<Record<string, any>>, submission: NormalizedInquirySubmission<Record<string, any>>,
accidentDate?: Date | string,
): Promise<any> { ): Promise<any> {
const subjects = resolveInquirySubjects(submission); const subjects = resolveInquirySubjects(submission);
const policyholderNationalCode = subjects.carBodyPolicyNationalCode; const policyholderNationalCode = subjects.carBodyPolicyNationalCode;
@@ -464,10 +543,11 @@ export class RequestManagementService {
this.sandHubService.getCarBodyInquiry({ this.sandHubService.getCarBodyInquiry({
nationalCodeOfInsurer: policyholderNationalCode, nationalCodeOfInsurer: policyholderNationalCode,
plate: plate as any, plate: plate as any,
...(accidentDate != null ? { accidentDate } : {}),
}), }),
isUsable: (value) => isUsable: (value) =>
!!value?.mapped && !!value?.mapped &&
isMappedPolicyCurrent(value.mapped) && isMappedBodyPolicyCovered(value.mapped, accidentDate) &&
!!( !!(
value.mapped.policyNumber || value.mapped.policyNumber ||
value.mapped.CompanyName || value.mapped.CompanyName ||
@@ -490,18 +570,20 @@ export class RequestManagementService {
*/ */
private async getCarBodyInquiryForVinSubmission( private async getCarBodyInquiryForVinSubmission(
submission: NormalizedInquirySubmission<Record<string, any>>, submission: NormalizedInquirySubmission<Record<string, any>>,
accidentDate?: Date | string,
): Promise<any> { ): Promise<any> {
if ( if (
submission.vehicle?.registrationState === submission.vehicle?.registrationState ===
VehicleRegistrationState.RECENTLY_TRANSFERRED VehicleRegistrationState.RECENTLY_TRANSFERRED
) { ) {
return this.getCarBodyPlateInquiry(submission); return this.getCarBodyPlateInquiry(submission, accidentDate);
} }
const subjects = resolveInquirySubjects(submission); const subjects = resolveInquirySubjects(submission);
return this.sandHubService.getCarBodyInquiry({ return this.sandHubService.getCarBodyInquiry({
nationalCodeOfInsurer: subjects.carBodyPolicyNationalCode!, nationalCodeOfInsurer: subjects.carBodyPolicyNationalCode!,
plate: submission.vehicle?.vin as any, plate: submission.vehicle?.vin as any,
...(accidentDate != null ? { accidentDate } : {}),
}); });
} }
@@ -2081,7 +2163,10 @@ export class RequestManagementService {
if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) { if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) {
let carBodyInfo: any; let carBodyInfo: any;
try { try {
carBodyInfo = await this.getCarBodyPlateInquiry(inquirySubmission); carBodyInfo = await this.getCarBodyPlateInquiry(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", role, true, { this.recordPartyCaseInquiryStatus(req, "carBody", role, true, {
source: carBodyInfo.source, source: carBodyInfo.source,
plateKind: carBodyInfo.plateKind, plateKind: carBodyInfo.plateKind,
@@ -2510,7 +2595,10 @@ export class RequestManagementService {
if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) { if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) {
try { try {
const carBodyInfo = const carBodyInfo =
await this.getCarBodyInquiryForVinSubmission(inquirySubmission); await this.getCarBodyInquiryForVinSubmission(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", role, true, { this.recordPartyCaseInquiryStatus(req, "carBody", role, true, {
source: carBodyInfo.source, source: carBodyInfo.source,
raw: carBodyInfo.raw, raw: carBodyInfo.raw,
@@ -2871,6 +2959,7 @@ export class RequestManagementService {
accidentDate: body.accidentDate, accidentDate: body.accidentDate,
accidentTime: body.accidentTime, accidentTime: body.accidentTime,
}); });
await this.validateCarBodyAccidentCoverage(party, body.accidentDate);
party.statement.accidentDate = body.accidentDate as any; party.statement.accidentDate = body.accidentDate as any;
party.statement.accidentTime = body.accidentTime; party.statement.accidentTime = body.accidentTime;
(party.statement as any).weatherCondition = body.weatherCondition; (party.statement as any).weatherCondition = body.weatherCondition;
@@ -5093,7 +5182,10 @@ export class RequestManagementService {
let carBodyInquiry: any; let carBodyInquiry: any;
try { try {
carBodyInquiry = await this.getCarBodyPlateInquiry(inquirySubmission); carBodyInquiry = await this.getCarBodyPlateInquiry(
inquirySubmission,
formData.expertDescription?.accidentDate,
);
} catch (error: any) { } catch (error: any) {
this.recordPartyCaseInquiryStatus( this.recordPartyCaseInquiryStatus(
req, req,
@@ -6905,7 +6997,10 @@ export class RequestManagementService {
) { ) {
try { try {
const carBodyInfo = const carBodyInfo =
await this.getCarBodyPlateInquiry(inquirySubmission); await this.getCarBodyPlateInquiry(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, { this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, {
source: carBodyInfo.source, source: carBodyInfo.source,
plateKind: carBodyInfo.plateKind, plateKind: carBodyInfo.plateKind,
@@ -7844,8 +7939,10 @@ export class RequestManagementService {
partyRole === PartyRole.FIRST partyRole === PartyRole.FIRST
) { ) {
try { try {
const carBodyInfo = const carBodyInfo = await this.getCarBodyInquiryForVinSubmission(
await this.getCarBodyInquiryForVinSubmission(inquirySubmission); inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, { this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, {
source: carBodyInfo.source, source: carBodyInfo.source,
raw: carBodyInfo.raw, raw: carBodyInfo.raw,
@@ -8630,6 +8727,9 @@ export class RequestManagementService {
this.assertCarBodyDescriptionMinimum(req.type, body.desc); this.assertCarBodyDescriptionMinimum(req.type, body.desc);
const party = req.parties[idx]; const party = req.parties[idx];
if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) {
await this.validateCarBodyAccidentCoverage(party, body.accidentDate);
}
if (!party.statement) party.statement = {} as any; if (!party.statement) party.statement = {} as any;
party.statement.description = body.desc; party.statement.description = body.desc;
if (body.accidentDate != null) if (body.accidentDate != null)
+20
View File
@@ -37,6 +37,26 @@ describe("SandHubService inquiry mocks", () => {
}, },
} as SandHubDetailDto; } as SandHubDetailDto;
it.each(["IRNKAEK4150012345", userDetail.plate])(
"forwards only accidentDate for dated hull inquiries (%s)",
async (plate) => {
externalInquirySettings.isInquiryLive.mockResolvedValue(true);
lookupsService.findLastProcessedCarPolicy.mockResolvedValue({
policy: {},
vehicle: {},
});
await service.getCarBodyInquiry({
...userDetail,
plate,
accidentDate: "1400/12/28",
});
expect(lookupsService.findLastProcessedCarPolicy).toHaveBeenCalledWith(
"car-body",
expect.objectContaining({ accidentDate: "1400/12/28" }),
);
},
);
beforeEach(() => { beforeEach(() => {
jest.clearAllMocks(); jest.clearAllMocks();
process.env.CLIENT_ID = "8"; process.env.CLIENT_ID = "8";
+7
View File
@@ -35,6 +35,7 @@ import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper";
type CarBodyInquiryDetail = Omit<SandHubDetailDto, "plate"> & { type CarBodyInquiryDetail = Omit<SandHubDetailDto, "plate"> & {
plate: Plates | string; plate: Plates | string;
accidentDate?: Date | string;
}; };
@Injectable() @Injectable()
@@ -1025,6 +1026,9 @@ export class SandHubService {
raw = await this.lookupsService.findLastProcessedCarPolicy("car-body", { raw = await this.lookupsService.findLastProcessedCarPolicy("car-body", {
nationalCode: String(userDetail.nationalCodeOfInsurer), nationalCode: String(userDetail.nationalCodeOfInsurer),
vin: plateOrVin, vin: plateOrVin,
...(userDetail.accidentDate != null
? { accidentDate: userDetail.accidentDate }
: {}),
}); });
} catch (error) { } catch (error) {
this.throwInquiryError(error, "carBodyVin"); this.throwInquiryError(error, "carBodyVin");
@@ -1059,6 +1063,9 @@ export class SandHubService {
plaqueLetter: String(plateOrVin.centerAlphabet), plaqueLetter: String(plateOrVin.centerAlphabet),
plaqueRight: String(plateOrVin.centerDigits), plaqueRight: String(plateOrVin.centerDigits),
plaqueSerial: String(plateOrVin.ir), plaqueSerial: String(plateOrVin.ir),
...(userDetail.accidentDate != null
? { accidentDate: userDetail.accidentDate }
: {}),
}; };
let raw: any; let raw: any;
try { try {