feat: route user claims by branch and align licence issue dates

Require the damaged party in user flows to select an active insurer branch and preserve branch access rules. Accept older licence issue dates, correct anniversary boundaries, and update Fanavaran audit documentation and regression coverage.
This commit is contained in:
SepehrYahyaee
2026-11-14 12:24:14 +03:30
parent f021793b00
commit a15c54d017
28 changed files with 1403 additions and 42 deletions
+38
View File
@@ -0,0 +1,38 @@
# Driver licence issue dates
Updated: 2026-11-14.
The inquiry field is the **issue date**, `driver.driverLicenseDate`, labelled
«تاریخ صدور گواهینامه». It is not an expiry date. Both UIs keep the existing
structured inquiry contract and send the actual selected date. No replacement
checkbox or client-generated Fanavaran status is added.
For a licensed driver, the date is still required and must be valid and not in
the future. The ten-year lower bound has been removed from both UI schemas and
the shared API inquiry validator; otherwise an older date would pass the form
and still fail at submission. Drivers without a licence retain their existing
payload behavior, which omits the licence date.
The API derives the Fanavaran flag against the **accident date**, preserving the
mapping introduced by the pulled changes:
| Age at accident | Outbound value |
|---|---|
| Through the third issue-date anniversary | `0` |
| After the third anniversary through the tenth anniversary | `null` |
| After the tenth anniversary | `1` |
Hull uses `IsLicenseReplaced`; third-party uses `IsLicenseReplacement`. Recent
licences still receive explicit `0` because the current Fanavaran rule requires
an answer. Users do not enter this flag themselves. Anniversary comparison uses
the actual Jalali year/month/day, so ten years plus one day no longer waits until
eleven completed years to become `1`.
The UIs validate against Iran's current date and reject invalid month/day
combinations rather than accepting a date-picker library's rollover. The
existing missing-date fallback for legacy records remains unchanged.
Validation covers old/current/future dates, invalid Jalali dates, Persian input,
both insurance products, licensed/unlicensed drivers, inquiry payloads, and
three-/ten-year anniversary boundaries. Run `npm run test:ui` in each UI and
`npm test -- --runInBand` in the API.
+4 -1
View File
@@ -56,7 +56,10 @@ 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` is `1` when licence issue is >10 years before the accident, otherwise `null`.
and durations remain expert data. Licence issue dates have no 10-year intake
cutoff. The server derives `IsLicenseReplaced`: `0` through the third anniversary,
`null` after three years through the tenth anniversary, and `1` after ten years,
measured against the accident date. Third-party uses `IsLicenseReplacement`.
| Name | Shared seed | Parsian override | Tejaratno | Moallem | Varies? |
|------|-------------|------------------|-----------|---------|---------|
+1
View File
@@ -38,6 +38,7 @@ source: fanavaran-module-docs
| — | [third-party-stage-fields.md](./third-party-stage-fields.md) | ثالث: each stage body, null vs required, lookup/inquiry vs user |
| — | [car-body-stage-fields.md](./car-body-stage-fields.md) | بدنه: each stage body, null vs required, lookup/inquiry vs user |
| — | [flow-design-user-vs-inquiry.md](./flow-design-user-vs-inquiry.md) | Proposed intake: user vs inquiry, Persian titles + types |
| — | [hardcoded-payload-audit.md](./hardcoded-payload-audit.md) | Current hardcoded outbound values, removed fallbacks, standalone-tool differences, and remediation priorities (2026-11-11) |
## Related sources (code)
+5 -1
View File
@@ -31,7 +31,11 @@ Built by `buildFanavaranSubmitPayload` then `enrichCarBodyHullBaseClaimPayload`
**Fanavaran has rejected as required (must not be null):**
`CustomerFaultPercent`, `AuthorityCulpritId`, `AccidentTypeId`, `CostSeparationToDmgSections`, `IsOwnerChanged`, `PolicyId`, `ClaimExpertId`, dates/time, `CulpritTypeId`.
**IsLicenseReplaced:** `1` when `CulpritLicenceIssuDate` is more than 10 years before `AccidentDate`; otherwise `null` (never send `0`). Dummy issue date when missing: `1404/08/20`.
**IsLicenseReplaced:** derived on the server from `CulpritLicenceIssuDate` and
`AccidentDate`: `0` through the third anniversary, `null` after three years
through the tenth anniversary, and `1` after ten years. Intake accepts valid past
issue dates older than ten years; no expiry-date or replacement-checkbox input
is required. The existing missing-date fallback is `1400/01/01`.
| Field | Persian | Type | Null? | Current value / source |
|-------|---------|------|-------|------------------------|
+278
View File
@@ -0,0 +1,278 @@
# Fanavaran hardcoded outbound values — current audit
Date: **2026-11-11**. Remote baseline: API `90bdc51` on `origin/main`, with the
existing local branch-routing work restored. This is a source audit of possible
outbound values, not a capture of production requests. Mongo configuration can
override seed defaults, so the numbers below are code defaults, not a claim about
what is configured on a particular production server.
**The requirement “never send guessed/default business codes” is not satisfied.**
The staff-location fix is present, and recent hull changes removed several
numeric fallbacks, but other defaults can still reach Fanavaran. Merely checking
that a default ID exists in a lookup does not establish that it describes this
accident, driver, vehicle, or assessment.
This document updates the outbound-default findings in
[lookup-coding-audit.md](./lookup-coding-audit.md), which predates the latest hull
and location changes. This audit changes documentation only.
## Audited paths
| Area | Sources and responsibility |
|---|---|
| Application write entry points | `src/fanavaran/fanavaran.controller.ts`: base claim, damage case, attachments, expertise preview/submit; automatic and soft-ensure stage calls in `ClaimRequestManagementService` use the same builders |
| Payloads and HTTP writes | `src/claim-request-management/claim-request-management.service.ts`: GEN.03, GEN.12, GEN.44, GEN.07, third-party GEN.08, hull base PUT and GEN.06 |
| Product-specific helpers | `src/claim-request-management/fanavaran-{hull-base-claim,hull-expertise,hull-expertise-lookups,hull-lookup-validation,party-roles,other-people,accident-vehicle-used,v15-third-party-base}.ts` |
| Configuration and headers | `src/core/config/fanavaran-client.config.ts`, `src/fanavaran/fanavaran-{client-config,auth,location}.service.ts`, config schema, system settings |
| Lookup/inquiry and local catalogues | `src/fanavaran/fanavaran-lookup.service.ts`, `fanavaran-lookup.config.ts`, `src/lookups/`, `src/static/outer-car-parts-catalog.ts`, part helpers, vehicle/stage review code |
| Expert and user UI | Expert Fanavaran API route, vehicle review, stage-field defaults, damage reply fields; user inquiry/part-selection consumers. No matching numeric payload defaults were found in the current UI source search; the expert UI does accept backend-prefilled defaults. |
| Standalone tools | `scripts/fanavaran-flow-ui-server.js`, `scripts/data/fanavaran-flow-ui.html`, `scripts/fanavaran-flow-test.sh`, `scripts/fanavaran-auth.sh`, `scripts/get-fanavaran-car-parts.sh`; report-seeding fixtures were distinguished from application writes |
The runtime tenant type supports `parsian`, `tejaratno`, and `moallem`.
`esg/src` had no direct Fanavaran references in the search. `rewrite` was excluded.
## 1. Business IDs that can still be sent from defaults
Line references are against the restored worktree at audit time. `service` means
`src/claim-request-management/claim-request-management.service.ts`.
| Field / stage | Hardcoded or seeded value | When it reaches the payload | Evidence / required source |
|---|---|---|---|
| `AccidentCauseId` — base, both products | **6** | Always initialized to 6. `accidentReason` is passed into the builder but its selected ID / `fanavaran` code is not applied. Hull checks membership, which can accept the wrong but active cause. | `service:405`, `1894`; use the actual selected cause mapped to this tenant. |
| `AccidentCityId` — base, both products | **701** | Profile default unless an expert stage review changes it. The shared builder does not resolve the supplied coordinates into a city. | Config `:100`; `service:1893`, `5691`; use accident-city selection/inquiry. |
| `AccidentReportTypeId` — base, both products | **155** | Profile default unless reviewed. | Config `:101`; `service:5692`; explicit report-type selection. |
| `CompensationReferenceId` — third-party base | **167** | Included from the profile; not among the current editable stage fields or manual-ID overrides. Hull's key whitelist removes it. | Config `:106`; `service:1893`; confirm the required contract/codebook and source. |
| `CulpritLicenceTypeId` — base, both products | **2** | Included from the profile. The resolved driver identity includes `licenseType`, but the payload does not use it. Hull checks whether 2 is active, not whether it is the driver's licence category. | Config `:107`; `service:4679` vicinity; map the actual stored driver's selection. |
| `LicenceTypeId` — third-party damage | **2** | Always assigned from `defaults.CulpritLicenceTypeId`, ignoring the damaged driver's stored licence type. | `service:3253`. |
| `CulpritTypeId` — third-party base | **337 / 338** | Final value comes from a static map: policyholder/driver same national code → 337, different → 338. Missing role information can default to 337. It is no longer simply the profile's 337. | `fanavaran-party-roles.ts:205–226`; `service:4687`; resolve current tenant IDs by confirmed role meaning and reject unknown roles. |
| `AccidentVehicleUsedId` — third-party base and damage | **1** | Fallback when inquiry/group resolution is unresolved; an expert's approved use type can override it. Hull base has removed this numeric fallback. | `service:4771`, `3208`; preserve the actual vehicle use or require a selection. |
| `DmgCaseTypeId` — third-party damage | **175** | Unconditionally taken from the profile. No current expert stage field for it. | `service:3235`; determine the actual damage-case classification. |
| `DmgHistoryStatus` — third-party damage | **5214** | Profile default unless reviewed. | `service:3231–3233`; actual history/explicit selection. |
| `PlaqueKindId` / `PlaqueSampleId` — third-party damage | **8 / 10** | National-plate fallback when matched Fanavaran vehicle has no kind. Even with a real kind, a missing sample still falls back to 10 and is labelled `vehicle-inquiry`. | `src/lookups/fanavaran-last-car-policy.ts:391–392`, `450–470`; require sourced plate IDs with compatible kind/sample. |
| `PlaqueMiddleCodeId` — third-party damage | Static **1–24** letter map | Used when the matched vehicle does not provide a middle code. These are explicit fixed mappings rather than a default letter, but are still tenant-unverified numeric codes. | `service:424–449`, `3266`; map through the tenant's plate-letter catalogue. |
| `PoliceOfficerId` — third-party base | **1** | Assigned directly; hull explicitly replaces it with null. | `service:1857`; `fanavaran-hull-base-claim.ts:164`; real officer selection or null if permitted. |
| `InspectionPlaceId` — third-party expertise | **282** | Default unless reviewed. Fetching the inspection-place list does not select or validate this fallback at the write boundary. | `service:6014–6020`; explicit inspection place. |
| `DropAmountStatus` — third-party expertise | **5458** | Always assigned directly, even though `drop-amount-status` is fetched. Not a current editable stage field. | `service:6015–6020`; derive from confirmed depreciation outcome or require selection. |
| `DmgSections[].AccidentLevel` — third-party expertise | **5456** | Any nonnumeric `typeOfDamage` falls back to 5456. **The ordinary expert UI sends `تعمیر` / `تعویض`, so normal UI replies take this fallback.** Those values express repair/replacement, not damage severity. | `service:5888–5899`; expert `damagePartTable.tsx:2292–2305`, `claimReplySubmit.tsx:183–192`; add a separate severity field rather than treating repair method as severity. |
| `FileTypeId`, including `Files[].FileTypeId` — attachments | **Parsian 63 / Tejaratno 23 / Moallem 17** | One configured type is assigned across collected document/photo categories. Hull checks that the ID is active, not that its meaning matches each document. | Config `:155`, `181`, `201` vicinity; `service:5126`, `5329`, `5495–5497`; per-document semantic mapping to current tenant catalogue. |
| `CityId` — GEN.44 person creation | **9131** | Fallback if a person's explicit city and caption lookup cannot resolve it; shared helper has no tenant argument. This remains despite the **HTTP Location** fix. | `fanavaran-other-people.ts:95`, `251–254`; actual person city, never a Parsian city ID for another tenant. |
| `PersonKindId` — GEN.44 | **46** | Natural-person caption lookup fallback; shared across all clients. | `fanavaran-other-people.ts:96`, `265–268`; resolve correct person kind for the tenant/person. |
| `IsIranian` — GEN.44 | **1 / 0** | Fallback when `ans` lookup is unavailable. The helper assumes Iranian unless explicitly false or a naturalized code is present. | `fanavaran-other-people.ts:214–215`, `259–261`; encode confirmed nationality using the proper contract. |
`ClaimFileTypeId` also has a startup migration: Moallem's stored **23 → 17**
(`fanavaran-client-config.service.ts:40–45`). Editing a stored value back to 23
does not survive that startup migration.
The static plate-letter map is:
`الف=1، ب=2، پ=3، ج=4، د=5، س=6، ص=7، ط=8، ع=9، ق=10، ل=11، م=12، ن=13، و=14، ه=15، ی=16، ک=17، ژ=18، ت=19، ث=20، ز=21، ش=22، ف=23، گ=24`.
## 2. Default values that are not lookup IDs but still assert case facts
| Field | Current assumption | Source / consequence |
|---|---|---|
| `AccidentLocationAddress` | **`استان تهران شهر تهران`** | `service:404`, `1910`, `5690`. Location coordinates are accepted by the builder but not used here. Expert review/manual text can replace it. **This address default is separate from the fixed HTTP `Location` header.** |
| `CulpritLicenceNo`, damage `LicenceNo` | Environment dummy, else **`9705463515`** | `service:412–413`, `1812`, `1818`, `3250`, `7570`. Real licence preferred, but missing/empty values and even empty manual overrides are replaced by a fabricated number. |
| `CulpritLicenceIssuDate`, damage `LicenceIssuDate` | **`1394/10/13`** | `fanavaran-party-roles.ts:11`, `237–242`; shared builder also initializes it at `service:1835`. Real stored date wins if available. |
| `EstimateAmount` | **1000 rials** | `service:407`, `1770`, `3238`. Base uses it when no positive calculated estimate exists; damage builder always initializes to it, with manual amount override available. |
| `FaultPercent` — damage | **100** | Profile default, `service:3239`; does not derive an actual percentage. |
| `CustomerFaultPercent` — hull | **100** | `service:2642`, `fanavaran-hull-base-claim.ts:59`, `154–157`; expert stage review can replace it. |
| `RepairDuration` — hull expertise | **3 days** | `service:2844–2846`, `fanavaran-hull-expertise.ts:80`, `121–122`; review can replace it. Optional `HullExpertiseRepairDuration` exists in the profile interface but this builder does not use it. |
| `DamagedCount` — third-party base | **1** | `service:1838`. Current two-party flow has one beneficiary, but this is a fixed scenario assumption. |
| `IsLicenseMatchWithVehicleKind` | **1** | `service:1842`; no actual licence/category compatibility calculation here. |
| `HasOtherCulprit`, `IsAccidentOutOfBorder`, `IsFatalAccident`, `IsPlaqueChanged`, `IsLicenseReplacement` — third-party base | **0** | `service:1843–1848`, `1865`; assertions of “no”, not inferred accident facts. |
| `IsLicenseReplaced` — hull | **Always 0** | `fanavaran-hull-base-claim.ts:126–129`; forced even if the incoming builder value differs. Current code intentionally implements the previous contract decision. |
| `IsOwnerChanged`, `CostSeparationToDmgSections` — hull | **0 when absent** | `fanavaran-hull-base-claim.ts:135–142`. Encoded through `ans`, validated for membership on hull writes. |
| `Count` — hull damage section | **1** | `fanavaran-hull-expertise.ts:156`; one item per selected part row. Must be explicit if quantities can differ. |
| `ComponentReplacementTaxAndToll` — third-party expertise | **0** | `service:6051`; not computed from an expert-entered tax value. |
| `PoliceReportDesc` | **`شرح گزارش`** | `service:1858`; arbitrary placeholder, manual text override possible. |
Calculated sums starting at zero, optional nulls, empty collections, retry counts,
timeouts and pagination limits are not themselves guessed business IDs. They
must be distinguished from asserting “zero tax”, “100% fault”, or “no fatality”.
## 3. Implicit guesses that still violate the intention
These no longer necessarily use a numeric fallback, but still choose a business
meaning without evidence from the case:
1. **Vehicle use:** `fanavaran-accident-vehicle-used.ts:37–80` preserves a valid
preferred use, otherwise chooses a caption containing `شخص`, otherwise the
first active row in the vehicle group. A live row is not proof of actual use.
Used by third-party base/damage; hull base now bypasses this substitution.
2. **Vehicle model:** `service:2029–2065` can select the first caption matching a
broad body type such as sedan/SUV. This is a fallback in the damage builder;
an approved exact vehicle kind has priority. A broad type is not a model.
3. **Hull accident/culprit/authority:** `service:2642–2653` selects
`تصادف(حادثه)`, `بیمه‌گذار`, and an authority caption containing `بیمه‌گذار`
unless review supplies alternatives. IDs come from current lookup responses,
but the scenario is still assumed.
4. **Hull damage kind/cost kind:** `service:2746–2752` chooses `تخریب` and
`مجموع لوازم` for the sections. The removed 5485/1 numeric fallbacks are gone,
but the same two meanings are still automatically applied to all parts.
5. **Hull accessory:** `fanavaran-hull-expertise-lookups.ts:77–102` first matches
the part's accessory kind; otherwise picks the policy's factory-parts bundle.
This is a policy-sourced fallback, not a fixed record ID, but bundle
applicability still requires a business rule.
6. **Hull culprit identity/value:** policy `CustomerId` can substitute for the
driver when person inquiry misses (`service:2625` vicinity), and insured
`VehicleValue` can substitute for market/current value. Neither is a fixed
number, but policyholder is not necessarily driver and insured value is not
necessarily current market value.
## 4. Cross-stage default leakage in the base payload
`fanavaranPayloadDefaultsWithoutExpertIds` (`service:3426–3437`) removes only
`ClaimExpertId` and `ExpertiseClaimExpertId`. The base builder spreads **all
remaining profile defaults** (`service:1892–1894`).
For **Parsian/Moallem third-party** payloads, unlike the hull and Tejarat V15
whitelists, this can leave these extra defaults on the outgoing base object:
- `DmgCaseTypeId=175`
- `DmgHistoryStatus=5214`
- `DriverIsOwner=0`
- `FaultPercent=100`
- `ClaimFileTypeId=63` (Parsian) / `17` (Moallem)
- Optional `HullExpertiseRepairDuration`, if present in stored defaults.
The numbers reflect seeds and may differ in Mongo. The defect is the unrestricted
spread, regardless of values. These fields belong to other stages; approval of
the base accident fields does not fix their leakage. Each product/stage needs an
explicit outbound key whitelist.
## 5. What the recent fixes actually solved
- **Claim HTTP `Location`: fixed for application claim writes.**
`service:3375–3423` requests `requireStaffLocation: true`; the location service
uses assigned staff `locations[].id` or that staff member's branch **code**,
and throws `FANAVARAN_STAFF_LOCATION_MISSING` when none exists. This is used
by claim base, damage, attachment, expertise, hull update, and claim-linked
GEN.44 writes. The branch Mongo `_id` is not sent as the OpBUId.
- **General lookup/read headers still have a tenant Location fallback.**
`fanavaran-auth.service.ts:281` uses `auth.location` when no explicit override
exists. Generic `FanavaranLookupService.postToFanavaran` also uses those
headers, although its `createOtherPerson` wrapper currently has no production
caller in `src`. This does not undo the strict claim-write resolver.
- **Hull base `UsedId`: fixed.** Exact policy vehicle/version is used; a missing
value blocks the write rather than falling back to 1.
- **Hull `VehicleHullAccessoryId=3043330`: removed.** It now comes from the
current policy's accessories, with exact-part/factory-bundle resolution.
- **Hull numeric accident/culprit/authority/damage/cost fallbacks:** the old
2/300/first-row-or-1/5485/1 substitutions have been removed. Caption-derived
defaults and other fields listed above remain.
- **`PoliceOfficerId=1`: removed for hull**, still present for third-party.
- **Assessor/case-owner expert IDs: fixed in application payloads.** Assigned
staff's product-specific codes are required; profile `ClaimExpertId` and
`ExpertiseClaimExpertId` seeds are stripped rather than used as write fallbacks.
Their numeric presence in config alone must not be reported as an active
application expert-ID fallback.
## 6. Standalone Fanavaran flow UI has separate defaults
The file currently open in the IDE, `scripts/fanavaran-flow-ui-server.js`, launches
`scripts/fanavaran-flow-test.sh` (`:962–970`). It does **not** call the Nest claim
builder. Fixing one implementation does not automatically fix the other.
| Tool / location | Defaults or fixed choices |
|---|---|
| Flow shell `:409–448` | City701, report155, third-party use1, compensation167, licence2, culprit337, cause6, damage type175, history5214, plate8/10, fault100, estimate1000, inspection282, drop5458, severity5456, Tehran address, dummy licence/date, hull repair3. Environment values override these; absent ones silently use the defaults. |
| Flow shell `:352–380` | Fixed tenant CorpId/ContractId and Location: Tejaratno **3539/263/100**, Parsian **543/28/210050**, Moallem **5650/304/30900**. Shell hull contract falls back to the configured third-party contract if a hull contract is not supplied. |
| Flow HTML `:1052–1092`, `:1316–1399` | Static expert/branch lists. Tejaratno auto-selects case-owner2721 and assessor2709 at location100; Moallem defaults to first case-owner5347 and assessor5350 at location30900; Parsian chooses branch210110 and the first listed maker32/reviewer3989 when no preference exists. Other static choices remain in these tables. |
| Flow HTML `:789–790`, `:1611–1619` | Static culprit337/338 mapping by role scenario. |
| Flow HTML `:851–853`, `:879–900` | Prefilled GEN.44 city9131/person-kind46/Iranian1, example amounts, repair3, fault100, example vehicle current value0. Also contains sample identity/plate/licence values; do not treat these as real inquiry evidence. |
| Flow server `:1168` | Party inquiry falls back to Location **100** if neither environment nor query supplies it. |
| Auth shell `scripts/fanavaran-auth.sh:26–55` | Independent hardcoded tenant auth scope/location defaults. |
| Car-parts GET shell | Prompts for business credentials/scope; defaults the connection URL. It does not build claim/damage/expertise payloads. |
The flow UI now requires live active hull lookup selections for relevant stages;
that does not remove the shell's underlying defaults, nor static staff/branch
choices. It can still write real records when its submission actions are run.
## 7. Fixed identifiers that need a different treatment
- `InsuranceLineId=5` (third-party) / **4** (car-body): explicit product routing
constants in `src/lookups/fanavaran-last-car-policy.ts:5–6`. These encode the
selected product; they are not a fallback to a random policy/person record.
- Role IDs161/166 (and the defined owner role163) identify accepted response
roles. `fanavaran-driver-inquiry.ts` selects actual returned person IDs rather
than sending 161/166 as `DriverId` or falling back to the first arbitrary row.
- Tejarat notifier lists in `src/fanavaran/tejarat-notifier.ts` contain the
tenant-supplied IDs5516/5517 and5519–5526. They are allowed choices, **not an
automatic notifier selection**; review is required. The shared DB lookup's
tenant provenance still needs attention.
- Tenant CorpId/ContractId, authentication identities and API URL roots are
deployment configuration. They must be configured for the deployment rather
than deleted as though they were guessed accident data. Auth material also
exists in seed/tool source; no secret values are reproduced in this report.
- Seed expert IDs still exist (Parsian154/29, Tejaratno2721/2709,
Moallem5347/5350; shared4543092/2709). As noted above, the application excludes
them from outbound expert-ID resolution; the standalone HTML does not.
- Runtime auth-location seeds are Parsian110011 / Tejaratno100 / Moallem1;
standalone auth/flow tools have different Parsian/Moallem defaults. Scope them
explicitly when using those tools.
## 8. Catalogue/cache provenance also needs to be fixed
Removing numeric `?? default` statements alone is insufficient:
1. `getLiveFanavaranCatalogItems` (`service:774–784`) falls back to the shared
static car-component list when lookup rows are empty. This helper is used for
selections, despite the snapshot comment saying it is legacy-only. Stored
`partId` is then passed into `DmgSectionId` / `AccessoryKindId`. Hull validates
membership against live rows; third-party has no equivalent complete guard.
2. Mongo `lookups` is keyed by `name` without tenant/product scope; vehicle-kinds
has globally unique `Id` without tenant scope. DB-first/cache fallback can
therefore produce a real code from the wrong insurer. Lookup startup sync
can also populate a tenant's disk cache from that shared DB.
3. `getRemoteLookup` accepts any non-null parsed cache value, including an API
error object; callers may turn it into an empty list and then use defaults.
4. Vehicle/stage review validation at save time is not comprehensive proof of
current-tenant outbound validity. Hull validates many codebook IDs immediately
before writing; third-party lacks an equivalent complete validation layer.
5. Offline/mock inquiry data is another explicit source of seeded values:
`src/offline-inquiry/`, SandHub and global system settings. Offline inquiries
default to enabled, and live SandHub requires an explicit true setting.
Production configuration must be verified separately; this audit did not read
production settings or treat fixture IDs as evidence of live inquiries.
## 9. Recommended implementation order
1. Whitelist every stage/product payload. Eliminate cross-stage default leakage.
2. Remove invented cause/licence/person/city/plate values and preserve actual
stored inquiry selections with tenant/product provenance. Missing required
values must produce an actionable Persian preview/submit error before any
remote write; optional unresolved values should be null/omitted per contract.
3. Add explicit expert fields for genuinely unavailable data: cause, licence
type, compensation reference, damage-case type, separate damage severity,
depreciation status, relevant flags, and document category as needed. Reuse
existing city/report/history/inspection controls, initially unselected.
4. Resolve tenant codes by selected meaning and current lookup response. Never
fall back to first/personal row, fixed record ID, or another insurer's code.
Keep a deliberate, documented distinction for product/role protocol constants.
5. Make lookup and vehicle-kind storage tenant-scoped. Reject invalid cache
shapes and refetch/review old unsourced IDs rather than migrating by number.
6. Apply the same strict rules to both standalone flow tools and application
writes. Replace static staff/branch defaults with explicit selections.
7. Update tests that currently assert defaults; add tests that missing, stale,
inactive, wrong-tenant and semantically unrelated IDs never trigger remote
POST/PUT. Test normal `تعمیر`/`تعویض` replies with independent severity data.
## Verification and limits
- Stashed tracked/untracked local changes, fast-forwarded API to `90bdc51`, and
restored the stash without conflicts. Other checked non-rewrite repositories
were already current; earlier stashes were preserved.
- The backend Jest run completed successfully: **94 suites, 823 tests** in the
restored worktree. Existing tests include intentional fallback expectations
(for example GEN.44 city9131/person-kind46); passing does not prove absence of
guessed values. External providers are mocked in these tests.
- An isolated local probe executed source-extracted builder methods without
initializing Nest/Mongo or calling HTTP. A supplied cause999 still produced
cause6; Parsian/Moallem shared base objects retained the cross-stage fields
listed above; both `تعمیر` and `تعویض` produced accident level5456. This probes
the builder before product filtering, not a complete production HTTP exchange.
- Source tracing covered the application's Fanavaran write builders and their
shared submission paths plus standalone tools. No Fanavaran write, real SMS,
production database change, or live tenant lookup was performed for this audit.
- Application behavior has not been changed. The table is a remediation worklist,
not a statement that the “no default codes” policy is already implemented.
+4
View File
@@ -1,5 +1,9 @@
# Fanavaran lookup coding audit
**Update (2026-11-11):** The latest hull/accessory/location changes supersede
several findings below. See [the current hardcoded-payload audit](./hardcoded-payload-audit.md)
for what remains, including exact outbound defaults and standalone tool behavior.
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
+57
View File
@@ -0,0 +1,57 @@
# User-selected claim branch (flows 1 and 6)
Before accepting the blame report/signature, the damaged party selects a city and an active branch of the insurer **paying** the claim. In third-party cases the payer is the guilty party's insurer, even if the damaged vehicle has another insurer. In car-body cases it is the first/only party's insurer. Both guilty-party positions and call-center cases are supported.
Expert/registrar/FileMaker-created flows retain their existing branch/ownership rules. The server determines applicability from the stored case flags, not a browser version parameter. Administrative insurer/super-admin oversight is unchanged.
## API
All routes below use existing user authentication and the user-role guard:
- `GET /v2/blame-request-management/:requestId/claim-branches`: authorize case access, resolve the beneficiary/payer, and return `{required, branchId, locked, branches}`. Only the beneficiary receives branch options. Each option contains `id`, `name`, `code`, `city`, `state`, `address`, and optional `phoneNumber`. Options are active branches from the payer only; the client cannot supply an insurer ID.
- `PUT /v2/blame-request-management/:requestId/claim-branch`: `{branchId}` saves a validated branch while waiting for signatures or after signing, before any claim exists. This supports historical cases that were already signed when the feature deployed. Other parties cannot select a branch. Existing claims freeze routing; this endpoint cannot move them to another branch.
- Existing `PUT /v2/blame-request-management/sign/:requestId` accepts an additional multipart `branchId`. When the damaged user accepts in a user-led flow, a valid branch is mandatory (either supplied now or previously saved). Branch validation occurs before creating the signature record. Confirmation and branch ID are saved in the same blame update. The guilty party signs normally without choosing a branch. Rejection does not require a branch.
Invalid IDs, inactive branches and branches from another insurer are rejected with Persian errors. The API checks the insurer relationship; UI filtering alone is insufficient. If there are no active branches, the user sees a support message and cannot confirm acceptance/create a new claim until the insurer provisions its branches.
`GET /v2/blame-request-management/:requestId` includes `claimBranch: {required, branchId}` for the current viewer.
## Claim creation and expert access
`createClaimFromBlameV2` revalidates the active branch and copies `blame.branchId` to `claim.branchId`. Missing/invalid selection prevents creation and automatic Fanavaran submission. Changing browser state or calling the creation endpoint directly cannot omit branch validation. This adds no Fanavaran lookup ID or payload field.
The existing expert claim list filter and detail/assignment/action authorization compare the claim branch with the expert's stored branch, in addition to insurer/tenant isolation. Thus a new routed claim appears in that branch's queue and is rejected for damage experts from another branch, including direct access by case ID. Missing expert branch assignments are already denied. Insurer administrators should assign claim experts to the appropriate branches before rollout.
Existing claims are not migrated or reassigned. Their current access/ownership rules remain in effect. Already-signed blame cases without a claim select their branch on the final screen before entering claim creation. Direct entry into `/claim` also checks selection and returns to that screen if necessary. Deactivation between signing and creation requires choosing another active branch.
## User interface
The city and branch selectors appear above the signature canvas, only for the damaged user. A city change clears the branch selection. Same-named cities in different provinces have separate choices. The selected branch's address and phone are displayed. Loading, fetch failure/retry, empty lists and locked routing have explicit Persian states. Confirmation is disabled until the selection is valid. The signature dialog scrolls vertically on small screens.
The final screen reuses the selector for cases already signed before rollout; the backend selection rule also protects direct claim entry. Later v6 claim-result signing no longer asks for another branch, avoiding a competing choice. Existing expert-created flows retain their existing result-signing UI.
## Deployment and verification
Deploy API and `ui-user` together. No environment variables or database migration are required: the existing `branchId` fields and branch indexes are reused. Configure active branches, city/state/address and expert branch membership in the management panels. `ui-expert` already implements the required branch checks; no UI change there is needed.
Backend tests cover beneficiary/payer resolution, car-body and both third-party guilty positions, active insurer-scoped options, rejected foreign/inactive IDs, signature enforcement/persistence, culprit restrictions, legacy pre-claim selection, immutable existing claims, claim inheritance and branch access. Existing v6 workflow and authorization tests remain in place. Frontend tests cover city grouping, actor/case partitioning, loading/error/empty states, signature navigation and claim-entry compatibility.
Production QA should exercise each product in v1 and v6, both signature orders, a signed historical case, no active branches, deactivation before creation, and experts from two branches in the same insurer. Verify the selected branch sees the submitted claim and the other branch cannot list/open/assign it. Repeat expert-created flows 2–5 to confirm their creator ownership is preserved.
## Combined verification — 2026-11-11
| Check | Result |
| --- | --- |
| Complete API unit/regression suite | 90 suites, 774 tests passed |
| HTTP branch/signature/claim integration | 16 scenarios passed (`npm run test:e2e`) |
| User and expert frontend regression suites | Both passed |
| Browser scenarios | 14 passed on real v1/v6 pages: desktop/mobile positive paths, legacy entry and guilty-party signing |
| TypeScript | API, user UI and expert UI checked |
The integration test is `test/claim-branch-flows.e2e-spec.ts`. It uses the production controllers, JWT verification, role guards, Persian error filter, branch service, signature service and claim creation method. Repository operations are isolated in-memory implementations that return fresh documents and apply persisted updates; media policy and external SMS/Fanavaran delivery are mocked. Generated test signature files are removed afterward. The resulting claim is passed through the actual expert tenant/branch authorization and queue-filter methods.
The matrix covers v1 car-body, v6 car-body, both possible v1 third-party damaged parties, v6's second/damaged party, and both valid third-party signature orders. It asserts the insurer comes from the paying party, validates branch inheritance, prevents guilty-party claim creation, rejects foreign/inactive branches, requires both signatures, preserves existing expert-created LINK branches, handles signed legacy cases, rechecks deactivation, blocks missing authentication/wrong roles/non-participants, freezes existing claim routing, and prevents duplicate sequential creation.
Browser tests draw a signature, verify its multipart request includes the selected branch, continue to claim creation once, and verify the claim can proceed. Changing city clears the previous branch. Existing signed cases entering `/claim` without a branch return to the branch picker. Separate v1/v6 guilty-party checks confirm no branch selection is requested and no claim-creation button appears. Existing suites cover the flow 2–5 ownership and file-maker/reviewer handoff rules.
No new application defect was found in this verification pass; the additional HTTP integration tests/configuration were retained as regression coverage. External-provider availability, production branch/staff configuration, real database connectivity/indexes and live SMS delivery were not exercised. Those still require deployment QA; these results do not claim an exhaustive proof of every possible application state.
@@ -55,6 +55,7 @@ function serviceFor(blame: any): any {
findOne: jest.fn().mockResolvedValue(null),
create: jest.fn().mockResolvedValue({ _id: claimId }),
};
service.userClaimBranchService = { validate: jest.fn().mockResolvedValue("650000000000000000000099") };
service.userDbService = { findAllByPhone: jest.fn().mockResolvedValue([]) };
service.generateUniqueClaimNumber = jest.fn().mockResolvedValue("C100");
service.autoSubmitToFanavaranV2OnClaimCreated = jest
@@ -260,4 +261,18 @@ describe("claim beneficiary authorization across shared user flows", () => {
service.assertEffectiveUserIsDamagedPartyOnClaim(claim, effectiveId),
).resolves.toBeUndefined();
});
it("copies the validated branch into the claim and blocks creation when branch validation fails", async () => {
const blame = source();
blame.branchId = "650000000000000000000099";
const service = serviceFor(blame);
await service.createClaimFromBlameV2(blameId, secondId);
expect(service.userClaimBranchService.validate).toHaveBeenCalledWith(blame, blame.branchId);
expect(String(service.claimCaseDbService.create.mock.calls[0][0].branchId)).toBe(blame.branchId);
const blocked = serviceFor(source());
blocked.userClaimBranchService.validate.mockRejectedValue(new BadRequestException("شعبه را انتخاب کنید"));
await expect(blocked.createClaimFromBlameV2(blameId, secondId)).rejects.toBeInstanceOf(BadRequestException);
expect(blocked.claimCaseDbService.create).not.toHaveBeenCalled();
expect(blocked.autoSubmitToFanavaranV2OnClaimCreated).not.toHaveBeenCalled();
});
});
@@ -1,3 +1,4 @@
import { UserClaimBranchService, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import {
hasReviewedTejaratNotifier,
isTejaratNotifierLookup,
@@ -505,6 +506,7 @@ export class ClaimRequestManagementService {
private readonly claimFactorsImageDbService: ClaimFactorsImageDbService,
private readonly branchDbService: BranchDbService,
private readonly userClaimBranchService: UserClaimBranchService,
private readonly claimRequiredDocumentDbService: ClaimRequiredDocumentDbService,
private readonly sandHubService: SandHubService,
@@ -8147,6 +8149,10 @@ export class ClaimRequestManagementService {
);
}
const selectedBranchId = usesUserClaimBranch(blameRequest)
? await this.userClaimBranchService.validate(blameRequest, (blameRequest as any).branchId?.toString())
: (blameRequest as any).branchId?.toString();
// 7. Generate claim number
const claimNo = await this.generateUniqueClaimNumber();
@@ -8163,6 +8169,7 @@ export class ClaimRequestManagementService {
publicId: blameRequest.publicId,
blameRequestId: new Types.ObjectId(blameRequestId),
blameRequestNo: blameRequest.requestNo,
...(selectedBranchId ? { branchId: new Types.ObjectId(selectedBranchId) } : {}),
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING,
inquiries: (blameRequest as any).inquiries ?? {},
@@ -304,7 +304,7 @@ export class ClaimCase {
@Prop({ type: Types.ObjectId, index: true })
initiatedByFieldExpertId?: Types.ObjectId;
/** Branch snapshot inherited from the originating expert-created blame. */
/** Routing branch inherited from the blame (user selection or expert-created branch). */
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@@ -10,7 +10,7 @@ function setup(accessories: unknown) {
"vehicle-hull-dmg-cost-kinds": [
{ Id: 8002, Caption: "مجموع لوازم", IsActive: 1 },
],
"car-components": [{ Id: 9 }, { Id: 13 }],
"car-components": [{ Id: 9 }, { Id: 13 }, { Id: 112 }],
})[name] ?? [],
);
service.fanavaranLookupService = {
@@ -34,6 +34,7 @@ function setup(accessories: unknown) {
priceDropTotal: 0,
priceDropCarPrice: null,
warnings: [],
infoWarnings: [],
});
return { service, build };
}
@@ -76,16 +77,17 @@ describe("hull expertise policy accessory mapping", () => {
AccessoryDesc: "کليه قطعات فابريک",
},
]);
const { payload, warnings } = await build();
const { payload, warnings, infoWarnings } = await build();
expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([3061139, 3061139]);
expect(payload.DmgSections.map((row: any) => row.AccessoryKindId)).toEqual([
9, 13,
112, 112,
]);
expect(warnings).toEqual(
expect(warnings).toEqual([]);
expect(infoWarnings).toEqual(
expect.arrayContaining([
expect.stringContaining("using factory bundle VehicleHullAccessoryId=3061139"),
expect.stringContaining("mapped to factory bundle VehicleHullAccessoryId=3061139 AccessoryKindId=112"),
]),
);
});
@@ -85,7 +85,7 @@ describe("fanavaran hull base claim", () => {
expect(hull.PolicyId).toBe(13764408);
expect(hull.AccidentTypeId).toBeNull();
expect(hull.IsLicenseReplaced).toBeNull();
expect(hull.IsLicenseReplaced).toBe(0);
expect(hull.CostSeparationToDmgSections).toBe(0);
expect(hull.IsOwnerChanged).toBe(0);
expect(hull.CulpritTypeId).toBeNull();
@@ -125,7 +125,7 @@ export function toFanavaranHullBaseClaimPayload(
const next: Record<string, unknown> = {};
for (const key of FANAVARAN_HULL_BASE_CLAIM_KEYS) {
if (key === "IsLicenseReplaced") {
// Fanavaran conditional: >10y since issue → 1; else null (never 0).
// Preserve the server's conditional 0 / null / 1 mapping for licence age.
if (
Object.prototype.hasOwnProperty.call(built, key) &&
(built[key] === 1 || built[key] === 0 || built[key] === null)
@@ -74,7 +74,7 @@ describe("fanavaran-party-roles", () => {
expect(resolveFanavaranLicenceIssuDate(driver)).toBe(
FANAVARAN_DUMMY_LICENCE_ISSU_DATE,
);
expect(FANAVARAN_DUMMY_LICENCE_ISSU_DATE).toBe("1404/08/20");
expect(FANAVARAN_DUMMY_LICENCE_ISSU_DATE).toBe("1400/01/01");
});
it("marks licence replaced only when issue date is more than 10 years before accident", () => {
@@ -86,7 +86,19 @@ describe("fanavaran-party-roles", () => {
).toBeNull();
expect(
resolveFanavaranIsLicenseReplaced("1404/08/20", "1405/08/20"),
).toBeNull();
).toBe(0);
});
it.each([
["1402/08/21", 0],
["1402/08/20", 0],
["1402/08/19", null],
["1395/08/21", null],
["1395/08/20", null],
["1395/08/19", 1],
["1380/08/20", 1],
])("uses the exact anniversary for issue date %s", (issueDate, expected) => {
expect(resolveFanavaranIsLicenseReplaced(issueDate, "1405/08/20")).toBe(expected);
});
it("marks DriverIsOwner false when driver and owner differ", () => {
@@ -35,14 +35,11 @@ export function isJalaliDateOlderThanYears(
const issue = parseJalaliDateParts(issueDate);
const reference = parseJalaliDateParts(referenceDate);
if (!issue || !reference) return false;
let age = reference.year - issue.year;
if (
reference.month < issue.month ||
(reference.month === issue.month && reference.day < issue.day)
) {
age -= 1;
}
return age > years;
const anniversary =
(issue.year + years) * 10000 + issue.month * 100 + issue.day;
const referenceDay =
reference.year * 10000 + reference.month * 100 + reference.day;
return referenceDay > anniversary;
}
/**
+15 -2
View File
@@ -1,3 +1,4 @@
import { UserClaimBranchService } from "./user-claim-branch.service";
import { Module } from "@nestjs/common";
import { MongooseModule } from "@nestjs/mongoose";
import { SystemSettingsModule } from "src/system-settings/system-settings.module";
@@ -27,7 +28,19 @@ import { ClientDbSchema, ClientModel } from "./entities/schema/client.schema";
ClientPanelController,
ClientExternalInquiriesController,
],
providers: [ClientService, ClientDbService, BranchDbService, ExternalInquirySettingsService],
exports: [ClientService, ClientDbService, BranchDbService, ExternalInquirySettingsService],
providers: [
UserClaimBranchService,
ClientService,
ClientDbService,
BranchDbService,
ExternalInquirySettingsService,
],
exports: [
UserClaimBranchService,
ClientService,
ClientDbService,
BranchDbService,
ExternalInquirySettingsService,
],
})
export class ClientModule {}
@@ -0,0 +1,213 @@
import { Types } from "mongoose";
import {
UserClaimBranchService,
userClaimBranchContext,
usesUserClaimBranch,
} from "./user-claim-branch.service";
import { RequestManagementService } from "src/request-management/request-management.service";
const firstId = "650000000000000000000001",
secondId = "650000000000000000000002";
const payer = "650000000000000000000003",
otherInsurer = "650000000000000000000004";
const branchId = "650000000000000000000005";
function blame(type = "THIRD_PARTY", guiltyId = firstId): any {
return {
_id: new Types.ObjectId(),
type,
status: "WAITING_FOR_SIGNATURES",
branchId: undefined,
expert: { decision: { guiltyPartyId: guiltyId } },
parties: [
{
role: "FIRST",
person: {
userId: firstId,
clientId:
guiltyId === firstId || type === "CAR_BODY" ? payer : otherInsurer,
},
},
...(type === "CAR_BODY"
? []
: [
{
role: "SECOND",
person: {
userId: secondId,
clientId: guiltyId === secondId ? payer : otherInsurer,
},
},
]),
],
history: [],
workflow: {},
};
}
function setup(source = blame()) {
const branches: any = {
findAllWithFilters: jest
.fn()
.mockResolvedValue([
{
_id: branchId,
clientKey: payer,
isActive: true,
name: "شعبه مرکزی",
code: "100",
state: "تهران",
city: "تهران",
address: "نشانی",
secretInternal: "excluded",
},
]),
findById: jest
.fn()
.mockResolvedValue({ _id: branchId, clientKey: payer, isActive: true }),
};
const routing = new UserClaimBranchService(branches);
const api: any = Object.create(RequestManagementService.prototype);
api.sourceId = source._id;
api.userClaimBranchService = routing;
api.blameRequestDbService = {
findById: jest.fn().mockResolvedValue(source),
findByIdAndUpdate: jest.fn(async (_id, update) => {
for (const [path, value] of Object.entries(update.$set ?? {})) {
let obj = source;
const bits = path.split(".");
for (const bit of bits.slice(0, -1)) obj = obj[bit] ??= {};
obj[bits.at(-1)!] = value;
}
return source;
}),
};
api.userSign = { create: jest.fn().mockResolvedValue({ _id: "sign-id" }) };
api.claimCaseDbService = { findOne: jest.fn().mockResolvedValue(null) };
api.logger = { log: jest.fn() };
return { routing, branches, api, source };
}
const sign = { filename: "sign.png", path: "files/sign.png" };
describe("user-selected claim branch", () => {
it.each([false, true])(
"requires a branch only for the beneficiary in v1/v6 (%s)",
(callCenterInitiated) => {
const source = { ...blame(), callCenterInitiated };
expect(userClaimBranchContext(source, firstId).required).toBe(false);
expect(userClaimBranchContext(source, secondId).required).toBe(true);
expect(
userClaimBranchContext(blame("THIRD_PARTY", secondId), firstId)
.required,
).toBe(true);
expect(userClaimBranchContext(blame("CAR_BODY"), firstId).required).toBe(
true,
);
expect(userClaimBranchContext(source, "outsider").required).toBe(false);
},
);
it.each([
{ expertInitiated: true },
{ registrarInitiated: true },
{ isMadeByFileMaker: true },
{ creationMethod: "IN_PERSON" },
])("preserves expert-created flow %j", (flags) => {
expect(usesUserClaimBranch({ ...blame(), ...flags })).toBe(false);
});
it("lists only active branches of the paying insurer, with minimal public data", async () => {
const { routing, branches } = setup(blame("THIRD_PARTY", secondId));
const result = await routing.options(blame("THIRD_PARTY", secondId));
expect(branches.findAllWithFilters).toHaveBeenCalledWith(payer, {
isActive: true,
});
expect(result[0]).toMatchObject({
id: branchId,
city: "تهران",
address: "نشانی",
});
expect(result[0]).not.toHaveProperty("secretInternal");
});
it.each([undefined, "", "not-an-id", { id: branchId }])(
"rejects missing/malformed branch %j",
async (id) => {
const { routing } = setup();
await expect(routing.validate(blame(), id)).rejects.toThrow();
},
);
it.each([
null,
{ clientKey: payer, isActive: false },
{ clientKey: payer },
{ clientKey: otherInsurer, isActive: true },
])("rejects missing, inactive and foreign branches %j", async (branch) => {
const { routing, branches } = setup();
branches.findById.mockResolvedValue(branch);
await expect(routing.validate(blame(), branchId)).rejects.toThrow();
});
it.each([blame(), blame("CAR_BODY"), blame("THIRD_PARTY", secondId)])(
"validates branch against payer, not damaged vehicle insurer",
async (source) => {
const { routing } = setup(source);
await expect(routing.validate(source, branchId)).resolves.toBe(branchId);
},
);
it("blocks beneficiary signature before saving any signature if no branch is selected", async () => {
const { api } = setup();
await expect(
api.userSignDecisionV2(String(api.sourceId), secondId, true, sign),
).rejects.toThrow();
expect(api.userSign.create).not.toHaveBeenCalled();
expect(api.blameRequestDbService.findByIdAndUpdate).not.toHaveBeenCalled();
});
it("persists accepted beneficiary signature and validated branch together", async () => {
const { api, source } = setup();
await api.userSignDecisionV2(String(api.sourceId), secondId, true, sign, branchId);
expect(String(source.branchId)).toBe(branchId);
expect(source.parties[1].confirmation.accepted).toBe(true);
expect(api.blameRequestDbService.findByIdAndUpdate).toHaveBeenCalledWith(
String(source._id),
expect.objectContaining({
$set: expect.objectContaining({
branchId: new Types.ObjectId(branchId),
"parties.1.confirmation": expect.any(Object),
}),
}),
);
});
it("guilty party may sign without selecting a branch but cannot choose one", async () => {
const { api } = setup();
await expect(
api.userSignDecisionV2(String(api.sourceId), firstId, true, sign, branchId),
).rejects.toThrow();
await expect(
api.userSignDecisionV2(String(api.sourceId), firstId, true, sign),
).resolves.toMatchObject({ accepted: true });
});
it("rejecting does not require a branch", async () => {
const { api } = setup();
await expect(
api.userSignDecisionV2(String(api.sourceId), secondId, false, sign),
).resolves.toMatchObject({ status: "STOPPED" });
});
it("authorizes case reads before offering branch data", async () => {
const { api, branches } = setup();
api.getBlameRequestV2 = jest.fn().mockRejectedValue(new Error("forbidden"));
await expect(
api.getUserClaimBranches("case", { sub: secondId }),
).rejects.toThrow("forbidden");
expect(branches.findAllWithFilters).not.toHaveBeenCalled();
});
it("supports already signed cases, prevents culprit selection, and freezes branch after claim creation", async () => {
const { api, source } = setup();
api.getBlameRequestV2 = jest.fn().mockResolvedValue({});
source.status = "COMPLETED";
await expect(
api.selectUserClaimBranch("case", { sub: firstId }, branchId),
).rejects.toThrow();
await expect(
api.selectUserClaimBranch("case", { sub: secondId }, branchId),
).resolves.toEqual({ branchId });
api.claimCaseDbService.findOne.mockResolvedValue({ branchId });
await expect(
api.selectUserClaimBranch("case", { sub: secondId }, branchId),
).rejects.toThrow();
});
});
+84
View File
@@ -0,0 +1,84 @@
import { BadRequestException, Injectable } from "@nestjs/common";
import { Types } from "mongoose";
import { BranchDbService } from "./entities/db-service/branch.db.service";
import { resolveClaimBeneficiary } from "src/helpers/blame-claim-eligibility";
import { resolveClaimOwnerParty } from "src/helpers/blame-damaged-party";
/** User-led v1/v6 only. Expert/registrar-created flows retain their ownership. */
export function usesUserClaimBranch(blame: any): boolean {
return (
!!blame.callCenterInitiated ||
(!blame.expertInitiated &&
!blame.registrarInitiated &&
!blame.isMadeByFileMaker &&
blame.creationMethod !== "IN_PERSON")
);
}
export function userClaimBranchContext(blame: any, userId: string) {
const beneficiary = resolveClaimBeneficiary(blame);
return {
required:
usesUserClaimBranch(blame) &&
!!beneficiary?.person?.userId &&
String(beneficiary.person.userId) === String(userId),
branchId: blame.branchId ? String(blame.branchId) : null,
};
}
@Injectable()
export class UserClaimBranchService {
constructor(private readonly branches: BranchDbService) {}
private payerId(blame: any): string {
const id = String(resolveClaimOwnerParty(blame)?.person?.clientId ?? "");
if (!Types.ObjectId.isValid(id)) {
throw new BadRequestException(
"شرکت بیمه پرداخت‌کننده خسارت مشخص نیست. اطلاعات بیمه‌نامه را بررسی کنید.",
);
}
return id;
}
async options(blame: any) {
const clientId = this.payerId(blame);
const branches = await this.branches.findAllWithFilters(clientId, {
isActive: true,
});
return branches
.map((branch: any) => ({
id: String(branch._id),
name: branch.fullName || branch.name,
code: branch.code,
city: branch.city,
state: branch.state,
address: branch.address,
phoneNumber: branch.phoneNumber,
}))
.sort(
(a, b) =>
a.city.localeCompare(b.city, "fa") ||
a.name.localeCompare(b.name, "fa"),
);
}
async validate(blame: any, branchId: unknown): Promise<string> {
const id = typeof branchId === "string" ? branchId.trim() : "";
if (!Types.ObjectId.isValid(id)) {
throw new BadRequestException(
"شهر و شعبه رسیدگی به خسارت را انتخاب کنید.",
);
}
const branch = await this.branches.findById(id);
if (
!branch ||
branch.isActive !== true ||
String(branch.clientKey) !== this.payerId(blame)
) {
throw new BadRequestException(
"شعبه انتخاب‌شده فعال نیست یا متعلق به شرکت بیمه پرداخت‌کننده خسارت نیست. شعبه دیگری انتخاب کنید.",
);
}
return id;
}
}
+34 -2
View File
@@ -471,7 +471,9 @@ describe("ExpertClaimService FileReviewer assignment", () => {
const blameId = new Types.ObjectId();
const claimId = new Types.ObjectId();
service.expireClaimWorkflowLockV2IfStale = jest.fn().mockResolvedValue(undefined);
service.expireClaimWorkflowLockV2IfStale = jest
.fn()
.mockResolvedValue(undefined);
service.claimCaseDbService = {
findById: jest.fn().mockResolvedValue({
_id: claimId,
@@ -494,7 +496,9 @@ describe("ExpertClaimService FileReviewer assignment", () => {
}),
};
service.fanavaranLocationService = {
assertMakerReviewerBranchCompatible: jest.fn().mockResolvedValue(undefined),
assertMakerReviewerBranchCompatible: jest
.fn()
.mockResolvedValue(undefined),
};
service.assertExpertActorOnClaim = jest.fn();
@@ -536,4 +540,32 @@ describe("ExpertClaimService branch-scoped claim views", () => {
),
).resolves.toEqual([inBranch, legacyUnscoped]);
});
it("denies direct access and assignment scope for an expert in another branch", async () => {
const service = createService() as any;
const branchId = new Types.ObjectId();
const otherBranch = new Types.ObjectId();
service.damageExpertDbService = {
findById: jest.fn().mockResolvedValue({ branchId: otherBranch }),
};
await expect(
service.assertActorBranchAccess(
{ branchId },
{ sub: V2_EXPERT_ID, role: RoleEnum.DAMAGE_EXPERT },
),
).rejects.toThrow();
service.damageExpertDbService.findById.mockResolvedValue({ branchId });
await expect(
service.assertActorBranchAccess(
{ branchId },
{ sub: V2_EXPERT_ID, role: RoleEnum.DAMAGE_EXPERT },
),
).resolves.toBeUndefined();
service.damageExpertDbService.findById.mockResolvedValue({});
await expect(
service.assertActorBranchAccess(
{ branchId },
{ sub: V2_EXPERT_ID, role: RoleEnum.DAMAGE_EXPERT },
),
).rejects.toThrow();
});
});
@@ -79,6 +79,7 @@ function setup(type = Kind.CAR_BODY) {
for (const bit of bits.slice(0, -1)) obj = obj[bit] ??= {};
obj[bits[bits.length - 1]] = value;
};
api.userClaimBranchService = { validate: jest.fn().mockResolvedValue("650000000000000000000099") };
api.publicIdService = {
generateRequestPublicId: jest.fn().mockResolvedValue("V6-TEST"),
};
@@ -94,7 +94,7 @@ export class BlameRequest {
@Prop({ type: Types.ObjectId })
initiatedByFieldExpertId?: Types.ObjectId;
/** Branch snapshot of the expert/FileMaker who created this file. */
/** Routing branch: user selection in v1/v6, or originating expert/FileMaker in other flows. */
@Prop({ type: Types.ObjectId, index: true })
branchId?: Types.ObjectId;
@@ -18,19 +18,20 @@ import {
} from "./inquiry-participant-resolver";
describe("inquiry participant resolver", () => {
it("accepts a driver licence date within the ten-year window", () => {
expect(validateDriverLicenseDate("2016-09-26", "2026-09-26")).toBe(
"2016-09-26",
it.each(["2016-09-26", "2016-09-25", "1995-01-01", "1374/01/01", 13740101])(
"accepts a past driver licence date without a ten-year cutoff: %s",
(date) => {
expect(validateDriverLicenseDate(date, "2026-09-26")).toBe(String(date));
},
);
});
it("rejects future and older-than-ten-year driver licence dates", () => {
it("still rejects future and malformed driver licence dates", () => {
expect(() =>
validateDriverLicenseDate("2026-09-27", "2026-09-26"),
).toThrow("نمی‌تواند در آینده");
expect(() =>
validateDriverLicenseDate("2016-09-25", "2026-09-26"),
).toThrow("بیشتر از ۱۰ سال قبل");
validateDriverLicenseDate("invalid", "2026-09-26"),
).toThrow("نامعتبر است");
});
it("requires the date only for a licensed driver", () => {
@@ -267,20 +267,11 @@ export function validateDriverLicenseDate(
throw new BadRequestException("تاریخ صدور گواهینامه راننده نامعتبر است.");
}
const today = jalaliToGregorianDate(todayGregorian) ?? todayGregorian;
const todayDate = new Date(`${today}T00:00:00Z`);
const minimumDate = new Date(todayDate);
minimumDate.setUTCFullYear(minimumDate.getUTCFullYear() - 10);
const minimum = minimumDate.toISOString().slice(0, 10);
if (parsed > today) {
throw new BadRequestException(
"تاریخ صدور گواهینامه راننده نمی‌تواند در آینده باشد.",
);
}
if (parsed < minimum) {
throw new BadRequestException(
"تاریخ صدور گواهینامه راننده نباید بیشتر از ۱۰ سال قبل باشد.",
);
}
return raw;
}
@@ -1,3 +1,4 @@
import { UserClaimBranchService, userClaimBranchContext } from "src/client/user-claim-branch.service";
import {
BadRequestException,
ConflictException,
@@ -1144,6 +1145,7 @@ export class RequestManagementService {
private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService,
private readonly lookupsService: LookupsService,
private readonly userClaimBranchService: UserClaimBranchService,
) {}
async assertFileReviewerBranchAccess(
@@ -4861,6 +4863,7 @@ export class RequestManagementService {
carBodyInsuranceDetail: plain.carBodyInsuranceDetail,
claimCreation,
userSide: viewerParty?.role ?? null,
claimBranch: userClaimBranchContext(plain, String(user?.sub ?? "")),
nextAction: resolveBlameUserNextAction(
plain.status,
viewerParty,
@@ -6341,6 +6344,41 @@ export class RequestManagementService {
};
}
/** Same access boundary as the user case detail; never accept an insurer id from the browser. */
async getUserClaimBranches(requestId: string, user: any) {
await this.getBlameRequestV2(requestId, user);
const req = await this.blameRequestDbService.findById(requestId);
if (!req) throw new NotFoundException("پرونده پیدا نشد.");
const context = userClaimBranchContext(req, String(user.sub));
if (!context.required) return { ...context, branches: [], locked: true };
const claim = await this.claimCaseDbService.findOne({ blameRequestId: req._id });
return {
...context,
branchId: claim?.branchId ? String(claim.branchId) : context.branchId,
locked: !!claim,
branches: await this.userClaimBranchService.options(req),
};
}
/** Also supports already-signed legacy cases, before their first claim is created. */
async selectUserClaimBranch(requestId: string, user: any, branchId: unknown) {
await this.getBlameRequestV2(requestId, user);
const req = await this.blameRequestDbService.findById(requestId);
if (!req) throw new NotFoundException("پرونده پیدا نشد.");
if (!userClaimBranchContext(req, String(user.sub)).required) {
throw new ForbiddenException("فقط طرف زیان‌دیده می‌تواند شعبه رسیدگی به خسارت را انتخاب کند.");
}
if (![CaseStatus.WAITING_FOR_SIGNATURES, CaseStatus.COMPLETED].includes(req.status)) {
throw new BadRequestException("انتخاب شعبه در مرحله امضا یا پیش از ثبت درخواست خسارت امکان‌پذیر است.");
}
if (await this.claimCaseDbService.findOne({ blameRequestId: req._id })) {
throw new ConflictException("درخواست خسارت ایجاد شده است و شعبه آن قابل تغییر نیست.");
}
const id = await this.userClaimBranchService.validate(req, branchId);
await this.blameRequestDbService.findByIdAndUpdate(requestId, { $set: { branchId: new Types.ObjectId(id) } });
return { branchId: id };
}
/**
* V2: User signs and accepts/rejects (expert decision for THIRD_PARTY, or final acknowledgment for CAR_BODY).
*/
@@ -6349,6 +6387,7 @@ export class RequestManagementService {
userId: string,
isAccept: boolean,
signFile: Express.Multer.File,
branchId?: string,
): Promise<UserSignatureResponseDto> {
if (!signFile) {
throw new BadRequestException("A signature file is required");
@@ -6393,6 +6432,17 @@ export class RequestManagementService {
throw new BadRequestException("You have already signed this decision");
}
const branchContext = userClaimBranchContext(request, userId);
let selectedBranchId: string | undefined;
if (branchId && !branchContext.required) {
throw new ForbiddenException("انتخاب شعبه فقط برای طرف زیان‌دیده در پرونده‌های کاربرمحور مجاز است.");
}
if (isAccept && branchContext.required) {
selectedBranchId = await this.userClaimBranchService.validate(
request, branchId ?? branchContext.branchId,
);
}
// Create signature document
const signDoc = await this.userSign.create({
fileName: signFile.filename,
@@ -6449,6 +6499,7 @@ export class RequestManagementService {
await this.blameRequestDbService.findByIdAndUpdate(requestId, {
$set: {
[`parties.${partyIndex}.confirmation`]: confirmationPayload,
...(selectedBranchId ? { branchId: new Types.ObjectId(selectedBranchId) } : {}),
},
});
@@ -349,6 +349,19 @@ export class RequestManagementV2Controller {
/**
* V2: User signs/accepts or rejects expert decision
*/
@Get(":requestId/claim-branches")
@ApiOperation({ summary: "Active paying-insurer branches for the damaged user (v1/v6)" })
getUserClaimBranches(@Param("requestId") id: string, @CurrentUser() user: any) {
return this.requestManagementService.getUserClaimBranches(id, user);
}
@Put(":requestId/claim-branch")
@ApiOperation({ summary: "Choose claim branch before a user-led claim is created" })
@ApiBody({ schema: { type: "object", required: ["branchId"], properties: { branchId: { type: "string" } } } })
selectUserClaimBranch(@Param("requestId") id: string, @CurrentUser() user: any, @Body("branchId") branchId: string) {
return this.requestManagementService.selectUserClaimBranch(id, user, branchId);
}
@Put("sign/:requestId")
@ApiParam({ name: "requestId", description: "Blame request ID" })
@ApiConsumes("multipart/form-data")
@@ -363,6 +376,7 @@ export class RequestManagementV2Controller {
format: "binary",
description: "Signature image file",
},
branchId: { type: "string", description: "Required when the damaged user accepts in v1/v6; active branch of the paying insurer" },
isAccept: {
type: "boolean",
description: "true to accept expert decision, false to reject",
@@ -389,6 +403,7 @@ export class RequestManagementV2Controller {
async userSignDecision(
@Param("requestId") requestId: string,
@Body("isAccept") isAccept: string | boolean,
@Body("branchId") branchId: string,
@CurrentUser() user: any,
@UploadedFile() sign: Express.Multer.File,
) {
@@ -403,6 +418,7 @@ export class RequestManagementV2Controller {
user.sub,
acceptDecision,
sign,
branchId,
);
}
+482
View File
@@ -0,0 +1,482 @@
/** Real HTTP controllers, JWT/role guards and services; in-memory DB and no external delivery. */
import "reflect-metadata";
import { Test } from "@nestjs/testing";
import { JwtModule, JwtService } from "@nestjs/jwt";
import { HttpAdapterHost } from "@nestjs/core";
import { INestApplication } from "@nestjs/common";
import * as request from "supertest";
import { unlink } from "node:fs/promises";
import { Types } from "mongoose";
import { GlobalGuard } from "src/auth/guards/global.guard";
import { RolesGuard } from "src/auth/guards/role.guard";
import { PersianErrorFilter } from "src/common/errors/persian-error.filter";
import { MediaPolicyService } from "src/media-policy/media-policy.service";
import { UserClaimBranchService } from "src/client/user-claim-branch.service";
import { RequestManagementV2Controller } from "src/request-management/request-management.v2.controller";
import { RequestManagementService } from "src/request-management/request-management.service";
import { ClaimRequestManagementV2Controller } from "src/claim-request-management/claim-request-management.v2.controller";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import { ExpertClaimService } from "src/expert-claim/expert-claim.service";
const ids = {
first: "650000000000000000000001",
second: "650000000000000000000002",
payer: "650000000000000000000003",
otherInsurer: "650000000000000000000004",
branch: "650000000000000000000005",
otherBranch: "650000000000000000000006",
foreignBranch: "650000000000000000000007",
inactiveBranch: "650000000000000000000008",
outsider: "650000000000000000000009",
expert: "650000000000000000000010",
};
const clone = <T>(value: T): T => JSON.parse(JSON.stringify(value));
const png = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jTncAAAAASUVORK5CYII=",
"base64",
);
function setPath(target: any, path: string, value: any) {
const bits = path.split(".");
let current = target;
for (const bit of bits.slice(0, -1)) current = current[bit] ??= {};
current[bits[bits.length - 1]] = clone(value);
}
describe("v1/v6 branch routing through HTTP", () => {
let app: INestApplication, jwt: JwtService;
let blame: any, claims: any[], signatures: any[], branches: any[];
let userService: any, claimService: any, expertService: any;
const files: string[] = [];
const originalSecret = process.env.JWT_SECRET;
const logger = {
log: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
};
const loadBlame = async () => ({
...clone(blame),
save: async function () {
const { save, ...plain } = this;
blame = clone(plain);
},
});
const claimRepo = {
findOne: jest.fn(async (filter) =>
clone(
claims.find(
(c) => String(c.blameRequestId) === String(filter.blameRequestId),
) ?? null,
),
),
findById: jest.fn(async (id) =>
clone(claims.find((c) => c._id === String(id)) ?? null),
),
create: jest.fn(async (body) => {
const claim = clone({ _id: new Types.ObjectId(), ...body });
claims.push(claim);
return clone(claim);
}),
};
beforeAll(async () => {
process.env.JWT_SECRET = "branch-flow-integration-test-only";
const blameRepo = {
findById: jest.fn(loadBlame),
findByIdAndUpdate: jest.fn(async (_id, update) => {
for (const [key, value] of Object.entries(update.$set ?? {}))
setPath(blame, key, value);
for (const [key, value] of Object.entries(update.$push ?? {})) {
const old =
key.split(".").reduce((row, bit) => row?.[bit], blame) ?? [];
setPath(blame, key, [...old, value]);
}
return loadBlame();
}),
find: jest.fn(async () => [clone(blame)]),
};
const routing = new UserClaimBranchService({
findAllWithFilters: async (payerId, filter) =>
clone(
branches.filter(
(b) => b.clientKey === payerId && b.isActive === filter.isActive,
),
),
findById: async (id) => clone(branches.find((b) => b._id === id) ?? null),
} as any);
const users = { findAllByPhone: async () => [] };
userService = Object.create(RequestManagementService.prototype);
Object.assign(userService, {
blameRequestDbService: blameRepo,
claimCaseDbService: claimRepo,
userDbService: users,
userClaimBranchService: routing,
logger,
userSign: {
create: async (body) => {
const sign = { _id: String(new Types.ObjectId()), ...body };
signatures.push(sign);
return sign;
},
},
smsOrchestrationService: {
buildBlamePartyLink: (id, role, flow) =>
`https://test.invalid/${flow}/${role}?token=${id}`,
sendThirdPartyDamagedPartyClaimLinkNotice: async () => true,
},
});
claimService = Object.create(ClaimRequestManagementService.prototype);
Object.assign(claimService, {
blameRequestDbService: blameRepo,
claimCaseDbService: claimRepo,
userDbService: users,
userClaimBranchService: routing,
logger,
generateUniqueClaimNumber: async () => "TEST-CLAIM",
autoSubmitToFanavaranV2OnClaimCreated: jest.fn(async () => ({
attempted: false,
submitted: false,
})),
withFanavaranAutoSubmitMessage: (message) => message,
});
expertService = Object.create(ExpertClaimService.prototype);
Object.assign(expertService, {
blameRequestDbService: blameRepo,
damageExpertDbService: {
findById: async (id) => ({
branchId: id === ids.expert ? ids.branch : ids.otherBranch,
}),
},
});
const module = await Test.createTestingModule({
imports: [JwtModule.register({})],
controllers: [
RequestManagementV2Controller,
ClaimRequestManagementV2Controller,
],
providers: [
GlobalGuard,
RolesGuard,
{ provide: RequestManagementService, useValue: userService },
{ provide: ClaimRequestManagementService, useValue: claimService },
{
provide: MediaPolicyService,
useValue: {
assertForBlame: async (file) => {
if (file?.path) files.push(file.path);
},
},
},
],
}).compile();
app = module.createNestApplication({ logger: false });
app.useGlobalFilters(new PersianErrorFilter(app.get(HttpAdapterHost)));
await app.init();
jwt = app.get(JwtService);
});
afterAll(async () => {
await app?.close();
await Promise.all(files.map((file) => unlink(file).catch(() => {})));
if (originalSecret === undefined) delete process.env.JWT_SECRET;
else process.env.JWT_SECRET = originalSecret;
});
function fixture(flow: string, type: string, guilty: string) {
claims = [];
signatures = [];
branches = [
{
_id: ids.branch,
clientKey: ids.payer,
isActive: true,
name: "مرکزی",
city: "تهران",
state: "تهران",
code: "100",
address: "نشانی شعبه مرکزی",
},
{
_id: ids.otherBranch,
clientKey: ids.payer,
isActive: true,
name: "دوم",
city: "اصفهان",
state: "اصفهان",
code: "200",
address: "نشانی شعبه دوم",
},
{
_id: ids.foreignBranch,
clientKey: ids.otherInsurer,
isActive: true,
name: "شرکت دیگر",
city: "تهران",
state: "تهران",
},
{
_id: ids.inactiveBranch,
clientKey: ids.payer,
isActive: false,
name: "غیرفعال",
city: "تهران",
state: "تهران",
},
];
blame = {
_id: String(new Types.ObjectId()),
type,
publicId: "TEST-BLAME",
requestNo: "TEST-BLAME",
status: "WAITING_FOR_SIGNATURES",
blameStatus: "AGREED",
callCenterInitiated: flow === "v6",
workflow: {
currentStep: "WAITING_FOR_SIGNATURES",
completedSteps: ["FIRST_INITIAL_FORM"],
},
history: [],
...(type === "THIRD_PARTY"
? { expert: { decision: { guiltyPartyId: guilty } } }
: {}),
parties: [
{
role: "FIRST",
person: {
userId: ids.first,
phoneNumber: "09120000001",
clientId:
type === "CAR_BODY" || guilty === ids.first
? ids.payer
: ids.otherInsurer,
},
},
...(type === "CAR_BODY"
? []
: [
{
role: "SECOND",
person: {
userId: ids.second,
phoneNumber: "09120000002",
clientId:
guilty === ids.second ? ids.payer : ids.otherInsurer,
},
},
]),
],
};
claimRepo.create.mockClear();
claimService.autoSubmitToFanavaranV2OnClaimCreated.mockClear();
}
const auth = (id: string, role = "user") =>
"Bearer " +
jwt.sign(
{ sub: id, role },
{ secret: process.env.JWT_SECRET, expiresIn: "5m" },
);
const url = () => `/v2/blame-request-management/${blame._id}`;
const sign = (user: string, branch?: string, accept = true) => {
let req = request(app.getHttpServer())
.put(`/v2/blame-request-management/sign/${blame._id}`)
.set("Authorization", auth(user))
.field("isAccept", String(accept));
if (branch) req = req.field("branchId", branch);
return req.attach("sign", png, {
filename: "branch-http-test.png",
contentType: "image/png",
});
};
const create = (user: string) =>
request(app.getHttpServer())
.post(`/v2/claim-request-management/create-from-blame/${blame._id}`)
.set("Authorization", auth(user));
const scenarios = [
["v1", "CAR_BODY", ids.first, "damaged-first"],
["v6", "CAR_BODY", ids.first, "damaged-first"],
...["v1", "v6"].flatMap((flow) =>
(flow === "v1" ? [ids.first, ids.second] : [ids.first]).flatMap(
(guilty) =>
["damaged-first", "guilty-first"].map((order) => [
flow,
"THIRD_PARTY",
guilty,
order,
]),
),
),
];
it.each(scenarios)(
"%s %s (guilty=%s, %s): choose → sign → create → branch-scoped experts",
async (flow, type, guilty, order) => {
fixture(flow, type, guilty);
const damaged =
type === "CAR_BODY" || guilty === ids.second ? ids.first : ids.second;
const options = await request(app.getHttpServer())
.get(url() + "/claim-branches")
.set("Authorization", auth(damaged))
.expect(200);
expect(options.body.required).toBe(true);
expect(options.body.branches.map((b) => b.id)).toEqual(
expect.arrayContaining([ids.branch, ids.otherBranch]),
);
expect(options.body.branches).toHaveLength(2);
await sign(damaged).expect(400);
expect(signatures).toHaveLength(0);
await sign(damaged, ids.foreignBranch).expect(400);
expect(signatures).toHaveLength(0);
await sign(damaged, ids.inactiveBranch).expect(400);
expect(signatures).toHaveLength(0);
if (type === "THIRD_PARTY") {
const culpritOptions = await request(app.getHttpServer())
.get(url() + "/claim-branches")
.set("Authorization", auth(guilty))
.expect(200);
expect(culpritOptions.body.required).toBe(false);
expect(culpritOptions.body.branches).toHaveLength(0);
await request(app.getHttpServer())
.put(url() + "/claim-branch")
.set("Authorization", auth(guilty))
.send({ branchId: ids.branch })
.expect(403);
if (order === "guilty-first") await sign(guilty).expect(200);
}
await sign(damaged, ids.branch).expect(200);
if (type === "THIRD_PARTY" && order === "damaged-first") {
await create(damaged).expect(400);
expect(claims).toHaveLength(0);
await sign(guilty).expect(200);
}
expect(blame.status).toBe("COMPLETED");
expect(blame.branchId).toBe(ids.branch);
const view = await request(app.getHttpServer())
.get(url())
.set("Authorization", auth(damaged))
.expect(200);
expect(view.body.nextAction).toBe("CREATE_CLAIM");
if (type === "THIRD_PARTY") await create(guilty).expect(403);
const created = await create(damaged).expect(201);
expect(created.body.claimRequestId).toBe(claims[0]._id);
expect(claims[0]).toMatchObject({
branchId: ids.branch,
owner: { clientId: ids.payer, userId: damaged },
});
const claim = claims[0],
own = { sub: ids.expert, clientKey: ids.payer, role: "damage_expert" },
other = { ...own, sub: ids.outsider };
await expect(
expertService.assertExpertActorOnClaim(claim, own),
).resolves.toBeUndefined();
await expect(
expertService.assertExpertActorOnClaim(claim, other),
).rejects.toThrow();
await expect(
expertService.filterDamageExpertClaimsByBranch([claim], own),
).resolves.toHaveLength(1);
await expect(
expertService.filterDamageExpertClaimsByBranch([claim], other),
).resolves.toHaveLength(0);
await expect(
expertService.assertExpertActorOnClaim(claim, {
...own,
clientKey: ids.otherInsurer,
}),
).rejects.toThrow();
await request(app.getHttpServer())
.put(url() + "/claim-branch")
.set("Authorization", auth(damaged))
.send({ branchId: ids.otherBranch })
.expect(409);
expect(claims[0].branchId).toBe(ids.branch);
await create(damaged).expect(409);
expect(claims).toHaveLength(1);
},
);
it.each(
["v1", "v6"].flatMap((flow) =>
["CAR_BODY", "THIRD_PARTY"].map((type) => [flow, type]),
),
)(
"%s %s: already-signed case must choose an active branch before direct claim creation",
async (flow, type) => {
fixture(flow, type, ids.first);
blame.status = "COMPLETED";
const damaged = type === "CAR_BODY" ? ids.first : ids.second;
for (const party of blame.parties)
party.confirmation = {
accepted: true,
signature: { fileId: "historic-sign" },
};
await create(damaged).expect(400);
expect(claims).toHaveLength(0);
await request(app.getHttpServer())
.put(url() + "/claim-branch")
.set("Authorization", auth(damaged))
.send({ branchId: ids.branch })
.expect(200);
branches.find((b) => b._id === ids.branch).isActive = false;
await create(damaged).expect(400);
expect(claims).toHaveLength(0);
await request(app.getHttpServer())
.put(url() + "/claim-branch")
.set("Authorization", auth(damaged))
.send({ branchId: ids.otherBranch })
.expect(200);
await create(damaged).expect(201);
expect(claims[0].branchId).toBe(ids.otherBranch);
},
);
it("authentication, role and participant boundaries apply to branch endpoints", async () => {
fixture("v1", "CAR_BODY", ids.first);
await request(app.getHttpServer())
.get(url() + "/claim-branches")
.expect(401);
await request(app.getHttpServer())
.get(url() + "/claim-branches")
.set("Authorization", auth(ids.outsider))
.expect(403);
await request(app.getHttpServer())
.get(url() + "/claim-branches")
.set("Authorization", auth(ids.first, "field_expert"))
.expect(403);
expect(signatures).toHaveLength(0);
expect(claims).toHaveLength(0);
});
it("rejection needs no branch and does not permit claim creation", async () => {
fixture("v6", "CAR_BODY", ids.first);
await sign(ids.first, undefined, false).expect(200);
expect(blame.status).toBe("STOPPED");
await create(ids.first).expect(400);
expect(claims).toHaveLength(0);
});
it("an expert-created LINK case retains its originating branch without user selection", async () => {
fixture("v1", "CAR_BODY", ids.first);
blame.expertInitiated = true;
blame.initiatedByFieldExpertId = ids.expert;
blame.creationMethod = "LINK";
blame.branchId = ids.otherBranch;
const options = await request(app.getHttpServer())
.get(url() + "/claim-branches")
.set("Authorization", auth(ids.first))
.expect(200);
expect(options.body.required).toBe(false);
expect(options.body.branches).toHaveLength(0);
await sign(ids.first).expect(200);
await create(ids.first).expect(201);
expect(claims[0].branchId).toBe(ids.otherBranch);
});
it("no active branches means no signature acceptance or new claim", async () => {
fixture("v6", "CAR_BODY", ids.first);
for (const branch of branches) branch.isActive = false;
const options = await request(app.getHttpServer())
.get(url() + "/claim-branches")
.set("Authorization", auth(ids.first))
.expect(200);
expect(options.body.required).toBe(true);
expect(options.body.branches).toHaveLength(0);
await sign(ids.first, ids.branch).expect(400);
expect(signatures).toHaveLength(0);
await create(ids.first).expect(400);
expect(claims).toHaveLength(0);
});
});
+51
View File
@@ -1150,6 +1150,18 @@
"registrar"
]
},
{
"controller": "RequestManagementV2Controller",
"method": "GET",
"path": "/v2/blame-request-management/:requestId/claim-branches",
"guards": [
"GlobalGuard",
"RolesGuard"
],
"roles": [
"user"
]
},
{
"controller": "RequestManagementV2Controller",
"method": "GET",
@@ -1606,6 +1618,33 @@
],
"roles": []
},
{
"controller": "FanavaranHullReadController",
"method": "GET",
"path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/hull/expertise/dmg-sections",
"guards": [
"LocalActorAuthGuard"
],
"roles": []
},
{
"controller": "FanavaranHullReadController",
"method": "GET",
"path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/hull/files",
"guards": [
"LocalActorAuthGuard"
],
"roles": []
},
{
"controller": "FanavaranHullReadController",
"method": "GET",
"path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/hull/files/:fileId",
"guards": [
"LocalActorAuthGuard"
],
"roles": []
},
{
"controller": "FanavaranController",
"method": "GET",
@@ -4249,6 +4288,18 @@
],
"roles": []
},
{
"controller": "RequestManagementV2Controller",
"method": "PUT",
"path": "/v2/blame-request-management/:requestId/claim-branch",
"guards": [
"GlobalGuard",
"RolesGuard"
],
"roles": [
"user"
]
},
{
"controller": "RequestManagementV2Controller",
"method": "PUT",
+8
View File
@@ -0,0 +1,8 @@
{
"moduleFileExtensions": ["js", "json", "ts"],
"rootDir": "..",
"testEnvironment": "node",
"testRegex": ".e2e-spec.ts$",
"transform": { "^.+\\.(t|j)s$": "ts-jest" },
"moduleNameMapper": { "^src/(.*)$": "<rootDir>/src/$1" }
}