Files
yara724api/docs/user-claim-branch-routing.md
s.hajizadeh cda424a536 fix(claims): defer flow 1 fanavaran submission at creation
Skip creation-time submission for Flow 1 while preserving branch validation, later staged submission, and other flows.
2026-11-21 10:33:11 +03:30

14 KiB
Raw Permalink Blame History

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, claimRequestId?}. claimRequestId is included when a claim already exists for the beneficiary so reloading claim entry can resume it. Locked claims do not fetch branch options. 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.

Flow 1 skips automatic Fanavaran submission during local claim creation. Later staged submission hooks remain enabled and can create the base Fanavaran claim when needed. Flow 6 and expert/registrar/FileMaker-created flows retain their existing submission timing.

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 displays the saved branch by name. It only shows the selector for signed cases without a valid active selection (including historical cases); 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.

Reliability corrections — 2026-11-16

The original implementation hydrated the complete case (voice/video URLs, expert profile and claim hints) just to authorize branch loading, then loaded that case again. The branch endpoint now reuses the exact authorization, user binding and workflow recovery logic directly, with no media/profile hydration. Legacy branch city/state values are normalized before sorting.

The frontend branch query has a 15-second timeout and explicit retry. A disabled query no longer renders a loader; an unparseable local JWT no longer silently disables the query forever. Options are cached for 30 seconds by actor and case; every save/signature and claim creation still validates the selected branch on the server. Empty active-branch lists remain a real setup error, with an explicit Persian explanation. They cannot be bypassed by accepting an arbitrary branch.

Accepting a signature now returns the persisted status, the viewer's nextAction, their confirmation, claimBranch, and claimCreation. The frontend applies that acknowledgement to both the case and branch caches immediately. It does not wait for an additional case GET before navigating. That cache update is essential: without it the next screen still has the pre-signature branchId: null and asks for the same branch again. A normal signed case therefore has one city/branch selection, on the blame-signature screen. Later acceptance of the financial assessment remains a separate legal decision and does not ask v1/v6 users for another branch.

User-led signatures use conditional writes: the case must still be waiting and the viewer must not already have a confirmation. A repeated identical acceptance returns the stored confirmation and branch without replacing them. A conflicting decision cannot overwrite an existing signature. Signature upload filenames use UUIDs so two users uploading signature.png in the same millisecond cannot overwrite each other's image. Completing the case is conditional on the persisted required signatures and waiting status; it uses $addToSet for workflow history. The same completion logic recovers interrupted records where all required accepted signatures exist but status remains waiting, on detail/list/branch reads or a safe retry. Stopped files and expert-created flows are excluded from this recovery. A notification failure after saving cannot turn a persisted signature into a failed submission.

Case status polling continues while waiting for the other party, and the next action switches to claim creation only for the beneficiary. The culprit can sign without a branch and cannot create the claim. Case-detail requests are cancellable and bounded; intentional cancellation does not show a false error toast. Failed signing shows the actual Persian error and preserves the canvas while rechecking the saved state. Closing the signature dialog returns to a page with a signing link. Claim entry offers retry, and an existing claim returned by the branch preflight is resumed instead of creating a second claim.

Regression commands

# API unit/regression suite, plus authenticated HTTP scenarios (mock repositories/providers).
npm test -- --runInBand
npm run test:e2e -- --runInBand

# In ui-user:
npm run test:ui
npx tsc --noEmit

The HTTP suite also has an optional combined browser tier. Start the user UI with a temporary test-only API URL, then run the test with Playwright installed. The browser forwards only that mock API prefix to the actual test HTTP controllers; JWT/role guards, case/branch/signature services and claim creation run normally. Database operations and SMS/Fanavaran remain isolated fixtures.

# ui-user terminal (use a separate dev build if another dev server is running):
NEXT_PUBLIC_BASE_URL=http://127.0.0.1:3217/mock-api NEXT_PUBLIC_BASE_PATH='' npm run dev -- --hostname 127.0.0.1 --port 3217

# api terminal; PLAYWRIGHT_MODULE may point to a locally installed Playwright package.
CLAIM_BRANCH_UI_URL=http://127.0.0.1:3217 PLAYWRIGHT_MODULE=/path/to/playwright npm run test:e2e -- --runInBand
# Optional: CLAIM_BRANCH_BROWSER_EXECUTABLE=/path/to/chrome-or-brave

Deploy API and ui-user together. No environment/schema migration is needed. Existing active branches and expert branch assignments are still required. No production data, real provider availability or live SMS delivery is exercised by these isolated tests.

Verification of the corrections

  • API: 97 suites / 874 tests passed.
  • Authenticated HTTP + combined mobile browser tier: 30 scenarios passed, including four real UI → controller → persistence scenarios for v1/v6 × car-body/third-party. Database repositories and providers are mocked.
  • Additional isolated browser matrix: 13 normal/legacy/error scenarios and 6 recovery scenarios passed, covering desktop/mobile layouts, delayed GETs after signing, guilty-party access, historic signed cases, branch errors/timeouts, empty options, waiting for the other signature, failed signing, double-clicks and cancellation. These use Chromium/Brave with emulated desktop/mobile viewports and drawn canvas signatures.
  • Complete user UI regression script, API/user TypeScript checks and whitespace checks passed.
  • The default Next.js production build (npm run build) passed with normal build-worker permissions. The initial sandboxed compilation was stopped after stalling; no deployment configuration was changed.

The tests do not change production data or contact SMS/Fanavaran. The browser tier is intentionally opt-in so a developer without Playwright can still run all HTTP tests; use the command above to include it.