fix(licence): validate driving licence IDs and preserve verified captions

This commit is contained in:
SepehrYahyaee
2026-10-03 15:08:16 +03:30
parent b20250b4b3
commit d9a8ec4b2f
11 changed files with 319 additions and 7 deletions
@@ -661,7 +661,7 @@ function buildParticipantRolesSection(
? `${PR.licenseType}: ${asString(
persianReportValue(
"participant.licenseType",
participant.licenseType,
participant.licenseTypeLabel ?? participant.licenseType,
),
)}`
: undefined,
@@ -725,7 +725,7 @@ function buildDriverSection(
asString(
persianReportValue(
"participant.licenseType",
licenseType ?? person.licenseType,
person.licenseTypeLabel ?? person.licenseType ?? licenseType,
),
) ??
(person.driverLicense ? PR.driverLicense : undefined),
@@ -291,9 +291,6 @@ const INQUIRY_ERROR_LABELS: Record<string, string> = {
};
const LICENSE_TYPE_LABELS: Record<string, string> = {
"1": "پایه یک",
"2": "پایه دو",
"3": "پایه سه",
BASE_1: "پایه یک",
BASE1: "پایه یک",
GRADE_1: "پایه یک",
+70
View File
@@ -0,0 +1,70 @@
import {
BadRequestException,
ServiceUnavailableException,
} from "@nestjs/common";
import {
normalizeDrivingLicenceTypes,
selectedDrivingLicenceType,
} from "./driving-licence-types";
import { LookupsService } from "./lookups.service";
const types = [
{ Id: 3, Caption: "ریلی", IsActive: 1 },
{ Id: 10, Caption: "پایه ۳", IsActive: 1 },
{ Id: 20, Caption: "غیرفعال", IsActive: 0 },
];
describe("canonical driving licence types", () => {
it.each([types, { data: types }, { data: { data: types } }, { Data: types }])(
"preserves provider IDs and captions across lookup envelopes",
(payload) => {
const normalized = normalizeDrivingLicenceTypes(payload);
expect(normalized).toEqual(types);
expect(selectedDrivingLicenceType("10", normalized).Caption).toBe(
"پایه ۳",
);
expect(selectedDrivingLicenceType("3", normalized).Caption).toBe("ریلی");
},
);
it.each(["پایه ۳", "BASE_3", "999", "20", "undefined"])(
"rejects unverified or inactive selection %s",
(value) => {
expect(() => selectedDrivingLicenceType(value, types)).toThrow(
BadRequestException,
);
},
);
it.each([
[],
{},
[{ Id: 3, Caption: "" }],
[{ Id: "invalid", Caption: "پایه ۳" }],
])(
"fails rather than inventing options for an unusable lookup",
(payload) => {
expect(() => normalizeDrivingLicenceTypes(payload)).toThrow(
ServiceUnavailableException,
);
},
);
it("rejects contradictory captions for the same ID", () => {
expect(() =>
normalizeDrivingLicenceTypes([
types[0],
{ ...types[0], Caption: "پایه ۳" },
]),
).toThrow(ServiceUnavailableException);
});
it("uses the existing tenant-specific remote/cache lookup", async () => {
const service = new LookupsService({} as any, {} as any, {} as any);
const lookup = jest
.spyOn(service, "getClientRemoteLookup")
.mockResolvedValue({ data: types });
expect(await service.getDrivingLicenceTypes()).toEqual(types);
expect(lookup).toHaveBeenCalledWith("driving-licence-types");
});
});
+60
View File
@@ -0,0 +1,60 @@
import {
BadRequestException,
ServiceUnavailableException,
} from "@nestjs/common";
export interface DrivingLicenceType {
Id: number;
Caption: string;
IsActive: number;
}
export function normalizeDrivingLicenceTypes(
payload: unknown,
): DrivingLicenceType[] {
let rows = payload;
for (let depth = 0; depth < 4 && !Array.isArray(rows); depth++) {
if (!rows || typeof rows !== "object") break;
const record = rows as Record<string, unknown>;
rows = record.data ?? record.Data;
}
const byId = new Map<number, DrivingLicenceType>();
for (const row of Array.isArray(rows) ? rows : []) {
if (!row || typeof row !== "object") continue;
const Id = Number(row.Id);
const Caption = typeof row.Caption === "string" ? row.Caption.trim() : "";
if (!Number.isSafeInteger(Id) || Id <= 0 || !Caption) continue;
if (byId.has(Id) && byId.get(Id)!.Caption !== Caption) {
throw new ServiceUnavailableException(
"فهرست انواع گواهینامه دارای کدهای متناقض است.",
);
}
byId.set(Id, {
Id,
Caption,
IsActive: row.IsActive == null ? 1 : Number(row.IsActive) === 0 ? 0 : 1,
});
}
if (!byId.size) {
throw new ServiceUnavailableException(
"فهرست انواع گواهینامه در دسترس نیست؛ دوباره تلاش کنید.",
);
}
return [...byId.values()];
}
export function selectedDrivingLicenceType(
value: unknown,
types: DrivingLicenceType[],
): DrivingLicenceType {
const code = String(value ?? "").trim();
const selected = types.find(
(item) => String(item.Id) === code && item.IsActive !== 0,
);
if (!selected) {
throw new BadRequestException(
"نوع گواهینامه را از فهرست استعلام‌شده انتخاب کنید.",
);
}
return selected;
}
+5 -2
View File
@@ -45,6 +45,7 @@ import {
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 = {
id: number;
@@ -188,8 +189,10 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy {
return await this.getClientRemoteLookup("dmg-pay-method");
}
async getDrivingLicenceTypes(): Promise<any> {
return await this.getClientRemoteLookup("driving-licence-types");
async getDrivingLicenceTypes(): Promise<DrivingLicenceType[]> {
return normalizeDrivingLicenceTypes(
await this.getClientRemoteLookup("driving-licence-types"),
);
}
async getAccidentCulpritType(): Promise<any> {
@@ -26,6 +26,8 @@ export class Person {
@Prop() driverLicenseDate?: string;
/** Driving licence type code from the Fanavaran lookup (GET /lookups/driving-licence-types). */
@Prop() licenseType?: string;
/** Server-verified caption at selection time; the provider ID remains licenseType. */
@Prop() licenseTypeLabel?: string;
@Prop({ type: Boolean })
driverIsInsurer?: boolean;
@@ -67,6 +69,7 @@ export class InquiryParticipant {
@Prop({ type: Boolean }) hasDrivingLicense?: boolean;
@Prop() licenseNumber?: string;
@Prop() licenseType?: string;
@Prop() licenseTypeLabel?: string;
@Prop() driverLicenseDate?: string;
}
export const InquiryParticipantSchema =
@@ -18,6 +18,7 @@ export interface ResolvedInquiryParticipant {
hasDrivingLicense?: boolean;
licenseNumber?: string;
licenseType?: string;
licenseTypeLabel?: string;
driverLicenseDate?: string;
}
@@ -41,6 +42,7 @@ export interface NormalizedInquirySubmission<T extends Record<string, any>> {
driverLicense?: string;
driverLicenseDate?: string;
licenseType?: string;
licenseTypeLabel?: string;
userNoCertificate?: boolean;
nationalCodeOfInsurer: string;
insurerBirthday: string;
@@ -0,0 +1,131 @@
import { model } from "mongoose";
import { RequestManagementService } from "./request-management.service";
import { normalizeInquirySubmission } from "./inquiry-participant-resolver";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import {
BlameRequest,
BlameRequestSchema,
} from "./entities/schema/blame-cases.schema";
import { persianReportValue } from "src/case-expert-report/persian-report-labels";
describe("licence selection integrity", () => {
const types = [
{ Id: 3, Caption: "ریلی", IsActive: 1 },
{ Id: 10, Caption: "پایه ۳", IsActive: 1 },
];
const input = (licenseType = "10", hasDrivingLicense = true) => ({
driver: {
nationalCode: "0022324224",
birthday: "1378/04/26",
hasDrivingLicense,
...(hasDrivingLicense
? {
licenseType,
licenseNumber: "1001011111",
driverLicenseDate: "1400/01/01",
}
: {}),
},
vehicleOwner: { sameAs: "DRIVER" },
thirdPartyPolicyholder: { sameAs: "DRIVER" },
vehicle: {
currentPlate: {
leftDigits: "59",
centerAlphabet: "ی",
centerDigits: "419",
ir: "78",
},
isNewCar: false,
},
});
const service = () => {
const instance = Object.create(RequestManagementService.prototype) as any;
instance.lookupsService = {
getDrivingLicenceTypes: jest.fn().mockResolvedValue(types),
};
return instance;
};
it.each([BlameRequestType.THIRD_PARTY, BlameRequestType.CAR_BODY])(
"keeps the selected provider ID and verified caption through normalization and persistence for %s",
async (caseType) => {
const submission = normalizeInquirySubmission(caseType, {
...input(),
...(caseType === BlameRequestType.CAR_BODY
? { carBodyPolicyholder: { sameAs: "DRIVER" } }
: {}),
});
await service().validateDrivingLicenceType(submission);
expect(submission.driver.licenseType).toBe("10");
expect(submission.driver.licenseTypeLabel).toBe("پایه ۳");
expect(submission.dto.licenseTypeLabel).toBe("پایه ۳");
expect(
submission.participants.participants.find(
(p) => p.participantId === submission.driver.participantId,
)?.licenseTypeLabel,
).toBe("پایه ۳");
const RequestModel = model<BlameRequest>(
`LicenceTypePersistence${caseType}`,
BlameRequestSchema,
);
const request = new RequestModel({
requestNo: "BL-LICENCE",
publicId: "LICENCE",
type: caseType,
parties: [
{
role: "FIRST",
person: {
licenseType: submission.dto.licenseType,
licenseTypeLabel: submission.dto.licenseTypeLabel,
},
participants: submission.participants.participants,
participantRoles: submission.participants.roles,
},
],
});
expect(request.validateSync()).toBeUndefined();
expect(request.toObject().parties[0].participants?.[0].licenseType).toBe(
"10",
);
expect(
request.toObject().parties[0].participants?.[0].licenseTypeLabel,
).toBe("پایه ۳");
expect(request.toObject().parties[0].person.licenseTypeLabel).toBe(
"پایه ۳",
);
},
);
it("rejects IDs absent from the canonical lookup before inquiry work", async () => {
const submission = normalizeInquirySubmission(
BlameRequestType.THIRD_PARTY,
input("999"),
);
await expect(
service().validateDrivingLicenceType(submission),
).rejects.toThrow("فهرست استعلام‌شده");
expect(submission.driver.licenseTypeLabel).toBeUndefined();
});
it("does not require a lookup for a driver without a licence", async () => {
const instance = service();
const submission = normalizeInquirySubmission(
BlameRequestType.THIRD_PARTY,
input("", false),
);
await instance.validateDrivingLicenceType(submission);
expect(
instance.lookupsService.getDrivingLicenceTypes,
).not.toHaveBeenCalled();
});
it("does not guess numeric meanings in reports", () => {
expect(persianReportValue("participant.licenseType", "3")).toBe("3");
expect(persianReportValue("participant.licenseType", "BASE_3")).toBe(
"پایه سه",
);
});
});
@@ -10,6 +10,7 @@ import { BlameRequestDbService } from "src/request-management/entities/db-servic
import { SandHubModule } from "src/sand-hub/sand-hub.module";
import { UsersModule } from "src/users/users.module";
import { FanavaranLookupModule } from "src/fanavaran/fanavaran-lookup.module";
import { LookupsModule } from "src/lookups/lookups.module";
import { CronModule } from "src/utils/cron/cron.module";
import { PublicIdModule } from "src/utils/public-id/public-id.module";
import { HashModule } from "src/utils/hash/hash.module";
@@ -66,6 +67,7 @@ import { CallCenterBlameV6Controller } from "./call-center-blame-v6.controller";
WorkflowStepManagementModule,
PlatesModule,
FanavaranLookupModule,
LookupsModule,
MulterModule.register({
dest: "./files/video",
}),
@@ -13,6 +13,8 @@ import {
import { ExternalExceptionFilter } from "@nestjs/core/exceptions/external-exception-filter";
import { Types } from "mongoose";
import { ClientService } from "src/client/client.service";
import { LookupsService } from "src/lookups/lookups.service";
import { selectedDrivingLicenceType } from "src/lookups/driving-licence-types";
import { AddPlateDto } from "src/profile/dto/user/AddPlateDto";
import { VehicleRegistrationState } from "src/common/dto/inquiry-participants.dto";
import {
@@ -372,6 +374,19 @@ export class RequestManagementService {
return normalizeInquirySubmission(type, input);
}
private async validateDrivingLicenceType(
submission: NormalizedInquirySubmission<Record<string, any>>,
): Promise<void> {
if (submission.driver.hasDrivingLicense !== true) return;
const selected = selectedDrivingLicenceType(
submission.driver.licenseType,
await this.lookupsService.getDrivingLicenceTypes(),
);
// Store the provider ID unchanged and a server-verified caption for display.
submission.driver.licenseTypeLabel = selected.Caption;
submission.dto.licenseTypeLabel = selected.Caption;
}
private applyInquiryParticipantsToParty(
party: any,
submission: NormalizedInquirySubmission<Record<string, any>>,
@@ -1163,6 +1178,7 @@ export class RequestManagementService {
private readonly fanavaranLocationService: FanavaranLocationService,
private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService,
private readonly lookupsService: LookupsService,
) {}
async assertFileReviewerBranchAccess(
@@ -1857,6 +1873,7 @@ export class RequestManagementService {
req.type,
body,
);
await this.validateDrivingLicenceType(inquirySubmission);
body = inquirySubmission.dto as unknown as AddPlateDto;
this.applyInquiryParticipantsToParty(party, inquirySubmission);
@@ -2304,6 +2321,7 @@ export class RequestManagementService {
req.type,
body,
);
await this.validateDrivingLicenceType(inquirySubmission);
body = inquirySubmission.dto as unknown as InitialFormVinDto;
const subjects = resolveInquirySubjects(inquirySubmission);
this.applyInquiryParticipantsToParty(party, inquirySubmission);
@@ -3822,6 +3840,7 @@ export class RequestManagementService {
request.type as BlameRequestType,
body,
);
await this.validateDrivingLicenceType(inquirySubmission);
body = inquirySubmission.dto as unknown as AddPlateDto;
if (!isFirstParty) {
@@ -7207,6 +7226,7 @@ export class RequestManagementService {
req.type,
formData.firstPartyPlate,
);
await this.validateDrivingLicenceType(inquirySubmission);
this.recordInquiryParticipantContext(
req,
PartyRole.FIRST,
@@ -7538,6 +7558,7 @@ export class RequestManagementService {
req.type,
plateDto,
);
await this.validateDrivingLicenceType(inquirySubmission);
this.recordInquiryParticipantContext(req, role, inquirySubmission);
const existingPartyIndex = this.getPartyIndex(req, role);
if (existingPartyIndex !== -1) {
@@ -8324,6 +8345,7 @@ export class RequestManagementService {
BlameRequestType.THIRD_PARTY,
formData.firstPartyPlate,
);
await this.validateDrivingLicenceType(firstInquirySubmission);
const firstPartyPlate = firstInquirySubmission.dto;
let firstPolicyInquiry: any;
try {
@@ -8464,6 +8486,7 @@ export class RequestManagementService {
BlameRequestType.THIRD_PARTY,
formData.secondParty.plate,
);
await this.validateDrivingLicenceType(secondInquirySubmission);
let secondPolicyInquiry: any;
try {
const secondPartyPlate = secondInquirySubmission.dto;
@@ -8819,6 +8842,7 @@ export class RequestManagementService {
BlameRequestType.CAR_BODY,
formData.firstPartyPlate,
);
await this.validateDrivingLicenceType(firstInquirySubmission);
const firstPartyPlate = firstInquirySubmission.dto;
let thirdPartyPolicyInquiry: any;
let carBodyInquiry: any;
@@ -10071,6 +10095,7 @@ export class RequestManagementService {
req.type,
partyData,
);
await this.validateDrivingLicenceType(inquirySubmission);
partyData = inquirySubmission.dto as RunInquiriesV3Dto;
const subjects = resolveInquirySubjects(inquirySubmission);
this.applyInquiryParticipantsToParty(party, inquirySubmission);
@@ -10224,6 +10249,7 @@ export class RequestManagementService {
party.person.driverLicenseDate = (partyData as any).driverLicenseDate;
if ((partyData as any).licenseType)
(party.person as any).licenseType = (partyData as any).licenseType;
(party.person as any).licenseTypeLabel = (partyData as any).licenseTypeLabel;
if (!party.vehicle) party.vehicle = {} as any;
party.vehicle.plateId = this.plateToPlateIdString(partyData.plate);
@@ -11001,6 +11027,7 @@ export class RequestManagementService {
req.type,
partyData,
);
await this.validateDrivingLicenceType(inquirySubmission);
partyData = inquirySubmission.dto as RunInquiriesVinV3Dto;
const subjects = resolveInquirySubjects(inquirySubmission);
this.applyInquiryParticipantsToParty(party, inquirySubmission);
@@ -11134,6 +11161,7 @@ export class RequestManagementService {
party.person.driverLicenseDate = (partyData as any).driverLicenseDate;
if ((partyData as any).licenseType)
(party.person as any).licenseType = (partyData as any).licenseType;
(party.person as any).licenseTypeLabel = (partyData as any).licenseTypeLabel;
if (!party.vehicle) party.vehicle = {} as any;
// Derive plateId from the plate parts returned by the VIN inquiry.
@@ -12972,6 +13000,7 @@ export class RequestManagementService {
driverBirthday: p.person?.driverBirthday,
clientId: p.person?.clientId ? String(p.person.clientId) : undefined,
licenseType: p.person?.licenseType ?? undefined,
licenseTypeLabel: p.person?.licenseTypeLabel ?? undefined,
},
insurance: p.insurance
? {
@@ -13318,6 +13347,7 @@ export class RequestManagementService {
userId: p.person?.userId ? String(p.person.userId) : undefined,
clientId: p.person?.clientId ? String(p.person.clientId) : undefined,
licenseType: p.person?.licenseType ?? undefined,
licenseTypeLabel: p.person?.licenseTypeLabel ?? undefined,
},
insurance: p.insurance
? {
@@ -13561,6 +13591,7 @@ export class RequestManagementService {
userId: p.person?.userId ? String(p.person.userId) : undefined,
clientId: p.person?.clientId ? String(p.person.clientId) : undefined,
licenseType: p.person?.licenseType ?? undefined,
licenseTypeLabel: p.person?.licenseTypeLabel ?? undefined,
},
insurance: p.insurance
? {