Compare commits

...
3 Commits
19 changed files with 1200 additions and 181 deletions
+28 -1
View File
@@ -23,14 +23,41 @@ Secrets are **not** printed here — read from Mongo `fanavaranClientConfigs` or
| `password` | *(config)* | Login | Password | ✅ | | `password` | *(config)* | Login | Password | ✅ |
| `corpId` | `543` | All business calls | Corp scope | ✅ | | `corpId` | `543` | All business calls | Corp scope | ✅ |
| `contractId` | `28` | All business calls | Contract | ✅ | | `contractId` | `28` | All business calls | Contract | ✅ |
| `location` | `210050` | Fallback only when no staff location | Tenant default OpBUId | ✅ (per expert `locations[].id` at runtime) | | `location` | `210050` | General calls without claim context | Tenant default OpBUId | ✅ (claim submissions require a staff location or branch code) |
Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(key)`. Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(key)`.
Claim submissions resolve `Location` from staff profiles in the `file-maker`,
`file-reviewer`, `expert`, `damage-expert`, and `field-expert` collections. Each
profile stores `locations: [{ id, name }]`; the first non-empty `id` is its primary
Fanavaran OpBUId. When staff locations are missing, null, or empty, resolve that
staff member's `branchId` in the `branches` collection and use the branch's `code`
as the OpBUId. This branch fallback is checked before moving to another staff
candidate. The branch document's `_id` is never sent as the HTTP Location.
Resolution priority: claim initiator → blame initiator → active damage reply actor
→ assigned damage reviewer → assigned FileReviewer → assigned blame expert → blame
decision actor. The first candidate with a location wins. A missing blame record
does not discard the claim's own staff. When none has a location, claim submission
fails with `FANAVARAN_STAFF_LOCATION_MISSING` instead of sending the tenant default.
Base claim, damage, attachment, expertise, hull update, and GEN.44 create calls use
the same claim header resolver. Authentication requests do not send Location;
the cached login token can be reused across staff locations.
--- ---
## Payload defaults (tenant profile.defaults) ## 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? | | Name | Shared seed | Parsian override | Tejaratno | Moallem | Varies? |
|------|-------------|------------------|-----------|---------|---------| |------|-------------|------------------|-----------|---------|---------|
| `AccidentCityId` | 701 | same | same | same | usually ❌ | | `AccidentCityId` | 701 | same | same | same | usually ❌ |
+1 -1
View File
@@ -190,7 +190,7 @@ curl -sS -X POST \
| `AccidentTypeId` | `GET /lookups/vehicle-hull-accident-types` | **2** = تصادف(حادثه) | | `AccidentTypeId` | `GET /lookups/vehicle-hull-accident-types` | **2** = تصادف(حادثه) |
| `CostSeparationToDmgSections` | `GET /lookups/ans` | **0** = خیر | | `CostSeparationToDmgSections` | `GET /lookups/ans` | **0** = خیر |
| `IsOwnerChanged` | `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`) | | `CulpritTypeId` | `GET /lookups/vehicle-hull-accident-culprit-type` | **301** = حادثه مقصر شناخته شده دارد (not ثالث `337`) |
| `CustomerFaultPercent` | — | **100** | | `CustomerFaultPercent` | — | **100** |
| `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` | بیمه‌گذار (`Id` from lookup, fallback **1**) | | `AuthorityCulpritId` | `GET /lookups/detection-accident-culprits` | بیمه‌گذار (`Id` from lookup, fallback **1**) |
+8 -8
View File
@@ -44,21 +44,21 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
| AccidentCauseId | علت حادثه | number | **no** | **system** `6` · lookup `accident-causes` | | AccidentCauseId | علت حادثه | number | **no** | **system** `6` · lookup `accident-causes` |
| AccidentCityId | شهر حادثه | number | **no** | **user** expert review, else **system** `701` · lookup `cities` | | AccidentCityId | شهر حادثه | number | **no** | **user** expert review, else **system** `701` · lookup `cities` |
| AccidentReportTypeId | نحوه اعلام | number | **no** | **user** expert review, else **system** `155` · lookup `accident-report-type` | | 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` | | AccidentTypeId | نوع حادثه بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-types` row caption تصادف(حادثه); no numeric fallback |
| CulpritTypeId | نوع مقصر بدنه | number | **no** | **user** expert review, else **system** `300` (ثالث `337` remapped) · **lookup** `GET /lookups/vehicle-hull-accident-culprit-type` | | CulpritTypeId | نوع مقصر بدنه | number | **no** | Reviewed choice, else current `vehicle-hull-accident-culprit-type` row caption بیمه‌گذار; never reuse third-party `337` |
| AuthorityCulpritId | مرجع تعیین مقصر | number | **no** | **user** expert review, else **lookup** `GET /lookups/detection-accident-culprits` (caption بیمه‌گذار, fallback `1`) | | 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` | | AccidentCulpritId | شناسه مقصر فناوران | number | preferred | **inquiry** parties `inquiry-by-unique-identifier`, fallback hull policy `CustomerId` |
| CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` | | CustomerFaultPercent | درصد تقصیر بیمه‌گذار | number | **no** | **user** expert review, else **system** `100` |
| CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` | | CostSeparationToDmgSections | تفکیک هزینه به نقاط | number (ans) | **no** | **system** `0` خیر · lookup `ans` |
| IsOwnerChanged | مالک تغییر یافته؟ | 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}` | | ActualPremium | حق بیمه واقعی | number | preferred | **inquiry** hull policy `TotalPremium` via `GET /lookups/body-policy/{PolicyId}` |
| EstimateAmount | برآورد | number | **no** | **user** expert prices / provisional | | EstimateAmount | برآورد | number | **no** | **user** expert prices / provisional |
| CulpritLicenceNo | شماره گواهینامه | string | **no** | dummy / **user** | | CulpritLicenceNo | شماره گواهینامه | string | **no** | dummy / **user** |
| CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **system** `"1394/10/13"` | | CulpritLicenceIssuDate | تاریخ صدور گواهینامه | string Jalali | **no** | **system** `"1394/10/13"` |
| CulpritLicenceTypeId | نوع گواهینامه | number | sent | tenant `2` · lookup `driving-licence-types` | | 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. | | 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` | | IsAccidentOutOfBorder | خارج از مرز | number | sent | **system** `0` |
| ArchiveNo | بایگانی | string | yes | null | | ArchiveNo | بایگانی | string | yes | null |
| EntryDate | تاریخ ورود | 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[].Desc | شرح قطعه | string | **no** | **user** part label |
| DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** | | DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** |
| DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` | | DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` |
| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | **lookup** `vehicle-hull-dmg-kind` caption تخریب, fallback `5485` | | DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | Current `vehicle-hull-dmg-kind` API row caption تخریب; no numeric fallback |
| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | **no** | **system** `3043330` (فابریک) for **every** row | | 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[].Caption | عنوان هزینه | string | **no** | **user** label |
| DmgSections[].DmgSectionCosts[].Amount | مبلغ (قطعه+اجرت) | number | **no** | **user** | | 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). **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).
@@ -115,7 +115,7 @@ Hull is **first party**. One vehicle, one policy.
| درصد تقصیر بیمه‌گذار | CustomerFaultPercent | number 0–100 | **user** if not 100%; today always 100 | | درصد تقصیر بیمه‌گذار | CustomerFaultPercent | number 0–100 | **user** if not 100%; today always 100 |
| تفکیک هزینه به نقاط | CostSeparationToDmgSections | ans | **user** default خیر | | تفکیک هزینه به نقاط | CostSeparationToDmgSections | ans | **user** default خیر |
| مالک تغییر یافته؟ | IsOwnerChanged | 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** | | قطعات آسیب‌دیده | selectedParts | catalog ids | **user** |
### Expert pricing (بدنه) ### Expert pricing (بدنه)
+1 -1
View File
@@ -53,7 +53,7 @@ Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `
All four codes are optional, editable and clearable for blame, claim and field experts. FileMaker accounts accept only the first two, FileReviewer accounts accept only the last two, and call-center accounts reject all four through the API. The panel presents these four named fields rather than the legacy generic `expertCode` input; existing `expertCode` values are preserved. All four codes are optional, editable and clearable for blame, claim and field experts. FileMaker accounts accept only the first two, FileReviewer accounts accept only the last two, and call-center accounts reject all four through the API. The panel presents these four named fields rather than the legacy generic `expertCode` input; existing `expertCode` values are preserved.
`locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran OpBUId / HTTP `Location` values, rather than branch codes. On every Fanavaran business call for a claim, the integration prefers the assigned staff member's primary `locations[].id` (file-maker, file-reviewer, field, blame, or damage expert) for all tenants; the tenant auth `location` is only a fallback. Shared locations still participate in Parsian FileMaker/FileReviewer matching; management does not alter that matching logic. `locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran OpBUId / HTTP `Location` values. Claim submissions prefer the responsible staff member's primary `locations[].id` (file-maker, file-reviewer, field, blame, or damage expert) for all tenants. When that array is missing, null, or empty, the integration loads the staff member's branch using `branchId` and uses `branches.code`. It checks this branch fallback before moving to another staff candidate. If no candidate supplies a staff location or branch code, submission reports `FANAVARAN_STAFF_LOCATION_MISSING` instead of sending the tenant default. Shared staff locations still participate in Parsian FileMaker/FileReviewer matching; management does not alter that matching logic.
Branches require `code`, `name`, `city`, `state`, and `address`. `fullName`, `phoneNumber`, `isActive` (default true) and `activityStartDate` are optional and editable. Branch codes remain unique within an insurer. Insurer login accounts support name, email, password and optional contact/address fields; their role and tenant are assigned by the server. Branches require `code`, `name`, `city`, `state`, and `address`. `fullName`, `phoneNumber`, `isActive` (default true) and `activityStartDate` are optional and editable. Branch codes remain unique within an insurer. Insurer login accounts support name, email, password and optional contact/address fields; their role and tenant are assigned by the server.
@@ -188,7 +188,8 @@ import {
actualPremiumFromHullPolicyRecord, actualPremiumFromHullPolicyRecord,
authorityCulpritIdFromDetectionRows, authorityCulpritIdFromDetectionRows,
customerIdFromHullPolicyRecord, customerIdFromHullPolicyRecord,
FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID, FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION,
FANAVARAN_HULL_CULPRIT_TYPE_CAPTION,
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
fanavaranHullNestedClaimId, fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload, toFanavaranHullBaseClaimPayload,
@@ -205,13 +206,16 @@ import {
vehicleCurrentValueFromHullPolicyRecord, vehicleCurrentValueFromHullPolicyRecord,
} from './fanavaran-hull-expertise'; } from './fanavaran-hull-expertise';
import { 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_COST_KIND_CAPTION,
FANAVARAN_HULL_DMG_KIND_CAPTION, FANAVARAN_HULL_DMG_KIND_CAPTION,
findLookupIdByCaption, findLookupIdByCaption,
asHullDmgAccessoryRows,
resolveVehicleHullAccessoryId,
} from './fanavaran-hull-expertise-lookups'; } from './fanavaran-hull-expertise-lookups';
import {
validateFanavaranHullLookupIds,
type HullLookupStage,
} from './fanavaran-hull-lookup-validation';
import { import {
activeStageLookupRows, activeStageLookupRows,
applyFanavaranStageFieldReview, applyFanavaranStageFieldReview,
@@ -2636,23 +2640,15 @@ export class ClaimRequestManagementService {
input.payload.CustomerFaultPercent = input.payload.CustomerFaultPercent =
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT; FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT;
if (parseFanavaranId(input.payload.AuthorityCulpritId) == null) { const [accidentTypes, culpritTypes, authorities] = await Promise.all([
try { this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-types', true),
const authorityRows = await this.getFanavaranLookupRows( this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-culprit-type', true),
input.clientKey, this.getFanavaranLookupRows(input.clientKey, 'detection-accident-culprits', true),
'detection-accident-culprits', ]);
); input.payload.AccidentTypeId ??= findLookupIdByCaption(accidentTypes, FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION);
input.payload.AuthorityCulpritId = if (input.payload.CulpritTypeId == null || input.payload.CulpritTypeId === 337)
authorityCulpritIdFromDetectionRows(authorityRows); input.payload.CulpritTypeId = findLookupIdByCaption(culpritTypes, FANAVARAN_HULL_CULPRIT_TYPE_CAPTION);
} catch (error) { input.payload.AuthorityCulpritId ??= authorityCulpritIdFromDetectionRows(authorities);
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;
}
}
} }
/** GEN.06: VehicleCurrentValue from hull policy when price-drop / frontend value is missing. */ /** 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([ const [dmgKindRows, dmgCostKindRows, policyRecord, componentRows] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind'), this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind', true),
this.getFanavaranLookupRows( this.getFanavaranLookupRows(
input.clientKey, input.clientKey,
'vehicle-hull-dmg-cost-kinds', 'vehicle-hull-dmg-cost-kinds',
true,
), ),
policyId != null policyId != null
? this.fanavaranLookupService.bodyPolicyById( ? this.fanavaranLookupService.bodyPolicyById(
@@ -2741,16 +2738,34 @@ export class ClaimRequestManagementService {
contractOptions, contractOptions,
) )
: Promise.resolve(null), : Promise.resolve(null),
input.parts.length ? this.getFanavaranLookupRows(input.clientKey, 'car-components', true) : Promise.resolve([]),
]); ]);
const dmgKindId = const dmgKindId =
findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION) ?? findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION);
FANAVARAN_DEFAULT_HULL_DMG_KIND_ID;
const dmgCostKindId = const dmgCostKindId =
findLookupIdByCaption( findLookupIdByCaption(
dmgCostKindRows, dmgCostKindRows,
FANAVARAN_HULL_DMG_COST_KIND_CAPTION, 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 vehicle = pickHullVehicleIdentity(input.blame);
let colorId: number | null = null; let colorId: number | null = null;
@@ -2795,6 +2810,10 @@ export class ClaimRequestManagementService {
); );
const hullSections = input.parts.map((part: any) => { const hullSections = input.parts.map((part: any) => {
const vehicleHullAccessoryId = resolveVehicleHullAccessoryId(
accessories,
parseFanavaranId(part?.partId),
);
return toFanavaranHullExpertiseDmgSection({ return toFanavaranHullExpertiseDmgSection({
partId: part?.partId, partId: part?.partId,
desc: this.fanavaranPartLabel(part), desc: this.fanavaranPartLabel(part),
@@ -2804,7 +2823,7 @@ export class ClaimRequestManagementService {
this.parseFanavaranMoney(part?.salary), this.parseFanavaranMoney(part?.salary),
dmgKindId, dmgKindId,
dmgCostKindId, dmgCostKindId,
vehicleHullAccessoryId: FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID, vehicleHullAccessoryId,
}); });
}); });
@@ -2824,23 +2843,27 @@ export class ClaimRequestManagementService {
input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ?? input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ??
FANAVARAN_DEFAULT_HULL_REPAIR_DURATION; 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 { return {
replyKey: input.replyKey, replyKey: input.replyKey,
warnings: input.warnings, warnings: input.warnings,
payload: toFanavaranHullExpertisePayload({ payload,
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,
}),
}; };
} }
@@ -3367,46 +3390,35 @@ export class ClaimRequestManagementService {
/** /**
* Fanavaran HTTP Location from assigned staff `locations[].id` * Fanavaran HTTP Location from assigned staff `locations[].id`
* (file-maker / file-reviewer / field / blame / damage expert), for every * (file-maker / file-reviewer / field / blame / damage expert), for every
* tenant. Falls back to tenant auth.location only when no staff location is set. * tenant. Prefer the claim creator, then the originating file's staff.
* Missing staff configuration must not submit a claim to a default branch.
*/ */
private async resolveFanavaranLocationForClaim( private async resolveFanavaranLocationForClaim(
claimCaseId: string, claimCaseId: string,
clientKey: FanavaranClientKey, clientKey: FanavaranClientKey,
): Promise<string> { ): Promise<string> {
const defaultLocation = getFanavaranClientProfile(clientKey).auth.location; const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
try { throw new NotFoundException('Claim case not found');
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase?.blameRequestId) {
return defaultLocation;
}
const blame = await this.blameRequestDbService.findById(
String(claimCase.blameRequestId),
);
if (!blame) {
return defaultLocation;
}
return this.fanavaranLocationService.resolveBusinessLocation({
clientKey,
staffCandidateIds: [
(blame as any)?.initiatedByFieldExpertId,
(blame as any)?.expert?.assignedExpertId,
(blame as any)?.expert?.decision?.decidedByExpertId,
(claimCase as any)?.initiatedByFieldExpertId,
this.fanavaranDamageReplyActorId(claimCase),
(claimCase as any)?.workflow?.assignedForReviewBy?.actorId,
(blame as any)?.assignedFileReviewerId,
],
});
} catch (error) {
this.logger.warn(
`[Fanavaran Location] Failed to resolve for claimCaseId=${claimCaseId}; using tenant default`,
error,
);
return defaultLocation;
} }
const blame = claimCase.blameRequestId
? await this.blameRequestDbService.findById(String(claimCase.blameRequestId))
: null;
return this.fanavaranLocationService.resolveBusinessLocation({
clientKey,
requireStaffLocation: true,
staffCandidateIds: [
claimCase.initiatedByFieldExpertId,
blame?.initiatedByFieldExpertId,
this.fanavaranDamageReplyActorId(claimCase),
claimCase.workflow?.assignedForReviewBy?.actorId,
blame?.assignedFileReviewerId,
blame?.expert?.assignedExpertId,
blame?.expert?.decision?.decidedByExpertId,
].map((id) => (id == null ? undefined : String(id))),
});
} }
private fanavaranPayloadDefaultsWithoutExpertIds( private fanavaranPayloadDefaultsWithoutExpertIds(
@@ -3839,17 +3851,6 @@ export class ClaimRequestManagementService {
InsuranceLineId: insuranceLineId, InsuranceLineId: insuranceLineId,
}; };
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.STARTED,
requestUrl: policyInquiryUrl,
requestMethod: 'GET',
requestMeta,
});
}
try { try {
this.fanavaranAuthService.assertNotInBackoff(clientKey); this.fanavaranAuthService.assertNotInBackoff(clientKey);
const headers = await this.getFanavaranAuthHeaders( const headers = await this.getFanavaranAuthHeaders(
@@ -3861,6 +3862,19 @@ export class ClaimRequestManagementService {
...headers, ...headers,
'Content-Type': 'application/json', 'Content-Type': 'application/json',
}; };
requestMeta.location = headers.Location;
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.STARTED,
requestUrl: policyInquiryUrl,
requestMethod: 'GET',
requestHeaders,
requestMeta,
});
}
this.logger.log( this.logger.log(
`${logPrefix} Calling policy inquiry API for nationalCode: ${nationalCodeOfInsurer}`, `${logPrefix} Calling policy inquiry API for nationalCode: ${nationalCodeOfInsurer}`,
@@ -4220,10 +4234,14 @@ export class ClaimRequestManagementService {
}); });
try { try {
const created = await this.fanavaranLookupService.createOtherPerson( const response = await this.postFanavaranJson(
input.clientKey, url,
payload, payload,
input.clientKey,
auditSession,
input.claimCaseId,
); );
const created = response.data;
const personId = pickFanavaranRecordId(created); const personId = pickFanavaranRecordId(created);
await this.fanavaranAuditService.recordStep({ await this.fanavaranAuditService.recordStep({
session: auditSession, session: auditSession,
@@ -4780,6 +4798,18 @@ export class ClaimRequestManagementService {
const hull = toFanavaranHullBaseClaimPayload(payload, clientKey); const hull = toFanavaranHullBaseClaimPayload(payload, clientKey);
for (const key of Object.keys(payload)) delete payload[key]; for (const key of Object.keys(payload)) delete payload[key];
Object.assign(payload, hull); 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 ( if (
@@ -5660,8 +5690,8 @@ export class ClaimRequestManagementService {
AccidentReportTypeId: defaults.AccidentReportTypeId, AccidentReportTypeId: defaults.AccidentReportTypeId,
DmgHistoryStatus: defaults.DmgHistoryStatus, DmgHistoryStatus: defaults.DmgHistoryStatus,
InspectionPlaceId: 282, InspectionPlaceId: 282,
AccidentTypeId: 2, AccidentTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-types') ?? [], FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION),
CulpritTypeId: 300, CulpritTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-culprit-type') ?? [], FANAVARAN_HULL_CULPRIT_TYPE_CAPTION),
AuthorityCulpritId: authorityCulpritIdFromDetectionRows( AuthorityCulpritId: authorityCulpritIdFromDetectionRows(
options.get('detection-accident-culprits') ?? [], options.get('detection-accident-culprits') ?? [],
), ),
@@ -5720,11 +5750,65 @@ export class ClaimRequestManagementService {
}; };
} }
private async assertFanavaranHullApiValues(
url: string,
payload: Record<string, unknown>,
clientKey: FanavaranClientKey,
claimCaseId?: string,
): Promise<void> {
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( private async getFanavaranLookupRows(
clientKey: FanavaranClientKey, clientKey: FanavaranClientKey,
name: string, name: string,
requireRemote = false,
): Promise<unknown[]> { ): Promise<unknown[]> {
if (clientKey === 'tejaratno' && isTejaratNotifierLookup(name)) { if (
!requireRemote && clientKey === 'tejaratno' && isTejaratNotifierLookup(name)
) {
const stored = await this.fanavaranLookupService.readStoredLookup(name); const stored = await this.fanavaranLookupService.readStoredLookup(name);
let rows: unknown = stored; let rows: unknown = stored;
for ( for (
@@ -5738,11 +5822,15 @@ export class ClaimRequestManagementService {
} }
const definition = this.fanavaranLookupDefinition(name); const definition = this.fanavaranLookupDefinition(name);
try { try {
const data = await this.fanavaranLookupService.getRemoteLookup( const data = requireRemote
clientKey, ? await this.fanavaranLookupService.fetchFromFanavaran(clientKey, definition.url, {
definition.url, contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
definition.cacheFile, })
); : await this.fanavaranLookupService.getRemoteLookup(
clientKey,
definition.url,
definition.cacheFile,
);
let rows: unknown = data; let rows: unknown = data;
for ( for (
let level = 0; let level = 0;
@@ -5895,13 +5983,26 @@ export class ClaimRequestManagementService {
warnings.push('No submit-ready expert pricing lines exist yet.'); 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([ const [inspectionPlaces, dropAmountStatuses] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'inspection-place'), this.getFanavaranLookupRows(input.clientKey, 'inspection-place'),
this.getFanavaranLookupRows(input.clientKey, 'drop-amount-status'), this.getFanavaranLookupRows(input.clientKey, 'drop-amount-status'),
]); ]);
const priceDrop = input.claimCase.evaluation?.priceDrop ?? {};
const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total);
const inspectionPlaceId = const inspectionPlaceId =
input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282; input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282;
const dropAmountStatus = 5458; const dropAmountStatus = 5458;
@@ -5925,28 +6026,6 @@ export class ClaimRequestManagementService {
(sum, section) => sum + this.parseFanavaranMoney(section.WasteValue), (sum, section) => sum + this.parseFanavaranMoney(section.WasteValue),
0, 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<string, unknown> = { const payload: Record<string, unknown> = {
ClaimExpertId: claimExpertId, ClaimExpertId: claimExpertId,
ComponentReplacementCost: componentReplacementCost, ComponentReplacementCost: componentReplacementCost,
@@ -6515,6 +6594,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string, claimCaseId?: string,
) { ) {
this.fanavaranAuthService.assertNotInBackoff(clientKey); this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders( const headers = await this.getFanavaranAuthHeaders(
clientKey, clientKey,
auditSession, auditSession,
@@ -6546,6 +6626,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string, claimCaseId?: string,
) { ) {
this.fanavaranAuthService.assertNotInBackoff(clientKey); this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders( const headers = await this.getFanavaranAuthHeaders(
clientKey, clientKey,
auditSession, auditSession,
@@ -6623,6 +6704,7 @@ export class ClaimRequestManagementService {
claimCaseId?: string, claimCaseId?: string,
) { ) {
this.fanavaranAuthService.assertNotInBackoff(clientKey); this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, content, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders( const headers = await this.getFanavaranAuthHeaders(
clientKey, clientKey,
auditSession, auditSession,
@@ -7512,6 +7594,7 @@ export class ClaimRequestManagementService {
claimCaseId, claimCaseId,
); );
const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId); const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId);
await this.assertFanavaranHullApiValues(submitUrl, fanavaranData, clientKey, claimCaseId);
const requestHeaders = { const requestHeaders = {
...headers, ...headers,
@@ -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"),
]),
);
},
);
});
@@ -1,7 +1,7 @@
import { import {
actualPremiumFromHullPolicyRecord, actualPremiumFromHullPolicyRecord,
customerIdFromHullPolicyRecord, customerIdFromHullPolicyRecord,
FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID, authorityCulpritIdFromDetectionRows,
fanavaranHullNestedClaimId, fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload, toFanavaranHullBaseClaimPayload,
} from "./fanavaran-hull-base-claim"; } from "./fanavaran-hull-base-claim";
@@ -34,12 +34,13 @@ describe("fanavaran hull base claim", () => {
expect(fanavaranHullNestedClaimId({ ClaimNo: 2268 })).toBeNull(); 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({ const hull = toFanavaranHullBaseClaimPayload({
PolicyId: 1, PolicyId: 1,
IsLicenseReplacement: 0, 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", () => { 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.PolicyId).toBe(13764408);
expect(hull.AccidentTypeId).toBe(FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID); expect(hull.AccidentTypeId).toBeNull();
expect(hull.IsLicenseReplaced).toBeNull(); expect(hull.IsLicenseReplaced).toBe(0);
expect(hull.CostSeparationToDmgSections).toBe(0); expect(hull.CostSeparationToDmgSections).toBe(0);
expect(hull.IsOwnerChanged).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.DamagedCount).toBeUndefined();
expect(hull.HasOtherCulprit).toBeUndefined(); expect(hull.HasOtherCulprit).toBeUndefined();
expect(hull.CompensationReferenceId).toBeUndefined(); expect(hull.CompensationReferenceId).toBeUndefined();
@@ -84,4 +86,10 @@ describe("fanavaran hull base claim", () => {
expect(hull.Id).toBeUndefined(); expect(hull.Id).toBeUndefined();
expect(hull.ClaimNo).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();
});
}); });
@@ -47,14 +47,13 @@ export const FANAVARAN_HULL_BASE_CLAIM_KEYS = [
"CostSeparationToDmgSections", "CostSeparationToDmgSections",
] as const; ] as const;
/** GEN.03 default: تصادف(حادثه). Lookup: GET /lookups/vehicle-hull-accident-types */ /** Select the current API row for the default collision scenario. */
export const FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID = 2; export const FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION = "تصادف(حادثه)";
/** GEN.03 ans (0=خیر). Used for CostSeparationToDmgSections, IsOwnerChanged, IsLicenseReplaced. */ /** GEN.03 ans (0=خیر). Used for CostSeparationToDmgSections, IsOwnerChanged, IsLicenseReplaced. */
export const FANAVARAN_HULL_ANS_NO = 0; 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_HULL_CULPRIT_TYPE_CAPTION = "بيمه گذار";
export const FANAVARAN_DEFAULT_HULL_CULPRIT_TYPE_ID = 300;
/** GEN.03 required: درصد تقصير بيمه گذار. Proven Parsian submit uses 100. */ /** GEN.03 required: درصد تقصير بيمه گذار. Proven Parsian submit uses 100. */
export const FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT = 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: مرجع تعيين مقصر. * GEN.03 required: مرجع تعيين مقصر.
* Lookup: GET /lookups/detection-accident-culprits. Fallback is بیمه‌گذار. * Lookup: GET /lookups/detection-accident-culprits. Fallback is بیمه‌گذار.
*/ */
export const FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID = 1;
export const FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION = "بيمه گذار"; export const FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION = "بيمه گذار";
/** GEN.03 ActualPremium from GET car/vehicle-hull-policies/{PolicyId} → TotalPremium. */ /** GEN.03 ActualPremium from GET car/vehicle-hull-policies/{PolicyId} → TotalPremium. */
@@ -72,6 +70,7 @@ export function actualPremiumFromHullPolicyRecord(
): number | null { ): number | null {
if (!policy) return null; if (!policy) return null;
const raw = policy.TotalPremium ?? policy.totalPremium; const raw = policy.TotalPremium ?? policy.totalPremium;
if (raw == null || raw === "") return null;
const n = typeof raw === "number" ? raw : Number(raw); const n = typeof raw === "number" ? raw : Number(raw);
return Number.isFinite(n) && n >= 0 ? n : null; return Number.isFinite(n) && n >= 0 ? n : null;
} }
@@ -80,6 +79,7 @@ function normalizeHullCaption(value: unknown): string {
return String(value ?? "") return String(value ?? "")
.replace(/ي/g, "ی") .replace(/ي/g, "ی")
.replace(/ك/g, "ک") .replace(/ك/g, "ک")
.replace(/\u200c/g, " ")
.replace(/\s+/g, " ") .replace(/\s+/g, " ")
.trim(); .trim();
} }
@@ -87,13 +87,15 @@ function normalizeHullCaption(value: unknown): string {
/** AuthorityCulpritId from GET /lookups/detection-accident-culprits. */ /** AuthorityCulpritId from GET /lookups/detection-accident-culprits. */
export function authorityCulpritIdFromDetectionRows( export function authorityCulpritIdFromDetectionRows(
rows: unknown, rows: unknown,
): number { ): number | null {
const list = Array.isArray(rows) ? rows : []; const list = Array.isArray(rows) ? rows : [];
const wanted = normalizeHullCaption( const wanted = normalizeHullCaption(
FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION, FANAVARAN_HULL_AUTHORITY_CULPRIT_CAPTION,
); );
for (const row of list) { for (const row of list) {
if (!row || typeof row !== "object") continue; 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( const caption = normalizeHullCaption(
(row as { Caption?: unknown }).Caption, (row as { Caption?: unknown }).Caption,
); );
@@ -102,13 +104,7 @@ export function authorityCulpritIdFromDetectionRows(
const n = typeof raw === "number" ? raw : Number(raw); const n = typeof raw === "number" ? raw : Number(raw);
if (Number.isFinite(n) && n > 0) return n; if (Number.isFinite(n) && n > 0) return n;
} }
for (const row of list) { return null;
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;
} }
/** Fallback AccidentCulpritId when parties inquiry is unavailable. */ /** Fallback AccidentCulpritId when parties inquiry is unavailable. */
@@ -128,13 +124,12 @@ export function toFanavaranHullBaseClaimPayload(
const next: Record<string, unknown> = {}; const next: Record<string, unknown> = {};
for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) { for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) {
if (key === "IsLicenseReplaced") { if (key === "IsLicenseReplaced") {
// GEN.03: must be empty/null. Do not map ثالث IsLicenseReplacement (default 0). // Hull GEN.03: explicitly send خیر. Keep the hull field name.
next[key] = null; next[key] = FANAVARAN_HULL_ANS_NO;
continue; continue;
} }
if (key === "AccidentTypeId") { if (key === "AccidentTypeId") {
next[key] = next[key] = built.AccidentTypeId ?? null;
built.AccidentTypeId ?? FANAVARAN_DEFAULT_HULL_ACCIDENT_TYPE_ID;
continue; continue;
} }
if (key === "CostSeparationToDmgSections") { if (key === "CostSeparationToDmgSections") {
@@ -150,7 +145,7 @@ export function toFanavaranHullBaseClaimPayload(
const raw = built.CulpritTypeId; const raw = built.CulpritTypeId;
// ثالث profile default 337 is not in vehicle-hull-accident-culprit-type. // ثالث profile default 337 is not in vehicle-hull-accident-culprit-type.
if (raw == null || raw === 337) { if (raw == null || raw === 337) {
next[key] = FANAVARAN_DEFAULT_HULL_CULPRIT_TYPE_ID; next[key] = null;
} else { } else {
next[key] = raw; next[key] = raw;
} }
@@ -163,8 +158,12 @@ export function toFanavaranHullBaseClaimPayload(
continue; continue;
} }
if (key === "AuthorityCulpritId") { if (key === "AuthorityCulpritId") {
next[key] = next[key] = built.AuthorityCulpritId ?? null;
built.AuthorityCulpritId ?? FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID; continue;
}
if (key === "PoliceOfficerId") {
// The shared third-party builder supplies a sample 1; hull has no officer source.
next[key] = null;
continue; continue;
} }
next[key] = Object.prototype.hasOwnProperty.call(built, key) next[key] = Object.prototype.hasOwnProperty.call(built, key)
@@ -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_KIND_CAPTION = "تخریب";
export const FANAVARAN_HULL_DMG_COST_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 = { export type FanavaranHullDmgAccessoryRow = {
Id?: unknown; Id?: unknown;
AccessoryKindId?: unknown; AccessoryKindId?: unknown;
@@ -17,6 +10,14 @@ export type FanavaranHullDmgAccessoryRow = {
}; };
export function asLookupRows(value: unknown): Record<string, unknown>[] { export function asLookupRows(value: unknown): Record<string, unknown>[] {
for (
let depth = 0;
depth < 4 && value && !Array.isArray(value) && typeof value === "object";
depth++
) {
const record = value as Record<string, unknown>;
value = record.data ?? record.Data;
}
if (!Array.isArray(value)) return []; if (!Array.isArray(value)) return [];
return value.filter( return value.filter(
(row): row is Record<string, unknown> => (row): row is Record<string, unknown> =>
@@ -24,7 +25,9 @@ export function asLookupRows(value: unknown): Record<string, unknown>[] {
); );
} }
export function asHullDmgAccessoryRows(value: unknown): FanavaranHullDmgAccessoryRow[] { export function asHullDmgAccessoryRows(
value: unknown,
): FanavaranHullDmgAccessoryRow[] {
return asLookupRows(value) as FanavaranHullDmgAccessoryRow[]; return asLookupRows(value) as FanavaranHullDmgAccessoryRow[];
} }
@@ -32,16 +35,31 @@ export function findLookupIdByCaption(
rows: unknown, rows: unknown,
caption: string, caption: string,
): number | null { ): 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)) { 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); const id = parseFanavaranId(row.Id);
if (id != null) return id; if (id != null) return id;
} }
return null; return null;
} }
function isFactoryDefaultAccessoryRow(row: FanavaranHullDmgAccessoryRow): boolean { function isFactoryDefaultAccessoryRow(
row: FanavaranHullDmgAccessoryRow,
): boolean {
const desc = String(row.AccessoryDesc ?? "").trim(); const desc = String(row.AccessoryDesc ?? "").trim();
return ( return (
desc.includes("کليه قطعات فابريک") || desc.includes("کليه قطعات فابريک") ||
@@ -74,5 +92,5 @@ export function resolveVehicleHullAccessoryId(
const factoryId = parseFanavaranId(factory?.Id); const factoryId = parseFanavaranId(factory?.Id);
if (factoryId != null) return factoryId; if (factoryId != null) return factoryId;
return parseFanavaranId(accessories[0]?.Id); return null;
} }
@@ -72,8 +72,6 @@ function text(value: unknown): string | null {
} }
export { export {
FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID,
FANAVARAN_DEFAULT_HULL_DMG_KIND_ID,
FANAVARAN_HULL_DMG_COST_KIND_CAPTION, FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
FANAVARAN_HULL_DMG_KIND_CAPTION, FANAVARAN_HULL_DMG_KIND_CAPTION,
} from "./fanavaran-hull-expertise-lookups"; } from "./fanavaran-hull-expertise-lookups";
@@ -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<string, unknown> = {
PolicyId: 14231020,
CulpritTypeId: 337,
};
await service.enrichCarBodyHullBaseClaimPayload({
clientKey: "parsian",
payload,
blameCase: {},
logPrefix: "test",
});
expect(payload).toMatchObject({
AccidentTypeId: 804,
CulpritTypeId: 805,
AuthorityCulpritId: 806,
ActualPremium: 123456,
});
});
});
@@ -0,0 +1,113 @@
import { asLookupRows } from "./fanavaran-hull-expertise-lookups";
export type HullLookupStage = "baseClaim" | "expertise" | "files";
type LookupField = {
row: Record<string, unknown>;
key: string;
lookup: string;
path: string;
};
/** Validate outbound IDs against responses for this tenant, never a sample ID. */
export async function validateFanavaranHullLookupIds(
payload: Record<string, unknown>,
stage: HullLookupStage,
fetchRows: (lookup: string) => Promise<unknown>,
): Promise<string[]> {
const fields: LookupField[] = [];
const add = (
row: Record<string, unknown>,
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<string, Record<string, unknown>[]>();
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;
}
@@ -0,0 +1,342 @@
import { Logger } from "@nestjs/common";
import { of } from "rxjs";
import { getFanavaranClientProfile } from "src/core/config/fanavaran-client.config";
import { FanavaranAuthService } from "src/fanavaran/fanavaran-auth.service";
import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service";
import { ClaimRequestManagementService } from "./claim-request-management.service";
function createHarness(blame: object, claim: object, role: number) {
const staff = Array.from({ length: 5 }, (_, index) => ({
findById: jest
.fn()
.mockResolvedValue(
index === role
? { locations: [{ id: "987654", name: "Test branch" }] }
: null,
),
}));
const http = {
post: jest.fn((url: string, _body: unknown, _config: { headers: object }) =>
of({
status: 200,
headers: url.includes("GetAppToken")
? { apptoken: "app-test" }
: { authenticationtoken: "auth-test" },
data: {},
}),
),
get: jest.fn().mockReturnValue(
of({
status: 200,
headers: {},
data: [{ PolicyId: 1, EndDate: "1499/01/01" }],
}),
),
};
const audit = {
generateTrackingCode: () => "location-header-test",
recordStep: jest.fn().mockResolvedValue(undefined),
maskNationalCode: () => "masked",
captureAxiosExchange: (_response: unknown, headers: unknown) => ({
requestHeaders: headers,
}),
};
const tokenModel = {
findOne: () => ({ lean: () => ({ exec: async () => null }) }),
findOneAndUpdate: () => ({ exec: async () => null }),
};
const management = Object.create(ClaimRequestManagementService.prototype);
const branches = { findById: jest.fn().mockResolvedValue(null) };
Object.assign(management, {
logger: new Logger("LocationHeaderTest"),
httpService: http,
fanavaranAuditService: audit,
claimCaseDbService: {
findById: jest
.fn()
.mockResolvedValue({ blameRequestId: "blame-1", ...claim }),
findByIdAndUpdate: jest.fn().mockResolvedValue(undefined),
},
blameRequestDbService: {
findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY", ...blame }),
},
fanavaranLocationService: new FanavaranLocationService(
...(staff as [any, any, any, any, any]),
branches as any,
),
fanavaranAuthService: new FanavaranAuthService(
http as any,
audit as any,
tokenModel as any,
),
});
return { management, http, audit, staff, branches };
}
describe("Fanavaran outgoing Location headers", () => {
it.each([{ locations: null }, { locations: [] }, { locations: undefined }])(
"uses the creator's branch code when staff locations are %j",
async ({ locations }) => {
const { management, http, staff, branches } = createHarness(
{ expert: { assignedExpertId: "blame-expert" } },
{ initiatedByFieldExpertId: "damage-creator" },
-1,
);
staff[3].findById.mockImplementation(async (id: string) =>
id === "damage-creator" ? { locations, branchId: "branch-1" } : null,
);
staff[2].findById.mockImplementation(async (id: string) =>
id === "blame-expert"
? { locations: [{ id: "210050", name: "Other" }] }
: null,
);
branches.findById.mockResolvedValue({ code: "110011" });
await management.postFanavaranJson(
"https://example.test/claims",
{},
"parsian",
undefined,
"claim-1",
);
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
Location: "110011",
});
expect(branches.findById).toHaveBeenCalledWith("branch-1");
},
);
it("uses the damage expert handling a user-created claim before the previous blame expert", async () => {
const { management, http, staff } = createHarness(
{ expert: { assignedExpertId: "blame-expert" } },
{ workflow: { assignedForReviewBy: { actorId: "damage-expert" } } },
-1,
);
staff[2].findById.mockImplementation(async (id: string) =>
id === "blame-expert"
? { locations: [{ id: "210050", name: "Blame branch" }] }
: null,
);
staff[3].findById.mockImplementation(async (id: string) =>
id === "damage-expert"
? { locations: [{ id: "110011", name: "Claim branch" }] }
: null,
);
management.assertFanavaranVehicleReviewApproved = jest.fn();
management.previewFanavaranSubmitV2 = jest.fn().mockResolvedValue({
PolicyId: 1,
AccidentCauseId: 6,
CulpritLicenceNo: "1234567890",
});
await management.executeFanavaranV2Submit("claim-1", "parsian");
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
Location: "110011",
});
});
it("prefers the claim creator over the linked blame creator", async () => {
const { management, http, staff } = createHarness(
{ initiatedByFieldExpertId: "blame-creator" },
{ initiatedByFieldExpertId: "claim-creator" },
-1,
);
staff[0].findById.mockImplementation(async (id: string) =>
id === "blame-creator"
? { locations: [{ id: "210050", name: "Blame branch" }] }
: null,
);
staff[1].findById.mockImplementation(async (id: string) =>
id === "claim-creator"
? { locations: [{ id: "110011", name: "Claim branch" }] }
: null,
);
await management.postFanavaranJson(
"https://example.test/claims",
{},
"parsian",
undefined,
"claim-1",
);
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
Location: "110011",
});
});
it.each(["unlinked", "deleted"])(
"uses the assigned damage expert when the blame case is %s",
async (kind) => {
const { management, http } = createHarness(
{},
{
...(kind === "unlinked" ? { blameRequestId: undefined } : {}),
workflow: { assignedForReviewBy: { actorId: "damage-1" } },
},
3,
);
if (kind === "deleted")
management.blameRequestDbService.findById.mockResolvedValue(null);
await management.postFanavaranJson(
"https://example.test/claims",
{},
"parsian",
undefined,
"claim-1",
);
expect(http.post.mock.calls.at(-1)?.[2].headers).toMatchObject({
Location: "987654",
});
},
);
it.each([{}, { initiatedByFieldExpertId: "unconfigured-staff" }])(
"does not submit a claim using the tenant default when no staff location can be resolved: %j",
async (claim) => {
const { management, http } = createHarness({}, claim, -1);
await expect(
management.postFanavaranJson(
"https://example.test/claims",
{},
"parsian",
undefined,
"claim-1",
),
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_STAFF_LOCATION_MISSING",
}),
});
expect(http.post).not.toHaveBeenCalled();
},
);
it.each([
[
"file maker",
{ initiatedByFieldExpertId: "staff-1", isMadeByFileMaker: true },
{},
0,
],
["file reviewer", { assignedFileReviewerId: "staff-1" }, {}, 1],
["blame expert", { expert: { assignedExpertId: "staff-1" } }, {}, 2],
[
"damage expert",
{},
{ workflow: { assignedForReviewBy: { actorId: "staff-1" } } },
3,
],
["field expert", { initiatedByFieldExpertId: "staff-1" }, {}, 4],
])(
"sends the %s location on claim POSTs",
async (_name, blame, claim, role) => {
const { management, http } = createHarness(
blame as object,
claim as object,
role as number,
);
await management.postFanavaranJson(
"https://example.test/claims",
{},
"tejaratno",
undefined,
"claim-1",
);
expect(http.post).toHaveBeenLastCalledWith(
"https://example.test/claims",
{},
{
headers: expect.objectContaining({ Location: "987654" }),
},
);
},
);
it("keeps concurrent claims' staff locations separate while sharing a login token", async () => {
const { management, http, staff } = createHarness({}, {}, -1);
management.claimCaseDbService.findById.mockImplementation(
async (id: string) => ({
blameRequestId: "blame-1",
initiatedByFieldExpertId: id,
}),
);
staff[3].findById.mockImplementation(async (id: string) => ({
locations: [
{ id: id === "claim-a" ? "110011" : "210050", name: "Branch" },
],
}));
await Promise.all(
["claim-a", "claim-b"].map((id) =>
management.postFanavaranJson(
`https://example.test/${id}`,
{},
"parsian",
undefined,
id,
),
),
);
const calls = http.post.mock.calls.filter(([url]) =>
url.startsWith("https://example.test/"),
);
const headersByUrl = Object.fromEntries(
calls.map(([url, , options]) => [url, options.headers]),
);
expect(headersByUrl).toEqual({
"https://example.test/claim-a": expect.objectContaining({
Location: "110011",
authenticationToken: "auth-test",
}),
"https://example.test/claim-b": expect.objectContaining({
Location: "210050",
authenticationToken: "auth-test",
}),
});
expect(http.post).toHaveBeenCalledTimes(4);
});
it("changes Location while reusing the same login token", async () => {
const { management, http } = createHarness({}, {}, -1);
const auth = management.fanavaranAuthService as FanavaranAuthService;
const first = await auth.getRequestHeaders("tejaratno", {
locationOverride: "987654",
});
const second = await auth.getRequestHeaders("tejaratno", {
locationOverride: "123456",
});
expect(first.Location).toBe("987654");
expect(second.Location).toBe("123456");
expect(first.authenticationToken).toBe(second.authenticationToken);
expect(http.post).toHaveBeenCalledTimes(2);
for (const [, , config] of http.post.mock.calls) {
expect(config.headers).not.toHaveProperty("Location");
}
});
it("records the outgoing staff location in policy inquiry audit metadata", async () => {
const { management, http, audit } = createHarness(
{ initiatedByFieldExpertId: "staff-1" },
{},
4,
);
await management.getPolicyIdFromNationalCode(
"1234567890",
getFanavaranClientProfile("tejaratno").auth,
"test",
{ claimCaseId: "claim-1", clientKey: "tejaratno" },
{ claimCaseId: "claim-1", clientKey: "tejaratno" },
);
expect(http.get).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
headers: expect.objectContaining({ Location: "987654" }),
}),
);
const inquiryMetadata = audit.recordStep.mock.calls
.map(([entry]) => entry)
.filter((entry) => entry.requestMethod === "GET")
.map((entry) => entry.requestMeta);
expect(inquiryMetadata).toHaveLength(2);
expect(inquiryMetadata).toEqual([
expect.objectContaining({ location: "987654" }),
expect.objectContaining({ location: "987654" }),
]);
});
});
@@ -49,6 +49,10 @@ function setup(product = "third-party", extra: any = {}) {
"vehicle-hull-accident-types": 4, "vehicle-hull-accident-types": 4,
"vehicle-hull-accident-culprit-type": 301, "vehicle-hull-accident-culprit-type": 301,
"detection-accident-culprits": 8, "detection-accident-culprits": 8,
"accident-causes": 6,
"driving-licence-types": 2,
"vehicle-use-types": 1,
ans: 0,
}; };
return [ return [
{ Id: ids[name], Caption: "گزینه معتبر", IsActive: 1 }, { Id: ids[name], Caption: "گزینه معتبر", IsActive: 1 },
@@ -166,6 +170,9 @@ describe("Expert Fanavaran stage fields", () => {
payload.CustomerFaultPercent = 100; payload.CustomerFaultPercent = 100;
payload.AuthorityCulpritId = 1; payload.AuthorityCulpritId = 1;
}); });
management.fanavaranLookupService = {
bodyPolicyById: jest.fn().mockResolvedValue({ TotalPremium: 123456 }),
};
const payload = await management.previewFanavaranSubmitV2(id, clientKey, { const payload = await management.previewFanavaranSubmitV2(id, clientKey, {
persistPayload: false, persistPayload: false,
forceRefreshPolicy: false, forceRefreshPolicy: false,
@@ -195,7 +202,7 @@ describe("Expert Fanavaran stage fields", () => {
CulpritTypeId: 301, CulpritTypeId: 301,
AuthorityCulpritId: 8, AuthorityCulpritId: 8,
CustomerFaultPercent: 0, CustomerFaultPercent: 0,
IsLicenseReplaced: null, IsLicenseReplaced: 0,
}); });
expect(payload.DamagedCount).toBeUndefined(); expect(payload.DamagedCount).toBeUndefined();
expect(payload.IsLicenseReplacement).toBeUndefined(); expect(payload.IsLicenseReplacement).toBeUndefined();
@@ -124,7 +124,7 @@ export class CreateInsurerExpertDto {
@ApiPropertyOptional({ @ApiPropertyOptional({
type: [ExpertLocationDto], type: [ExpertLocationDto],
description: description:
'Fanavaran Location entries (id = OpBUId). Sent as the HTTP Location header on Fanavaran business calls for this expert.', 'Fanavaran Location entries (id = OpBUId), stored on the staff profile. The first id is used as the HTTP Location header. When empty, the code of the branch referenced by branchId is used. Claim submissions require a staff location or branch code.',
}) })
@IsOptional() @IsOptional()
@IsArray() @IsArray()
@@ -14,6 +14,7 @@ describe("FanavaranLocationService", () => {
expert?: Record<string, unknown> | null; expert?: Record<string, unknown> | null;
damage?: Record<string, unknown> | null; damage?: Record<string, unknown> | null;
field?: Record<string, unknown> | null; field?: Record<string, unknown> | null;
branch?: Record<string, unknown> | null;
}) => }) =>
new FanavaranLocationService( new FanavaranLocationService(
{ {
@@ -44,6 +45,7 @@ describe("FanavaranLocationService", () => {
return null; return null;
}), }),
} as any, } as any,
{ findById: jest.fn().mockResolvedValue(opts?.branch ?? null) } as any,
); );
describe("branch scope", () => { describe("branch scope", () => {
@@ -92,6 +94,66 @@ describe("FanavaranLocationService", () => {
}); });
describe("resolveBusinessLocation", () => { describe("resolveBusinessLocation", () => {
it.each(["maker", "reviewer", "expert", "damage", "field"])(
"uses the branch code for %s staff without their own locations",
async (role) => {
const service = createService({
[role]: { branchId: "branch-1", locations: null },
branch: { code: " 110011 " },
});
const staffId =
role === "maker"
? makerId
: role === "reviewer"
? reviewerId
: role === "field"
? fieldExpertId
: "expert-1";
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [staffId],
requireStaffLocation: true,
}),
).resolves.toBe("110011");
},
);
it("prefers staff locations over the branch code", async () => {
const service = createService({
field: { branchId: "branch-1", locations: [{ id: "110011" }] },
branch: { code: "210050" },
});
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [fieldExpertId],
requireStaffLocation: true,
}),
).resolves.toBe("110011");
});
it.each([null, { code: "" }, { code: " " }])(
"reports missing configuration when neither staff nor branch supplies a location: %j",
async (branch) => {
const service = createService({
field: { branchId: "branch-1", locations: null },
branch,
});
await expect(
service.resolveBusinessLocation({
clientKey: "parsian",
staffCandidateIds: [fieldExpertId],
requireStaffLocation: true,
}),
).rejects.toMatchObject({
response: expect.objectContaining({
code: "FANAVARAN_STAFF_LOCATION_MISSING",
}),
});
},
);
it("uses the first staff candidate location for any tenant", async () => { it("uses the first staff candidate location for any tenant", async () => {
const service = createService({ const service = createService({
field: { locations: [{ id: "210050", name: "غرب" }] }, field: { locations: [{ id: "210050", name: "غرب" }] },
+34 -7
View File
@@ -1,4 +1,10 @@
import { ForbiddenException, Injectable, Logger } from "@nestjs/common"; import {
BadRequestException,
ForbiddenException,
Injectable,
Logger,
} from "@nestjs/common";
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import { import {
FanavaranClientKey, FanavaranClientKey,
getFanavaranClientProfile, getFanavaranClientProfile,
@@ -14,7 +20,7 @@ type LocationEntry = { id?: string; name?: string };
/** /**
* Resolve Fanavaran HTTP `Location` (OpBUId) from assigned staff * Resolve Fanavaran HTTP `Location` (OpBUId) from assigned staff
* `locations[].id` for every tenant, and enforce maker/reviewer match on * `locations[].id` or their branch code for every tenant, and enforce maker/reviewer match on
* Parsian FileMaker flows. * Parsian FileMaker flows.
*/ */
@Injectable() @Injectable()
@@ -27,6 +33,7 @@ export class FanavaranLocationService {
private readonly expertDbService: ExpertDbService, private readonly expertDbService: ExpertDbService,
private readonly damageExpertDbService: DamageExpertDbService, private readonly damageExpertDbService: DamageExpertDbService,
private readonly fieldExpertDbService: FieldExpertDbService, private readonly fieldExpertDbService: FieldExpertDbService,
private readonly branchDbService: BranchDbService,
) {} ) {}
isParsianClient(clientKey?: FanavaranClientKey): boolean { isParsianClient(clientKey?: FanavaranClientKey): boolean {
@@ -44,12 +51,15 @@ export class FanavaranLocationService {
} }
/** /**
* First staff candidate with a stored `locations[].id` wins. * First staff candidate with a stored `locations[].id` or branch code wins.
* Fallback: tenant auth.location (lookups / cases with no staff locations). * A staff member's own locations take priority over their branch's code.
* Tenant auth.location is allowed only when requireStaffLocation is false.
*/ */
async resolveBusinessLocation(input: { async resolveBusinessLocation(input: {
clientKey: FanavaranClientKey; clientKey: FanavaranClientKey;
staffCandidateIds?: Array<string | null | undefined>; staffCandidateIds?: Array<string | null | undefined>;
/** Claim submissions must never silently use a tenant-wide branch. */
requireStaffLocation?: boolean;
/** @deprecated Prefer staffCandidateIds — kept for older call sites. */ /** @deprecated Prefer staffCandidateIds — kept for older call sites. */
isMadeByFileMaker?: boolean; isMadeByFileMaker?: boolean;
fileMakerId?: string | null; fileMakerId?: string | null;
@@ -79,8 +89,17 @@ export class FanavaranLocationService {
} }
} }
this.logger.debug( if (input.requireStaffLocation) {
`Fanavaran Location fallback to tenant default → ${defaultLocation}`, throw new BadRequestException({
code: "FANAVARAN_STAFF_LOCATION_MISSING",
message:
"Cannot submit this claim to Fanavaran: no attached expert has a configured locations[].id or branch code (OpBUId). Configure the responsible staff member's location or branch and retry.",
staffCandidateIds: [...seen],
});
}
this.logger.warn(
`[${input.clientKey}] Fanavaran Location fallback to tenant default=${defaultLocation}; no staff location or branch code found for staff candidates=${[...seen].join(",") || "none"}`,
); );
return defaultLocation; return defaultLocation;
} }
@@ -181,7 +200,15 @@ export class FanavaranLocationService {
try { try {
const doc = await load(); const doc = await load();
if (doc) { if (doc) {
return this.extractLocationIds((doc as any)?.locations); const locationIds = this.extractLocationIds(doc.locations);
if (locationIds.length > 0) return locationIds;
if (!doc.branchId) return [];
const branch = await this.branchDbService.findById(
String(doc.branchId),
);
const branchCode = String(branch?.code ?? "").trim();
return branchCode ? [branchCode] : [];
} }
} catch { } catch {
// invalid ObjectId / cast errors — try next collection // invalid ObjectId / cast errors — try next collection
+7
View File
@@ -2,6 +2,11 @@ import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios"; import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config"; import { ConfigModule, ConfigService } from "@nestjs/config";
import { MongooseModule } from "@nestjs/mongoose"; import { MongooseModule } from "@nestjs/mongoose";
import { BranchDbService } from "src/client/entities/db-service/branch.db.service";
import {
BranchModel,
BranchSchema,
} from "src/client/entities/schema/branch.schema";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory"; import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { import {
LookupModel, LookupModel,
@@ -36,11 +41,13 @@ import {
schema: FanavaranClientConfigSchema, schema: FanavaranClientConfigSchema,
}, },
{ name: LookupModel.name, schema: LookupSchema }, { name: LookupModel.name, schema: LookupSchema },
{ name: BranchModel.name, schema: BranchSchema },
]), ]),
FanavaranAuditModule, FanavaranAuditModule,
UsersModule, UsersModule,
], ],
providers: [ providers: [
BranchDbService,
FanavaranClientConfigService, FanavaranClientConfigService,
FanavaranAuthService, FanavaranAuthService,
FanavaranLookupService, FanavaranLookupService,