diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 6410c8d..87a2296 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -1,6 +1,6 @@ import { hasReviewedTejaratNotifier, - tejaratNotifierLookup, + isTejaratNotifierLookup, } from "src/fanavaran/tejarat-notifier"; import { BadGatewayException, @@ -187,6 +187,7 @@ import { fanavaranHullNestedClaimId, toFanavaranHullBaseClaimPayload, } from "./fanavaran-hull-base-claim"; +import { toTejaratV15ThirdPartyBasePayload } from "./fanavaran-v15-third-party-base"; import { collectFanavaranExpertiseReadinessWarnings, FANAVARAN_DEFAULT_HULL_REPAIR_DURATION, @@ -2335,6 +2336,64 @@ export class ClaimRequestManagementService { return parseJalaliDateParts(birthday); } + private async tejaratNotifierAllowedIds( + clientKey: FanavaranClientKey, + ): Promise<{ types: number[]; relations: number[] }> { + const [types, relations] = await Promise.all([ + this.getFanavaranLookupRows(clientKey, "notifier-type"), + this.getFanavaranLookupRows(clientKey, "notifier-relation"), + ]); + const ids = (rows: unknown[]) => + rows + .map((row) => Number((row as { Id?: unknown })?.Id)) + .filter((id) => Number.isInteger(id) && id > 0); + return { types: ids(types), relations: ids(relations) }; + } + + /** + * V15 GEN.03 announcer: guilty insurer, RoleId 161 then 166. + * Missing people are registered with GEN.44 (mobile comes from the user profile). + */ + private async resolveTejaratNotifierPartyId(input: { + clientKey: FanavaranClientKey; + blameCase: { + parties?: Array<{ person?: any }>; + expert?: { decision?: { guiltyPartyId?: unknown } }; + }; + claimCaseId?: string; + }): Promise { + const parties = input.blameCase.parties ?? []; + const guiltyPartyId = this.resolveGuiltyPartyIdV2( + parties as any, + input.blameCase.expert?.decision?.guiltyPartyId as any, + ); + const guilty = parties.find( + (party) => + String(party?.person?.userId ?? "") === String(guiltyPartyId ?? ""), + ); + const person = guilty?.person; + const nationalCode = + pickPersonNationalCode(person) ?? + this.getNationalCodeOfInsurerForGuiltyPartyV2( + parties as any, + guiltyPartyId as any, + ); + const birthday = pickPersonBirthday(person); + const existing = await this.resolveDriverFanavaranId( + input.clientKey, + nationalCode, + birthday, + true, + ); + if (existing != null) return existing; + if (!person) return null; + return this.registerFanavaranOtherPerson({ + clientKey: input.clientKey, + person, + claimCaseId: input.claimCaseId, + }); + } + private async resolveDriverFanavaranId( clientKey: FanavaranClientKey, nationalCode: string | null | undefined, @@ -4309,6 +4368,26 @@ export class ClaimRequestManagementService { "baseClaim", clientKey, ); + if (clientKey === "tejaratno") { + const notifierPartyId = await this.resolveTejaratNotifierPartyId({ + clientKey, + blameCase, + claimCaseId, + }); + if (requirePolicyId && notifierPartyId == null) { + throw new ConflictException({ + code: "FANAVARAN_NOTIFIER_PARTY_REQUIRED", + message: + "اعلام‌کننده خسارت در فناوران پیدا نشد. کد ملی، تاریخ تولد و موبایل بیمه‌گذار مقصر برای ثبت شخص لازم است.", + }); + } + const v15 = toTejaratV15ThirdPartyBasePayload( + payload, + notifierPartyId, + ); + for (const key of Object.keys(payload)) delete payload[key]; + Object.assign(payload, v15); + } } const fileRoleExpertIds = @@ -5143,7 +5222,9 @@ export class ClaimRequestManagementService { fields: definitions.map((field) => { const sent = fanavaranFieldStageSent(claim, field.stage); const sentValue = sent - ? claim.fanavaranSync?.[field.stage]?.lastPayload?.[field.key] + ? (claim.fanavaranSync?.[field.stage]?.lastPayload?.[field.key] ?? + claim.fanavaranSync?.[field.stage]?.lastPayload + ?.DmgNotifications?.[0]?.[field.key]) : undefined; const reviewedValue = claim.fanavaranFieldReview?.values?.[field.key]; const value = sentValue ?? reviewedValue ?? initial[field.key] ?? null; @@ -5180,9 +5261,17 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, name: string, ): Promise { - if (clientKey === "tejaratno") { - const supplied = tejaratNotifierLookup(name); - if (supplied) return supplied; + if (clientKey === "tejaratno" && isTejaratNotifierLookup(name)) { + const stored = await this.fanavaranLookupService.readStoredLookup(name); + let rows: unknown = stored; + for ( + let level = 0; + level < 3 && rows && !Array.isArray(rows) && typeof rows === "object"; + level++ + ) { + rows = (rows as { data?: unknown }).data; + } + return Array.isArray(rows) ? rows : []; } const definition = this.fanavaranLookupDefinition(name); try { @@ -5792,10 +5881,16 @@ export class ClaimRequestManagementService { return "Expert vehicle review is required before Fanavaran submission"; } + const clientKey = resolveFanavaranClientKey(); + const notifierAllowed = + clientKey === "tejaratno" + ? await this.tejaratNotifierAllowedIds(clientKey) + : undefined; if ( !hasReviewedTejaratNotifier( claimCase.fanavaranFieldReview?.values, - resolveFanavaranClientKey(), + clientKey, + notifierAllowed, ) ) { return "نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران انتخاب شوند."; @@ -6882,8 +6977,16 @@ export class ClaimRequestManagementService { } if (!existing) throw new NotFoundException("Claim case not found"); this.assertFanavaranVehicleReviewApproved(existing); + const notifierAllowed = + clientKey === "tejaratno" + ? await this.tejaratNotifierAllowedIds(clientKey) + : undefined; if ( - !hasReviewedTejaratNotifier(existing.fanavaranFieldReview?.values, clientKey) + !hasReviewedTejaratNotifier( + existing.fanavaranFieldReview?.values, + clientKey, + notifierAllowed, + ) ) { throw new ConflictException({ code: "FANAVARAN_NOTIFIER_REVIEW_REQUIRED", diff --git a/src/claim-request-management/fanavaran-stage-fields.ts b/src/claim-request-management/fanavaran-stage-fields.ts index 81893a6..51634d9 100644 --- a/src/claim-request-management/fanavaran-stage-fields.ts +++ b/src/claim-request-management/fanavaran-stage-fields.ts @@ -220,9 +220,13 @@ export function applyFanavaranStageFieldReview( ): void { const values = claim?.fanavaranFieldReview?.values; if (clientKey === "tejaratno" && stage === "baseClaim") { + const nested = claim?.fanavaranSync?.baseClaim?.lastPayload + ?.DmgNotifications?.[0]; for (const key of Object.keys(TEJARAT_NOTIFIER_FIELDS)) { const value = - values?.[key] ?? claim?.fanavaranSync?.baseClaim?.lastPayload?.[key]; + values?.[key] ?? + claim?.fanavaranSync?.baseClaim?.lastPayload?.[key] ?? + nested?.[key]; // Preserve legacy submitted claims: adding fields must not overwrite unknown remote data. if (value != null || !fanavaranFieldStageSent(claim, stage)) payload[key] = value ?? null; diff --git a/src/claim-request-management/fanavaran-v15-third-party-base.ts b/src/claim-request-management/fanavaran-v15-third-party-base.ts new file mode 100644 index 0000000..15e1b8b --- /dev/null +++ b/src/claim-request-management/fanavaran-v15-third-party-base.ts @@ -0,0 +1,94 @@ +/** + * TejaratNo third-party GEN.03 (package V15.00). + * Same keys the flow UI writes for FANAVARAN_API_VERSION=v15: + * AnnouncementDate and the extra v14 nulls are omitted, and the announcer + * goes in DmgNotifications rather than on the claim root. + */ + +const V15_BASE_KEYS = [ + "AccidentCityId", + "AccidentReportTypeId", + "AccidentVehicleUsedId", + "ClaimExpertId", + "CompensationReferenceId", + "CulpritLicenceTypeId", + "CulpritTypeId", + "AccidentCauseId", + "AccidentDate", + "DocReceivedDate", + "AccidentTime", + "AccidentLocationAddress", + "EstimateAmount", + "AccidentCulpritId", + "CouponNo", + "CourtArchiveNo", + "CulpritLicenceCityId", + "CulpritLicenceCountryId", + "CulpritLicenceForeignCityName", + "CulpritLicenceIssuDate", + "CulpritLicenceNo", + "DamagedCount", + "DmgAssessorFirstCreationTime", + "EntryDate", + "IsLicenseMatchWithVehicleKind", + "HasOtherCulprit", + "IsAccidentOutOfBorder", + "IsFatalAccident", + "IsPlaqueChanged", + "PlaqueCityId", + "PlaqueKindId", + "PlaqueLeftNo", + "PlaqueMiddleCodeId", + "PlaqueNo", + "PlaqueRightNo", + "PlaqueSampleId", + "PlaqueSerial", + "PoliceOfficerId", + "PoliceReportDesc", + "PoliceReportSeri", + "PoliceReportSerial", + "PolicyId", + "PreviousPolicyEndDate", + "TrackingCode", + "IsLicenseReplacement", + "UnknownCulpritCauseId", +] as const; + +function positiveId(value: unknown): number | null { + if (typeof value === "number" && Number.isFinite(value) && value > 0) return value; + if (typeof value === "string" && /^\d+$/.test(value.trim())) { + const parsed = Number(value.trim()); + return parsed > 0 ? parsed : null; + } + return null; +} + +export function toTejaratV15ThirdPartyBasePayload( + source: Record, + notifierPartyId: number | null, +): Record { + const payload: Record = {}; + for (const key of V15_BASE_KEYS) { + payload[key] = source[key] === undefined ? null : source[key]; + } + const accidentDate = + typeof source.AccidentDate === "string" && source.AccidentDate.trim() + ? source.AccidentDate + : null; + payload.DmgNotifications = [ + { + LetterNo: null, + ClaimNotificationDate: accidentDate, + LetterDate: accidentDate, + InjuredCount: null, + DeathCount: null, + Desc: null, + NotifierTypeId: positiveId(source.NotifierTypeId), + NotifierRelationId: positiveId(source.NotifierRelationId), + NotifierPartyId: notifierPartyId, + IsInjuredPartyIdentified: null, + InjuredPartyId: null, + }, + ]; + return payload; +} diff --git a/src/core/config/fanavaran-client.config.ts b/src/core/config/fanavaran-client.config.ts index 4d8fb26..e4fe663 100644 --- a/src/core/config/fanavaran-client.config.ts +++ b/src/core/config/fanavaran-client.config.ts @@ -54,7 +54,7 @@ export interface FanavaranPayloadDefaults { ClaimExpertId: number; /** * GEN.08 expertise — کارشناس ارزیاب خسارت ثالث مالی / وکیل معتمد / کارشناس تحقیق - * (Parsian: 29; Tejaratno proven: 2709). + * (Parsian: 29; Tejaratno: 3709 کارشناس ارزیاب خسارت ثالث مالی). */ ExpertiseClaimExpertId: number; /** GEN.06 hull RepairDuration when configured per tenant (optional). */ @@ -121,9 +121,9 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record< }, defaults: { ...SHARED_FANAVARAN_DEFAULTS, - // GEN.03 — کارشناس مسئول پرونده مالی + // GEN.03 — کارشناس مسئول پرونده مالی (یارا ۷۲۴) ClaimExpertId: 2721, - // GEN.08 — ارزیاب (proven successful submit 2026-07-18 ClaimExpertId: 2709) + // GEN.08 — کارشناس ارزیاب خسارت ثالث مالی (یارا ۷۲۴) ExpertiseClaimExpertId: 2709, ClaimFileTypeId: 23, }, diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index 3067a91..6bef285 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -4025,6 +4025,25 @@ export class ExpertClaimService { return []; } + private async tejaratNotifierAllowedIds(): Promise< + { types: number[]; relations: number[] } | undefined + > { + if (resolveFanavaranClientKey() !== "tejaratno") return undefined; + const ids = (raw: unknown) => + this.asFanavaranLookupRows(raw) + .map((row) => Number(row.Id)) + .filter((id) => Number.isInteger(id) && id > 0); + try { + const [typesRaw, relationsRaw] = await Promise.all([ + this.lookupsService.getClientRemoteLookup("notifier-type"), + this.lookupsService.getClientRemoteLookup("notifier-relation"), + ]); + return { types: ids(typesRaw), relations: ids(relationsRaw) }; + } catch { + return { types: [], relations: [] }; + } + } + private activeFanavaranLookupRows(value: unknown) { return this.asFanavaranLookupRows(value) .filter((row) => row.IsActive !== 0 && Number(row.Id) > 0) @@ -4111,6 +4130,7 @@ export class ExpertClaimService { !hasReviewedTejaratNotifier( fields?.review.values ?? claim.fanavaranFieldReview?.values, resolveFanavaranClientKey(), + await this.tejaratNotifierAllowedIds(), ) ) { throw new BadRequestException( diff --git a/src/expert-claim/fanavaran-stage-fields.spec.ts b/src/expert-claim/fanavaran-stage-fields.spec.ts index 16e6d18..29802a0 100644 --- a/src/expert-claim/fanavaran-stage-fields.spec.ts +++ b/src/expert-claim/fanavaran-stage-fields.spec.ts @@ -83,6 +83,8 @@ function setup(product = "third-party", extra: any = {}) { service.claimRequestManagementService = management; service.lookupsService = { getClientRemoteLookup: jest.fn().mockImplementation(async (name) => { + const notifier = tejaratNotifierLookup(name); + if (notifier) return notifier; if (name === "vehicle-groups") return [{ Id: 1, Caption: "سواری" }]; if (name === "vehicle-use-types") return [{ Id: 1, Caption: "شخصی", VehicleGroupId: 1 }]; diff --git a/src/fanavaran/fanavaran-lookup.service.ts b/src/fanavaran/fanavaran-lookup.service.ts index 2ffc112..8396aa0 100644 --- a/src/fanavaran/fanavaran-lookup.service.ts +++ b/src/fanavaran/fanavaran-lookup.service.ts @@ -34,6 +34,13 @@ export class FanavaranLookupService { private readonly lookupModel: Model, ) {} + /** Stored `lookups` collection row. Does not call Fanavaran. */ + async readStoredLookup(name: string): Promise { + const doc = await this.lookupModel.findOne({ name }).lean().exec(); + if (!doc) return null; + return (doc as { response?: unknown }).response ?? null; + } + private cacheFilePath(clientKey: FanavaranClientKey, fileName: string): string { return join(fanavaranLookupCacheDir(clientKey), fileName); } diff --git a/src/fanavaran/schema/fanavaran-client-config.schema.ts b/src/fanavaran/schema/fanavaran-client-config.schema.ts index 6abccb5..8b4dd4c 100644 --- a/src/fanavaran/schema/fanavaran-client-config.schema.ts +++ b/src/fanavaran/schema/fanavaran-client-config.schema.ts @@ -53,7 +53,7 @@ export class FanavaranPayloadDefaultsEmbed { /** * GEN.08 expertise — کارشناس ارزیاب خسارت ثالث مالی (or وکیل/تحقیق). - * (Parsian example: 29; Tejaratno proven send: 2709). + * (Parsian example: 29; Tejaratno: 3709 کارشناس ارزیاب خسارت ثالث مالی). */ @Prop({ type: Number, required: true }) ExpertiseClaimExpertId: number; diff --git a/src/fanavaran/tejarat-notifier.spec.ts b/src/fanavaran/tejarat-notifier.spec.ts index ee96d7b..0d32b3b 100644 --- a/src/fanavaran/tejarat-notifier.spec.ts +++ b/src/fanavaran/tejarat-notifier.spec.ts @@ -8,21 +8,23 @@ import { describe("TejaratNo notifier contract", () => { it.each(["notifier-type", "notifier-relation"])( - "exposes the supplied %s without querying Fanavaran or the database", + "reads %s from the lookups collection and does not call Fanavaran", async (name) => { + const stored = tejaratNotifierLookup(name); const service = Object.create(LookupsService.prototype) as any; service.activeClientKey = jest.fn().mockReturnValue("tejaratno"); - service.fanavaranLookupService = { getRemoteLookup: jest.fn() }; - service.lookupDbService = { findOne: jest.fn() }; + service.fanavaranLookupService = { + getRemoteLookup: jest.fn(), + readStoredLookup: jest.fn().mockResolvedValue(stored), + }; const result = await service.getClientRemoteLookup(name); - expect(result).toEqual(tejaratNotifierLookup(name)); - expect(result.every((row) => row.IsActive === 1 && row.Id !== 5518)).toBe( - true, + expect(result).toEqual(stored); + expect(service.fanavaranLookupService.readStoredLookup).toHaveBeenCalledWith( + name, ); expect( service.fanavaranLookupService.getRemoteLookup, ).not.toHaveBeenCalled(); - expect(service.lookupDbService.findOne).not.toHaveBeenCalled(); }, ); diff --git a/src/fanavaran/tejarat-notifier.ts b/src/fanavaran/tejarat-notifier.ts index bd9d11b..f5b8f35 100644 --- a/src/fanavaran/tejarat-notifier.ts +++ b/src/fanavaran/tejarat-notifier.ts @@ -23,21 +23,32 @@ export const TEJARAT_NOTIFIER_FIELDS = { NotifierRelationId: "notifier-relation", } as const; -export function tejaratNotifierLookup(name: string) { - if (!Object.prototype.hasOwnProperty.call(TEJARAT_NOTIFIER_LOOKUPS, name)) - return undefined; - return TEJARAT_NOTIFIER_LOOKUPS[ - name as keyof typeof TEJARAT_NOTIFIER_LOOKUPS - ].map((row) => ({ ...row })); +export function isTejaratNotifierLookup( + name: string, +): name is keyof typeof TEJARAT_NOTIFIER_LOOKUPS { + return Object.prototype.hasOwnProperty.call(TEJARAT_NOTIFIER_LOOKUPS, name); } -/** Both selections must be explicit, canonical numeric IDs; 5518 is excluded. */ +export function tejaratNotifierLookup(name: string) { + if (!isTejaratNotifierLookup(name)) return undefined; + return TEJARAT_NOTIFIER_LOOKUPS[name].map((row) => ({ ...row })); +} + +/** Both selections must be explicit numeric IDs from the allowed codebook. */ export function hasReviewedTejaratNotifier( values: Record | null | undefined, clientKey: FanavaranClientKey, + allowed?: { types?: number[]; relations?: number[] }, ): boolean { if (clientKey !== "tejaratno") return true; - return Object.entries(TEJARAT_NOTIFIER_FIELDS).every(([key, lookup]) => - TEJARAT_NOTIFIER_LOOKUPS[lookup].some((row) => row.Id === values?.[key]), + const typeIds = + allowed?.types ?? + TEJARAT_NOTIFIER_LOOKUPS["notifier-type"].map((row) => row.Id); + const relationIds = + allowed?.relations ?? + TEJARAT_NOTIFIER_LOOKUPS["notifier-relation"].map((row) => row.Id); + return ( + typeIds.includes(values?.NotifierTypeId as number) && + relationIds.includes(values?.NotifierRelationId as number) ); } diff --git a/src/lookups/lookups.controller.ts b/src/lookups/lookups.controller.ts index 0fbfbfa..0195f0b 100644 --- a/src/lookups/lookups.controller.ts +++ b/src/lookups/lookups.controller.ts @@ -671,7 +671,7 @@ export class LookupsController { description: "Generic cached Fanavaran lookup fetcher. Configured names use their catalogue URL; " + "unlisted slugs (e.g. vehicle-groups) fall back to car/base-info/{lookupName}. " + - "TejaratNo notifier-type and notifier-relation use the supplied local tenant codebooks without a remote fetch.", + "TejaratNo notifier-type and notifier-relation are read from the lookups collection and are not fetched from Fanavaran.", }) @ApiParam({ name: "lookupName", diff --git a/src/lookups/lookups.service.ts b/src/lookups/lookups.service.ts index 8cae616..fe67591 100644 --- a/src/lookups/lookups.service.ts +++ b/src/lookups/lookups.service.ts @@ -1,4 +1,4 @@ -import { tejaratNotifierLookup } from "src/fanavaran/tejarat-notifier"; +import { isTejaratNotifierLookup } from "src/fanavaran/tejarat-notifier"; import { BadRequestException, Injectable, @@ -126,12 +126,15 @@ export class LookupsService implements OnModuleInit, OnModuleDestroy { async getClientRemoteLookup(lookupName: string): Promise { const clientKey = this.activeClientKey(); - const notifier = tejaratNotifierLookup(lookupName); - if (notifier) { + if (isTejaratNotifierLookup(lookupName)) { if (clientKey !== "tejaratno") { throw new BadRequestException("Notifier lookups apply only to TejaratNo."); } - return notifier; + const stored = await this.fanavaranLookupService.readStoredLookup(lookupName); + if (stored == null) { + throw new NotFoundException(`Lookup "${lookupName}" not found`); + } + return stored; } const definition = this.findRemoteLookup(lookupName);