From 90bdc517151c79832b9b951c0141840abcccaf93 Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Wed, 11 Nov 2026 17:20:02 +0330 Subject: [PATCH] update the IsLicenseReplaced and for the accessories --- docs/fanavaran/03-constants.md | 10 + docs/fanavaran/car-body-curl-flow.md | 2 +- docs/fanavaran/car-body-stage-fields.md | 16 +- docs/fanavaran/flow-design-user-vs-inquiry.md | 2 +- .../claim-request-management.service.ts | 234 ++++++++++++------ .../fanavaran-hull-accessory-mapping.spec.ts | 138 +++++++++++ .../fanavaran-hull-base-claim.spec.ts | 20 +- .../fanavaran-hull-base-claim.ts | 39 ++- .../fanavaran-hull-expertise-lookups.ts | 42 +++- .../fanavaran-hull-expertise.ts | 2 - .../fanavaran-hull-live-lookups.spec.ts | 190 ++++++++++++++ .../fanavaran-hull-lookup-validation.ts | 113 +++++++++ .../fanavaran-stage-fields.spec.ts | 9 +- 13 files changed, 693 insertions(+), 124 deletions(-) create mode 100644 src/claim-request-management/fanavaran-hull-accessory-mapping.spec.ts create mode 100644 src/claim-request-management/fanavaran-hull-live-lookups.spec.ts create mode 100644 src/claim-request-management/fanavaran-hull-lookup-validation.ts diff --git a/docs/fanavaran/03-constants.md b/docs/fanavaran/03-constants.md index b8c3b68..cf67e91 100644 --- a/docs/fanavaran/03-constants.md +++ b/docs/fanavaran/03-constants.md @@ -48,6 +48,16 @@ the cached login token can be reused across staff locations. ## Payload defaults (tenant profile.defaults) +Hull submissions validate selected codebook IDs against fresh Fanavaran API +responses before every create, base update, attachment upload, and expertise write. +These checks bypass lookup-file and database caches. Missing or inactive IDs block +the remote write with `FANAVARAN_HULL_LOOKUP_INVALID`; they are never accepted merely +because they appear in the defaults below. Hull collision type, culprit type, +authority, damage kind, and cost kind select matching captions from API responses +without numeric fallbacks. Policy accessories are read for the current PolicyId; +ActualPremium is refreshed from that policy's TotalPremium. Expert-entered amounts +and durations remain expert data. `IsLicenseReplaced` stays explicitly 0. + | Name | Shared seed | Parsian override | Tejaratno | Moallem | Varies? | |------|-------------|------------------|-----------|---------|---------| | `AccidentCityId` | 701 | same | same | same | usually ❌ | diff --git a/docs/fanavaran/car-body-curl-flow.md b/docs/fanavaran/car-body-curl-flow.md index 2dbafd0..0f8e430 100644 --- a/docs/fanavaran/car-body-curl-flow.md +++ b/docs/fanavaran/car-body-curl-flow.md @@ -190,7 +190,7 @@ curl -sS -X POST \ | `AccidentTypeId` | `GET /lookups/vehicle-hull-accident-types` | **2** = تصادف(حادثه) | | `CostSeparationToDmgSections` | `GET /lookups/ans` | **0** = خیر | | `IsOwnerChanged` | `GET /lookups/ans` | **0** = خیر | -| `IsLicenseReplaced` | — | **`null`** (must be empty; do not send `0` or ثالث `IsLicenseReplacement`) | +| `IsLicenseReplaced` | `GET /lookups/ans` | **0** = خیر (use the hull field name, not ثالث `IsLicenseReplacement`) | | `CulpritTypeId` | `GET /lookups/vehicle-hull-accident-culprit-type` | **301** = حادثه مقصر شناخته شده دارد (not ثالث `337`) | | `CustomerFaultPercent` | — | **100** | | `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` | بیمه‌گذار (`Id` from lookup, fallback **1**) | diff --git a/docs/fanavaran/car-body-stage-fields.md b/docs/fanavaran/car-body-stage-fields.md index 57112ac..92ae7d5 100644 --- a/docs/fanavaran/car-body-stage-fields.md +++ b/docs/fanavaran/car-body-stage-fields.md @@ -44,21 +44,21 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload` | AccidentCauseId | علت حادثه | number | **no** | **system** `6` · lookup `accident-causes` | | AccidentCityId | شهر حادثه | number | **no** | **user** expert review, else **system** `701` · lookup `cities` | | AccidentReportTypeId | نحوه اعلام | number | **no** | **user** expert review, else **system** `155` · lookup `accident-report-type` | -| AccidentTypeId | نوع حادثه بدنه | number | **no** | **user** expert review, else **system** `2` تصادف(حادثه) · **lookup** `GET /lookups/vehicle-hull-accident-types` | -| CulpritTypeId | نوع مقصر بدنه | number | **no** | **user** expert review, else **system** `300` (ثالث `337` remapped) · **lookup** `GET /lookups/vehicle-hull-accident-culprit-type` | -| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | **user** expert review, else **lookup** `GET /lookups/detection-accident-culprits` (caption بیمه‌گذار, fallback `1`) | +| AccidentTypeId | نوع حادثه بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-types` row caption تصادف(حادثه); no numeric fallback | +| CulpritTypeId | نوع مقصر بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-culprit-type` row caption بیمه‌گذار; never reuse third-party `337` | +| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | Reviewed choice, else current `detection-accident-culprits` row caption بیمه‌گذار; no numeric fallback | | AccidentCulpritId | شناسه مقصر فناوران | number | preferred | **inquiry** parties `inquiry-by-unique-identifier`, fallback hull policy `CustomerId` | | CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` | | CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` | | IsOwnerChanged | مالک تغییر یافته؟ | number (ans) | **no** | **system** `0` · lookup `ans` | -| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | **must be null** | never copy ثالث `IsLicenseReplacement` | +| IsLicenseReplaced | گواهینامه تعویضی است؟ | number | **no** | **system** `0` (خیر); use the hull field name | | ActualPremium | حق بیمه واقعی | number | preferred | **inquiry** hull policy `TotalPremium` via `GET /lookups/body-policy/{PolicyId}` | | EstimateAmount | برآورد | number | **no** | **user** expert prices / provisional | | CulpritLicenceNo | شماره گواهینامه | string | **no** | dummy / **user** | | CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **system** `"1394/10/13"` | | CulpritLicenceTypeId | نوع گواهینامه | number | sent | tenant `2` · lookup `driving-licence-types` | | AccidentVehicleUsedId | کاربری خودرو | number | **no** | **inquiry** hull policy `VehicleId` + `VehicleVersionNo` → vehicle GET `UsedId`; no default or expert override. Unresolved inquiry warns in preview and blocks submit. | -| PoliceOfficerId | افسر | number | sent | **system** `1` | +| PoliceOfficerId | افسر | number | yes | null; do not copy the shared third-party sample `1` | | IsAccidentOutOfBorder | خارج از مرز | number | sent | **system** `0` | | ArchiveNo | بایگانی | string | yes | null | | EntryDate | تاریخ ورود | string | yes | null | @@ -141,11 +141,11 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro | DmgSections[].Desc | شرح قطعه | string | **no** | **user** part label | | DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** | | DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` | -| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | **lookup** `vehicle-hull-dmg-kind` caption تخریب, fallback `5485` | -| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | **no** | **system** `3043330` (فابریک) for **every** row | +| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | Current `vehicle-hull-dmg-kind` API row caption تخریب; no numeric fallback | +| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | **no** | Current policy `dmg-accessories`: match `AccessoryKindId`, else that policy's factory bundle; warn and block submission if unresolved | | DmgSections[].DmgSectionCosts[].Caption | عنوان هزینه | string | **no** | **user** label | | DmgSections[].DmgSectionCosts[].Amount | مبلغ (قطعه+اجرت) | number | **no** | **user** | -| DmgSections[].DmgSectionCosts[].DmgCostKindId | نوع هزینه | number | **no** | **lookup** `vehicle-hull-dmg-cost-kinds` caption مجموع لوازم, fallback `1` | +| DmgSections[].DmgSectionCosts[].DmgCostKindId | نوع هزینه | number | **no** | Current `vehicle-hull-dmg-cost-kinds` API row caption مجموع لوازم; no numeric fallback | **Lookups used:** `vehicle-hull-dmg-kind`, `vehicle-hull-dmg-cost-kinds`, `detection-accident-culprits`, `vehicle-hull-accident-types`, `vehicle-hull-accident-culprit-type`, `ans`, optional `vehicle-hull-policies/{id}/dmg-accessories` (no longer used for AccessoryId). diff --git a/docs/fanavaran/flow-design-user-vs-inquiry.md b/docs/fanavaran/flow-design-user-vs-inquiry.md index 180aa5c..ebec984 100644 --- a/docs/fanavaran/flow-design-user-vs-inquiry.md +++ b/docs/fanavaran/flow-design-user-vs-inquiry.md @@ -115,7 +115,7 @@ Hull is **first party**. One vehicle, one policy. | درصد تقصیر بیمه‌گذار | CustomerFaultPercent | number 0–100 | **user** if not 100%; today always 100 | | تفکیک هزینه به نقاط | CostSeparationToDmgSections | ans | **user** default خیر | | مالک تغییر یافته؟ | IsOwnerChanged | ans | **user** default خیر | -| گواهینامه تعویضی؟ | IsLicenseReplaced | ans or empty | **must stay empty/null** unless Fanavaran later requires a value | +| گواهینامه تعویضی؟ | IsLicenseReplaced | ans | Currently sent as **0** (خیر) | | قطعات آسیب‌دیده | selectedParts | catalog ids | **user** | ### Expert pricing (بدنه) diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 5e1b49c..4d368c0 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -188,7 +188,8 @@ import { actualPremiumFromHullPolicyRecord, authorityCulpritIdFromDetectionRows, customerIdFromHullPolicyRecord, - FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID, + FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION, + FANAVARAN_HULL_CULPRIT_TYPE_CAPTION, FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, fanavaranHullNestedClaimId, toFanavaranHullBaseClaimPayload, @@ -205,13 +206,16 @@ import { vehicleCurrentValueFromHullPolicyRecord, } from './fanavaran-hull-expertise'; import { - FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID, - FANAVARAN_DEFAULT_HULL_DMG_KIND_ID, - FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID, FANAVARAN_HULL_DMG_COST_KIND_CAPTION, FANAVARAN_HULL_DMG_KIND_CAPTION, findLookupIdByCaption, + asHullDmgAccessoryRows, + resolveVehicleHullAccessoryId, } from './fanavaran-hull-expertise-lookups'; +import { + validateFanavaranHullLookupIds, + type HullLookupStage, +} from './fanavaran-hull-lookup-validation'; import { activeStageLookupRows, applyFanavaranStageFieldReview, @@ -2636,23 +2640,15 @@ export class ClaimRequestManagementService { input.payload.CustomerFaultPercent = FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT; - if (parseFanavaranId(input.payload.AuthorityCulpritId) == null) { - try { - const authorityRows = await this.getFanavaranLookupRows( - input.clientKey, - 'detection-accident-culprits', - ); - input.payload.AuthorityCulpritId = - authorityCulpritIdFromDetectionRows(authorityRows); - } catch (error) { - this.logger.warn( - `${input.logPrefix} detection-accident-culprits lookup failed; using default AuthorityCulpritId=${FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID}`, - error, - ); - input.payload.AuthorityCulpritId = - FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID; - } - } + const [accidentTypes, culpritTypes, authorities] = await Promise.all([ + this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-types', true), + this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-culprit-type', true), + this.getFanavaranLookupRows(input.clientKey, 'detection-accident-culprits', true), + ]); + input.payload.AccidentTypeId ??= findLookupIdByCaption(accidentTypes, FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION); + if (input.payload.CulpritTypeId == null || input.payload.CulpritTypeId === 337) + input.payload.CulpritTypeId = findLookupIdByCaption(culpritTypes, FANAVARAN_HULL_CULPRIT_TYPE_CAPTION); + input.payload.AuthorityCulpritId ??= authorityCulpritIdFromDetectionRows(authorities); } /** GEN.06: VehicleCurrentValue from hull policy when price-drop / frontend value is missing. */ @@ -2728,11 +2724,12 @@ export class ClaimRequestManagementService { ), }; - const [dmgKindRows, dmgCostKindRows, policyRecord] = await Promise.all([ - this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind'), + const [dmgKindRows, dmgCostKindRows, policyRecord, componentRows] = await Promise.all([ + this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind', true), this.getFanavaranLookupRows( input.clientKey, 'vehicle-hull-dmg-cost-kinds', + true, ), policyId != null ? this.fanavaranLookupService.bodyPolicyById( @@ -2741,16 +2738,34 @@ export class ClaimRequestManagementService { contractOptions, ) : Promise.resolve(null), + input.parts.length ? this.getFanavaranLookupRows(input.clientKey, 'car-components', true) : Promise.resolve([]), ]); const dmgKindId = - findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION) ?? - FANAVARAN_DEFAULT_HULL_DMG_KIND_ID; + findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION); const dmgCostKindId = findLookupIdByCaption( dmgCostKindRows, FANAVARAN_HULL_DMG_COST_KIND_CAPTION, - ) ?? FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID; + ); + + let accessories = asHullDmgAccessoryRows([]); + if (policyId == null && input.parts.length > 0) input.warnings.push('VehicleHullAccessoryId cannot be resolved: missing PolicyId.'); + if (policyId != null && input.parts.length > 0) { + try { + accessories = asHullDmgAccessoryRows( + await this.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId( + input.clientKey, + policyId, + contractOptions, + ), + ); + } catch (error) { + this.logger.warn( + `[buildCarBodyFanavaranExpertisePayload] policy ${policyId} dmg-accessories lookup failed: ${error instanceof Error ? error.message : error}`, + ); + } + } let vehicle = pickHullVehicleIdentity(input.blame); let colorId: number | null = null; @@ -2795,6 +2810,10 @@ export class ClaimRequestManagementService { ); const hullSections = input.parts.map((part: any) => { + const vehicleHullAccessoryId = resolveVehicleHullAccessoryId( + accessories, + parseFanavaranId(part?.partId), + ); return toFanavaranHullExpertiseDmgSection({ partId: part?.partId, desc: this.fanavaranPartLabel(part), @@ -2804,7 +2823,7 @@ export class ClaimRequestManagementService { this.parseFanavaranMoney(part?.salary), dmgKindId, dmgCostKindId, - vehicleHullAccessoryId: FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID, + vehicleHullAccessoryId, }); }); @@ -2824,23 +2843,27 @@ export class ClaimRequestManagementService { input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ?? FANAVARAN_DEFAULT_HULL_REPAIR_DURATION; + const payload = toFanavaranHullExpertisePayload({ + claimExpertId: input.claimExpertId, + dmgAssessmentDate: this.convertToPersianDate(input.submittedAt), + inspectionTime: this.getTime24Hour(input.submittedAt), + wage, componentReplacementCost, wasteValue, + dropAmount: input.priceDropTotal || 0, + vehicleCurrentValue, vehicle, colorId, repairDuration, + dmgSections: hullSections, + }); + const sources = { + 'vehicle-hull-dmg-kind': dmgKindRows, + 'vehicle-hull-dmg-cost-kinds': dmgCostKindRows, + 'car-components': componentRows, + 'policy-dmg-accessories': accessories, + }; + input.warnings.push(...await validateFanavaranHullLookupIds(payload, 'expertise', async lookup => sources[lookup] ?? [])); + return { replyKey: input.replyKey, warnings: input.warnings, - payload: toFanavaranHullExpertisePayload({ - claimExpertId: input.claimExpertId, - dmgAssessmentDate: this.convertToPersianDate(input.submittedAt), - inspectionTime: this.getTime24Hour(input.submittedAt), - wage, - componentReplacementCost, - wasteValue, - dropAmount: input.priceDropTotal || 0, - vehicleCurrentValue, - vehicle, - colorId, - repairDuration, - dmgSections: hullSections, - }), + payload, }; } @@ -4775,6 +4798,18 @@ export class ClaimRequestManagementService { const hull = toFanavaranHullBaseClaimPayload(payload, clientKey); for (const key of Object.keys(payload)) delete payload[key]; Object.assign(payload, hull); + try { + await this.assertFanavaranHullApiValues( + `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims`, + payload, clientKey, claimCaseId, + ); + } catch (error) { + if (requirePolicyId) throw error; + previewWarnings.push({ + code: 'FANAVARAN_HULL_LOOKUP_INVALID', field: 'lookups', + message: error instanceof Error ? error.message : String(error), + }); + } } if ( @@ -5655,8 +5690,8 @@ export class ClaimRequestManagementService { AccidentReportTypeId: defaults.AccidentReportTypeId, DmgHistoryStatus: defaults.DmgHistoryStatus, InspectionPlaceId: 282, - AccidentTypeId: 2, - CulpritTypeId: 300, + AccidentTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-types') ?? [], FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION), + CulpritTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-culprit-type') ?? [], FANAVARAN_HULL_CULPRIT_TYPE_CAPTION), AuthorityCulpritId: authorityCulpritIdFromDetectionRows( options.get('detection-accident-culprits') ?? [], ), @@ -5715,11 +5750,65 @@ export class ClaimRequestManagementService { }; } + private async assertFanavaranHullApiValues( + url: string, + payload: Record, + clientKey: FanavaranClientKey, + claimCaseId?: string, + ): Promise { + if (!/\/car\/vehicle-hull-claims(?:\/|$)/.test(url)) return; + const stage: HullLookupStage = url.endsWith('/expertise') + ? 'expertise' + : url.endsWith('/files') ? 'files' : 'baseClaim'; + const warnings = await validateFanavaranHullLookupIds( + payload, stage, async (lookup) => { + if (lookup !== 'policy-dmg-accessories') { + return this.getFanavaranLookupRows(clientKey, lookup, true); + } + const claim = claimCaseId + ? await this.claimCaseDbService.findById(claimCaseId) + : null; + const policyId = this.parseHullClaimPolicyId(claim); + if (policyId == null) return []; + return this.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId( + clientKey, policyId, { + contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'), + }, + ); + }, + ); + if (stage === 'baseClaim') { + const policyId = parseFanavaranId(payload.PolicyId); + try { + const policy = policyId == null ? null : asObjectRecord( + await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId, { + contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'), + }), + ); + const premium = actualPremiumFromHullPolicyRecord(policy); + if (premium == null) warnings.push('ActualPremium could not be resolved from the current hull policy API response.'); + else payload.ActualPremium = premium; + } catch { + warnings.push('Hull policy API is unavailable; policy values could not be verified.'); + } + } + if (warnings.length) { + throw new BadRequestException({ + code: 'FANAVARAN_HULL_LOOKUP_INVALID', + message: 'Hull submission requires valid values from the current Fanavaran API responses.', + warnings, + }); + } + } + private async getFanavaranLookupRows( clientKey: FanavaranClientKey, name: string, + requireRemote = false, ): Promise { - if (clientKey === 'tejaratno' && isTejaratNotifierLookup(name)) { + if ( + !requireRemote && clientKey === 'tejaratno' && isTejaratNotifierLookup(name) + ) { const stored = await this.fanavaranLookupService.readStoredLookup(name); let rows: unknown = stored; for ( @@ -5733,11 +5822,15 @@ export class ClaimRequestManagementService { } const definition = this.fanavaranLookupDefinition(name); try { - const data = await this.fanavaranLookupService.getRemoteLookup( - clientKey, - definition.url, - definition.cacheFile, - ); + const data = requireRemote + ? await this.fanavaranLookupService.fetchFromFanavaran(clientKey, definition.url, { + contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'), + }) + : await this.fanavaranLookupService.getRemoteLookup( + clientKey, + definition.url, + definition.cacheFile, + ); let rows: unknown = data; for ( let level = 0; @@ -5890,13 +5983,26 @@ export class ClaimRequestManagementService { warnings.push('No submit-ready expert pricing lines exist yet.'); } + const priceDrop = input.claimCase.evaluation?.priceDrop ?? {}; + const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total); + const submittedAt = reply?.submittedAt ?? new Date(); + const product = await this.resolveFanavaranClaimProduct( + input.claimCase?._id ? String(input.claimCase._id) : undefined, + ); + if (product === 'car-body') { + return this.buildCarBodyFanavaranExpertisePayload({ + clientKey: input.clientKey, claimCase: input.claimCase, + blame: blameForExpertIds, profile, parts, claimExpertId, + submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice, + warnings, replyKey: active?.replyKey, + }); + } + const [inspectionPlaces, dropAmountStatuses] = await Promise.all([ this.getFanavaranLookupRows(input.clientKey, 'inspection-place'), this.getFanavaranLookupRows(input.clientKey, 'drop-amount-status'), ]); - const priceDrop = input.claimCase.evaluation?.priceDrop ?? {}; - const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total); const inspectionPlaceId = input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282; const dropAmountStatus = 5458; @@ -5920,28 +6026,6 @@ export class ClaimRequestManagementService { (sum, section) => sum + this.parseFanavaranMoney(section.WasteValue), 0, ); - const submittedAt = reply?.submittedAt ?? new Date(); - const product = await this.resolveFanavaranClaimProduct( - input.claimCase?._id ? String(input.claimCase._id) : undefined, - ); - - if (product === 'car-body') { - const blame = blameForExpertIds; - return this.buildCarBodyFanavaranExpertisePayload({ - clientKey: input.clientKey, - claimCase: input.claimCase, - blame, - profile, - parts, - claimExpertId, - submittedAt, - priceDropTotal, - priceDropCarPrice: priceDrop?.carPrice, - warnings, - replyKey: active?.replyKey, - }); - } - const payload: Record = { ClaimExpertId: claimExpertId, ComponentReplacementCost: componentReplacementCost, @@ -6510,6 +6594,7 @@ export class ClaimRequestManagementService { claimCaseId?: string, ) { this.fanavaranAuthService.assertNotInBackoff(clientKey); + await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId); const headers = await this.getFanavaranAuthHeaders( clientKey, auditSession, @@ -6541,6 +6626,7 @@ export class ClaimRequestManagementService { claimCaseId?: string, ) { this.fanavaranAuthService.assertNotInBackoff(clientKey); + await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId); const headers = await this.getFanavaranAuthHeaders( clientKey, auditSession, @@ -6618,6 +6704,7 @@ export class ClaimRequestManagementService { claimCaseId?: string, ) { this.fanavaranAuthService.assertNotInBackoff(clientKey); + await this.assertFanavaranHullApiValues(url, content, clientKey, claimCaseId ?? auditSession?.claimCaseId); const headers = await this.getFanavaranAuthHeaders( clientKey, auditSession, @@ -7507,6 +7594,7 @@ export class ClaimRequestManagementService { claimCaseId, ); const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId); + await this.assertFanavaranHullApiValues(submitUrl, fanavaranData, clientKey, claimCaseId); const requestHeaders = { ...headers, diff --git a/src/claim-request-management/fanavaran-hull-accessory-mapping.spec.ts b/src/claim-request-management/fanavaran-hull-accessory-mapping.spec.ts new file mode 100644 index 0000000..2133945 --- /dev/null +++ b/src/claim-request-management/fanavaran-hull-accessory-mapping.spec.ts @@ -0,0 +1,138 @@ +import { ClaimRequestManagementService } from "./claim-request-management.service"; + +function setup(accessories: unknown) { + const service = Object.create(ClaimRequestManagementService.prototype) as any; + service.logger = { warn: jest.fn(), log: jest.fn() }; + service.getFanavaranLookupRows = jest.fn().mockImplementation( + async (_client: string, name: string) => + ({ + "vehicle-hull-dmg-kind": [{ Id: 8001, Caption: "تخريب", IsActive: 1 }], + "vehicle-hull-dmg-cost-kinds": [ + { Id: 8002, Caption: "مجموع لوازم", IsActive: 1 }, + ], + "car-components": [{ Id: 9 }, { Id: 13 }], + })[name] ?? [], + ); + service.fanavaranLookupService = { + bodyPolicyById: jest.fn().mockResolvedValue({ VehicleValue: 15000000000 }), + vehicleHullDmgAccessoriesByPolicyId: jest + .fn() + .mockResolvedValue(accessories), + }; + const build = (policyId = 123) => + service.buildCarBodyFanavaranExpertisePayload({ + clientKey: "parsian", + claimCase: { fanavaranSync: { baseClaim: { policyId } } }, + blame: { parties: [] }, + profile: {}, + parts: [ + { partId: 9, partName: "سپر جلو", price: 50000000, salary: 25000000 }, + { partId: 13, partName: "چراغ جلو چپ", price: 0, salary: 2000000 }, + ], + claimExpertId: 4044, + submittedAt: new Date("2026-11-11T09:09:00Z"), + priceDropTotal: 0, + priceDropCarPrice: null, + warnings: [], + }); + return { service, build }; +} + +describe("hull expertise policy accessory mapping", () => { + it("uses the current policy accessory IDs for the bumper and headlamp", async () => { + const { service, build } = setup([ + { Id: 900001, AccessoryKindId: 9, AccessoryDesc: "سپر جلو" }, + { Id: 900002, AccessoryKindId: 13, AccessoryDesc: "چراغ جلو چپ" }, + ]); + const { payload, warnings } = await build(); + expect( + payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId), + ).toEqual([900001, 900002]); + expect(warnings).toEqual([]); + expect(payload.DmgSections[0]).toMatchObject({ + DmgKindId: 8001, + DmgSectionCosts: [ + { + DmgCostKindId: 8002, + Caption: expect.any(String), + Amount: expect.any(Number), + }, + ], + }); + expect( + service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId, + ).toHaveBeenCalledWith( + "parsian", + 123, + expect.objectContaining({ contractIdOverride: expect.any(String) }), + ); + }); + + it("uses a factory bundle only when it belongs to the current policy", async () => { + const { build } = setup([ + { Id: 900003, AccessoryDesc: "کليه قطعات فابريک" }, + ]); + const { payload } = await build(); + expect( + payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId), + ).toEqual([900003, 900003]); + }); + + it("does not replace unavailable lookup values with 5485 or 1", async () => { + const { service, build } = setup([ + { Id: 2810613, AccessoryDesc: "کليه قطعات فابريک" }, + ]); + service.getFanavaranLookupRows.mockResolvedValue([]); + const { payload, warnings } = await build(); + expect(payload.DmgSections[0]).toMatchObject({ DmgKindId: null }); + expect(payload.DmgSections[0].DmgSectionCosts[0].DmgCostKindId).toBeNull(); + expect(warnings).toEqual( + expect.arrayContaining([ + expect.stringContaining("DmgKindId"), + expect.stringContaining("DmgCostKindId"), + ]), + ); + }); + + it("reports unavailable lookup data without reusing the old hardcoded ID", async () => { + const { service, build } = setup([]); + service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId.mockRejectedValue( + new Error("lookup unavailable"), + ); + const { payload, warnings } = await build(); + expect( + payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId), + ).toEqual([null, null]); + expect(warnings).toHaveLength(2); + }); + + it("reports a missing hull PolicyId instead of using the claim ID as a policy", async () => { + const { service, build } = setup([]); + const { warnings } = await build(null); + expect( + service.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId, + ).not.toHaveBeenCalled(); + expect(warnings).toEqual( + expect.arrayContaining([expect.stringContaining("missing PolicyId")]), + ); + }); + + it.each([ + { rows: [] }, + { rows: [{ Id: 900004, AccessoryKindId: 99, AccessoryDesc: "unrelated" }] }, + ])( + "reports unmapped accessories instead of guessing an ID: %j", + async ({ rows }) => { + const { build } = setup(rows); + const { payload, warnings } = await build(); + expect( + payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId), + ).toEqual([null, null]); + expect(warnings).toEqual( + expect.arrayContaining([ + expect.stringContaining("VehicleHullAccessoryId"), + ]), + ); + }, + ); +}); diff --git a/src/claim-request-management/fanavaran-hull-base-claim.spec.ts b/src/claim-request-management/fanavaran-hull-base-claim.spec.ts index 65325f1..20739dd 100644 --- a/src/claim-request-management/fanavaran-hull-base-claim.spec.ts +++ b/src/claim-request-management/fanavaran-hull-base-claim.spec.ts @@ -1,7 +1,7 @@ import { actualPremiumFromHullPolicyRecord, customerIdFromHullPolicyRecord, - FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID, + authorityCulpritIdFromDetectionRows, fanavaranHullNestedClaimId, toFanavaranHullBaseClaimPayload, } from "./fanavaran-hull-base-claim"; @@ -34,12 +34,13 @@ describe("fanavaran hull base claim", () => { expect(fanavaranHullNestedClaimId({ ClaimNo: 2268 })).toBeNull(); }); - it("keeps IsLicenseReplaced null even when ثالث IsLicenseReplacement is 0", () => { + it("sends IsLicenseReplaced as 0 using the hull field name", () => { const hull = toFanavaranHullBaseClaimPayload({ PolicyId: 1, IsLicenseReplacement: 0, }); - expect(hull.IsLicenseReplaced).toBeNull(); + expect(hull.IsLicenseReplaced).toBe(0); + expect(hull).not.toHaveProperty("IsLicenseReplacement"); }); it("strips ثالث-only fields from a live hull create echo", () => { @@ -72,11 +73,12 @@ describe("fanavaran hull base claim", () => { }); expect(hull.PolicyId).toBe(13764408); - expect(hull.AccidentTypeId).toBe(FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID); - expect(hull.IsLicenseReplaced).toBeNull(); + expect(hull.AccidentTypeId).toBeNull(); + expect(hull.IsLicenseReplaced).toBe(0); expect(hull.CostSeparationToDmgSections).toBe(0); expect(hull.IsOwnerChanged).toBe(0); - expect(hull.CulpritTypeId).toBe(300); + expect(hull.CulpritTypeId).toBeNull(); + expect(hull.AuthorityCulpritId).toBeNull(); expect(hull.DamagedCount).toBeUndefined(); expect(hull.HasOtherCulprit).toBeUndefined(); expect(hull.CompensationReferenceId).toBeUndefined(); @@ -84,4 +86,10 @@ describe("fanavaran hull base claim", () => { expect(hull.Id).toBeUndefined(); expect(hull.ClaimNo).toBeUndefined(); }); + + it("selects the authority from the response without inventing an ID when absent", () => { + expect(authorityCulpritIdFromDetectionRows([{ Id: 888, Caption: "بیمه گذار" }])).toBe(888); + expect(authorityCulpritIdFromDetectionRows([])).toBeNull(); + expect(actualPremiumFromHullPolicyRecord({})).toBeNull(); + }); }); diff --git a/src/claim-request-management/fanavaran-hull-base-claim.ts b/src/claim-request-management/fanavaran-hull-base-claim.ts index 153e8d5..ff57650 100644 --- a/src/claim-request-management/fanavaran-hull-base-claim.ts +++ b/src/claim-request-management/fanavaran-hull-base-claim.ts @@ -47,14 +47,13 @@ export const FANAVARAN_HULL_BASE_CLAIM_KEYS = [ "CostSeparationToDmgSections", ] as const; -/** GEN.03 default: تصادف(حادثه). Lookup: GET /lookups/vehicle-hull-accident-types */ -export const FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID = 2; +/** Select the current API row for the default collision scenario. */ +export const FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION = "تصادف(حادثه)"; /** GEN.03 ans (0=خیر). Used for CostSeparationToDmgSections, IsOwnerChanged, IsLicenseReplaced. */ export const FANAVARAN_HULL_ANS_NO = 0; -/** GEN.03 hull culprit type when third-party is at fault. Lookup: vehicle-hull-accident-culprit-type */ -export const FANAVARAN_DEFAULT_HULL_CULPRIT_TYPE_ID = 300; +export const FANAVARAN_HULL_CULPRIT_TYPE_CAPTION = "بيمه گذار"; /** GEN.03 required: درصد تقصير بيمه گذار. Proven Parsian submit uses 100. */ export const FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT = 100; @@ -63,7 +62,6 @@ export const FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT = 100; * GEN.03 required: مرجع تعيين مقصر. * Lookup: GET /lookups/detection-accident-culprits. Fallback is بیمه‌گذار. */ -export const FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID = 1; export const FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION = "بيمه گذار"; /** GEN.03 ActualPremium from GET car/vehicle-hull-policies/{PolicyId} → TotalPremium. */ @@ -72,6 +70,7 @@ export function actualPremiumFromHullPolicyRecord( ): number | null { if (!policy) return null; const raw = policy.TotalPremium ?? policy.totalPremium; + if (raw == null || raw === "") return null; const n = typeof raw === "number" ? raw : Number(raw); return Number.isFinite(n) && n >= 0 ? n : null; } @@ -80,6 +79,7 @@ function normalizeHullCaption(value: unknown): string { return String(value ?? "") .replace(/ي/g, "ی") .replace(/ك/g, "ک") + .replace(/\u200c/g, " ") .replace(/\s+/g, " ") .trim(); } @@ -87,13 +87,15 @@ function normalizeHullCaption(value: unknown): string { /** AuthorityCulpritId from GET /lookups/detection-accident-culprits. */ export function authorityCulpritIdFromDetectionRows( rows: unknown, -): number { +): number | null { const list = Array.isArray(rows) ? rows : []; const wanted = normalizeHullCaption( FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION, ); for (const row of list) { if (!row || typeof row !== "object") continue; + const active = (row as { IsActive?: unknown }).IsActive; + if (active === false || (active != null && Number(active) === 0)) continue; const caption = normalizeHullCaption( (row as { Caption?: unknown }).Caption, ); @@ -102,13 +104,7 @@ export function authorityCulpritIdFromDetectionRows( const n = typeof raw === "number" ? raw : Number(raw); if (Number.isFinite(n) && n > 0) return n; } - for (const row of list) { - if (!row || typeof row !== "object") continue; - const raw = (row as { Id?: unknown }).Id; - const n = typeof raw === "number" ? raw : Number(raw); - if (Number.isFinite(n) && n > 0) return n; - } - return FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID; + return null; } /** Fallback AccidentCulpritId when parties inquiry is unavailable. */ @@ -128,13 +124,12 @@ export function toFanavaranHullBaseClaimPayload( const next: Record = {}; for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) { if (key === "IsLicenseReplaced") { - // GEN.03: must be empty/null. Do not map ثالث IsLicenseReplacement (default 0). - next[key] = null; + // Hull GEN.03: explicitly send خیر. Keep the hull field name. + next[key] = FANAVARAN_HULL_ANS_NO; continue; } if (key === "AccidentTypeId") { - next[key] = - built.AccidentTypeId ?? FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID; + next[key] = built.AccidentTypeId ?? null; continue; } if (key === "CostSeparationToDmgSections") { @@ -150,7 +145,7 @@ export function toFanavaranHullBaseClaimPayload( const raw = built.CulpritTypeId; // ثالث profile default 337 is not in vehicle-hull-accident-culprit-type. if (raw == null || raw === 337) { - next[key] = FANAVARAN_DEFAULT_HULL_CULPRIT_TYPE_ID; + next[key] = null; } else { next[key] = raw; } @@ -163,8 +158,12 @@ export function toFanavaranHullBaseClaimPayload( continue; } if (key === "AuthorityCulpritId") { - next[key] = - built.AuthorityCulpritId ?? FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID; + next[key] = built.AuthorityCulpritId ?? null; + continue; + } + if (key === "PoliceOfficerId") { + // The shared third-party builder supplies a sample 1; hull has no officer source. + next[key] = null; continue; } next[key] = Object.prototype.hasOwnProperty.call(built, key) diff --git a/src/claim-request-management/fanavaran-hull-expertise-lookups.ts b/src/claim-request-management/fanavaran-hull-expertise-lookups.ts index 6137adf..6652801 100644 --- a/src/claim-request-management/fanavaran-hull-expertise-lookups.ts +++ b/src/claim-request-management/fanavaran-hull-expertise-lookups.ts @@ -3,13 +3,6 @@ import { parseFanavaranId } from "src/lookups/fanavaran-last-car-policy"; export const FANAVARAN_HULL_DMG_KIND_CAPTION = "تخریب"; export const FANAVARAN_HULL_DMG_COST_KIND_CAPTION = "مجموع لوازم"; -/** Fallback when lookup fetch fails (Parsian `vehicle-hull-dmg-kind`). */ -export const FANAVARAN_DEFAULT_HULL_DMG_KIND_ID = 5485; -/** Fallback when lookup fetch fails (`vehicle-hull-dmg-cost-kinds` Id). */ -export const FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID = 1; -/** GEN.06 factory (فابریک) accessory row. Used for every hull DmgSection. */ -export const FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID = 3043330; - export type FanavaranHullDmgAccessoryRow = { Id?: unknown; AccessoryKindId?: unknown; @@ -17,6 +10,14 @@ export type FanavaranHullDmgAccessoryRow = { }; export function asLookupRows(value: unknown): Record[] { + for ( + let depth = 0; + depth < 4 && value && !Array.isArray(value) && typeof value === "object"; + depth++ + ) { + const record = value as Record; + value = record.data ?? record.Data; + } if (!Array.isArray(value)) return []; return value.filter( (row): row is Record => @@ -24,7 +25,9 @@ export function asLookupRows(value: unknown): Record[] { ); } -export function asHullDmgAccessoryRows(value: unknown): FanavaranHullDmgAccessoryRow[] { +export function asHullDmgAccessoryRows( + value: unknown, +): FanavaranHullDmgAccessoryRow[] { return asLookupRows(value) as FanavaranHullDmgAccessoryRow[]; } @@ -32,16 +35,31 @@ export function findLookupIdByCaption( rows: unknown, caption: string, ): number | null { - const target = caption.trim(); + const normalize = (raw: unknown) => + String(raw ?? "") + .replace(/ي/g, "ی") + .replace(/ك/g, "ک") + .replace(/\u200c/g, " ") + .replace(/\s*([()])\s*/g, "$1") + .replace(/\s+/g, " ") + .trim(); + const target = normalize(caption); for (const row of asLookupRows(rows)) { - if (String(row.Caption ?? "").trim() !== target) continue; + if ( + row.IsActive === false || + (row.IsActive != null && Number(row.IsActive) === 0) + ) + continue; + if (normalize(row.Caption) !== target) continue; const id = parseFanavaranId(row.Id); if (id != null) return id; } return null; } -function isFactoryDefaultAccessoryRow(row: FanavaranHullDmgAccessoryRow): boolean { +function isFactoryDefaultAccessoryRow( + row: FanavaranHullDmgAccessoryRow, +): boolean { const desc = String(row.AccessoryDesc ?? "").trim(); return ( desc.includes("کليه قطعات فابريک") || @@ -74,5 +92,5 @@ export function resolveVehicleHullAccessoryId( const factoryId = parseFanavaranId(factory?.Id); if (factoryId != null) return factoryId; - return parseFanavaranId(accessories[0]?.Id); + return null; } diff --git a/src/claim-request-management/fanavaran-hull-expertise.ts b/src/claim-request-management/fanavaran-hull-expertise.ts index f85b84a..5db533b 100644 --- a/src/claim-request-management/fanavaran-hull-expertise.ts +++ b/src/claim-request-management/fanavaran-hull-expertise.ts @@ -72,8 +72,6 @@ function text(value: unknown): string | null { } export { - FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID, - FANAVARAN_DEFAULT_HULL_DMG_KIND_ID, FANAVARAN_HULL_DMG_COST_KIND_CAPTION, FANAVARAN_HULL_DMG_KIND_CAPTION, } from "./fanavaran-hull-expertise-lookups"; diff --git a/src/claim-request-management/fanavaran-hull-live-lookups.spec.ts b/src/claim-request-management/fanavaran-hull-live-lookups.spec.ts new file mode 100644 index 0000000..4e0b5f1 --- /dev/null +++ b/src/claim-request-management/fanavaran-hull-live-lookups.spec.ts @@ -0,0 +1,190 @@ +import { of } from "rxjs"; +import { ClaimRequestManagementService } from "./claim-request-management.service"; + +function setup() { + const service = Object.create(ClaimRequestManagementService.prototype) as any; + service.logger = { warn: jest.fn() }; + service.fanavaranLookupService = { + fetchFromFanavaran: jest + .fn() + .mockResolvedValue([{ Id: 63, Caption: "File" }]), + getRemoteLookup: jest.fn().mockResolvedValue([{ Id: 999 }]), + }; + service.fanavaranAuthService = { + assertNotInBackoff: jest.fn(), + clearBackoff: jest.fn(), + }; + service.getFanavaranAuthHeaders = jest.fn().mockResolvedValue({}); + service.httpService = { post: jest.fn().mockReturnValue(of({ data: {} })) }; + return service; +} + +describe("hull live lookup submission checks", () => { + it("bypasses file/database lookup caches when fresh responses are required", async () => { + const service = setup(); + expect( + await service.getFanavaranLookupRows("parsian", "file-types", true), + ).toEqual([{ Id: 63, Caption: "File" }]); + expect( + service.fanavaranLookupService.fetchFromFanavaran, + ).toHaveBeenCalled(); + expect( + service.fanavaranLookupService.getRemoteLookup, + ).not.toHaveBeenCalled(); + }); + + it("prevents a hull write with an attachment ID absent from the API response", async () => { + const service = setup(); + await expect( + service.postFanavaranJson( + "https://example.test/car/vehicle-hull-claims/123/files", + { FileTypeId: 999 }, + "parsian", + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ + code: "FANAVARAN_HULL_LOOKUP_INVALID", + }), + }); + expect(service.httpService.post).not.toHaveBeenCalled(); + }); + + it("sends a valid attachment ID obtained from the current API response", async () => { + const service = setup(); + const url = "https://example.test/car/vehicle-hull-claims/123/files"; + await service.postFanavaranJson(url, { FileTypeId: 63 }, "parsian"); + expect( + service.fanavaranLookupService.fetchFromFanavaran, + ).toHaveBeenCalled(); + expect(service.httpService.post).toHaveBeenCalledWith( + url, + { FileTypeId: 63 }, + expect.anything(), + ); + }); + + it("validates base-claim selections against live responses and refreshes the premium from the policy", async () => { + const service = setup(); + const rows = { + cities: 801, + "accident-report-type": 802, + "accident-causes": 803, + "vehicle-hull-accident-types": 804, + "vehicle-hull-accident-culprit-type": 805, + "detection-accident-culprits": 806, + "driving-licence-types": 807, + "vehicle-use-types": 808, + ans: 0, + }; + service.fanavaranLookupService.fetchFromFanavaran.mockImplementation( + async (_client: string, url: string) => ({ + data: [ + { Id: rows[url.split("/").at(-1)], Caption: "Valid", IsActive: 1 }, + ], + }), + ); + service.fanavaranLookupService.bodyPolicyById = jest + .fn() + .mockResolvedValue({ TotalPremium: 123456 }); + const payload = { + PolicyId: 14231020, + ActualPremium: 111, + AccidentCityId: 801, + AccidentReportTypeId: 802, + AccidentCauseId: 803, + AccidentTypeId: 804, + CulpritTypeId: 805, + AuthorityCulpritId: 806, + CulpritLicenceTypeId: 807, + AccidentVehicleUsedId: 808, + IsLicenseReplaced: 0, + }; + const url = "https://example.test/car/vehicle-hull-claims"; + await service.postFanavaranJson(url, payload, "parsian"); + expect(payload.ActualPremium).toBe(123456); + expect( + service.fanavaranLookupService.getRemoteLookup, + ).not.toHaveBeenCalled(); + service.httpService.post.mockClear(); + await expect( + service.postFanavaranJson( + url, + { ...payload, AccidentTypeId: 2 }, + "parsian", + ), + ).rejects.toMatchObject({ + response: expect.objectContaining({ + warnings: expect.arrayContaining([ + expect.stringContaining("AccidentTypeId=2"), + ]), + }), + }); + expect(service.httpService.post).not.toHaveBeenCalled(); + }); + + it("rejects inactive attachment types even when their IDs match", async () => { + const service = setup(); + service.fanavaranLookupService.fetchFromFanavaran.mockResolvedValue([ + { Id: 63, IsActive: 0 }, + ]); + await expect( + service.postFanavaranJson( + "https://example.test/car/vehicle-hull-claims/123/files", + { FileTypeId: 63 }, + "parsian", + ), + ).rejects.toThrow(); + expect(service.httpService.post).not.toHaveBeenCalled(); + }); + + it("blocks invalid lookup values on hull PUTs and multipart uploads too", async () => { + const service = setup(); + service.httpService.put = jest.fn(); + service.fanavaranLookupService.fetchFromFanavaran.mockResolvedValue([]); + const url = "https://example.test/car/vehicle-hull-claims/123/files"; + await expect( + service.putFanavaranJson(url, { FileTypeId: 63 }, "parsian"), + ).rejects.toThrow(); + await expect( + service.postFanavaranMultipart(url, { FileTypeId: 63 }, [], "parsian"), + ).rejects.toThrow(); + expect(service.httpService.post).not.toHaveBeenCalled(); + expect(service.httpService.put).not.toHaveBeenCalled(); + }); + + it("resolves default hull base selections from changed lookup IDs", async () => { + const service = setup(); + service.logger.log = jest.fn(); + service.getFanavaranLookupRows = jest.fn().mockImplementation( + async (_client: string, name: string) => + ({ + "vehicle-hull-accident-types": [ + { Id: 804, Caption: "تصادف (حادثه)" }, + ], + "vehicle-hull-accident-culprit-type": [ + { Id: 805, Caption: "بیمه گذار" }, + ], + "detection-accident-culprits": [{ Id: 806, Caption: "بیمه گذار" }], + })[name], + ); + service.fanavaranLookupService.bodyPolicyById = jest + .fn() + .mockResolvedValue({ TotalPremium: 123456 }); + const payload: Record = { + PolicyId: 14231020, + CulpritTypeId: 337, + }; + await service.enrichCarBodyHullBaseClaimPayload({ + clientKey: "parsian", + payload, + blameCase: {}, + logPrefix: "test", + }); + expect(payload).toMatchObject({ + AccidentTypeId: 804, + CulpritTypeId: 805, + AuthorityCulpritId: 806, + ActualPremium: 123456, + }); + }); +}); diff --git a/src/claim-request-management/fanavaran-hull-lookup-validation.ts b/src/claim-request-management/fanavaran-hull-lookup-validation.ts new file mode 100644 index 0000000..ee56b94 --- /dev/null +++ b/src/claim-request-management/fanavaran-hull-lookup-validation.ts @@ -0,0 +1,113 @@ +import { asLookupRows } from "./fanavaran-hull-expertise-lookups"; + +export type HullLookupStage = "baseClaim" | "expertise" | "files"; +type LookupField = { + row: Record; + key: string; + lookup: string; + path: string; +}; + +/** Validate outbound IDs against responses for this tenant, never a sample ID. */ +export async function validateFanavaranHullLookupIds( + payload: Record, + stage: HullLookupStage, + fetchRows: (lookup: string) => Promise, +): Promise { + const fields: LookupField[] = []; + const add = ( + row: Record, + key: string, + lookup: string, + path = key, + required = true, + ) => { + if (required || row[key] != null) fields.push({ row, key, lookup, path }); + }; + if (stage === "baseClaim") { + for (const [key, lookup] of Object.entries({ + AccidentCityId: "cities", + AccidentReportTypeId: "accident-report-type", + AccidentCauseId: "accident-causes", + AccidentTypeId: "vehicle-hull-accident-types", + CulpritTypeId: "vehicle-hull-accident-culprit-type", + AuthorityCulpritId: "detection-accident-culprits", + CulpritLicenceTypeId: "driving-licence-types", + AccidentVehicleUsedId: "vehicle-use-types", + })) + add(payload, key, lookup); + for (const key of [ + "IsLicenseReplaced", + "IsOwnerChanged", + "CostSeparationToDmgSections", + "IsAccidentOutOfBorder", + "IsSurplusArticleEighthLaw", + ]) + add(payload, key, "ans", key, false); + add(payload, "CulpritLicenceCountryId", "countries", undefined, false); + add(payload, "CulpritLicenceCityId", "cities", undefined, false); + add(payload, "NotifierTypeId", "notifier-type", undefined, false); + add(payload, "NotifierRelationId", "notifier-relation", undefined, false); + } else if (stage === "files") { + add(payload, "FileTypeId", "file-types"); + for (const [i, row] of asLookupRows(payload.Files).entries()) + add(row, "FileTypeId", "file-types", `Files[${i}].FileTypeId`); + } else { + for (const [i, row] of asLookupRows(payload.DmgSections).entries()) { + const prefix = `DmgSections[${i}]`; + add( + row, + "AccessoryKindId", + "car-components", + `${prefix}.AccessoryKindId`, + ); + add( + row, + "VehicleHullAccessoryId", + "policy-dmg-accessories", + `${prefix}.VehicleHullAccessoryId`, + ); + add(row, "DmgKindId", "vehicle-hull-dmg-kind", `${prefix}.DmgKindId`); + for (const [j, cost] of asLookupRows(row.DmgSectionCosts).entries()) + add( + cost, + "DmgCostKindId", + "vehicle-hull-dmg-cost-kinds", + `${prefix}.DmgSectionCosts[${j}].DmgCostKindId`, + ); + } + } + const sources = new Map[]>(); + await Promise.all( + [...new Set(fields.map((field) => field.lookup))].map(async (lookup) => { + try { + sources.set(lookup, asLookupRows(await fetchRows(lookup))); + } catch { + sources.set(lookup, []); + } + }), + ); + const warnings: string[] = []; + for (const field of fields) { + const raw = field.row[field.key]; + const id = raw == null || String(raw).trim() === "" ? NaN : Number(raw); + const matched = + Number.isSafeInteger(id) && id >= 0 + ? sources + .get(field.lookup) + ?.find( + (row) => + row.Id != null && + Number(row.Id) === id && + row.IsActive !== false && + (row.IsActive == null || Number(row.IsActive) !== 0), + ) + : undefined; + if (!matched) + warnings.push( + `${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response.`, + ); + else field.row[field.key] = Number(matched.Id); + } + return warnings; +} diff --git a/src/expert-claim/fanavaran-stage-fields.spec.ts b/src/expert-claim/fanavaran-stage-fields.spec.ts index 81e5c81..7ca4fe3 100644 --- a/src/expert-claim/fanavaran-stage-fields.spec.ts +++ b/src/expert-claim/fanavaran-stage-fields.spec.ts @@ -49,6 +49,10 @@ function setup(product = "third-party", extra: any = {}) { "vehicle-hull-accident-types": 4, "vehicle-hull-accident-culprit-type": 301, "detection-accident-culprits": 8, + "accident-causes": 6, + "driving-licence-types": 2, + "vehicle-use-types": 1, + ans: 0, }; return [ { Id: ids[name], Caption: "گزینه معتبر", IsActive: 1 }, @@ -166,6 +170,9 @@ describe("Expert Fanavaran stage fields", () => { payload.CustomerFaultPercent = 100; payload.AuthorityCulpritId = 1; }); + management.fanavaranLookupService = { + bodyPolicyById: jest.fn().mockResolvedValue({ TotalPremium: 123456 }), + }; const payload = await management.previewFanavaranSubmitV2(id, clientKey, { persistPayload: false, forceRefreshPolicy: false, @@ -195,7 +202,7 @@ describe("Expert Fanavaran stage fields", () => { CulpritTypeId: 301, AuthorityCulpritId: 8, CustomerFaultPercent: 0, - IsLicenseReplaced: null, + IsLicenseReplaced: 0, }); expect(payload.DamagedCount).toBeUndefined(); expect(payload.IsLicenseReplacement).toBeUndefined();