From 658a8a74ccee8fa85e202db9583069d81717c2ee Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Wed, 11 Nov 2026 14:10:01 +0330 Subject: [PATCH] dynamic locations --- docs/fanavaran/01-write-apis.md | 2 +- docs/fanavaran/03-constants.md | 4 +- docs/fanavaran/07-data-mapping.md | 2 +- docs/fanavaran/lookup-coding-audit.md | 146 +++++++++++++++++ docs/insurer-staff-management.md | 4 +- .../claim-request-management.service.ts | 26 +-- src/core/config/fanavaran-client.config.ts | 4 +- .../dto/create-insurer-expert.dto.ts | 33 ++-- src/expert-insurer/expert-insurer.service.ts | 2 + .../fanavaran-client-config.service.spec.ts | 38 +++++ .../fanavaran-client-config.service.ts | 8 +- .../fanavaran-location.service.spec.ts | 149 ++++++++++++++---- src/fanavaran/fanavaran-location.service.ts | 84 ++++++---- src/management/management.service.spec.ts | 4 + src/management/management.service.ts | 12 +- .../entities/schema/damage-expert.schema.ts | 16 ++ src/users/entities/schema/expert.schema.ts | 15 ++ .../entities/schema/field-expert.schema.ts | 16 ++ 18 files changed, 454 insertions(+), 111 deletions(-) create mode 100644 docs/fanavaran/lookup-coding-audit.md create mode 100644 src/fanavaran/fanavaran-client-config.service.spec.ts diff --git a/docs/fanavaran/01-write-apis.md b/docs/fanavaran/01-write-apis.md index 91db288..a495083 100644 --- a/docs/fanavaran/01-write-apis.md +++ b/docs/fanavaran/01-write-apis.md @@ -20,7 +20,7 @@ Common business headers (after Login): | `authenticationToken` | Login response | | `CorpId` | Tenant auth | | `ContractId` | Tenant auth | -| `Location` | Tenant auth | +| `Location` | Assigned staff `locations[].id` (all expert roles); tenant auth only as fallback | | `Content-Type` | `application/json` (except GEN.07 multipart) | Template values below are **Parsian-proven** unless noted. diff --git a/docs/fanavaran/03-constants.md b/docs/fanavaran/03-constants.md index f3c7897..c2b33cd 100644 --- a/docs/fanavaran/03-constants.md +++ b/docs/fanavaran/03-constants.md @@ -23,7 +23,7 @@ Secrets are **not** printed here — read from Mongo `fanavaranClientConfigs` or | `password` | *(config)* | Login | Password | ✅ | | `corpId` | `543` | All business calls | Corp scope | ✅ | | `contractId` | `28` | All business calls | Contract | ✅ | -| `location` | `210050` | All business calls / OpBUId | Branch/location | ✅ | +| `location` | `210050` | Fallback only when no staff location | Tenant default OpBUId | ✅ (per expert `locations[].id` at runtime) | Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(key)`. @@ -47,7 +47,7 @@ Seed: `SEED_FANAVARAN_CLIENT_PROFILES` · Runtime: `getFanavaranClientProfile(ke | `PlaqueSampleId` | 10 | same | same | same | may ✅ | | `DriverIsOwner` | 0 | same | same | same | ❌ | | `FaultPercent` | 100 | same | same | same | ❌ | -| `ClaimFileTypeId` (GEN.07) | 23 | **63** | 23 | 23 TBD | ✅ | +| `ClaimFileTypeId` (GEN.07) | 23 | **63** | 23 | **17** | ✅ | **Never swap** GEN.03 `ClaimExpertId` with GEN.08 `ExpertiseClaimExpertId` — different Fanavaran roles. diff --git a/docs/fanavaran/07-data-mapping.md b/docs/fanavaran/07-data-mapping.md index 70bd336..07e0b38 100644 --- a/docs/fanavaran/07-data-mapping.md +++ b/docs/fanavaran/07-data-mapping.md @@ -90,7 +90,7 @@ Create only on GEN.12 submit when inquiry missed. Cache `otherPersonId` + `drive |-------------------|------------------| | `corpId` | `CorpId` | | `contractId` | `ContractId` | -| `location` | `Location` | +| staff `locations[].id` (else tenant `auth.location`) | `Location` | | token from Login | `authenticationToken` | ## Not mapped / out of scope diff --git a/docs/fanavaran/lookup-coding-audit.md b/docs/fanavaran/lookup-coding-audit.md new file mode 100644 index 0000000..c649e2d --- /dev/null +++ b/docs/fanavaran/lookup-coding-audit.md @@ -0,0 +1,146 @@ +# Fanavaran lookup coding audit + +Date: 2026-11-10. Clients: Moallem, Tejaratno, Parsian. Scope: current base, +damage-case, attachment, expertise and other-person payload builders shared by +app flows V1–V6. This is a code and local-snapshot audit, not a live acceptance +test against the three insurers. No runtime mappings were changed by this audit. + +## Finding + +The integration does not yet guarantee correct tenant-specific codes for every +outbound field. Tenant-specific URLs and disk folders exist, but several payload +builders use unvalidated defaults, and Mongo lookup storage has no tenant key. +The recent strict policy-vehicle mapping applies to hull base claims only. + +## Inquiry-derived values + +| Fields | Current source | Remaining limitation | +|---|---|---| +| `PolicyId` | Product-specific policy inquiry / previously stored policy reference | Stored policy references need client/product provenance when reused across explicit client routes | +| Base/expertise `ClaimExpertId` | Assigned staff's product-specific Mongo codes | Staff profile correctness is required; tenant config expert defaults are excluded | +| Hull base `AccidentVehicleUsedId` | Hull policy `VehicleId` + `VehicleVersionNo` → vehicle GET `UsedId` | Missing inquiry warns / blocks submit; active lookup/group compatibility is not independently revalidated here | +| Third-party base `AccidentVehicleUsedId` | Guilty VIN inquiry, then policy vehicle, with generic lookup selection; cache/expert review can take precedence | Can choose personal/first group row or tenant default rather than preserve the actual inquiry value | +| Damage-case `AccidentVehicleUsedId` | Approved expert vehicle use, matched damaged vehicle, group lookup, then tenant default | Still permits guessed/default codes | +| Damage-case `VehicleKindId` | Expert selection → matched vehicle GET → caption keyword search from broad local `carType` | Final fallback can select an arbitrary vehicle model from the correct broad category | +| `DriverId`, `OwnerId` | Person national code + birthday inquiry, accepted roles 161/166; GEN.44 creation on submit | Reused person references need client provenance; these are person record IDs, not generic lookup values | +| Hull `AccidentCulpritId` | Driver/person inquiry; fallback hull policy `CustomerId` | Driver and policy customer may differ; fallback is not proof of driver identity | +| Hull `ActualPremium` | Policy GET `TotalPremium` | Already inquiry-derived | +| Hull `VehicleCurrentValue` | Local/reviewed value, then hull policy `VehicleValue` | Policy insured value is the fallback, not an independent market valuation | +| Damage-case plaque coding | Matched Fanavaran vehicle fields | `PlaqueKindId`/`PlaqueSampleId` still fall back to national-plate 8/10; plate-letter map is static | +| Hull `ColorId` | Exact policy vehicle GET | Already inquiry-derived when the API returns it | +| VIN, motor/chassis, plate text, model year, policy number/CI/dates | Vehicle/policy inquiries and stored provider-mapped fields | These are identity/data values; provider-local numeric codes must not be treated as Fanavaran lookup IDs | +| `InsuranceCorpId` | Environment caption matched against client's `insurance-corp` | Resolved scalar cache is not tied to caption changes; localhost fallback uses deployment's active tenant, which can differ from an explicit client route | + +## Base-claim codebooks + +| Field | Codebook / correct source | Actual current behavior | +|---|---|---| +| `AccidentCityId` | `cities`, based on accident location / explicit selection | Tenant default 701 unless reviewed | +| `AccidentReportTypeId` | `accident-report-type`, explicit accident report selection | Tenant default 155 unless reviewed | +| `AccidentCauseId` | `accident-causes`, explicit accident cause | Hardcoded 6; builder receives accident reason but does not apply its code | +| `CulpritLicenceTypeId` | `driving-licence-types`, correct licence category | Tenant default 2 | +| Third-party `CulpritTypeId` | `accident-culprit-type` | Tenant default 337 | +| `CompensationReferenceId` | Confirm the product contract/codebook | Tenant default 167; no dedicated remote lookup definition in current catalogue | +| `PoliceOfficerId` | Confirm the product contract/codebook | Hardcoded 1; no dedicated remote lookup definition in current catalogue | +| Hull `AccidentTypeId` | `vehicle-hull-accident-types`, actual accident type | Reviewed selection, else numeric 2; inactive in Moallem/Tejaratno snapshots | +| Hull `CulpritTypeId` | `vehicle-hull-accident-culprit-type` | Reviewed selection, else 300; third-party 337 is remapped | +| Hull `AuthorityCulpritId` | `detection-accident-culprits` | Reviewed selection or caption بیمه‌گذار; then first row / numeric 1 fallback | +| Tejaratno notifier type/relation | `notifier-type`, `notifier-relation` | Required reviewed choices; shared Mongo source remains a tenant-isolation concern | + +Reviewed stage choices are checked against active lookup rows when saved. +However, defaults and previously stored choices are not uniformly validated +against the outbound request's client immediately before submission. + +## Damage-case, expertise, files and GEN.44 codebooks + +| Field | Codebook / correct source | Actual current behavior | +|---|---|---| +| Damage `DmgCaseTypeId` | `dmg-case-type` | Tenant default 175 | +| Damage `DmgHistoryStatus` | `dmg-history-status` | Reviewed choice, else tenant default 5214 | +| Damage `LicenceTypeId` | `driving-licence-types` | Tenant `CulpritLicenceTypeId`, normally 2 | +| Third-party expertise `InspectionPlaceId` | `inspection-place` | Reviewed choice, else 282; lookup is fetched but fallback not selected from it | +| Third-party expertise `DropAmountStatus` | `drop-amount-status` | Hardcoded 5458 even though lookup is fetched | +| Third-party `DmgSections[].DmgSectionId` | Client `car-components` | Saved local `partId`; catalog can fall back to a shared static snapshot; no outbound membership check | +| Third-party `DmgSections[].AccidentLevel` | Client `accident-level` | Numeric `typeOfDamage`, else 5456; no outbound codebook validation | +| Hull `DmgSections[].AccessoryKindId` | Client `car-components` | Saved local `partId`; same catalogue provenance concern | +| Hull `DmgSections[].DmgKindId` | `vehicle-hull-dmg-kind` | Exact caption تخریب search; fallback 5485. Persian ی vs Arabic ي mismatch can trigger fallback | +| Hull section cost `DmgCostKindId` | `vehicle-hull-dmg-cost-kinds` | Caption مجموع لوازم, else 1 | +| Hull `VehicleHullAccessoryId` | **Policy** `GET car/vehicle-hull-policies/{policyId}/dmg-accessories` | **Hardcoded 3043330 for every section**; existing lookup API/helper is not wired into builder | +| Attachment `FileTypeId` | Client `file-types`, confirmed document category | Configured defaults: Moallem 17, Tejaratno 23, Parsian 63; no automatic outbound membership/category validation | +| GEN.44 `CityId` | User/person city matched to client `cities` | Explicit/inquiry city, caption match, else Parsian-specific 9131 | +| GEN.44 `GenderId` | Inquiry or client `gender` | Inquiry code or caption match | +| GEN.44 `PersonKindId` | Client `person-kind` | Explicit code or caption حقیقی, else Parsian-specific 46 | +| GEN.44 `IsIranian`, `NationalityId`, `MaritalStatus` | Client `ans`, `countries`, `marital-status` plus actual person data | Yes/no fallbacks 1/0; marital status unset; nationality not inferred reliably for foreign people | + +`PlaqueDesignId`, hull expertise `PlaqueCityId`/`AccidentPercent`, licence city/country +and glass-break reason are currently generally null, not resolved code mappings. +Boolean flags, fault percentages, amounts, dates, counts and text are not all +tenant-specific codebook IDs. In particular, the requested hardcoded +`PoliceReportDesc="شرح گزارش"` is text and is unaffected by lookup coding. + +## Confirmed cross-client differences in local snapshots + +| Meaning / ID | Moallem | Tejaratno | Parsian | +|---|---|---|---| +| File ID 17 | Other documents, active | Driving licence, active | Police/judicial documents, inactive | +| File ID 23 | Printed form, active | Other documents, active | Contract/agreement, inactive | +| Intended general-document file ID | 17 | 23 | 63 | +| Hull accident ID 2 | Collision, **inactive** | Collision, **inactive** | Collision, active | +| Vehicle vs vehicle hull accident | 19, active | 18, active | No identical dedicated row in snapshot; general collision 2 is active | +| Hull accident ID 21 | Collision with objects/animals | Overturn/fall | Not present in snapshot | + +Some Tejaratno disk files (including accident-causes, accident-report-type and +inspection-place) contain authentication-error objects rather than codebook +arrays. This does not establish the client's live codes; it establishes that +the local cache is unusable and must be refreshed, not accepted as a lookup. + +## Infrastructure gaps + +1. `lookups` Mongo schema and reads/writes identify a codebook by `name` only. + Parsian defaults to this unscoped DB source; notifier lookup paths also use it. + Tenant-specific disk paths do not protect a cache populated from another tenant's DB row. +2. `getRemoteLookup` accepts any non-null cache value, including API error objects. + These prevent remote refresh and become empty rows in payload mapping. +3. `vehicle-kinds` Mongo collection uses globally unique `Id`, with no client key. + Search/approval can therefore validate against another tenant's catalogue. +4. Vehicle-kind live sync calls `fetchFromFanavaran` with the generic definition + URL directly. Tenant host rewriting occurs in `getRemoteLookup`, not in this + direct-fetch path; Moallem can be sent to the generic host. +5. Saved vehicle/stage reviews and remote person/policy caches do not uniformly + record/verify the client/product before an explicit client-route submission. + +## Required completion order + +1. Scope persistent codebooks and vehicle-kind rows by client (and product or + contract where the lookup requires it), with a migration/re-fetch strategy + for existing unscoped data. Reject cached API-error objects. +2. Preserve inquiry record provenance: exact policy vehicle/version for base + claims; identity-matched damaged vehicle for GEN.12; policy-specific accessory + IDs for hull expertise. Remove generic first-row guesses from these paths. +3. Use current-client codebooks for explicit accident/review selections. The + policy cannot supply accident cause, inspection location or damage severity. + Resolve equivalent concepts by normalized meaning, never by reusing another + client's numeric ID, and leave ambiguous choices for the expert. +4. Validate every non-null code and its relationships at outbound time. Required + unresolved/invalid codes should warn in preview and prevent the Fanavaran + write, while existing best-effort handling preserves the local app workflow. +5. Test clients with intentionally different IDs/captions and inactive rows, + plus cache errors and wrong-client saved references. Then run read-only live + inquiry checks per client before claiming end-to-end compatibility. + +## Source entry points + +- `src/claim-request-management/claim-request-management.service.ts`: base, + damage, expertise and attachment builders; catalogue and lookup wrappers. +- `src/claim-request-management/fanavaran-accident-vehicle-used.ts`: group-based + default vehicle-use selection. +- `src/claim-request-management/fanavaran-hull-base-claim.ts`: hull default codes. +- `src/claim-request-management/fanavaran-hull-expertise-lookups.ts`: damage-kind + defaults and existing accessory resolver. +- `src/claim-request-management/fanavaran-other-people.ts`: person code mapping. +- `src/claim-request-management/fanavaran-stage-fields.ts`: reviewed lookup fields. +- `src/fanavaran/fanavaran-lookup.service.ts`: lookup cache/source resolution. +- `src/lookups/lookups.service.ts`: shared Mongo persistence and vehicle-kind sync. +- `src/lookups/entities/schema/lookup.schema.ts` and `vehicle-kind.schema.ts`: + current unscoped storage models. +- `files/fanavaran-lookups/{moallem,tejaratno,parsian}/`: inspected snapshots. diff --git a/docs/insurer-staff-management.md b/docs/insurer-staff-management.md index 451ea51..d2cd067 100644 --- a/docs/insurer-staff-management.md +++ b/docs/insurer-staff-management.md @@ -39,7 +39,7 @@ Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, ` | Role | Additional optional fields | | --- | --- | -| Blame, claim and field expert | All four Fanavaran codes below | +| Blame, claim and field expert | All four Fanavaran codes below, plus `locations` | | FileMaker | `ThirdPartyClaimExpertId`, `CarBodyClaimExpertId`, `locations` | | FileReviewer | `ThirdPartyExpertiseClaim`, `CarBodyExpertiseClaim`, `locations` | | Call-center agent | None of the four product/stage codes | @@ -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. -`locations` is an editable array of `{id, name}`. Both properties must be nonempty, and IDs must be unique within the array. These are Fanavaran location IDs, rather than branch codes. Shared locations participate in the existing 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, 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. 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. diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 54cf69b..3c718a3 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -3365,17 +3365,15 @@ export class ClaimRequestManagementService { } /** - * Parsian + V4/V5 FileMaker flows: Location from file-maker.locations[].id, - * else file-reviewer.locations[].id, else tenant auth.location. + * Fanavaran HTTP Location from assigned staff `locations[].id` + * (file-maker / file-reviewer / field / blame / damage expert), for every + * tenant. Falls back to tenant auth.location only when no staff location is set. */ private async resolveFanavaranLocationForClaim( claimCaseId: string, clientKey: FanavaranClientKey, ): Promise { const defaultLocation = getFanavaranClientProfile(clientKey).auth.location; - if (clientKey !== "parsian") { - return defaultLocation; - } try { const claimCase = await this.claimCaseDbService.findById(claimCaseId); @@ -3386,19 +3384,21 @@ export class ClaimRequestManagementService { const blame = await this.blameRequestDbService.findById( String(claimCase.blameRequestId), ); - if (!(blame as any)?.isMadeByFileMaker) { + if (!blame) { return defaultLocation; } return this.fanavaranLocationService.resolveBusinessLocation({ clientKey, - isMadeByFileMaker: true, - fileMakerId: (blame as any)?.initiatedByFieldExpertId - ? String((blame as any).initiatedByFieldExpertId) - : null, - fileReviewerId: (blame as any)?.assignedFileReviewerId - ? String((blame as any).assignedFileReviewerId) - : null, + 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( diff --git a/src/core/config/fanavaran-client.config.ts b/src/core/config/fanavaran-client.config.ts index ca948d2..b87af8a 100644 --- a/src/core/config/fanavaran-client.config.ts +++ b/src/core/config/fanavaran-client.config.ts @@ -117,7 +117,8 @@ const SHARED_FANAVARAN_DEFAULTS: FanavaranPayloadDefaults = { /** * Seed / code fallback profiles. On app boot these are inserted into - * `fanavaranClientConfigs` only when a key is missing (never overwrite DB edits). + * `fanavaranClientConfigs` only when a key is missing. The config service also + * migrates known legacy defaults on existing documents. * Runtime reads prefer the in-memory cache loaded from Mongo. */ export const SEED_FANAVARAN_CLIENT_PROFILES: Record< @@ -182,6 +183,7 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record< // GEN.03 financial case owner / GEN.08 third-party financial assessor. ClaimExpertId: 5347, ExpertiseClaimExpertId: 5350, + ClaimFileTypeId: 17, }, }, }; diff --git a/src/expert-insurer/dto/create-insurer-expert.dto.ts b/src/expert-insurer/dto/create-insurer-expert.dto.ts index f642bf0..87a8da1 100644 --- a/src/expert-insurer/dto/create-insurer-expert.dto.ts +++ b/src/expert-insurer/dto/create-insurer-expert.dto.ts @@ -120,6 +120,17 @@ export class CreateInsurerExpertDto { @IsOptional() @IsString() address?: string; + + @ApiPropertyOptional({ + type: [ExpertLocationDto], + description: + "Fanavaran Location entries (id = OpBUId). Sent as the HTTP Location header on Fanavaran business calls for this expert.", + }) + @IsOptional() + @IsArray() + @ValidateNested({ each: true }) + @Type(() => ExpertLocationDto) + locations?: ExpertLocationDto[]; } export class CreateBlameExpertByInsurerDto extends CreateInsurerExpertDto { @@ -147,17 +158,6 @@ export class CreateFileMakerByInsurerDto extends OmitType( default: RoleEnum.FILE_MAKER, }) role?: RoleEnum.FILE_MAKER; - - @ApiPropertyOptional({ - type: [ExpertLocationDto], - description: - "Fanavaran Location entries (id = OpBUId). Used for Parsian V4/V5 submits.", - }) - @IsOptional() - @IsArray() - @ValidateNested({ each: true }) - @Type(() => ExpertLocationDto) - locations?: ExpertLocationDto[]; } export class CreateFileReviewerByInsurerDto extends OmitType( @@ -169,15 +169,4 @@ export class CreateFileReviewerByInsurerDto extends OmitType( default: RoleEnum.FILE_REVIEWER, }) role?: RoleEnum.FILE_REVIEWER; - - @ApiPropertyOptional({ - type: [ExpertLocationDto], - description: - "Fanavaran Location entries. Must overlap FileMaker locations on Parsian V4/V5 cases.", - }) - @IsOptional() - @IsArray() - @ValidateNested({ each: true }) - @Type(() => ExpertLocationDto) - locations?: ExpertLocationDto[]; } diff --git a/src/expert-insurer/expert-insurer.service.ts b/src/expert-insurer/expert-insurer.service.ts index 0e91e46..c8c42d2 100644 --- a/src/expert-insurer/expert-insurer.service.ts +++ b/src/expert-insurer/expert-insurer.service.ts @@ -2038,6 +2038,7 @@ export class ExpertInsurerService { } const hashedPassword = await this.hashService.hash(payload.password); + const locations = this.normalizeExpertLocations(payload.locations); const basePayload: any = { ...payload, email, @@ -2049,6 +2050,7 @@ export class ExpertInsurerService { role === RoleEnum.EXPERT ? String(clientObjectId) : clientObjectId, branchId: new Types.ObjectId(payload.branchId), insuActivityCo: String(clientObjectId), + ...(locations ? { locations } : {}), }; const created = diff --git a/src/fanavaran/fanavaran-client-config.service.spec.ts b/src/fanavaran/fanavaran-client-config.service.spec.ts new file mode 100644 index 0000000..ee9d84a --- /dev/null +++ b/src/fanavaran/fanavaran-client-config.service.spec.ts @@ -0,0 +1,38 @@ +import { SEED_FANAVARAN_CLIENT_PROFILES } from "src/core/config/fanavaran-client.config"; +import { FanavaranClientConfigService } from "./fanavaran-client-config.service"; + +describe("Moallem attachment file type", () => { + it("seeds file type 17 for Moallem and retains the other tenant file types", () => { + expect( + SEED_FANAVARAN_CLIENT_PROFILES.moallem.defaults.ClaimFileTypeId, + ).toBe(17); + expect( + SEED_FANAVARAN_CLIENT_PROFILES.parsian.defaults.ClaimFileTypeId, + ).toBe(63); + expect( + SEED_FANAVARAN_CLIENT_PROFILES.tejaratno.defaults.ClaimFileTypeId, + ).toBe(23); + }); + + it("migrates only Moallem's old shared default on existing installations", async () => { + const service = Object.create( + FanavaranClientConfigService.prototype, + ) as any; + service.configModel = { + updateOne: jest.fn().mockResolvedValue({ modifiedCount: 1 }), + findOne: jest.fn().mockReturnValue({ + select: () => ({ + lean: () => ({ exec: async () => ({ _id: "existing" }) }), + }), + }), + create: jest.fn(), + }; + await service.seedMissingProfiles(); + expect(service.configModel.updateOne).toHaveBeenCalledTimes(1); + expect(service.configModel.updateOne).toHaveBeenCalledWith( + { key: "moallem", "defaults.ClaimFileTypeId": 23 }, + { $set: { "defaults.ClaimFileTypeId": 17 } }, + ); + expect(service.configModel.create).not.toHaveBeenCalled(); + }); +}); diff --git a/src/fanavaran/fanavaran-client-config.service.ts b/src/fanavaran/fanavaran-client-config.service.ts index 42e781d..f85a762 100644 --- a/src/fanavaran/fanavaran-client-config.service.ts +++ b/src/fanavaran/fanavaran-client-config.service.ts @@ -20,7 +20,7 @@ import { * through the sync helpers in fanavaran-client.config.ts. * * Boot behaviour: for each known client key, if no document exists, insert the - * seed profile. Existing documents are never overwritten (ops can edit Mongo). + * seed profile. Existing documents retain ops edits except known legacy defaults. */ @Injectable() export class FanavaranClientConfigService implements OnModuleInit { @@ -38,6 +38,12 @@ export class FanavaranClientConfigService implements OnModuleInit { } async seedMissingProfiles(): Promise { + // Moallem previously inherited the shared file type 23. Correct that legacy + // default on existing deployments while preserving other configured ids. + await this.configModel.updateOne( + { key: "moallem", "defaults.ClaimFileTypeId": 23 }, + { $set: { "defaults.ClaimFileTypeId": 17 } }, + ); for (const key of FANAVARAN_CLIENT_KEYS) { const seed = SEED_FANAVARAN_CLIENT_PROFILES[key]; const existing = await this.configModel diff --git a/src/fanavaran/fanavaran-location.service.spec.ts b/src/fanavaran/fanavaran-location.service.spec.ts index 6e02697..65b7b18 100644 --- a/src/fanavaran/fanavaran-location.service.spec.ts +++ b/src/fanavaran/fanavaran-location.service.spec.ts @@ -1,55 +1,136 @@ import { ForbiddenException } from "@nestjs/common"; import { FanavaranLocationService } from "./fanavaran-location.service"; -describe("FanavaranLocationService branch scope", () => { +describe("FanavaranLocationService", () => { const makerId = "maker-1"; const reviewerId = "reviewer-1"; + const fieldExpertId = "field-1"; - const createService = (makerBranch?: string, reviewerBranch?: string) => + const emptyFind = () => jest.fn().mockResolvedValue(null); + + const createService = (opts?: { + maker?: Record | null; + reviewer?: Record | null; + expert?: Record | null; + damage?: Record | null; + field?: Record | null; + }) => new FanavaranLocationService( { - findById: jest.fn().mockResolvedValue( - makerBranch ? { branchId: makerBranch } : {}, - ), + findById: jest.fn().mockImplementation(async (id: string) => { + if (opts?.maker && String(id) === makerId) return opts.maker; + return null; + }), } as any, { - findById: jest.fn().mockResolvedValue( - reviewerBranch ? { branchId: reviewerBranch } : {}, - ), + findById: jest.fn().mockImplementation(async (id: string) => { + if (opts?.reviewer && String(id) === reviewerId) return opts.reviewer; + return null; + }), + } as any, + { + findById: opts?.expert + ? jest.fn().mockResolvedValue(opts.expert) + : emptyFind(), + } as any, + { + findById: opts?.damage + ? jest.fn().mockResolvedValue(opts.damage) + : emptyFind(), + } as any, + { + findById: jest.fn().mockImplementation(async (id: string) => { + if (opts?.field && String(id) === fieldExpertId) return opts.field; + return null; + }), } as any, ); - it("allows a reviewer to view a file from the same branch", async () => { - const service = createService("branch-1", "branch-1"); + describe("branch scope", () => { + it("allows a reviewer to view a file from the same branch", async () => { + const service = createService({ + maker: { branchId: "branch-1" }, + reviewer: { branchId: "branch-1" }, + }); - await expect( - service.assertMakerReviewerBranchCompatible({ - fileMakerId: makerId, - fileReviewerId: reviewerId, - }), - ).resolves.toBeUndefined(); + await expect( + service.assertMakerReviewerBranchCompatible({ + fileMakerId: makerId, + fileReviewerId: reviewerId, + }), + ).resolves.toBeUndefined(); + }); + + it("rejects a reviewer from another branch", async () => { + const service = createService({ + maker: { branchId: "branch-1" }, + reviewer: { branchId: "branch-2" }, + }); + + await expect( + service.assertMakerReviewerBranchCompatible({ + fileMakerId: makerId, + fileReviewerId: reviewerId, + }), + ).rejects.toBeInstanceOf(ForbiddenException); + }); + + it("prefers the immutable case branch snapshot", async () => { + const service = createService({ + maker: { branchId: "old-branch" }, + reviewer: { branchId: "branch-2" }, + }); + + await expect( + service.assertMakerReviewerBranchCompatible({ + fileMakerId: makerId, + fileReviewerId: reviewerId, + caseBranchId: "branch-2", + }), + ).resolves.toBeUndefined(); + }); }); - it("rejects a reviewer from another branch", async () => { - const service = createService("branch-1", "branch-2"); + describe("resolveBusinessLocation", () => { + it("uses the first staff candidate location for any tenant", async () => { + const service = createService({ + field: { locations: [{ id: "210050", name: "غرب" }] }, + reviewer: { locations: [{ id: "100100", name: "دیگر" }] }, + }); - await expect( - service.assertMakerReviewerBranchCompatible({ - fileMakerId: makerId, - fileReviewerId: reviewerId, - }), - ).rejects.toBeInstanceOf(ForbiddenException); - }); + await expect( + service.resolveBusinessLocation({ + clientKey: "tejaratno", + staffCandidateIds: [fieldExpertId, reviewerId], + }), + ).resolves.toBe("210050"); + }); - it("prefers the immutable case branch snapshot", async () => { - const service = createService("old-branch", "branch-2"); + it("falls through to a later candidate when earlier staff has no location", async () => { + const service = createService({ + field: { locations: [] }, + reviewer: { locations: [{ id: "100100", name: "مرکزی" }] }, + }); - await expect( - service.assertMakerReviewerBranchCompatible({ - fileMakerId: makerId, - fileReviewerId: reviewerId, - caseBranchId: "branch-2", - }), - ).resolves.toBeUndefined(); + await expect( + service.resolveBusinessLocation({ + clientKey: "parsian", + staffCandidateIds: [fieldExpertId, reviewerId], + }), + ).resolves.toBe("100100"); + }); + + it("falls back to the tenant auth.location when no staff location exists", async () => { + const service = createService({ + field: { locations: [] }, + }); + + await expect( + service.resolveBusinessLocation({ + clientKey: "moallem", + staffCandidateIds: [fieldExpertId], + }), + ).resolves.toBe("1"); + }); }); }); diff --git a/src/fanavaran/fanavaran-location.service.ts b/src/fanavaran/fanavaran-location.service.ts index 7b9aad7..a8f73fe 100644 --- a/src/fanavaran/fanavaran-location.service.ts +++ b/src/fanavaran/fanavaran-location.service.ts @@ -4,14 +4,18 @@ import { getFanavaranClientProfile, resolveFanavaranClientKey, } from "src/core/config/fanavaran-client.config"; +import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; +import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; +import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; type LocationEntry = { id?: string; name?: string }; /** - * Parsian V4/V5 FileMaker flows: resolve Fanavaran HTTP `Location` from - * file-maker / file-reviewer `locations[].id`, and enforce maker/reviewer match. + * Resolve Fanavaran HTTP `Location` (OpBUId) from assigned staff + * `locations[].id` for every tenant, and enforce maker/reviewer match on + * Parsian FileMaker flows. */ @Injectable() export class FanavaranLocationService { @@ -20,6 +24,9 @@ export class FanavaranLocationService { constructor( private readonly fileMakerDbService: FileMakerDbService, private readonly fileReviewerDbService: FileReviewerDbService, + private readonly expertDbService: ExpertDbService, + private readonly damageExpertDbService: DamageExpertDbService, + private readonly fieldExpertDbService: FieldExpertDbService, ) {} isParsianClient(clientKey?: FanavaranClientKey): boolean { @@ -37,11 +44,13 @@ export class FanavaranLocationService { } /** - * Maker primary location → reviewer primary → tenant auth.location. - * Non-parsian or non-FileMaker flows always use the tenant default. + * First staff candidate with a stored `locations[].id` wins. + * Fallback: tenant auth.location (lookups / cases with no staff locations). */ async resolveBusinessLocation(input: { clientKey: FanavaranClientKey; + staffCandidateIds?: Array; + /** @deprecated Prefer staffCandidateIds — kept for older call sites. */ isMadeByFileMaker?: boolean; fileMakerId?: string | null; fileReviewerId?: string | null; @@ -49,30 +58,25 @@ export class FanavaranLocationService { const defaultLocation = getFanavaranClientProfile(input.clientKey).auth .location; - if (input.clientKey !== "parsian" || input.isMadeByFileMaker !== true) { - return defaultLocation; - } - - const makerLocation = await this.loadPrimaryLocationId( + const candidateIds = [ + ...(input.staffCandidateIds ?? []), input.fileMakerId, - "maker", - ); - if (makerLocation) { - this.logger.debug( - `Fanavaran Location from file-maker id=${input.fileMakerId} → ${makerLocation}`, - ); - return makerLocation; - } - - const reviewerLocation = await this.loadPrimaryLocationId( input.fileReviewerId, - "reviewer", - ); - if (reviewerLocation) { - this.logger.debug( - `Fanavaran Location from file-reviewer id=${input.fileReviewerId} → ${reviewerLocation}`, - ); - return reviewerLocation; + ]; + + const seen = new Set(); + for (const rawId of candidateIds) { + const staffId = rawId != null ? String(rawId).trim() : ""; + if (!staffId || seen.has(staffId)) continue; + seen.add(staffId); + + const location = await this.loadPrimaryLocationIdFromAnyStaff(staffId); + if (location) { + this.logger.debug( + `Fanavaran Location from staff id=${staffId} → ${location}`, + ); + return location; + } } this.logger.debug( @@ -158,14 +162,34 @@ export class FanavaranLocationService { } } - private async loadPrimaryLocationId( - userId: string | null | undefined, - kind: "maker" | "reviewer", + private async loadPrimaryLocationIdFromAnyStaff( + userId: string, ): Promise { - const ids = await this.loadLocationIds(userId, kind); + const ids = await this.loadLocationIdsFromAnyStaff(userId); return ids[0]; } + private async loadLocationIdsFromAnyStaff(userId: string): Promise { + const loaders = [ + () => this.fileMakerDbService.findById(userId), + () => this.fileReviewerDbService.findById(userId), + () => this.expertDbService.findById(userId), + () => this.damageExpertDbService.findById(userId), + () => this.fieldExpertDbService.findById(userId), + ]; + for (const load of loaders) { + try { + const doc = await load(); + if (doc) { + return this.extractLocationIds((doc as any)?.locations); + } + } catch { + // invalid ObjectId / cast errors — try next collection + } + } + return []; + } + private async loadLocationIds( userId: string | null | undefined, kind: "maker" | "reviewer", diff --git a/src/management/management.service.spec.ts b/src/management/management.service.spec.ts index 6a5c59b..89f7a10 100644 --- a/src/management/management.service.spec.ts +++ b/src/management/management.service.spec.ts @@ -172,6 +172,9 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", it.each([ ["file_maker", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], ["file_reviewer", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"], + ["expert", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], + ["damage_expert", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], + ["field_expert", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], ])( "persists and edits %s Fanavaran IDs and locations using the real schemas", async (role, first, second) => { @@ -187,6 +190,7 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries", ); expect(row[first]).toBe("100"); expect(row[second]).toBe("200"); + expect(row.locations).toMatchObject([{ id: "1", name: "تهران" }]); const edited = await service.updateStaff(tenant, role, String(row._id), { [first]: "300", [second]: null, diff --git a/src/management/management.service.ts b/src/management/management.service.ts index e4c9946..66e2111 100644 --- a/src/management/management.service.ts +++ b/src/management/management.service.ts @@ -199,12 +199,16 @@ export class ManagementService { } if (field === "locations") { if ( - ![RoleEnum.FILE_MAKER, RoleEnum.FILE_REVIEWER].includes( - role as RoleEnum, - ) + ![ + RoleEnum.EXPERT, + RoleEnum.DAMAGE_EXPERT, + RoleEnum.FIELD_EXPERT, + RoleEnum.FILE_MAKER, + RoleEnum.FILE_REVIEWER, + ].includes(role as RoleEnum) ) throw new BadRequestException( - "Locations apply only to file makers and reviewers", + "Locations apply only to expert staff roles", ); if (!Array.isArray(value)) throw new BadRequestException("Locations must be an array"); diff --git a/src/users/entities/schema/damage-expert.schema.ts b/src/users/entities/schema/damage-expert.schema.ts index a41514e..8b27bf9 100644 --- a/src/users/entities/schema/damage-expert.schema.ts +++ b/src/users/entities/schema/damage-expert.schema.ts @@ -9,6 +9,19 @@ import { RoleEnum } from "src/Types&Enums/role.enum"; import { UserType } from "src/Types&Enums/userType.enum"; +@Schema({ _id: false, versionKey: false }) +export class DamageExpertLocationModel { + @Prop({ type: String, required: true }) + id: string; + + @Prop({ type: String, required: true }) + name: string; +} + +export const DamageExpertLocationDbSchema = SchemaFactory.createForClass( + DamageExpertLocationModel, +); + @Schema({ _id: false }) export class PersonalInfo { @Prop({ type: "string" }) @@ -126,6 +139,9 @@ export class DamageExpertModel { @Prop({ type: Types.ObjectId, index: true }) branchId?: Types.ObjectId; + @Prop({ type: [DamageExpertLocationDbSchema], default: [] }) + locations?: DamageExpertLocationModel[]; + @Prop({ type: PersonalInfoSchema }) personalInfo?: PersonalInfo; diff --git a/src/users/entities/schema/expert.schema.ts b/src/users/entities/schema/expert.schema.ts index 7d1c9c2..1b69934 100644 --- a/src/users/entities/schema/expert.schema.ts +++ b/src/users/entities/schema/expert.schema.ts @@ -4,6 +4,18 @@ import { Degrees } from "src/Types&Enums/degrees.enum"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { UserType } from "src/Types&Enums/userType.enum"; +@Schema({ _id: false, versionKey: false }) +export class ExpertLocationModel { + @Prop({ type: String, required: true }) + id: string; + + @Prop({ type: String, required: true }) + name: string; +} + +export const ExpertLocationDbSchema = + SchemaFactory.createForClass(ExpertLocationModel); + @Schema({ collection: "expert", versionKey: false, timestamps: true }) export class ExpertModel { @Prop({}) @@ -69,6 +81,9 @@ export class ExpertModel { @Prop({ type: Types.ObjectId, index: true }) branchId?: Types.ObjectId; + @Prop({ type: [ExpertLocationDbSchema], default: [] }) + locations?: ExpertLocationModel[]; + @Prop({ type: "string" }) otp: string; diff --git a/src/users/entities/schema/field-expert.schema.ts b/src/users/entities/schema/field-expert.schema.ts index 111abde..a3f7a2d 100644 --- a/src/users/entities/schema/field-expert.schema.ts +++ b/src/users/entities/schema/field-expert.schema.ts @@ -2,6 +2,19 @@ import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; import { Types } from "mongoose"; import { RoleEnum } from "src/Types&Enums/role.enum"; +@Schema({ _id: false, versionKey: false }) +export class FieldExpertLocationModel { + @Prop({ type: String, required: true }) + id: string; + + @Prop({ type: String, required: true }) + name: string; +} + +export const FieldExpertLocationDbSchema = SchemaFactory.createForClass( + FieldExpertLocationModel, +); + @Schema({ collection: "field-expert", versionKey: false, @@ -31,6 +44,9 @@ export class FieldExpertModel { @Prop({ type: Types.ObjectId, index: true }) branchId?: Types.ObjectId; + @Prop({ type: [FieldExpertLocationDbSchema], default: [] }) + locations?: FieldExpertLocationModel[]; + @Prop({ required: true }) password: string;