diff --git a/docs/driving-licence-type-integrity.md b/docs/driving-licence-type-integrity.md new file mode 100644 index 0000000..ac24618 --- /dev/null +++ b/docs/driving-licence-type-integrity.md @@ -0,0 +1,13 @@ +# Driving licence selection and display + +`GET /lookups/driving-licence-types` is the source of licence type IDs and captions. It uses the existing tenant-specific Fanavaran disk/DB cache and remote lookup chain. The response is a normalized array of `{ Id, Caption, IsActive }`; unusable or contradictory lookups fail instead of supplying guessed options. + +Both creation interfaces select the actual lookup ID. They disable selection and provide retry when the list is unavailable. They never assume numeric IDs `1`, `2`, or `3` correspond to licence grades, and never substitute free text for a provider ID. + +All ten inquiry entry points in `RequestManagementService` validate licensed drivers against this lookup before saving their inquiry attributes or running the participant inquiries. Unknown/inactive IDs are rejected. Drivers without a licence do not need the lookup. + +`licenseType` remains the selected provider ID. The API adds `licenseTypeLabel`, a caption resolved by the server from that ID, to the normalized driver participant and legacy person data. The existing schemas persist this optional display snapshot; claim party snapshots reuse the same schema. Downstream Fanavaran submissions continue using the original ID. + +Expert views keep IDs unchanged during normalization and resolve them at render time. A saved caption takes priority; older records use the current canonical lookup. Without either source, an unresolved numeric code is explicitly marked as missing its title. Reports no longer apply guessed numeric grade mappings, and licence numbers are not passed through licence type label resolution. + +Deploy API, expert UI, and user UI together. Existing records created with an invented fallback ID cannot be distinguished from valid provider IDs using the stored number alone. Do not automatically remap those records: review the original selection or licence evidence and correct only confirmed cases. No bulk data migration is part of this fix. diff --git a/src/case-expert-report/case-expert-report.builder.ts b/src/case-expert-report/case-expert-report.builder.ts index 2c4c490..11e1d11 100644 --- a/src/case-expert-report/case-expert-report.builder.ts +++ b/src/case-expert-report/case-expert-report.builder.ts @@ -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), diff --git a/src/case-expert-report/persian-report-labels.ts b/src/case-expert-report/persian-report-labels.ts index 8405b46..831ef41 100644 --- a/src/case-expert-report/persian-report-labels.ts +++ b/src/case-expert-report/persian-report-labels.ts @@ -291,9 +291,6 @@ const INQUIRY_ERROR_LABELS: Record = { }; const LICENSE_TYPE_LABELS: Record = { - "1": "پایه یک", - "2": "پایه دو", - "3": "پایه سه", BASE_1: "پایه یک", BASE1: "پایه یک", GRADE_1: "پایه یک", diff --git a/src/lookups/driving-licence-types.spec.ts b/src/lookups/driving-licence-types.spec.ts new file mode 100644 index 0000000..ee6070a --- /dev/null +++ b/src/lookups/driving-licence-types.spec.ts @@ -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"); + }); +}); diff --git a/src/lookups/driving-licence-types.ts b/src/lookups/driving-licence-types.ts new file mode 100644 index 0000000..edda0cd --- /dev/null +++ b/src/lookups/driving-licence-types.ts @@ -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; + rows = record.data ?? record.Data; + } + const byId = new Map(); + 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; +} diff --git a/src/lookups/lookups.service.ts b/src/lookups/lookups.service.ts index 3fb828c..94e4fc9 100644 --- a/src/lookups/lookups.service.ts +++ b/src/lookups/lookups.service.ts @@ -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 { - return await this.getClientRemoteLookup("driving-licence-types"); + async getDrivingLicenceTypes(): Promise { + return normalizeDrivingLicenceTypes( + await this.getClientRemoteLookup("driving-licence-types"), + ); } async getAccidentCulpritType(): Promise { diff --git a/src/request-management/entities/schema/partyRole.enum.ts b/src/request-management/entities/schema/partyRole.enum.ts index ca1c9cd..3e36d7b 100644 --- a/src/request-management/entities/schema/partyRole.enum.ts +++ b/src/request-management/entities/schema/partyRole.enum.ts @@ -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 = diff --git a/src/request-management/inquiry-participant-resolver.ts b/src/request-management/inquiry-participant-resolver.ts index 1a336c3..c89265e 100644 --- a/src/request-management/inquiry-participant-resolver.ts +++ b/src/request-management/inquiry-participant-resolver.ts @@ -18,6 +18,7 @@ export interface ResolvedInquiryParticipant { hasDrivingLicense?: boolean; licenseNumber?: string; licenseType?: string; + licenseTypeLabel?: string; driverLicenseDate?: string; } @@ -41,6 +42,7 @@ export interface NormalizedInquirySubmission> { driverLicense?: string; driverLicenseDate?: string; licenseType?: string; + licenseTypeLabel?: string; userNoCertificate?: boolean; nationalCodeOfInsurer: string; insurerBirthday: string; diff --git a/src/request-management/request-management.licence-type.spec.ts b/src/request-management/request-management.licence-type.spec.ts new file mode 100644 index 0000000..cbe64f3 --- /dev/null +++ b/src/request-management/request-management.licence-type.spec.ts @@ -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( + `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( + "پایه سه", + ); + }); +}); diff --git a/src/request-management/request-management.module.ts b/src/request-management/request-management.module.ts index 9c0690c..80db63f 100644 --- a/src/request-management/request-management.module.ts +++ b/src/request-management/request-management.module.ts @@ -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", }), diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index 053efe8..db59559 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -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>, + ): Promise { + 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>, @@ -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 ? {