Compare commits

..
2 Commits
Author SHA1 Message Date
s.hajizadeh 5d84b9697f location default changed 2026-11-11 14:39:55 +03:30
s.hajizadeh 658a8a74cc dynamic locations 2026-11-11 14:10:01 +03:30
18 changed files with 1677 additions and 1330 deletions
+1 -1
View File
@@ -20,7 +20,7 @@ Common business headers (after Login):
| `authenticationToken` | Login response | | `authenticationToken` | Login response |
| `CorpId` | Tenant auth | | `CorpId` | Tenant auth |
| `ContractId` | 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) | | `Content-Type` | `application/json` (except GEN.07 multipart) |
Template values below are **Parsian-proven** unless noted. Template values below are **Parsian-proven** unless noted.
+2 -2
View File
@@ -23,7 +23,7 @@ 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` | 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)`. 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 ✅ | | `PlaqueSampleId` | 10 | same | same | same | may ✅ |
| `DriverIsOwner` | 0 | same | same | same | ❌ | | `DriverIsOwner` | 0 | same | same | same | ❌ |
| `FaultPercent` | 100 | 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. **Never swap** GEN.03 `ClaimExpertId` with GEN.08 `ExpertiseClaimExpertId` — different Fanavaran roles.
+1 -1
View File
@@ -90,7 +90,7 @@ Create only on GEN.12 submit when inquiry missed. Cache `otherPersonId` + `drive
|-------------------|------------------| |-------------------|------------------|
| `corpId` | `CorpId` | | `corpId` | `CorpId` |
| `contractId` | `ContractId` | | `contractId` | `ContractId` |
| `location` | `Location` | | staff `locations[].id` (else tenant `auth.location`) | `Location` |
| token from Login | `authenticationToken` | | token from Login | `authenticationToken` |
## Not mapped / out of scope ## Not mapped / out of scope
+146
View File
@@ -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.
+2 -2
View File
@@ -39,7 +39,7 @@ Common optional properties are `branchId`, `phone`, `mobile`, `email`, `city`, `
| Role | Additional optional fields | | 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` | | FileMaker | `ThirdPartyClaimExpertId`, `CarBodyClaimExpertId`, `locations` |
| FileReviewer | `ThirdPartyExpertiseClaim`, `CarBodyExpertiseClaim`, `locations` | | FileReviewer | `ThirdPartyExpertiseClaim`, `CarBodyExpertiseClaim`, `locations` |
| Call-center agent | None of the four product/stage codes | | 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. 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. 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.
File diff suppressed because it is too large Load Diff
+40 -38
View File
@@ -1,9 +1,9 @@
export type FanavaranClientKey = "parsian" | "tejaratno" | "moallem"; export type FanavaranClientKey = 'parsian' | 'tejaratno' | 'moallem';
const FANAVARAN_API_ROOTS: Record<FanavaranClientKey, string> = { const FANAVARAN_API_ROOTS: Record<FanavaranClientKey, string> = {
parsian: "https://apimanager.iraneit.com/BimeApiManager/api", parsian: 'https://apimanager.iraneit.com/BimeApiManager/api',
tejaratno: "https://apimanager.iraneit.com/BimeApiManager/api", tejaratno: 'https://apimanager.iraneit.com/BimeApiManager/api',
moallem: "https://apimanager.iraneit.com/BimeApiManager/api", moallem: 'https://apimanager.iraneit.com/BimeApiManager/api',
}; };
export function getFanavaranApiRoot(clientKey: FanavaranClientKey): string { export function getFanavaranApiRoot(clientKey: FanavaranClientKey): string {
@@ -17,9 +17,9 @@ export function getFanavaranLookupBaseUrl(
} }
export const FANAVARAN_CLIENT_KEYS: readonly FanavaranClientKey[] = [ export const FANAVARAN_CLIENT_KEYS: readonly FanavaranClientKey[] = [
"parsian", 'parsian',
"tejaratno", 'tejaratno',
"moallem", 'moallem',
] as const; ] as const;
/** Swagger `@ApiParam({ enum })` value — keep in sync with {@link FANAVARAN_CLIENT_KEYS}. */ /** Swagger `@ApiParam({ enum })` value — keep in sync with {@link FANAVARAN_CLIENT_KEYS}. */
@@ -40,7 +40,7 @@ export function normalizeFanavaranClientKey(value: string): FanavaranClientKey {
return normalized; return normalized;
} }
throw new Error( throw new Error(
`Invalid Fanavaran client "${value}". Expected one of: ${FANAVARAN_CLIENT_KEYS.join(", ")}`, `Invalid Fanavaran client "${value}". Expected one of: ${FANAVARAN_CLIENT_KEYS.join(', ')}`,
); );
} }
@@ -117,7 +117,8 @@ const SHARED_FANAVARAN_DEFAULTS: FanavaranPayloadDefaults = {
/** /**
* Seed / code fallback profiles. On app boot these are inserted into * 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. * Runtime reads prefer the in-memory cache loaded from Mongo.
*/ */
export const SEED_FANAVARAN_CLIENT_PROFILES: Record< export const SEED_FANAVARAN_CLIENT_PROFILES: Record<
@@ -125,15 +126,15 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record<
FanavaranClientProfile FanavaranClientProfile
> = { > = {
tejaratno: { tejaratno: {
key: "tejaratno", key: 'tejaratno',
auth: { auth: {
appName: "fanhab", appName: 'fanhab',
secret: "5Fa@N#A2B", secret: '5Fa@N#A2B',
username: "fanhabUser", username: 'fanhabUser',
password: "Fan#@2U$3er", password: 'Fan#@2U$3er',
corpId: "3539", corpId: '3539',
contractId: "263", contractId: '263',
location: "100", location: '100',
}, },
defaults: { defaults: {
...SHARED_FANAVARAN_DEFAULTS, ...SHARED_FANAVARAN_DEFAULTS,
@@ -145,15 +146,15 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record<
}, },
}, },
parsian: { parsian: {
key: "parsian", key: 'parsian',
auth: { auth: {
appName: "ParsianService", appName: 'ParsianService',
secret: "P@r30@n$erv!ce", secret: 'P@r30@n$erv!ce',
username: "ParsianServiceUser", username: 'ParsianServiceUser',
password: "P@r30@n123", password: 'P@r30@n123',
corpId: "543", corpId: '543',
contractId: "28", contractId: '28',
location: "210050", location: '110011',
}, },
defaults: { defaults: {
...SHARED_FANAVARAN_DEFAULTS, ...SHARED_FANAVARAN_DEFAULTS,
@@ -167,21 +168,22 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record<
}, },
}, },
moallem: { moallem: {
key: "moallem", key: 'moallem',
auth: { auth: {
appName: "ItTalie", appName: 'ItTalie',
secret: "itT@l!3@api", secret: 'itT@l!3@api',
username: "itTalieUser", username: 'itTalieUser',
password: "itT@l!3@user", password: 'itT@l!3@user',
corpId: "5650", corpId: '5650',
contractId: "304", contractId: '304',
location: "1", location: '1',
}, },
defaults: { defaults: {
...SHARED_FANAVARAN_DEFAULTS, ...SHARED_FANAVARAN_DEFAULTS,
// GEN.03 financial case owner / GEN.08 third-party financial assessor. // GEN.03 financial case owner / GEN.08 third-party financial assessor.
ClaimExpertId: 5347, ClaimExpertId: 5347,
ExpertiseClaimExpertId: 5350, ExpertiseClaimExpertId: 5350,
ClaimFileTypeId: 17,
}, },
}, },
}; };
@@ -215,11 +217,11 @@ export function resolveFanavaranClientKey(): FanavaranClientKey {
} }
// Optional deployment hint when FANAVARAN_CLIENT is not set. // Optional deployment hint when FANAVARAN_CLIENT is not set.
if (String(process.env.CLIENT_ID ?? "") === "8") { if (String(process.env.CLIENT_ID ?? '') === '8') {
return "parsian"; return 'parsian';
} }
return "tejaratno"; return 'tejaratno';
} }
export function resolveFanavaranClientProfile(): FanavaranClientProfile { export function resolveFanavaranClientProfile(): FanavaranClientProfile {
@@ -237,10 +239,10 @@ export function getFanavaranClientProfile(
/** ثالث uses `contractId`. بدنه uses `hullContractId` when configured. */ /** ثالث uses `contractId`. بدنه uses `hullContractId` when configured. */
export function resolveFanavaranProductContractId( export function resolveFanavaranProductContractId(
clientKey: FanavaranClientKey, clientKey: FanavaranClientKey,
product: "third-party" | "car-body", product: 'third-party' | 'car-body',
): string { ): string {
const profile = getFanavaranClientProfile(clientKey); const profile = getFanavaranClientProfile(clientKey);
if (product === "car-body") { if (product === 'car-body') {
const hull = profile.auth.hullContractId?.trim(); const hull = profile.auth.hullContractId?.trim();
if (hull) return hull; if (hull) return hull;
} }
@@ -1,5 +1,5 @@
import { ApiProperty, ApiPropertyOptional, OmitType } from "@nestjs/swagger"; import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger';
import { Type } from "class-transformer"; import { Type } from 'class-transformer';
import { import {
IsArray, IsArray,
IsEmail, IsEmail,
@@ -10,20 +10,20 @@ import {
IsOptional, IsOptional,
IsString, IsString,
ValidateNested, ValidateNested,
} from "class-validator"; } from 'class-validator';
import { RoleEnum } from "src/Types&Enums/role.enum"; import { RoleEnum } from 'src/Types&Enums/role.enum';
import { UserType } from "src/Types&Enums/userType.enum"; import { UserType } from 'src/Types&Enums/userType.enum';
export class ExpertLocationDto { export class ExpertLocationDto {
@ApiProperty({ @ApiProperty({
example: "210050", example: '110011',
description: "Fanavaran Location / OpBUId", description: 'Fanavaran Location / OpBUId',
}) })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
id: string; id: string;
@ApiProperty({ example: "شعبه غرب" }) @ApiProperty({ example: 'شعبه غرب' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
name: string; name: string;
@@ -36,62 +36,62 @@ export class CreateInsurerExpertDto {
@Matches(/^\d+$/) @Matches(/^\d+$/)
expertCode?: string; expertCode?: string;
@ApiPropertyOptional({ description: "کارشناس مسئول پرونده مالی" }) @ApiPropertyOptional({ description: 'کارشناس مسئول پرونده مالی' })
@IsOptional() @IsOptional()
@IsString() @IsString()
@Matches(/^\d+$/) @Matches(/^\d+$/)
ThirdPartyClaimExpertId?: string; ThirdPartyClaimExpertId?: string;
@ApiPropertyOptional({ description: "کارشناس مسئول پرونده بدنه" }) @ApiPropertyOptional({ description: 'کارشناس مسئول پرونده بدنه' })
@IsOptional() @IsOptional()
@IsString() @IsString()
@Matches(/^\d+$/) @Matches(/^\d+$/)
CarBodyClaimExpertId?: string; CarBodyClaimExpertId?: string;
@ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت ثالث مالی" }) @ApiPropertyOptional({ description: 'کارشناس ارزیاب خسارت ثالث مالی' })
@IsOptional() @IsOptional()
@IsString() @IsString()
@Matches(/^\d+$/) @Matches(/^\d+$/)
ThirdPartyExpertiseClaim?: string; ThirdPartyExpertiseClaim?: string;
@ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت بدنه" }) @ApiPropertyOptional({ description: 'کارشناس ارزیاب خسارت بدنه' })
@IsOptional() @IsOptional()
@IsString() @IsString()
@Matches(/^\d+$/) @Matches(/^\d+$/)
CarBodyExpertiseClaim?: string; CarBodyExpertiseClaim?: string;
@ApiProperty({ example: "Ali" }) @ApiProperty({ example: 'Ali' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
firstName: string; firstName: string;
@ApiProperty({ example: "Ahmadi" }) @ApiProperty({ example: 'Ahmadi' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
lastName: string; lastName: string;
@ApiProperty({ example: "1234567890" }) @ApiProperty({ example: '1234567890' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
nationalCode: string; nationalCode: string;
@ApiProperty({ example: "expert@example.com" }) @ApiProperty({ example: 'expert@example.com' })
@IsEmail() @IsEmail()
email: string; email: string;
@ApiProperty({ example: "StrongPass!123" }) @ApiProperty({ example: 'StrongPass!123' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
password: string; password: string;
@ApiProperty({ example: "09121234567" }) @ApiProperty({ example: '09121234567' })
@IsString() @IsString()
@IsNotEmpty() @IsNotEmpty()
mobile: string; mobile: string;
@ApiProperty({ @ApiProperty({
example: "665f0e5ab74d670939b08920", example: '665f0e5ab74d670939b08920',
description: "Branch id this expert belongs to", description: 'Branch id this expert belongs to',
}) })
@IsMongoId() @IsMongoId()
branchId: string; branchId: string;
@@ -101,25 +101,36 @@ export class CreateInsurerExpertDto {
@IsEnum(UserType) @IsEnum(UserType)
userType?: UserType; userType?: UserType;
@ApiPropertyOptional({ example: "02112345678" }) @ApiPropertyOptional({ example: '02112345678' })
@IsOptional() @IsOptional()
@IsString() @IsString()
phone?: string; phone?: string;
@ApiPropertyOptional({ example: "Tehran" }) @ApiPropertyOptional({ example: 'Tehran' })
@IsOptional() @IsOptional()
@IsString() @IsString()
state?: string; state?: string;
@ApiPropertyOptional({ example: "Tehran" }) @ApiPropertyOptional({ example: 'Tehran' })
@IsOptional() @IsOptional()
@IsString() @IsString()
city?: string; city?: string;
@ApiPropertyOptional({ example: "No. 12, Sample St." }) @ApiPropertyOptional({ example: 'No. 12, Sample St.' })
@IsOptional() @IsOptional()
@IsString() @IsString()
address?: string; 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 { export class CreateBlameExpertByInsurerDto extends CreateInsurerExpertDto {
@@ -140,44 +151,22 @@ export class CreateClaimExpertByInsurerDto extends CreateInsurerExpertDto {
export class CreateFileMakerByInsurerDto extends OmitType( export class CreateFileMakerByInsurerDto extends OmitType(
CreateInsurerExpertDto, CreateInsurerExpertDto,
["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"] as const, ['ThirdPartyExpertiseClaim', 'CarBodyExpertiseClaim'] as const,
) { ) {
@ApiPropertyOptional({ @ApiPropertyOptional({
enum: [RoleEnum.FILE_MAKER], enum: [RoleEnum.FILE_MAKER],
default: RoleEnum.FILE_MAKER, default: RoleEnum.FILE_MAKER,
}) })
role?: 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( export class CreateFileReviewerByInsurerDto extends OmitType(
CreateInsurerExpertDto, CreateInsurerExpertDto,
["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"] as const, ['ThirdPartyClaimExpertId', 'CarBodyClaimExpertId'] as const,
) { ) {
@ApiPropertyOptional({ @ApiPropertyOptional({
enum: [RoleEnum.FILE_REVIEWER], enum: [RoleEnum.FILE_REVIEWER],
default: RoleEnum.FILE_REVIEWER, default: RoleEnum.FILE_REVIEWER,
}) })
role?: 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[];
} }
@@ -2038,6 +2038,7 @@ export class ExpertInsurerService {
} }
const hashedPassword = await this.hashService.hash(payload.password); const hashedPassword = await this.hashService.hash(payload.password);
const locations = this.normalizeExpertLocations(payload.locations);
const basePayload: any = { const basePayload: any = {
...payload, ...payload,
email, email,
@@ -2049,6 +2050,7 @@ export class ExpertInsurerService {
role === RoleEnum.EXPERT ? String(clientObjectId) : clientObjectId, role === RoleEnum.EXPERT ? String(clientObjectId) : clientObjectId,
branchId: new Types.ObjectId(payload.branchId), branchId: new Types.ObjectId(payload.branchId),
insuActivityCo: String(clientObjectId), insuActivityCo: String(clientObjectId),
...(locations ? { locations } : {}),
}; };
const created = const created =
@@ -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();
});
});
@@ -20,7 +20,7 @@ import {
* through the sync helpers in fanavaran-client.config.ts. * through the sync helpers in fanavaran-client.config.ts.
* *
* Boot behaviour: for each known client key, if no document exists, insert the * 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() @Injectable()
export class FanavaranClientConfigService implements OnModuleInit { export class FanavaranClientConfigService implements OnModuleInit {
@@ -38,6 +38,12 @@ export class FanavaranClientConfigService implements OnModuleInit {
} }
async seedMissingProfiles(): Promise<void> { async seedMissingProfiles(): Promise<void> {
// 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) { for (const key of FANAVARAN_CLIENT_KEYS) {
const seed = SEED_FANAVARAN_CLIENT_PROFILES[key]; const seed = SEED_FANAVARAN_CLIENT_PROFILES[key];
const existing = await this.configModel const existing = await this.configModel
+115 -34
View File
@@ -1,55 +1,136 @@
import { ForbiddenException } from "@nestjs/common"; import { ForbiddenException } from "@nestjs/common";
import { FanavaranLocationService } from "./fanavaran-location.service"; import { FanavaranLocationService } from "./fanavaran-location.service";
describe("FanavaranLocationService branch scope", () => { describe("FanavaranLocationService", () => {
const makerId = "maker-1"; const makerId = "maker-1";
const reviewerId = "reviewer-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<string, unknown> | null;
reviewer?: Record<string, unknown> | null;
expert?: Record<string, unknown> | null;
damage?: Record<string, unknown> | null;
field?: Record<string, unknown> | null;
}) =>
new FanavaranLocationService( new FanavaranLocationService(
{ {
findById: jest.fn().mockResolvedValue( findById: jest.fn().mockImplementation(async (id: string) => {
makerBranch ? { branchId: makerBranch } : {}, if (opts?.maker && String(id) === makerId) return opts.maker;
), return null;
}),
} as any, } as any,
{ {
findById: jest.fn().mockResolvedValue( findById: jest.fn().mockImplementation(async (id: string) => {
reviewerBranch ? { branchId: reviewerBranch } : {}, 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, } as any,
); );
it("allows a reviewer to view a file from the same branch", async () => { describe("branch scope", () => {
const service = createService("branch-1", "branch-1"); 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( await expect(
service.assertMakerReviewerBranchCompatible({ service.assertMakerReviewerBranchCompatible({
fileMakerId: makerId, fileMakerId: makerId,
fileReviewerId: reviewerId, fileReviewerId: reviewerId,
}), }),
).resolves.toBeUndefined(); ).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 () => { describe("resolveBusinessLocation", () => {
const service = createService("branch-1", "branch-2"); 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( await expect(
service.assertMakerReviewerBranchCompatible({ service.resolveBusinessLocation({
fileMakerId: makerId, clientKey: "tejaratno",
fileReviewerId: reviewerId, staffCandidateIds: [fieldExpertId, reviewerId],
}), }),
).rejects.toBeInstanceOf(ForbiddenException); ).resolves.toBe("210050");
}); });
it("prefers the immutable case branch snapshot", async () => { it("falls through to a later candidate when earlier staff has no location", async () => {
const service = createService("old-branch", "branch-2"); const service = createService({
field: { locations: [] },
reviewer: { locations: [{ id: "100100", name: "مرکزی" }] },
});
await expect( await expect(
service.assertMakerReviewerBranchCompatible({ service.resolveBusinessLocation({
fileMakerId: makerId, clientKey: "parsian",
fileReviewerId: reviewerId, staffCandidateIds: [fieldExpertId, reviewerId],
caseBranchId: "branch-2", }),
}), ).resolves.toBe("100100");
).resolves.toBeUndefined(); });
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");
});
}); });
}); });
+54 -30
View File
@@ -4,14 +4,18 @@ import {
getFanavaranClientProfile, getFanavaranClientProfile,
resolveFanavaranClientKey, resolveFanavaranClientKey,
} from "src/core/config/fanavaran-client.config"; } 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 { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service";
type LocationEntry = { id?: string; name?: string }; type LocationEntry = { id?: string; name?: string };
/** /**
* Parsian V4/V5 FileMaker flows: resolve Fanavaran HTTP `Location` from * Resolve Fanavaran HTTP `Location` (OpBUId) from assigned staff
* file-maker / file-reviewer `locations[].id`, and enforce maker/reviewer match. * `locations[].id` for every tenant, and enforce maker/reviewer match on
* Parsian FileMaker flows.
*/ */
@Injectable() @Injectable()
export class FanavaranLocationService { export class FanavaranLocationService {
@@ -20,6 +24,9 @@ export class FanavaranLocationService {
constructor( constructor(
private readonly fileMakerDbService: FileMakerDbService, private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService, private readonly fileReviewerDbService: FileReviewerDbService,
private readonly expertDbService: ExpertDbService,
private readonly damageExpertDbService: DamageExpertDbService,
private readonly fieldExpertDbService: FieldExpertDbService,
) {} ) {}
isParsianClient(clientKey?: FanavaranClientKey): boolean { isParsianClient(clientKey?: FanavaranClientKey): boolean {
@@ -37,11 +44,13 @@ export class FanavaranLocationService {
} }
/** /**
* Maker primary location → reviewer primary → tenant auth.location. * First staff candidate with a stored `locations[].id` wins.
* Non-parsian or non-FileMaker flows always use the tenant default. * Fallback: tenant auth.location (lookups / cases with no staff locations).
*/ */
async resolveBusinessLocation(input: { async resolveBusinessLocation(input: {
clientKey: FanavaranClientKey; clientKey: FanavaranClientKey;
staffCandidateIds?: Array<string | null | undefined>;
/** @deprecated Prefer staffCandidateIds — kept for older call sites. */
isMadeByFileMaker?: boolean; isMadeByFileMaker?: boolean;
fileMakerId?: string | null; fileMakerId?: string | null;
fileReviewerId?: string | null; fileReviewerId?: string | null;
@@ -49,30 +58,25 @@ export class FanavaranLocationService {
const defaultLocation = getFanavaranClientProfile(input.clientKey).auth const defaultLocation = getFanavaranClientProfile(input.clientKey).auth
.location; .location;
if (input.clientKey !== "parsian" || input.isMadeByFileMaker !== true) { const candidateIds = [
return defaultLocation; ...(input.staffCandidateIds ?? []),
}
const makerLocation = await this.loadPrimaryLocationId(
input.fileMakerId, 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, input.fileReviewerId,
"reviewer", ];
);
if (reviewerLocation) { const seen = new Set<string>();
this.logger.debug( for (const rawId of candidateIds) {
`Fanavaran Location from file-reviewer id=${input.fileReviewerId} → ${reviewerLocation}`, const staffId = rawId != null ? String(rawId).trim() : "";
); if (!staffId || seen.has(staffId)) continue;
return reviewerLocation; 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( this.logger.debug(
@@ -158,14 +162,34 @@ export class FanavaranLocationService {
} }
} }
private async loadPrimaryLocationId( private async loadPrimaryLocationIdFromAnyStaff(
userId: string | null | undefined, userId: string,
kind: "maker" | "reviewer",
): Promise<string | undefined> { ): Promise<string | undefined> {
const ids = await this.loadLocationIds(userId, kind); const ids = await this.loadLocationIdsFromAnyStaff(userId);
return ids[0]; return ids[0];
} }
private async loadLocationIdsFromAnyStaff(userId: string): Promise<string[]> {
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( private async loadLocationIds(
userId: string | null | undefined, userId: string | null | undefined,
kind: "maker" | "reviewer", kind: "maker" | "reviewer",
@@ -172,6 +172,9 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
it.each([ it.each([
["file_maker", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"], ["file_maker", "ThirdPartyClaimExpertId", "CarBodyClaimExpertId"],
["file_reviewer", "ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"], ["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", "persists and edits %s Fanavaran IDs and locations using the real schemas",
async (role, first, second) => { async (role, first, second) => {
@@ -187,6 +190,7 @@ describe("management accounts, optional Fanavaran fields and tenant boundaries",
); );
expect(row[first]).toBe("100"); expect(row[first]).toBe("100");
expect(row[second]).toBe("200"); expect(row[second]).toBe("200");
expect(row.locations).toMatchObject([{ id: "1", name: "تهران" }]);
const edited = await service.updateStaff(tenant, role, String(row._id), { const edited = await service.updateStaff(tenant, role, String(row._id), {
[first]: "300", [first]: "300",
[second]: null, [second]: null,
+8 -4
View File
@@ -199,12 +199,16 @@ export class ManagementService {
} }
if (field === "locations") { if (field === "locations") {
if ( 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( throw new BadRequestException(
"Locations apply only to file makers and reviewers", "Locations apply only to expert staff roles",
); );
if (!Array.isArray(value)) if (!Array.isArray(value))
throw new BadRequestException("Locations must be an array"); throw new BadRequestException("Locations must be an array");
@@ -9,6 +9,19 @@ import { RoleEnum } from "src/Types&Enums/role.enum";
import { UserType } from "src/Types&Enums/userType.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 }) @Schema({ _id: false })
export class PersonalInfo { export class PersonalInfo {
@Prop({ type: "string" }) @Prop({ type: "string" })
@@ -126,6 +139,9 @@ export class DamageExpertModel {
@Prop({ type: Types.ObjectId, index: true }) @Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId; branchId?: Types.ObjectId;
@Prop({ type: [DamageExpertLocationDbSchema], default: [] })
locations?: DamageExpertLocationModel[];
@Prop({ type: PersonalInfoSchema }) @Prop({ type: PersonalInfoSchema })
personalInfo?: PersonalInfo; personalInfo?: PersonalInfo;
@@ -4,6 +4,18 @@ import { Degrees } from "src/Types&Enums/degrees.enum";
import { RoleEnum } from "src/Types&Enums/role.enum"; import { RoleEnum } from "src/Types&Enums/role.enum";
import { UserType } from "src/Types&Enums/userType.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 }) @Schema({ collection: "expert", versionKey: false, timestamps: true })
export class ExpertModel { export class ExpertModel {
@Prop({}) @Prop({})
@@ -69,6 +81,9 @@ export class ExpertModel {
@Prop({ type: Types.ObjectId, index: true }) @Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId; branchId?: Types.ObjectId;
@Prop({ type: [ExpertLocationDbSchema], default: [] })
locations?: ExpertLocationModel[];
@Prop({ type: "string" }) @Prop({ type: "string" })
otp: string; otp: string;
@@ -2,6 +2,19 @@ import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose";
import { Types } from "mongoose"; import { Types } from "mongoose";
import { RoleEnum } from "src/Types&Enums/role.enum"; 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({ @Schema({
collection: "field-expert", collection: "field-expert",
versionKey: false, versionKey: false,
@@ -31,6 +44,9 @@ export class FieldExpertModel {
@Prop({ type: Types.ObjectId, index: true }) @Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId; branchId?: Types.ObjectId;
@Prop({ type: [FieldExpertLocationDbSchema], default: [] })
locations?: FieldExpertLocationModel[];
@Prop({ required: true }) @Prop({ required: true })
password: string; password: string;