new person registration + car body matching accident date with endDate

This commit is contained in:
2026-11-21 12:47:50 +03:30
parent 5c6e21dd14
commit ab3ae53ec0
8 changed files with 462 additions and 27 deletions
@@ -193,7 +193,6 @@ import { fanavaranAttachmentStatus } from './fanavaran-attachment-status';
import {
actualPremiumFromHullPolicyRecord,
authorityCulpritIdFromDetectionRows,
customerIdFromHullPolicyRecord,
FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION,
FANAVARAN_HULL_CULPRIT_TYPE_CAPTION,
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
@@ -295,6 +294,7 @@ import {
pickPersonBirthday,
pickPersonNationalCode,
selectFanavaranDriverId,
selectFanavaranOtherPersonId,
selectFanavaranOwnerId,
} from './fanavaran-driver-inquiry';
import {
@@ -2570,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. */
private async enrichCarBodyHullBaseClaimPayload(input: {
clientKey: FanavaranClientKey;
@@ -2579,6 +2652,12 @@ export class ClaimRequestManagementService {
firstParty?: { person?: unknown };
logPrefix: string;
claimCaseId?: string;
registerMissingDriver?: boolean;
cachedRegistration?: {
otherPersonId?: number;
otherPersonNationalCode?: string;
otherPersonBirthday?: string;
};
}): Promise<void> {
const policyId = parseFanavaranId(input.payload.PolicyId);
if (policyId == null) return;
@@ -2632,30 +2711,27 @@ export class ClaimRequestManagementService {
const driverIdentity = resolveDriverFromParty(input.firstParty as any);
const nationalCode =
driverIdentity.nationalCode ??
pickPersonNationalCode(person) ??
pickCarBodyPolicyNationalCode(input.blameCase as { parties?: unknown[] });
const birthday = driverIdentity.birthday ?? pickPersonBirthday(person);
let accidentCulpritId: number | null = null;
if (nationalCode && birthday) {
accidentCulpritId = await this.resolveDriverFanavaranId(
input.clientKey,
(person?.driverIsInsurer ? pickPersonNationalCode(person) : null);
const birthday =
driverIdentity.birthday ??
(person?.driverIsInsurer ? pickPersonBirthday(person) : null);
// Always use the actual driver identity; CustomerId identifies the policyholder.
input.payload.AccidentCulpritId = await this.resolveHullDriverFanavaranId({
clientKey: input.clientKey,
person: {
...person,
nationalCodeOfDriver: nationalCode,
nationalCodeOfInsurer: undefined,
nationalCode,
driverBirthday: birthday,
insurerBirthday: undefined,
birthday,
false,
);
}
if (accidentCulpritId == null) {
accidentCulpritId = customerIdFromHullPolicyRecord(policyRecord);
if (accidentCulpritId != null) {
this.logger.log(
`${input.logPrefix} AccidentCulpritId from policy CustomerId=${accidentCulpritId}`,
);
}
}
if (accidentCulpritId != null) {
input.payload.AccidentCulpritId = accidentCulpritId;
}
driverIsInsurer: false,
},
claimCaseId: input.claimCaseId,
registerMissingDriver: input.registerMissingDriver,
cachedRegistration: input.cachedRegistration,
});
input.payload.CulpritLicenceNo = resolveFanavaranLicenceNo(
driverIdentity,
@@ -4236,6 +4312,7 @@ export class ClaimRequestManagementService {
clientKey: FanavaranClientKey;
person: any;
claimCaseId?: string;
requiredRoleId?: 166;
}): Promise<number | null> {
const nationalCode = pickPersonNationalCode(input.person);
const birthday = pickPersonBirthday(input.person);
@@ -4288,6 +4365,10 @@ export class ClaimRequestManagementService {
birthDay: parsedBirthday.day,
},
);
if (input.requiredRoleId === 166) {
const existingId = selectFanavaranOtherPersonId(inquiryRows);
if (existingId != null) return existingId;
}
const parties = asPartyInquiryRows(inquiryRows);
const seedRow =
parties.find(
@@ -4320,10 +4401,11 @@ export class ClaimRequestManagementService {
}
} catch (error) {
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
}`,
);
if (input.requiredRoleId === 166) return null;
}
const lookups = await this.loadFanavaranOtherPeopleLookups(input.clientKey);
@@ -4417,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(
input.clientKey,
nationalCode,
@@ -4541,6 +4640,8 @@ export class ClaimRequestManagementService {
resolvePolicy?: boolean;
/** When true (submit), missing PolicyId throws. Preview keeps payload even if inquiry fails. */
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
* reported in previewWarnings instead of throwing.
@@ -4934,7 +5035,19 @@ export class ClaimRequestManagementService {
firstParty,
logPrefix,
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(
payload,
claimCase,
@@ -6988,6 +7101,7 @@ export class ClaimRequestManagementService {
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true,
registerMissingHullDriver: true,
persistPayload: true,
});
const hull = toFanavaranHullBaseClaimPayload(
@@ -7960,6 +8074,7 @@ export class ClaimRequestManagementService {
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true,
registerMissingHullDriver: true,
auditSession,
persistPayload: true,
forceRefreshPolicy: true,
@@ -90,10 +90,17 @@ export class FanavaranSyncStage {
@Prop({ type: 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 })
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. */
@Prop({ type: 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).
* 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 }),
);
});
});