forked from Yara724/api
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:
@@ -312,7 +312,10 @@ import {
|
||||
resolvePolicyholderFromParty,
|
||||
resolveThirdPartyCulpritTypeId,
|
||||
} from './fanavaran-party-roles';
|
||||
import { selectLatestActiveFanavaranPolicy } from './fanavaran-policy-selection';
|
||||
import {
|
||||
selectLatestActiveFanavaranPolicy,
|
||||
selectFanavaranPolicyForAccident,
|
||||
} from './fanavaran-policy-selection';
|
||||
|
||||
export interface FanavaranAutoSubmitResult {
|
||||
attempted: boolean;
|
||||
@@ -3959,6 +3962,7 @@ export class ClaimRequestManagementService {
|
||||
claimCaseId?: string;
|
||||
product?: FanavaranClaimProduct;
|
||||
insuranceLineId?: number;
|
||||
accidentDate?: Date | string;
|
||||
},
|
||||
): Promise<number | null> {
|
||||
const clientKey =
|
||||
@@ -4024,7 +4028,10 @@ export class ClaimRequestManagementService {
|
||||
this.logger.log(
|
||||
`${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(
|
||||
`${logPrefix} Selected latest active policy PolicyId=${selectedPolicy.policyId} EndDate=${selectedPolicy.endDate}`,
|
||||
);
|
||||
@@ -4719,7 +4726,12 @@ export class ClaimRequestManagementService {
|
||||
profile.auth,
|
||||
logPrefix,
|
||||
auditSession,
|
||||
{ clientKey, claimCaseId, product: 'car-body' },
|
||||
{
|
||||
clientKey,
|
||||
claimCaseId,
|
||||
product: 'car-body',
|
||||
accidentDate: firstParty?.statement?.accidentDate,
|
||||
},
|
||||
);
|
||||
debug.values.policyId = policyId;
|
||||
debug.steps.policyInquirySucceeded = policyId !== null;
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { BadRequestException } from "@nestjs/common";
|
||||
import { selectLatestActiveFanavaranPolicy } from "./fanavaran-policy-selection";
|
||||
import {
|
||||
selectLatestActiveFanavaranPolicy,
|
||||
selectFanavaranPolicyForAccident,
|
||||
} from "./fanavaran-policy-selection";
|
||||
|
||||
describe("selectLatestActiveFanavaranPolicy", () => {
|
||||
const today = "2026-06-30";
|
||||
@@ -61,3 +64,29 @@ describe("selectLatestActiveFanavaranPolicy", () => {
|
||||
).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 { jalaliToGregorianDate } from "src/helpers/date-jalali";
|
||||
import { gregorianDateInIran } from "src/helpers/iran-datetime";
|
||||
@@ -93,3 +98,34 @@ export function selectLatestActiveFanavaranPolicy(
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
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";
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/** 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 {
|
||||
if (!vehicle) return "";
|
||||
for (const key of ["VIN", "Vin", "VinNo", "vin", "ChassisNo", "chassisNo"]) {
|
||||
|
||||
@@ -874,6 +874,13 @@ export class LookupsController {
|
||||
@ApiQuery({ name: "plaqueLetter", required: false, example: "ب" })
|
||||
@ApiQuery({ name: "plaqueRight", required: false, example: "345" })
|
||||
@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({
|
||||
description: "Mapped last body policy plus vehicle",
|
||||
schema: { type: "object" },
|
||||
@@ -885,9 +892,11 @@ export class LookupsController {
|
||||
@Query("plaqueLetter") plaqueLetter?: string,
|
||||
@Query("plaqueRight") plaqueRight?: string,
|
||||
@Query("plaqueSerial") plaqueSerial?: string,
|
||||
@Query("accidentDate") accidentDate?: string,
|
||||
) {
|
||||
return this.lookupsService.findLastProcessedCarPolicy("car-body", {
|
||||
nationalCode,
|
||||
accidentDate,
|
||||
vin,
|
||||
plaqueLeft,
|
||||
plaqueLetter,
|
||||
|
||||
@@ -13,13 +13,17 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
|
||||
});
|
||||
|
||||
function createService(lookup: Record<string, jest.Mock>) {
|
||||
return new LookupsService({} as any, lookup as any, {
|
||||
countDocuments: jest.fn().mockResolvedValue(1),
|
||||
getLatestSyncedAt: jest.fn().mockResolvedValue(new Date()),
|
||||
findAllPublic: jest.fn().mockResolvedValue([]),
|
||||
searchActiveByCaption: jest.fn().mockResolvedValue([]),
|
||||
replaceAllFromFanavaran: jest.fn().mockResolvedValue(0),
|
||||
} as any);
|
||||
return new LookupsService(
|
||||
{} as any,
|
||||
lookup as any,
|
||||
{
|
||||
countDocuments: jest.fn().mockResolvedValue(1),
|
||||
getLatestSyncedAt: jest.fn().mockResolvedValue(new Date()),
|
||||
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 () => {
|
||||
@@ -44,7 +48,9 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
|
||||
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) =>
|
||||
Promise.resolve({
|
||||
PolicyId: policyId,
|
||||
@@ -138,45 +144,124 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
|
||||
expect(lookup.inquiryByVin).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects an expired car-body policy instead of treating it as active coverage", async () => {
|
||||
const lookup = {
|
||||
myPolicies: jest.fn().mockResolvedValue([
|
||||
{
|
||||
it.each(["1400/12/28", "1400/01/01", "1401/01/01", undefined])(
|
||||
"allows a covered accident date %s or defers an undated inquiry",
|
||||
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,
|
||||
InsuranceLineId: 4,
|
||||
VehicleId: 8,
|
||||
BeginDate: "1400/01/01",
|
||||
EndDate: "1401/01/01",
|
||||
},
|
||||
]),
|
||||
inquiryByVin: jest.fn(),
|
||||
bodyPolicyById: jest.fn().mockResolvedValue({
|
||||
PolicyId: 44,
|
||||
}),
|
||||
vehicleById: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ Id: 8, VIN: "IRNKAEK4150012345" }),
|
||||
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,
|
||||
},
|
||||
{
|
||||
PolicyId: 44,
|
||||
InsuranceLineId: 4,
|
||||
BeginDate: "1400/01/01",
|
||||
EndDate: "1401/01/01",
|
||||
}),
|
||||
vehicleById: jest.fn().mockResolvedValue({
|
||||
Id: 8,
|
||||
PlaqueLeftNo: "12",
|
||||
PlaqueMiddleCodeId: 2,
|
||||
PlaqueRightNo: "345",
|
||||
PlaqueSerial: "67",
|
||||
}),
|
||||
VehicleId: 8,
|
||||
},
|
||||
];
|
||||
const lookup = {
|
||||
myPolicies: jest.fn().mockResolvedValue(policies),
|
||||
bodyPolicyById: jest
|
||||
.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([]),
|
||||
customerById: jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
|
||||
await expect(
|
||||
createService(lookup).findLastProcessedCarPolicy("car-body", {
|
||||
nationalCode: "0012345678",
|
||||
plaqueLeft: "12",
|
||||
plaqueLetter: "ب",
|
||||
plaqueRight: "345",
|
||||
plaqueSerial: "67",
|
||||
vin: "IRNKAEK4150012345",
|
||||
accidentDate: "1400/12/28",
|
||||
}),
|
||||
).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 () => {
|
||||
const lookup = {
|
||||
myPolicies: jest.fn().mockResolvedValue([
|
||||
@@ -187,9 +272,9 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
|
||||
EndDate: "1406/01/01",
|
||||
},
|
||||
]),
|
||||
inquiryByVin: jest.fn().mockResolvedValue([
|
||||
{ Id: 4118289, VIN: "NAAR03HFFRDE07024" },
|
||||
]),
|
||||
inquiryByVin: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ Id: 4118289, VIN: "NAAR03HFFRDE07024" }]),
|
||||
bodyPolicyById: jest.fn().mockResolvedValue({
|
||||
PolicyId: 15292336,
|
||||
VehicleId: 4118289,
|
||||
@@ -226,7 +311,9 @@ describe("LookupsService.findLastProcessedCarPolicy", () => {
|
||||
EndDate: "1406/01/01",
|
||||
},
|
||||
]),
|
||||
inquiryByVin: jest.fn().mockResolvedValue([{ Id: 99, VIN: "IRNKAEK4150012345" }]),
|
||||
inquiryByVin: jest
|
||||
.fn()
|
||||
.mockResolvedValue([{ Id: 99, VIN: "IRNKAEK4150012345" }]),
|
||||
thirdPartyPolicyById: jest.fn().mockResolvedValue({
|
||||
PolicyId: 10,
|
||||
VehicleId: 1,
|
||||
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
insuranceLineIdForProduct,
|
||||
insuranceLineLabel,
|
||||
isPolicyActiveOn,
|
||||
policyAccidentDate,
|
||||
parseFanavaranId,
|
||||
parseLastCarPolicyInput,
|
||||
pickVehicleId,
|
||||
@@ -45,7 +46,6 @@ import {
|
||||
isVehicleKindsSyncStale,
|
||||
VEHICLE_KINDS_REFRESH_MS,
|
||||
} from "./vehicle-kind-search";
|
||||
import { gregorianDateInIran } from "src/helpers/iran-datetime";
|
||||
import { normalizeDrivingLicenceTypes, type DrivingLicenceType } from "./driving-licence-types";
|
||||
|
||||
type TejaratAccidentReasonRow = {
|
||||
@@ -612,6 +612,7 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
|
||||
product: FanavaranCarPolicyProduct,
|
||||
query: {
|
||||
nationalCode?: string;
|
||||
accidentDate?: Date | string;
|
||||
vin?: string;
|
||||
plaqueLeft?: string;
|
||||
plaqueLetter?: string;
|
||||
@@ -632,6 +633,11 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
|
||||
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 insuranceLineId = insuranceLineIdForProduct(product);
|
||||
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 (candidates.length === 0) {
|
||||
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
|
||||
// selector may intentionally return the latest expired policy for history;
|
||||
// that fallback is not valid for a new CAR_BODY case.
|
||||
// Before the description step the accident date may not be known yet.
|
||||
// Retrieve the policy now; validate coverage when that date is supplied.
|
||||
if (
|
||||
product === "car-body" &&
|
||||
!isPolicyActiveOn(selected, gregorianDateInIran(new Date()))
|
||||
accidentDate &&
|
||||
!isPolicyActiveOn(selected, accidentDate)
|
||||
) {
|
||||
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";
|
||||
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)
|
||||
|
||||
@@ -37,6 +37,26 @@ describe("SandHubService inquiry mocks", () => {
|
||||
},
|
||||
} 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(() => {
|
||||
jest.clearAllMocks();
|
||||
process.env.CLIENT_ID = "8";
|
||||
|
||||
@@ -35,6 +35,7 @@ import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper";
|
||||
|
||||
type CarBodyInquiryDetail = Omit<SandHubDetailDto, "plate"> & {
|
||||
plate: Plates | string;
|
||||
accidentDate?: Date | string;
|
||||
};
|
||||
|
||||
@Injectable()
|
||||
@@ -1025,6 +1026,9 @@ export class SandHubService {
|
||||
raw = await this.lookupsService.findLastProcessedCarPolicy("car-body", {
|
||||
nationalCode: String(userDetail.nationalCodeOfInsurer),
|
||||
vin: plateOrVin,
|
||||
...(userDetail.accidentDate != null
|
||||
? { accidentDate: userDetail.accidentDate }
|
||||
: {}),
|
||||
});
|
||||
} catch (error) {
|
||||
this.throwInquiryError(error, "carBodyVin");
|
||||
@@ -1059,6 +1063,9 @@ export class SandHubService {
|
||||
plaqueLetter: String(plateOrVin.centerAlphabet),
|
||||
plaqueRight: String(plateOrVin.centerDigits),
|
||||
plaqueSerial: String(plateOrVin.ir),
|
||||
...(userDetail.accidentDate != null
|
||||
? { accidentDate: userDetail.accidentDate }
|
||||
: {}),
|
||||
};
|
||||
let raw: any;
|
||||
try {
|
||||
|
||||
Reference in New Issue
Block a user