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.
This commit is contained in:
2026-11-21 12:04:09 +03:30
parent 8f15040080
commit 5c6e21dd14
13 changed files with 499 additions and 56 deletions
@@ -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";
import {
isMappedPolicyCurrent,
isMappedBodyPolicyCovered,
normalizeInquirySubmission,
participantForRole,
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 { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { jalaliToGregorianDate } from "src/helpers/date-jalali";
@@ -456,6 +460,27 @@ export function isMappedPolicyCurrent(
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 = [
"nationalCodeOfDriver",
"driverBirthday",
@@ -141,6 +141,7 @@ import {
import {
InquirySubjects,
isMappedPolicyCurrent,
isMappedBodyPolicyCovered,
NormalizedInquirySubmission,
normalizeInquirySubmission,
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(
submission: NormalizedInquirySubmission<Record<string, any>>,
accidentDate?: Date | string,
): Promise<any> {
const subjects = resolveInquirySubjects(submission);
const policyholderNationalCode = subjects.carBodyPolicyNationalCode;
@@ -464,10 +543,11 @@ export class RequestManagementService {
this.sandHubService.getCarBodyInquiry({
nationalCodeOfInsurer: policyholderNationalCode,
plate: plate as any,
...(accidentDate != null ? { accidentDate } : {}),
}),
isUsable: (value) =>
!!value?.mapped &&
isMappedPolicyCurrent(value.mapped) &&
isMappedBodyPolicyCovered(value.mapped, accidentDate) &&
!!(
value.mapped.policyNumber ||
value.mapped.CompanyName ||
@@ -490,18 +570,20 @@ export class RequestManagementService {
*/
private async getCarBodyInquiryForVinSubmission(
submission: NormalizedInquirySubmission<Record<string, any>>,
accidentDate?: Date | string,
): Promise<any> {
if (
submission.vehicle?.registrationState ===
VehicleRegistrationState.RECENTLY_TRANSFERRED
) {
return this.getCarBodyPlateInquiry(submission);
return this.getCarBodyPlateInquiry(submission, accidentDate);
}
const subjects = resolveInquirySubjects(submission);
return this.sandHubService.getCarBodyInquiry({
nationalCodeOfInsurer: subjects.carBodyPolicyNationalCode!,
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) {
let carBodyInfo: any;
try {
carBodyInfo = await this.getCarBodyPlateInquiry(inquirySubmission);
carBodyInfo = await this.getCarBodyPlateInquiry(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", role, true, {
source: carBodyInfo.source,
plateKind: carBodyInfo.plateKind,
@@ -2510,7 +2595,10 @@ export class RequestManagementService {
if (req.type === BlameRequestType.CAR_BODY && role === PartyRole.FIRST) {
try {
const carBodyInfo =
await this.getCarBodyInquiryForVinSubmission(inquirySubmission);
await this.getCarBodyInquiryForVinSubmission(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", role, true, {
source: carBodyInfo.source,
raw: carBodyInfo.raw,
@@ -2871,6 +2959,7 @@ export class RequestManagementService {
accidentDate: body.accidentDate,
accidentTime: body.accidentTime,
});
await this.validateCarBodyAccidentCoverage(party, body.accidentDate);
party.statement.accidentDate = body.accidentDate as any;
party.statement.accidentTime = body.accidentTime;
(party.statement as any).weatherCondition = body.weatherCondition;
@@ -5093,7 +5182,10 @@ export class RequestManagementService {
let carBodyInquiry: any;
try {
carBodyInquiry = await this.getCarBodyPlateInquiry(inquirySubmission);
carBodyInquiry = await this.getCarBodyPlateInquiry(
inquirySubmission,
formData.expertDescription?.accidentDate,
);
} catch (error: any) {
this.recordPartyCaseInquiryStatus(
req,
@@ -6905,7 +6997,10 @@ export class RequestManagementService {
) {
try {
const carBodyInfo =
await this.getCarBodyPlateInquiry(inquirySubmission);
await this.getCarBodyPlateInquiry(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, {
source: carBodyInfo.source,
plateKind: carBodyInfo.plateKind,
@@ -7844,8 +7939,10 @@ export class RequestManagementService {
partyRole === PartyRole.FIRST
) {
try {
const carBodyInfo =
await this.getCarBodyInquiryForVinSubmission(inquirySubmission);
const carBodyInfo = await this.getCarBodyInquiryForVinSubmission(
inquirySubmission,
party.statement?.accidentDate,
);
this.recordPartyCaseInquiryStatus(req, "carBody", partyRole, true, {
source: carBodyInfo.source,
raw: carBodyInfo.raw,
@@ -8628,6 +8725,9 @@ export class RequestManagementService {
if (idx === -1) throw new BadRequestException(`${role} party not found`);
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;
party.statement.description = body.desc;
if (body.accidentDate != null)