diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index b561ed0..bd79933 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -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 { 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; diff --git a/src/claim-request-management/fanavaran-policy-selection.spec.ts b/src/claim-request-management/fanavaran-policy-selection.spec.ts index 6759ab2..74e02cd 100644 --- a/src/claim-request-management/fanavaran-policy-selection.spec.ts +++ b/src/claim-request-management/fanavaran-policy-selection.spec.ts @@ -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, + ); + }, + ); +}); diff --git a/src/claim-request-management/fanavaran-policy-selection.ts b/src/claim-request-management/fanavaran-policy-selection.ts index d9e38cd..309c639 100644 --- a/src/claim-request-management/fanavaran-policy-selection.ts +++ b/src/claim-request-management/fanavaran-policy-selection.ts @@ -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); +} diff --git a/src/lookups/fanavaran-last-car-policy.ts b/src/lookups/fanavaran-last-car-policy.ts index ce5e1e4..d756c4b 100644 --- a/src/lookups/fanavaran-last-car-policy.ts +++ b/src/lookups/fanavaran-last-car-policy.ts @@ -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 | null): string { if (!vehicle) return ""; for (const key of ["VIN", "Vin", "VinNo", "vin", "ChassisNo", "chassisNo"]) { diff --git a/src/lookups/lookups.controller.ts b/src/lookups/lookups.controller.ts index bcf3919..c656d4d 100644 --- a/src/lookups/lookups.controller.ts +++ b/src/lookups/lookups.controller.ts @@ -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, diff --git a/src/lookups/lookups.service.last-car-policy.spec.ts b/src/lookups/lookups.service.last-car-policy.spec.ts index 227f2d2..8dfe125 100644 --- a/src/lookups/lookups.service.last-car-policy.spec.ts +++ b/src/lookups/lookups.service.last-car-policy.spec.ts @@ -13,13 +13,17 @@ describe("LookupsService.findLastProcessedCarPolicy", () => { }); function createService(lookup: Record) { - 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, diff --git a/src/lookups/lookups.service.ts b/src/lookups/lookups.service.ts index 18cf2fe..c29a933 100644 --- a/src/lookups/lookups.service.ts +++ b/src/lookups/lookups.service.ts @@ -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.", ); } diff --git a/src/request-management/car-body-accident-coverage.spec.ts b/src/request-management/car-body-accident-coverage.spec.ts new file mode 100644 index 0000000..ebabc09 --- /dev/null +++ b/src/request-management/car-body-accident-coverage.spec.ts @@ -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); + }); +}); diff --git a/src/request-management/inquiry-participant-resolver.spec.ts b/src/request-management/inquiry-participant-resolver.spec.ts index 5b1ef8a..e4aa21c 100644 --- a/src/request-management/inquiry-participant-resolver.spec.ts +++ b/src/request-management/inquiry-participant-resolver.spec.ts @@ -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); + }); +}); diff --git a/src/request-management/inquiry-participant-resolver.ts b/src/request-management/inquiry-participant-resolver.ts index 4eb549c..76d5520 100644 --- a/src/request-management/inquiry-participant-resolver.ts +++ b/src/request-management/inquiry-participant-resolver.ts @@ -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, + 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", diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index c05aea2..997d0fe 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -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 { + 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>, + accidentDate?: Date | string, ): Promise { 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>, + accidentDate?: Date | string, ): Promise { 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) diff --git a/src/sand-hub/sand-hub.service.spec.ts b/src/sand-hub/sand-hub.service.spec.ts index 82a5273..0702be3 100644 --- a/src/sand-hub/sand-hub.service.spec.ts +++ b/src/sand-hub/sand-hub.service.spec.ts @@ -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"; diff --git a/src/sand-hub/sand-hub.service.ts b/src/sand-hub/sand-hub.service.ts index 6981254..6dec062 100644 --- a/src/sand-hub/sand-hub.service.ts +++ b/src/sand-hub/sand-hub.service.ts @@ -35,6 +35,7 @@ import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper"; type CarBodyInquiryDetail = Omit & { 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 {