From a3f9aab8fb4275286439d173c06c88db34c2b744 Mon Sep 17 00:00:00 2001 From: SepehrYahyaee <7heycallmegray@gmail.com> Date: Mon, 5 Oct 2026 14:39:51 +0330 Subject: [PATCH] Enforce claim beneficiary access and retire unused legacy APIs --- docs/blame-claim-flow-architecture.html | 13 +- docs/claim-beneficiary-authorization.md | 15 + docs/legacy-api-cleanup.md | 216 + docs/panel-roles-reference.fa.html | 5 +- docs/panel-roles-reference.html | 5 +- .../claim-request-management/car-part.enum.ts | 21 - .../dropPrice.interface.ts | 7 - .../in-person-dcouments-enum.ts | 8 - src/Types&Enums/upload.enum.ts | 4 - .../actor/actor.auth.controller.ts | 58 +- src/auth/auth-services/actor.auth.service.ts | 44 +- src/auth/dto/user/forget-password.dto.ts | 0 .../claim-beneficiary-access.spec.ts | 263 + .../claim-optional-document.spec.ts | 10 - .../claim-request-management.controller.ts | 486 +- .../claim-request-management.module.ts | 10 +- .../claim-request-management.service.ts | 3868 +++------------ .../dto/claim-detail.ts | 16 - .../dto/claim-details-v2.dto.ts | 161 +- .../dto/claim-rs-dto.ts | 17 - .../dto/create-claim.dto.ts | 8 - .../dto/image-required.dto.ts | 8 - .../dto/my-request.dto.ts | 23 - .../dto/submit-reply.dto.ts | 19 - .../dto/user-comment.dto.ts | 12 - .../dto/user-reply.dto.ts | 4 - .../db-service/car-green-card.db.service.ts | 19 - .../db-service/claim-case.db.service.ts | 12 +- .../claim-request-management.db.service.ts | 72 - .../claim-required-document.db.service.ts | 27 +- .../db-service/damage-image.db.service.ts | 18 - .../db-service/factor-image.db.service.ts | 8 +- .../db-service/video-capture.db.service.ts | 8 +- .../entites/schema/action-user.schema.ts | 13 - .../entites/schema/claim-base.schema.ts | 29 - .../registrar-claim.v1.controller.ts | 137 - src/client/client.service.ts | 36 +- .../entities/db-service/branch.db.service.ts | 14 +- .../external-inquiry-settings.service.ts | 20 +- src/common/auth/constants/hash.constants.ts | 18 - src/common/auth/constants/index.ts | 8 - src/core/api-route-contract.spec.ts | 78 + .../dto/claim-list-perId-rs.dto.ts | 80 - src/expert-claim/dto/claim-list-rs.dto.ts | 22 - src/expert-claim/dto/reply.dto.ts | 91 - src/expert-claim/expert-claim.controller.ts | 172 +- src/expert-claim/expert-claim.service.spec.ts | 22 - src/expert-claim/expert-claim.service.ts | 1700 +------ src/expert-insurer/expert-insurer.service.ts | 377 +- src/fanavaran/fanavaran-audit.service.ts | 16 +- src/fanavaran/fanavaran-auth.service.spec.ts | 1 - src/fanavaran/fanavaran-auth.service.ts | 66 +- src/fanavaran/fanavaran-location.service.ts | 13 +- src/helpers/blame-claim-eligibility.ts | 61 + src/helpers/blame-user-progress.ts | 9 +- src/helpers/persian-pdf-document.ts | 166 - src/helpers/persian-pdf-text.ts | 40 - src/helpers/simple-pdf-writer.ts | 166 - .../entities/db-service/lookup.db.service.ts | 13 +- src/media-policy/media-policy.service.ts | 34 +- src/plates/interface/plate.interface.ts | 8 - src/plates/plates.service.ts | 26 +- src/profile/dto/actor/profile.dto.ts | 0 .../dto/claim-creation-hint.dto.ts | 19 - .../dto/expert-complete-car-body-form.dto.ts | 29 - .../dto/expert-complete-locations.dto.ts | 11 - .../expert-complete-third-party-form.dto.ts | 57 - .../dto/update-request-management.dto.ts | 0 src/request-management/dto/user-reply.dto.ts | 52 - .../db-service/blame-document.db.service.ts | 29 +- .../db-service/blame-request.db.service.ts | 6 - .../db-service/blame-video.db.service.ts | 4 - .../request-management.db.service.ts | 29 - .../entities/db-service/sign.db.service.ts | 6 +- .../expert-initiated.controller.ts | 270 +- ...file-maker-claim-approval-v5.controller.ts | 13 +- .../file-maker-claim-approval-v5.spec.ts | 22 +- .../registrar-initiated.controller.ts | 157 - .../request-management.controller.ts | 417 -- .../request-management.file-reviewer.spec.ts | 38 +- .../request-management.module.ts | 14 +- .../request-management.service.ts | 3821 +------------- .../request-management.user-progress.spec.ts | 40 +- .../entity/db-service/sand-hub.db.service.ts | 35 - src/sand-hub/sand-hub.module.ts | 5 +- src/sand-hub/sand-hub.service.spec.ts | 2 - src/sand-hub/sand-hub.service.ts | 52 +- src/super-admin/super-admin.controller.ts | 207 +- src/super-admin/super-admin.service.ts | 41 +- .../call-center-agent.db.service.ts | 8 - .../db-service/damage-expert.db.service.ts | 6 - .../expert-file-activity.db.service.ts | 25 - .../db-service/file-maker.db.service.ts | 15 +- .../db-service/file-reviewer.db.service.ts | 10 - .../db-service/registrar.db.service.ts | 5 - .../entities/db-service/user.db.service.ts | 4 - src/utils/pipes/parse-json.pipe.ts | 29 - .../dto/claim-workflow-step.examples.ts | 510 -- .../dto/create-claim-workflow-step.dto.ts | 254 - .../db-service/workflow-step.db.service.ts | 64 +- src/workflow-step-management/index.ts | 8 - .../workflow-step-management.controller.ts | 401 +- .../workflow-step-management.service.ts | 99 +- test/contracts/api-routes.json | 4372 +++++++++++++++++ 104 files changed, 6864 insertions(+), 13223 deletions(-) create mode 100644 docs/claim-beneficiary-authorization.md create mode 100644 docs/legacy-api-cleanup.md delete mode 100644 src/Types&Enums/claim-request-management/car-part.enum.ts delete mode 100644 src/Types&Enums/claim-request-management/dropPrice.interface.ts delete mode 100644 src/Types&Enums/claim-request-management/in-person-dcouments-enum.ts delete mode 100644 src/Types&Enums/upload.enum.ts delete mode 100644 src/auth/dto/user/forget-password.dto.ts create mode 100644 src/claim-request-management/claim-beneficiary-access.spec.ts delete mode 100644 src/claim-request-management/dto/claim-detail.ts delete mode 100644 src/claim-request-management/dto/claim-rs-dto.ts delete mode 100644 src/claim-request-management/dto/create-claim.dto.ts delete mode 100644 src/claim-request-management/dto/image-required.dto.ts delete mode 100644 src/claim-request-management/dto/my-request.dto.ts delete mode 100644 src/claim-request-management/dto/submit-reply.dto.ts delete mode 100644 src/claim-request-management/dto/user-comment.dto.ts delete mode 100644 src/claim-request-management/dto/user-reply.dto.ts delete mode 100644 src/claim-request-management/entites/db-service/car-green-card.db.service.ts delete mode 100644 src/claim-request-management/entites/db-service/damage-image.db.service.ts delete mode 100644 src/claim-request-management/entites/schema/action-user.schema.ts delete mode 100644 src/claim-request-management/entites/schema/claim-base.schema.ts delete mode 100644 src/claim-request-management/registrar-claim.v1.controller.ts delete mode 100644 src/common/auth/constants/hash.constants.ts delete mode 100644 src/common/auth/constants/index.ts create mode 100644 src/core/api-route-contract.spec.ts delete mode 100644 src/expert-claim/dto/claim-list-perId-rs.dto.ts delete mode 100644 src/expert-claim/dto/claim-list-rs.dto.ts delete mode 100644 src/expert-claim/dto/reply.dto.ts create mode 100644 src/helpers/blame-claim-eligibility.ts delete mode 100644 src/helpers/persian-pdf-document.ts delete mode 100644 src/helpers/persian-pdf-text.ts delete mode 100644 src/helpers/simple-pdf-writer.ts delete mode 100644 src/plates/interface/plate.interface.ts delete mode 100644 src/profile/dto/actor/profile.dto.ts delete mode 100644 src/request-management/dto/claim-creation-hint.dto.ts delete mode 100644 src/request-management/dto/expert-complete-car-body-form.dto.ts delete mode 100644 src/request-management/dto/expert-complete-locations.dto.ts delete mode 100644 src/request-management/dto/expert-complete-third-party-form.dto.ts delete mode 100644 src/request-management/dto/update-request-management.dto.ts delete mode 100644 src/request-management/dto/user-reply.dto.ts delete mode 100644 src/request-management/registrar-initiated.controller.ts delete mode 100644 src/request-management/request-management.controller.ts delete mode 100644 src/sand-hub/entity/db-service/sand-hub.db.service.ts delete mode 100644 src/utils/pipes/parse-json.pipe.ts delete mode 100644 src/workflow-step-management/dto/claim-workflow-step.examples.ts delete mode 100644 src/workflow-step-management/dto/create-claim-workflow-step.dto.ts delete mode 100644 src/workflow-step-management/index.ts create mode 100644 test/contracts/api-routes.json diff --git a/docs/blame-claim-flow-architecture.html b/docs/blame-claim-flow-architecture.html index d31a87d..59ce37f 100644 --- a/docs/blame-claim-flow-architecture.html +++ b/docs/blame-claim-flow-architecture.html @@ -290,7 +290,7 @@

Blame & Claim Flow Architecture

- All active flows — V1 (legacy) · V2 · V3 · V4 · V5 · V6 — with roles, + All active UI flows — V1 · V2 · V3 · V4 · V5 · V6 — with roles, route prefixes, and step sequences.

@@ -394,9 +394,9 @@ Claim / Review prefix - V1 (legacy) - blame-request-management/ - claim-request-management/ + V1 user screens + v2/blame-request-management/ + v2/claim-request-management/ V2 user @@ -478,8 +478,9 @@ First party fills blame info and invites the second party via SMS link. An expert blame review is optional. After blame completes the damaged party opens a claim which a damage expert prices. - V1 = legacy routes (deprecated, @ApiExcludeController) · - V2 = same logic, v2/ prefix, GlobalGuard + RolesGuard (USER). + Both current V1 and V2 user screens use the v2/ APIs with GlobalGuard + RolesGuard (USER). + Retired unversioned V1 mutations are removed; active V1 business rules and the blame-expert APIs remain. + See the route retirement audit for retained compatibility routes.

diff --git a/docs/claim-beneficiary-authorization.md b/docs/claim-beneficiary-authorization.md new file mode 100644 index 0000000..3c948de --- /dev/null +++ b/docs/claim-beneficiary-authorization.md @@ -0,0 +1,15 @@ +# Claim beneficiary authorization + +The shared user claim API supports the regular third-party and body-insurance flows. A third-party claim can be created only by the party opposite the recorded `expert.decision.guiltyPartyId`, after the blame case is `COMPLETED` and both parties have accepted and supplied signature files. Both identities must be present and distinct, and the guilty ID must match one of them. An unresolved decision does not grant either party claim creation. Body-insurance claims belong to the first party of the completed blame case. + +`helpers/blame-claim-eligibility.ts` supplies the same eligibility rule to claim creation and the viewer's blame-list/detail guidance. An existing claim remains viewable by both parties, but only the beneficiary receives `CONTINUE_CLAIM`. Claim details include `canAct`; read-only viewers receive no owner action guidance. The user UI sends those viewers to the evaluation screen and hides signing, objections, and invoice-upload controls. An unrelated actor cannot create or mutate the claim. + +New regular claims store the beneficiary in both `owner.userId` and `damagedPartyUserId`, as the in-person flows already do. `owner.clientId` and `owner.userClientKey` still identify the paying insurer (the guilty party's insurer for third-party claims). No existing database rows are rewritten. + +For historical regular claims whose owner is the guilty party, mutation authorization resolves the beneficiary from the linked blame decision rather than granting owner access. Phone-linked user identities remain supported. When the source is unavailable, an explicit `damagedPartyUserId` is authoritative. Snapshot membership alone cannot establish liability because historical and in-person claims have different owner conventions; an ambiguous linked claim is rejected. Standalone legacy claims with neither a linked blame nor snapshot parties retain owner access. + +The specialized expert/registrar creation and capture workflows retain their existing role and initiator checks, including the reorganized flows that create a claim before blame completion. The user creation rule is not imposed on those specialized endpoints. + +The user UI stores one active identity. Successful OTP or expert login clears the previous party's token, active case IDs, per-case claim caches, Redux case state, and query data. A legacy browser containing both token keys must log in again. Creation requests are deduplicated per identity and blame case, and a rejected request cannot enable the claim-entry button or borrow an unrelated claim ID. Responses arriving after an account switch cannot overwrite the new account's active claim. + +Regression coverage: `claim-beneficiary-access.spec.ts`, `request-management.user-progress.spec.ts`, and `ui-user/scripts/test-claim-session.cjs`. Run `npm test -- --runInBand` in `api` and `npm run test:ui` in each UI repository. diff --git a/docs/legacy-api-cleanup.md b/docs/legacy-api-cleanup.md new file mode 100644 index 0000000..b3e9ae1 --- /dev/null +++ b/docs/legacy-api-cleanup.md @@ -0,0 +1,216 @@ +# API legacy retirement and signature status + +Reviewed the API controller surface, both frontend source trees (including expert-panel server proxies), runtime service references, API scripts, and workflow/role documentation. This cleanup starts from the working tree containing the claim-beneficiary authorization fixes; it preserves those fixes. + +## Signature follow-up + +Ordinary users now get the same fresh case status on both the final page and the older waiting-for-signature URL. While waiting, the case is refreshed every 10 seconds and on window focus. The page explicitly says that their signature is recorded and the other party is still required. After the other signature arrives, server-provided nextAction and claimCreation determine the new message and allowed action. Only the beneficiary sees claim creation. Existing expert declaration behavior is retained. + +The silent refresh button was removed. A background refresh failure retains the last successful case, explains that it is the last known status, and offers a retry with a loading state. Initial failures still show the full retry screen. Long declarations can scroll on small screens. + +## Removed code + +- 77 retired routes: obsolete unversioned blame/claim mutations and reads, obsolete expert-claim review/price-drop workflows, hidden registrar V1 aliases, legacy genuine/legal registrations, and deprecated workflow-step helper routes. +- 215 unreachable service methods, including their private helper chains and unused database wrappers. Reachability includes controllers, other services, lifecycle hooks, decorated methods, scripts, callbacks, and conservative handling of dynamic property references. +- 35 orphaned TypeScript files: old DTOs, response types, unused PDF helpers, examples, barrels, and an obsolete JSON pipe. +- Three empty database providers, their unused injections, unused private configuration/price-drop fields, and three retired controllers. Persistent collection registrations and schemas still used by active or blame-expert paths remain. +- The unused frontend claim-picker component, its sort helper, and its unversioned claimable-list client method; the unused legacy Fanavaran client method was also removed. + +No database migration, document rewrite, or collection deletion is performed. + +## Deliberately retained + +- Every V1–V6 screen flow. The current V1 user screens call V2 APIs; UI flow versions and API prefixes are different concepts. V1-specific limits and historical workflow repair remain. +- Both unversioned and V2 blame-expert controllers, the entire blame-expert service, and its reachable legacy helpers, media and historical models. +- The unversioned GET /claim-request-management/car-other-part catalog, GET /expert-claim/imageRequired/:id, GET /expert-claim/stream/:id/voice, and POST /expert-initiated-blame/add-accident-fields/:requestId, because frontend clients/server proxies still reference them. Their guards, roles and responses are unchanged. +- Versioned expert-initiated and registrar APIs, all V3/V4/V5/V6 creation/review/approval/link workflows, role onboarding, inquiries, lookup caching, AI, current Fanavaran stages, uploads, reports, and background retry/maintenance jobs. +- Deprecated report routes that still have frontend callers, and Fanavaran preview query parameters retained for compatibility. A deprecation label by itself was not treated as proof of disuse. +- Historical data/status fallbacks reachable from current endpoints. “Legacy data” is not the same as an unused endpoint. + +The remaining large services implement active workflows and Fanavaran mappings; they were not split or rewritten during this cleanup. + +## Verification + +A structural comparison against the pre-cleanup working tree found identical executable method structure for all 1,336 retained controller/service methods. Formatting, imports and unused constructor dependencies changed; retained method logic did not. + +The public route/access contract in test/contracts/api-routes.json was captured from the pre-cleanup controllers after excluding the explicitly retired routes. src/core/api-route-contract.spec.ts checks all 381 remaining routes against live Nest metadata, including controller and method guards and role restrictions. Update this contract deliberately when changing the public API. + +Regression coverage includes active claim eligibility, cross-tenant/reviewer authorization, V4/V5 transitions, optional documents, captures/AI, licensing inquiries, Fanavaran stage fields, and pricing. Tests solely exercising removed legacy endpoints were retired; equivalent active V2 safeguards remain tested. Constructor mocks use named dependencies where removals changed argument positions. + +The UI status tests cover polling, completion, beneficiary-only actions, initial/background errors and retries. Local browser checks use mocked case responses on the real pages at 320px, 390px and 1366px; they exercise automatic completion and refresh error recovery. + +Final checks: 77 API suites / 486 tests passed; API production build passed; both frontend regression suites passed; user UI production build passed. The UI detector reported no findings. Blame-expert source files were not modified. + +## Controller audit + +Every controller was included. Counts are HTTP routes, including hidden routes. + +| Controller | Before | Retained | Retired | +| --- | ---: | ---: | ---: | +| `auth/auth-controllers/actor/actor.auth.controller.ts` | 14 | 12 | 2 | +| `auth/auth-controllers/user/user.auth.controller.ts` | 2 | 2 | 0 | +| `case-expert-report/case-expert-report.controller.ts` | 1 | 1 | 0 | +| `claim-request-management/claim-request-management.controller.ts` | 19 | 1 | 18 | +| `claim-request-management/claim-request-management.v2.controller.ts` | 17 | 17 | 0 | +| `claim-request-management/expert-initiated-claim.mirror.controller.ts` | 11 | 11 | 0 | +| `claim-request-management/registrar-claim.mirror.controller.ts` | 10 | 10 | 0 | +| `claim-request-management/registrar-claim.v1.controller.ts` | 7 | 0 | 7 | +| `client/client-external-inquiries.controller.ts` | 5 | 5 | 0 | +| `client/client-panel.controller.ts` | 2 | 2 | 0 | +| `client/client.controller.ts` | 4 | 4 | 0 | +| `expert-blame/expert-blame.controller.ts` | 10 | 10 | 0 | +| `expert-blame/expert-blame.v2.controller.ts` | 9 | 9 | 0 | +| `expert-claim/expert-claim.controller.ts` | 13 | 2 | 11 | +| `expert-claim/expert-claim.v2.controller.ts` | 23 | 23 | 0 | +| `expert-insurer/expert-insurer.controller.ts` | 23 | 23 | 0 | +| `fanavaran/fanavaran.controller.ts` | 9 | 9 | 0 | +| `lookups/lookups.controller.ts` | 48 | 48 | 0 | +| `profile/profile.controller.ts` | 4 | 4 | 0 | +| `reports/reports.controller.ts` | 5 | 5 | 0 | +| `request-management/call-center-blame-v6.controller.ts` | 6 | 6 | 0 | +| `request-management/expert-initiated-blame-v3.mirror.controller.ts` | 19 | 19 | 0 | +| `request-management/expert-initiated-blame.mirror.controller.ts` | 14 | 14 | 0 | +| `request-management/expert-initiated.controller.ts` | 8 | 1 | 7 | +| `request-management/expert-initiated.v2.controller.ts` | 14 | 14 | 0 | +| `request-management/file-maker-blame-v4.controller.ts` | 15 | 15 | 0 | +| `request-management/file-maker-blame-v5.controller.ts` | 15 | 15 | 0 | +| `request-management/file-maker-claim-approval-v5.controller.ts` | 2 | 2 | 0 | +| `request-management/file-reviewer-blame-v4.controller.ts` | 12 | 12 | 0 | +| `request-management/file-reviewer-blame-v5.controller.ts` | 12 | 12 | 0 | +| `request-management/inquiry-refresh.controller.ts` | 1 | 1 | 0 | +| `request-management/registrar-blame.mirror.controller.ts` | 13 | 13 | 0 | +| `request-management/registrar-initiated.controller.ts` | 10 | 0 | 10 | +| `request-management/request-management.controller.ts` | 14 | 0 | 14 | +| `request-management/request-management.v2.controller.ts` | 15 | 15 | 0 | +| `super-admin/super-admin.controller.ts` | 33 | 31 | 2 | +| `system-settings/system-settings.controller.ts` | 5 | 5 | 0 | +| `workflow-step-management/workflow-step-management.controller.ts` | 14 | 8 | 6 | + +## Removed service methods + +Line counts below exclude surrounding comments/imports and deleted orphan files. + +| Service | Methods | Implementation lines | +| --- | ---: | ---: | +| `users/entities/db-service/damage-expert.db.service.ts` | 1 | 5 | +| `users/entities/db-service/registrar.db.service.ts` | 1 | 3 | +| `users/entities/db-service/file-maker.db.service.ts` | 2 | 8 | +| `users/entities/db-service/file-reviewer.db.service.ts` | 2 | 8 | +| `users/entities/db-service/call-center-agent.db.service.ts` | 1 | 7 | +| `auth/auth-services/actor.auth.service.ts` | 3 | 12 | +| `users/entities/db-service/user.db.service.ts` | 1 | 3 | +| `users/entities/db-service/expert-file-activity.db.service.ts` | 1 | 24 | +| `fanavaran/fanavaran-audit.service.ts` | 1 | 7 | +| `fanavaran/fanavaran-auth.service.ts` | 1 | 3 | +| `fanavaran/fanavaran-location.service.ts` | 1 | 3 | +| `client/external-inquiry-settings.service.ts` | 1 | 11 | +| `client/client.service.ts` | 2 | 6 | +| `client/entities/db-service/branch.db.service.ts` | 1 | 6 | +| `lookups/entities/db-service/lookup.db.service.ts` | 2 | 6 | +| `sand-hub/entity/db-service/sand-hub.db.service.ts` | 4 | 21 | +| `sand-hub/sand-hub.service.ts` | 2 | 23 | +| `plates/plates.service.ts` | 1 | 21 | +| `request-management/entities/db-service/blame-video.db.service.ts` | 1 | 3 | +| `request-management/entities/db-service/request-management.db.service.ts` | 5 | 24 | +| `request-management/entities/db-service/blame-request.db.service.ts` | 1 | 5 | +| `workflow-step-management/entities/db-service/workflow-step.db.service.ts` | 2 | 15 | +| `workflow-step-management/workflow-step-management.service.ts` | 5 | 68 | +| `media-policy/media-policy.service.ts` | 1 | 11 | +| `request-management/entities/db-service/blame-document.db.service.ts` | 3 | 12 | +| `request-management/entities/db-service/sign.db.service.ts` | 1 | 3 | +| `claim-request-management/entites/db-service/claim-case.db.service.ts` | 1 | 3 | +| `claim-request-management/entites/db-service/claim-request-management.db.service.ts` | 11 | 63 | +| `request-management/request-management.service.ts` | 44 | 3222 | +| `claim-request-management/entites/db-service/car-green-card.db.service.ts` | 2 | 8 | +| `claim-request-management/entites/db-service/damage-image.db.service.ts` | 2 | 6 | +| `claim-request-management/entites/db-service/factor-image.db.service.ts` | 1 | 5 | +| `claim-request-management/entites/db-service/video-capture.db.service.ts` | 1 | 5 | +| `claim-request-management/entites/db-service/claim-required-document.db.service.ts` | 4 | 16 | +| `claim-request-management/claim-request-management.service.ts` | 66 | 2123 | +| `expert-claim/expert-claim.service.ts` | 31 | 1334 | +| `expert-insurer/expert-insurer.service.ts` | 3 | 86 | +| `super-admin/super-admin.service.ts` | 2 | 6 | + +## Retired route list + +These URLs now have no controller handler. Current frontend workflows use their versioned replacements or no longer expose the obsolete operation. + +| Method | Retired route | +| --- | --- | +| POST | `/actor/register/genuine` | +| POST | `/actor/register/legal` | +| POST | `/claim-request-management/:blameId` | +| PATCH | `/claim-request-management/car-part-damage/:claimRequestID` | +| PATCH | `/claim-request-management/car-other-part-damage/:claimRequestID` | +| GET | `/claim-request-management/required-documents-status/:claimRequestID` | +| GET | `/claim-request-management/car-part-image-required/:claimRequestID` | +| PATCH | `/claim-request-management/upload-required-document/:claimRequestID` | +| PATCH | `/claim-request-management/capture-car-part-damage/:claimRequestID/:partId` | +| PATCH | `/claim-request-management/car-capture/:claimRequestID` | +| GET | `/claim-request-management/requests` | +| GET | `/claim-request-management/request/:claimRequestId` | +| PUT | `/claim-request-management/request/reply/:claimRequestId` | +| PUT | `/claim-request-management/request/resend/:claimRequestId/objection` | +| PATCH | `/claim-request-management/request/resend/:claimRequestId` | +| PUT | `/claim-request-management/request/:claimRequestId/user-rating` | +| PATCH | `/claim-request-management/request/reply/:claimRequestId/:partId/upload-factor` | +| PATCH | `/claim-request-management/:id/visit` | +| GET | `/claim-request-management/fanavaran-submit/:claimRequestId` | +| POST | `/claim-request-management/fanavaran-submit/:claimRequestId` | +| POST | `/registrar-claim/create-from-blame/:blameRequestId` | +| GET | `/registrar-claim/request/:claimRequestId` | +| PATCH | `/registrar-claim/select-outer-parts/:claimRequestId` | +| PATCH | `/registrar-claim/select-other-parts/:claimRequestId` | +| GET | `/registrar-claim/capture-requirements/:claimRequestId` | +| POST | `/registrar-claim/upload-document/:claimRequestId` | +| POST | `/registrar-claim/capture-part/:claimRequestId` | +| GET | `/expert-claim` | +| GET | `/expert-claim/:id` | +| GET | `/expert-claim/required-documents/:id` | +| PUT | `/expert-claim/lock/:id` | +| PUT | `/expert-claim/reply/submit/:id` | +| PUT | `/expert-claim/resend/submit/:id` | +| GET | `/expert-claim/stream/:id/video` | +| GET | `/expert-claim/link/:id/video` | +| PATCH | `/expert-claim/validate-factors/:claimId` | +| PATCH | `/expert-claim/:id/visit` | +| GET | `/expert-claim/branches/:insuranceId` | +| GET | `/expert-initiated-blame/my-files` | +| POST | `/expert-initiated-blame/complete-blame-data/:requestId` | +| POST | `/expert-initiated-blame/complete-claim-data/:claimRequestId` | +| POST | `/expert-initiated-blame/complete-form-third-party/:requestId` | +| POST | `/expert-initiated-blame/complete-form-car-body/:requestId` | +| POST | `/expert-initiated-blame/upload-video/:requestId` | +| POST | `/expert-initiated-blame/upload-voice/:requestId` | +| POST | `/registrar-initiated-blame/create` | +| GET | `/registrar-initiated-blame/my-files` | +| GET | `/registrar-initiated-blame/blame/:requestId` | +| POST | `/registrar-initiated-blame/send-party-otps/:requestId` | +| POST | `/registrar-initiated-blame/verify-party-otps/:requestId` | +| POST | `/registrar-initiated-blame/complete-blame-data/:requestId` | +| POST | `/registrar-initiated-blame/upload-video/:requestId` | +| POST | `/registrar-initiated-blame/upload-voice/:requestId` | +| POST | `/registrar-initiated-blame/add-accident-fields/:requestId` | +| POST | `/registrar-initiated-blame/upload-party-signature/:requestId` | +| POST | `/blame-request-management/initial-form/:requestId` | +| POST | `/blame-request-management/upload-video/:requestId` | +| POST | `/blame-request-management/add-plate/:requestId` | +| POST | `/blame-request-management/carbody-form/:requestId` | +| POST | `/blame-request-management/carbody-secondform/:requestId` | +| POST | `/blame-request-management/add-detail-location/:requestId` | +| POST | `/blame-request-management/upload-voice/:requestId` | +| POST | `/blame-request-management/add-detail-description/:requestId` | +| POST | `/blame-request-management/add-second-party-details/:phoneNumber/:requestId/:frontendRoutes` | +| GET | `/blame-request-management/requests` | +| GET | `/blame-request-management/creatable-claims` | +| GET | `/blame-request-management/request/:requestId` | +| PUT | `/blame-request-management/request/reply/:requestId` | +| PUT | `/blame-request-management/request/resend/:requestId` | +| POST | `/super-admin/register/genuine` | +| POST | `/super-admin/register/legal` | +| POST | `/workflow-step-management/bulk-upsert` | +| POST | `/workflow-step-management/validate-access` | +| GET | `/workflow-step-management/category/:category` | +| GET | `/workflow-step-management/next-steps/:stepKey` | +| GET | `/workflow-step-management/fields/:stepKey` | +| GET | `/workflow-step-management/step/:stepKey` | diff --git a/docs/panel-roles-reference.fa.html b/docs/panel-roles-reference.fa.html index 831a321..c2185ad 100644 --- a/docs/panel-roles-reference.fa.html +++ b/docs/panel-roles-reference.fa.html @@ -536,8 +536,9 @@

-

ثبت تقصیر — registrar-initiated-blame/

-

توجه: @ApiExcludeController — مسیرها وجود دارند اما در مستندات Swagger نمایش داده نمی‌شوند.

+

مرجع تاریخی ثبت تقصیر — registrar-initiated-blame/

+

مسیرهای بدون نسخه زیر حذف شده‌اند. مسیر فعال ثبت تقصیر v2/registrar/blame-request-management/ است. گزارش حذف مسیرهای قدیمی

+

این جدول فقط مرجع تاریخی است؛ هندلرهای زیر دیگر ثبت نشده‌اند.

diff --git a/docs/panel-roles-reference.html b/docs/panel-roles-reference.html index 220f064..4b20f67 100644 --- a/docs/panel-roles-reference.html +++ b/docs/panel-roles-reference.html @@ -528,8 +528,9 @@

-

Blame filing — registrar-initiated-blame/

-

Note: @ApiExcludeController — routes exist but not surfaced in Swagger docs.

+

Historical blame filing — registrar-initiated-blame/

+

The unversioned routes below have been retired. Current filing uses v2/registrar/blame-request-management/. See the retirement audit.

+

Historical reference only — these handlers are no longer registered.

متدمسیرتوضیح
POSTregistrar-initiated-blame/createایجاد فایل تقصیر IN_PERSON.
diff --git a/src/Types&Enums/claim-request-management/car-part.enum.ts b/src/Types&Enums/claim-request-management/car-part.enum.ts deleted file mode 100644 index 61cbd50..0000000 --- a/src/Types&Enums/claim-request-management/car-part.enum.ts +++ /dev/null @@ -1,21 +0,0 @@ -export enum CarPartEnum { - LeftBackFender = "leftBackFender", - RightBackFender = "rightBackFender", - BackWheel = "backWheel", - LeftBackDoor = "leftBackDoor", - RightBackDoor = "rightBackDoor", - LeftFrontDoor = "leftFrontDoor", - RightFrontDoor = "rightFrontDoor", - LeftMirror = "leftMirror", - RightMirror = "rightMirror", - FrontWheel = "frontWheel", - LeftFrontFender = "leftFrontFender", - RightFrontFender = "RightFrontFender", - FrontBumper = "frontBumper", - FrontCarWindow = "frontCarWindow", - CarHood = "carHood", - BackBumper = "backBumper", - CarTrunk = "carTrunk", - BackCarWindow = "backCarWindow", - Roof = "roof", -} diff --git a/src/Types&Enums/claim-request-management/dropPrice.interface.ts b/src/Types&Enums/claim-request-management/dropPrice.interface.ts deleted file mode 100644 index 41c691c..0000000 --- a/src/Types&Enums/claim-request-management/dropPrice.interface.ts +++ /dev/null @@ -1,7 +0,0 @@ -export class PriceDropIF { - total: number; - carPrice: number; - carModel: number; - carValue: number[]; - sumOfSeverity: number; -} diff --git a/src/Types&Enums/claim-request-management/in-person-dcouments-enum.ts b/src/Types&Enums/claim-request-management/in-person-dcouments-enum.ts deleted file mode 100644 index 6cd2081..0000000 --- a/src/Types&Enums/claim-request-management/in-person-dcouments-enum.ts +++ /dev/null @@ -1,8 +0,0 @@ -export enum InPersonDocumentsEnum { - NationalCertificate = "nationalCertificate", - CarCertificate = "carCertificate", - DrivingLicense = "drivingLicense", - CarGreenCard = "carGreenCard", - Plate = "plate", - CarPlate = "carPlate", -} \ No newline at end of file diff --git a/src/Types&Enums/upload.enum.ts b/src/Types&Enums/upload.enum.ts deleted file mode 100644 index 8b9fbd4..0000000 --- a/src/Types&Enums/upload.enum.ts +++ /dev/null @@ -1,4 +0,0 @@ -export enum UploaderModeEnum { - Sign = "uploadService", - Certificate = "certService", -} diff --git a/src/auth/auth-controllers/actor/actor.auth.controller.ts b/src/auth/auth-controllers/actor/actor.auth.controller.ts index 3cbd777..0c1e73d 100644 --- a/src/auth/auth-controllers/actor/actor.auth.controller.ts +++ b/src/auth/auth-controllers/actor/actor.auth.controller.ts @@ -10,36 +10,32 @@ import { Res, UseGuards, } from "@nestjs/common"; -import type { Response } from "express"; import { - ApiBody, ApiAcceptedResponse, + ApiBearerAuth, + ApiBody, ApiOperation, ApiResponse, ApiTags, - ApiBearerAuth, } from "@nestjs/swagger"; +import type { Response } from "express"; import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; -import { CaptchaChallengeService } from "src/captcha/captcha-challenge.service"; -import { CaptchaResponseDto } from "src/auth/dto/captcha-response.dto"; -import { GetCaptchaImageQueryDto } from "src/auth/dto/get-captcha-image-query.dto"; +import { CreateFieldExpertDto } from "src/auth/dto/actor/create-field-expert.actor.dto"; +import { CreateRegistrarDto } from "src/auth/dto/actor/create-registrar.actor.dto"; import { ForgetPasswordSendCodeDto, ForgetPasswordVerifyCodeDto, } from "src/auth/dto/actor/forget-password.actor.dto"; import { LoginActorDto } from "src/auth/dto/actor/login.actor.dto"; import { ActorEditUserProfileDto } from "src/auth/dto/actor/profile.actor.dto"; -import { CreateFieldExpertDto } from "src/auth/dto/actor/create-field-expert.actor.dto"; -import { CreateRegistrarDto } from "src/auth/dto/actor/create-registrar.actor.dto"; -import { - GenuineRegisterDto, - InsurerRegisterDto, - LegalRegisterDto, -} from "src/auth/dto/actor/register.actor.dto"; +import { InsurerRegisterDto } from "src/auth/dto/actor/register.actor.dto"; +import { CaptchaResponseDto } from "src/auth/dto/captcha-response.dto"; +import { GetCaptchaImageQueryDto } from "src/auth/dto/get-captcha-image-query.dto"; import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; -import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard"; +import { CaptchaChallengeService } from "src/captcha/captcha-challenge.service"; import { Roles } from "src/decorators/roles.decorator"; import { CurrentUser } from "src/decorators/user.decorator"; +import { SuperAdminGuard } from "src/super-admin/guards/super-admin.guard"; @Controller("actor") @ApiTags("actor") @@ -91,40 +87,6 @@ export class ActorAuthController { res.send(svg); } - /** - * @deprecated Use the unified actor onboarding flow instead. This endpoint - * will be removed in a future release. - */ - @Post("register/genuine") - @UseGuards(SuperAdminGuard) - @ApiOperation({ - deprecated: true, - summary: "[DEPRECATED] Genuine actor registration", - description: - "Deprecated — kept only for legacy clients. Use the unified actor onboarding flow instead. Will be removed.", - }) - @ApiBody({ type: GenuineRegisterDto }) - async registerGenuine(@Body() body: GenuineRegisterDto) { - return await this.actorAuthService.genuineRegister(body); - } - - /** - * @deprecated Use the unified actor onboarding flow instead. This endpoint - * will be removed in a future release. - */ - @Post("register/legal") - @UseGuards(SuperAdminGuard) - @ApiOperation({ - deprecated: true, - summary: "[DEPRECATED] Legal actor registration", - description: - "Deprecated — kept only for legacy clients. Use the unified actor onboarding flow instead. Will be removed.", - }) - @ApiBody({ type: LegalRegisterDto }) - async registerLegal(@Body() body: LegalRegisterDto) { - return await this.actorAuthService.legalRegister(body); - } - @Post("register/insurer") @UseGuards(SuperAdminGuard) @ApiBody({ type: InsurerRegisterDto }) diff --git a/src/auth/auth-services/actor.auth.service.ts b/src/auth/auth-services/actor.auth.service.ts index 597b801..ac6072d 100644 --- a/src/auth/auth-services/actor.auth.service.ts +++ b/src/auth/auth-services/actor.auth.service.ts @@ -1,6 +1,4 @@ -import { readFileSync } from "node:fs"; import { - BadGatewayException, BadRequestException, ForbiddenException, Injectable, @@ -10,6 +8,7 @@ import { } from "@nestjs/common"; import { JwtService } from "@nestjs/jwt"; import { Types } from "mongoose"; +import { readFileSync } from "node:fs"; import { ForgetPasswordVerifyCodeDtoRs } from "src/auth/dto/actor/forget-password.actor.dto"; import { ProfileActor } from "src/auth/dto/actor/profile.actor.dto"; import { @@ -20,19 +19,19 @@ import { import { StateListDtoRs } from "src/auth/dto/actor/states.dto"; import { CaptchaChallengeService } from "src/captcha/captcha-challenge.service"; import { ClientDbService } from "src/client/entities/db-service/client.db.service"; +import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service"; +import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { UserType } from "src/Types&Enums/userType.enum"; -import { InsurerExpertDbService } from "src/users/entities/db-service/insurer-expert.db.service"; +import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service"; import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; -import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service"; import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; -import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service"; +import { InsurerExpertDbService } from "src/users/entities/db-service/insurer-expert.db.service"; +import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service"; import { HashService } from "src/utils/hash/hash.service"; -import { OtpGeneratorService } from "src/sms-orchestration/otp-generator.service"; -import { SuperAdminDbService } from "src/super-admin/entities/db-service/super-admin.db.service"; function pick(obj: Record, keys: string[]) { const out: Record = {}; @@ -71,7 +70,11 @@ export class ActorAuthService { res = await this.expertDbService.findOne({ _id: new Types.ObjectId(userId), }); - else res = await this.findActorByLoginIdentifier(this.expertDbService, username); + else + res = await this.findActorByLoginIdentifier( + this.expertDbService, + username, + ); break; case RoleEnum.DAMAGE_EXPERT: if (username == null && userId) @@ -107,7 +110,8 @@ export class ActorAuthService { res = await this.fileMakerDbService.findOne({ _id: new Types.ObjectId(userId), }); - else res = await this.fileMakerDbService.findByLoginIdentifier(username); + else + res = await this.fileMakerDbService.findByLoginIdentifier(username); break; case RoleEnum.FILE_REVIEWER: if (username == null && userId) @@ -123,7 +127,8 @@ export class ActorAuthService { res = await this.superAdminDbService.findOne({ _id: new Types.ObjectId(userId), }); - else res = await this.superAdminDbService.findByLoginIdentifier(username); + else + res = await this.superAdminDbService.findByLoginIdentifier(username); break; case RoleEnum.CALL_CENTER: if (username == null && userId) @@ -131,7 +136,8 @@ export class ActorAuthService { _id: new Types.ObjectId(userId), }); else - res = await this.callCenterAgentDbService.findByLoginIdentifier(username); + res = + await this.callCenterAgentDbService.findByLoginIdentifier(username); break; default: return null; @@ -240,14 +246,6 @@ export class ActorAuthService { return this.issueActorTokens(actor); } - /** @deprecated Prefer {@link loginFromCredentials}. Kept for internal callers. */ - async loginActors(user: any) { - if (user?.access_token && user?.sub) { - return user; - } - return this.loginFromCredentials(user as Record); - } - async registerActors( body: RegisterDto | InsurerRegisterDto, userType: UserType, @@ -335,14 +333,6 @@ export class ActorAuthService { } } - async legalRegister(body: RegisterDto) { - return await this.registerActors(body, UserType.LEGAL); - } - - async genuineRegister(body: RegisterDto) { - return await this.registerActors(body, UserType.GENUINE); - } - async insurerRegister(body: InsurerRegisterDto) { Object.assign(body, { role: RoleEnum.COMPANY }); return await this.registerActors(body, UserType.INSURER); diff --git a/src/auth/dto/user/forget-password.dto.ts b/src/auth/dto/user/forget-password.dto.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/claim-request-management/claim-beneficiary-access.spec.ts b/src/claim-request-management/claim-beneficiary-access.spec.ts new file mode 100644 index 0000000..8ba4e13 --- /dev/null +++ b/src/claim-request-management/claim-beneficiary-access.spec.ts @@ -0,0 +1,263 @@ +import { + BadRequestException, + ConflictException, + ForbiddenException, +} from "@nestjs/common"; +import { Types } from "mongoose"; +import { ClaimRequestManagementService } from "./claim-request-management.service"; +import { + canUserCreateClaim, + resolveClaimBeneficiary, +} from "src/helpers/blame-claim-eligibility"; +import { RoleEnum } from "src/Types&Enums/role.enum"; + +const firstId = "650000000000000000000001"; +const secondId = "650000000000000000000002"; +const blameId = "650000000000000000000003"; +const claimId = "650000000000000000000004"; +const payerId = "650000000000000000000005"; +const outsiderId = "650000000000000000000006"; +const signed = { accepted: true, signature: { fileId: "signed" } }; + +function source(guiltyId = firstId): any { + return { + _id: new Types.ObjectId(blameId), + type: "THIRD_PARTY", + status: "COMPLETED", + publicId: "A100", + requestNo: "A100", + expert: { decision: { guiltyPartyId: guiltyId } }, + parties: [ + { + role: "FIRST", + person: { + userId: firstId, + clientId: payerId, + phoneNumber: "09120000001", + }, + confirmation: signed, + }, + { + role: "SECOND", + person: { userId: secondId, phoneNumber: "09120000002" }, + confirmation: signed, + }, + ], + }; +} + +function serviceFor(blame: any): any { + const service = Object.create(ClaimRequestManagementService.prototype); + service.blameRequestDbService = { + findById: jest.fn().mockResolvedValue(blame), + }; + service.claimCaseDbService = { + findOne: jest.fn().mockResolvedValue(null), + create: jest.fn().mockResolvedValue({ _id: claimId }), + }; + service.userDbService = { findAllByPhone: jest.fn().mockResolvedValue([]) }; + service.generateUniqueClaimNumber = jest.fn().mockResolvedValue("C100"); + service.autoSubmitToFanavaranV2OnClaimCreated = jest + .fn() + .mockResolvedValue({}); + service.withFanavaranAutoSubmitMessage = (message: string) => message; + service.logger = { log: jest.fn(), error: jest.fn() }; + return service; +} + +describe("claim beneficiary authorization across shared user flows", () => { + it.each([firstId, secondId])( + "allows only the other party when guilt belongs to %s", + async (guiltyId) => { + const beneficiaryId = guiltyId === firstId ? secondId : firstId; + const blame = source(guiltyId); + const service = serviceFor(blame); + for (const actorId of [guiltyId, outsiderId]) { + await expect( + service.createClaimFromBlameV2(blameId, actorId), + ).rejects.toBeInstanceOf(ForbiddenException); + } + expect(service.claimCaseDbService.create).not.toHaveBeenCalled(); + await expect( + service.createClaimFromBlameV2(blameId, beneficiaryId), + ).resolves.toMatchObject({ claimRequestId: claimId }); + const saved = service.claimCaseDbService.create.mock.calls[0][0]; + expect(String(saved.owner.userId)).toBe(beneficiaryId); + expect(String(saved.damagedPartyUserId)).toBe(beneficiaryId); + const payer = blame.parties.find((p: any) => p.person.userId === guiltyId) + .person.clientId; + expect(saved.owner.userClientKey).toBe(payer); + expect( + service.autoSubmitToFanavaranV2OnClaimCreated, + ).toHaveBeenCalledTimes(1); + }, + ); + + it("blocks incomplete, unsigned, rejected, and unresolved cases without creating or submitting a claim", async () => { + const invalid = [ + { ...source(), status: "WAITING_FOR_SIGNATURES" }, + { ...source(), expert: { decision: { guiltyPartyId: outsiderId } } }, + { ...source(), expert: {} }, + ]; + for (const confirmation of [ + { accepted: true }, + { accepted: false, signature: { fileId: "signed" } }, + ]) { + const blame = source(); + blame.parties[0].confirmation = confirmation; + invalid.push(blame); + } + const duplicated = source(); + duplicated.parties[1].person.userId = firstId; + invalid.push(duplicated); + for (const blame of invalid) { + const service = serviceFor(blame); + expect(canUserCreateClaim(blame, secondId)).toBe(false); + await expect( + service.createClaimFromBlameV2(blameId, secondId), + ).rejects.toBeInstanceOf(BadRequestException); + expect(service.claimCaseDbService.create).not.toHaveBeenCalled(); + expect( + service.autoSubmitToFanavaranV2OnClaimCreated, + ).not.toHaveBeenCalled(); + } + }); + + it("never grants eligibility to an empty identity or an unknown case type", () => { + expect(canUserCreateClaim({ status: "COMPLETED", parties: [] }, "")).toBe( + false, + ); + expect(canUserCreateClaim({ ...source(), type: "UNKNOWN" }, secondId)).toBe( + false, + ); + }); + + it("retains existing-claim conflict handling for its legitimate beneficiary", async () => { + const service = serviceFor(source()); + service.claimCaseDbService.findOne.mockResolvedValue({ _id: claimId }); + await expect( + service.createClaimFromBlameV2(blameId, secondId), + ).rejects.toBeInstanceOf(ConflictException); + expect(service.claimCaseDbService.create).not.toHaveBeenCalled(); + }); + + it("keeps body-insurance creation restricted to the first party and persists its beneficiary", async () => { + const blame = source(); + blame.type = "CAR_BODY"; + blame.parties = [blame.parties[0]]; + const service = serviceFor(blame); + expect(resolveClaimBeneficiary(blame)?.person?.userId).toBe(firstId); + await expect( + service.createClaimFromBlameV2(blameId, secondId), + ).rejects.toBeInstanceOf(ForbiddenException); + await service.createClaimFromBlameV2(blameId, firstId); + const saved = service.claimCaseDbService.create.mock.calls[0][0]; + expect(String(saved.damagedPartyUserId)).toBe(firstId); + expect(String(saved.owner.clientId)).toBe(payerId); + }); + + it("denies historical guilty owners while allowing the damaged party and its phone-linked identity", async () => { + const service = serviceFor(source()); + const claim = { + blameRequestId: blameId, + owner: { userId: firstId }, + damagedPartyUserId: secondId, + }; + const check = (id: string, actor?: { username?: string }) => + service.assertEffectiveUserIsDamagedPartyOnClaim(claim, id, actor); + await expect(check(firstId)).rejects.toBeInstanceOf(ForbiddenException); + await expect(check(outsiderId)).rejects.toBeInstanceOf(ForbiddenException); + await expect(check(secondId)).resolves.toBeUndefined(); + service.userDbService.findAllByPhone.mockResolvedValue([{ _id: secondId }]); + await expect( + check(outsiderId, { username: "989120000002" }), + ).resolves.toBeUndefined(); + service.blameRequestDbService.findById.mockResolvedValue({ + ...source(), + expert: {}, + }); + await expect(check(firstId)).rejects.toBeInstanceOf(ForbiddenException); + }); + + it("returns read-only details for the guilty party and actionable guidance for the beneficiary", async () => { + const service = serviceFor(source()); + const claim = { + _id: new Types.ObjectId(claimId), + blameRequestId: new Types.ObjectId(blameId), + publicId: "A100", + requestNo: "C100", + owner: { userId: firstId }, + damagedPartyUserId: secondId, + status: "SELECTING_OUTER_PARTS", + }; + service.claimCaseDbService.findById = jest.fn().mockResolvedValue(claim); + service.blameRequestDbService.find = jest + .fn() + .mockResolvedValue([source()]); + const guilty = await service.getClaimDetailsV2(claimId, firstId, { + sub: firstId, + role: RoleEnum.USER, + }); + expect(guilty.canAct).toBe(false); + expect(guilty).not.toHaveProperty("ownerGuidance"); + const damaged = await service.getClaimDetailsV2(claimId, secondId, { + sub: secondId, + role: RoleEnum.USER, + }); + expect(damaged.canAct).toBe(true); + expect(damaged.ownerGuidance).toBeDefined(); + }); + + it("uses a persisted beneficiary when the source is unavailable, never guesses from snapshot non-ownership", async () => { + const service = serviceFor(null); + const claim = { + blameRequestId: blameId, + owner: { userId: firstId }, + damagedPartyUserId: secondId, + }; + await expect( + service.assertEffectiveUserIsDamagedPartyOnClaim(claim, firstId), + ).rejects.toBeInstanceOf(ForbiddenException); + await expect( + service.assertEffectiveUserIsDamagedPartyOnClaim(claim, secondId), + ).resolves.toBeUndefined(); + const ambiguous = { + blameRequestId: blameId, + snapshot: { parties: source().parties }, + owner: { userId: secondId }, + }; + await expect( + service.assertEffectiveUserIsDamagedPartyOnClaim(ambiguous, firstId), + ).rejects.toBeInstanceOf(ForbiddenException); + await expect( + service.assertEffectiveUserIsDamagedPartyOnClaim( + { owner: { userId: secondId } }, + secondId, + ), + ).resolves.toBeUndefined(); + }); + + it("keeps the authorized in-person expert acting for the beneficiary in reorganized flows", async () => { + const blame = { + ...source(), + creationMethod: "IN_PERSON", + expertInitiated: true, + initiatedByFieldExpertId: outsiderId, + }; + const service = serviceFor(blame); + const claim = { + blameRequestId: blameId, + owner: { userId: secondId }, + damagedPartyUserId: secondId, + }; + const effectiveId = await service.resolveClaimEffectiveUserId( + claim, + outsiderId, + RoleEnum.FIELD_EXPERT, + ); + expect(effectiveId).toBe(secondId); + await expect( + service.assertEffectiveUserIsDamagedPartyOnClaim(claim, effectiveId), + ).resolves.toBeUndefined(); + }); +}); diff --git a/src/claim-request-management/claim-optional-document.spec.ts b/src/claim-request-management/claim-optional-document.spec.ts index cae67af..b705b94 100644 --- a/src/claim-request-management/claim-optional-document.spec.ts +++ b/src/claim-request-management/claim-optional-document.spec.ts @@ -6,16 +6,6 @@ describe("optional accident sketch", () => { ClaimRequestManagementService.prototype, ) as ClaimRequestManagementService; - it("is excluded from legacy required-document completion", () => { - const requiredTypes = (service as any).getRequiredDocumentTypes({ - blameFile: { type: "THIRD_PARTY" }, - }); - - expect(requiredTypes).not.toContain( - ClaimRequiredDocumentType.ACCIDENT_SKETCH, - ); - }); - it("does not gate V2 owner-document completion", () => { const mandatoryKeys = (service as any).requiredDocumentKeysV2(false); const requiredDocuments = Object.fromEntries( diff --git a/src/claim-request-management/claim-request-management.controller.ts b/src/claim-request-management/claim-request-management.controller.ts index 300dc3a..c8cb78b 100644 --- a/src/claim-request-management/claim-request-management.controller.ts +++ b/src/claim-request-management/claim-request-management.controller.ts @@ -1,86 +1,17 @@ +import { Controller, Get, UseGuards } from "@nestjs/common"; +import { ApiBearerAuth, ApiExcludeController } from "@nestjs/swagger"; import { readFile } from "node:fs/promises"; -import { extname, parse } from "node:path"; -import { - BadRequestException, - Body, - Controller, - Get, - Param, - Patch, - Post, - Put, - Query, - UploadedFile, - UseGuards, - UseInterceptors, -} from "@nestjs/common"; -import { FileInterceptor } from "@nestjs/platform-express"; -import { - ApiBearerAuth, - ApiBody, - ApiConsumes, - ApiParam, - ApiQuery, - ApiTags, - ApiOperation, - ApiExcludeController, -} from "@nestjs/swagger"; -import { diskStorage } from "multer"; import { ClaimAccessGuard } from "src/auth/guards/claim-access.guard"; import { RolesGuard } from "src/auth/guards/role.guard"; import { Roles } from "src/decorators/roles.decorator"; -import { CurrentUser } from "src/decorators/user.decorator"; import { RoleEnum } from "src/Types&Enums/role.enum"; -import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service"; -import { ClaimRequestManagementService } from "./claim-request-management.service"; -import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum"; -import { CarDamagePartDto, OtherCarDamagePartDto } from "./dto/car-part.dto"; -import { UserCommentDto } from "./dto/user-comment.dto"; -import { UserObjectionDto } from "./dto/user-objection.dto"; -import { UserRatingDto } from "./dto/user-rating.dto"; @ApiExcludeController() @Controller("claim-request-management") -// @ApiTags("claim-request-management") @Roles(RoleEnum.USER, RoleEnum.EXPERT, RoleEnum.DAMAGE_EXPERT) @UseGuards(ClaimAccessGuard, RolesGuard) @ApiBearerAuth() export class ClaimRequestManagementController { - constructor( - private readonly claimRequestManagementService: ClaimRequestManagementService, - ) {} - - // @ApiParam({ name: "blameId" }) - // @ApiOperation({ deprecated: true }) - @Post("/:blameId") - async createClaimRequest( - @Param("blameId") requestId: string, - @CurrentUser() user, - ) { - return await this.claimRequestManagementService.createClaimRequest( - requestId, - user.role === RoleEnum.USER ? user.sub : undefined, - user, - ); - } - - // @ApiBody({ type: CarDamagePartDto }) - // @ApiOperation({ deprecated: true }) - @Patch("/car-part-damage/:claimRequestID") - // @ApiParam({ name: "claimRequestID" }) - async carPartDamage( - @Param("claimRequestID") requestId: string, - @Body() body: CarDamagePartDto, - @CurrentUser() user, - ) { - return await this.claimRequestManagementService.selectCarPartDamage( - requestId, - body, - user, - ); - } - - // @ApiOperation({ deprecated: true }) @Get("/car-other-part") async getCarOtherParts() { const carOtherPart = await readFile( @@ -89,417 +20,4 @@ export class ClaimRequestManagementController { ); return carOtherPart; } - - // @ApiBody({ type: OtherCarDamagePartDto }) - // @ApiParam({ name: "claimRequestID" }) - @UseInterceptors( - FileInterceptor("file", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/car-green-cards", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `${file.originalname.split(" ")[0]}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - @ApiConsumes("multipart/form-data") - // @ApiOperation({ deprecated: true }) - @Patch("/car-other-part-damage/:claimRequestID") - async carOtherPartDamage( - @Param("claimRequestID") requestId: string, - @UploadedFile() file, - @Body() body: OtherCarDamagePartDto, - @CurrentUser() user, - ) { - return await this.claimRequestManagementService.selectCarOtherPartDamage( - requestId, - body, - file, - user, - ); - } - - // @ApiOperation({ deprecated: true }) - @Get("required-documents-status/:claimRequestID") - // @ApiParam({ name: "claimRequestID" }) - async getRequiredDocumentsStatus(@Param("claimRequestID") requestId: string) { - return await this.claimRequestManagementService.getRequiredDocumentsStatus( - requestId, - ); - } - - // @ApiOperation({ deprecated: true }) - @Get("car-part-image-required/:claimRequestID") - // @ApiParam({ name: "claimRequestID" }) - async getImageRequired(@Param("claimRequestID") requestId) { - return await this.claimRequestManagementService.getImageRequiredList( - requestId, - ); - } - - // @ApiBody({ - // schema: { - // type: "object", - // properties: { - // file: { type: "string", format: "binary" }, - // }, - // }, - // }) - @UseInterceptors( - FileInterceptor("file", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/claim-required-documents/", - filename: (req, file, callback) => { - const extension = extname(file.originalname); - const basename = parse(file.originalname).name; - const unique = Date.now(); - const sanitizedBasename = basename - .replace(/\s/g, "_") - .replace(/[^\w\-_]/g, "") - .substring(0, 50); - const filename = `${sanitizedBasename}-${unique}${extension}`; - callback(null, filename); - }, - }), - }), - ) - // @ApiConsumes("multipart/form-data") - // // @ApiParam({ name: "claimRequestID" }) - // @ApiQuery({ - // name: "documentType", - // enum: ClaimRequiredDocumentType, - // description: "Type of required document to upload", - // }) - // @ApiOperation({ deprecated: true }) - @Patch("upload-required-document/:claimRequestID") - async uploadRequiredDocument( - @Param("claimRequestID") requestId: string, - @Query("documentType") documentType: string, - @UploadedFile("file") file: Express.Multer.File, - @CurrentUser() user, - ) { - if (!file) { - throw new BadRequestException("File is required"); - } - return await this.claimRequestManagementService.uploadRequiredDocument( - requestId, - documentType as any, - file, - user, - ); - } - - // @ApiBody({ - // schema: { - // type: "object", - // properties: { - // file: { type: "string", format: "binary" }, - // }, - // }, - // }) - @UseInterceptors( - FileInterceptor("file", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/car-parts/", - filename: (req, file, callback) => { - const extension = extname(file.originalname); - const basename = parse(file.originalname).name; - const unique = Date.now(); - // Sanitize filename: remove non-ASCII characters and special chars to avoid encoding issues - const sanitizedBasename = basename - .replace(/\s/g, "_") - .replace(/[^\w\-_]/g, "") // Remove all non-word characters except hyphens and underscores - .substring(0, 50); // Limit length - const filename = `${sanitizedBasename}-${unique}${extension}`; - callback(null, filename); - }, - }), - }), - ) - // @ApiConsumes("multipart/form-data") - // @ApiParam({ name: "claimRequestID" }) - // @ApiParam({ - // name: "partId", - // description: "The ID of the specific car part being photographed.", - // }) - // @ApiOperation({ deprecated: true }) - @Patch("capture-car-part-damage/:claimRequestID/:partId") - async captureCarPartDamage( - @Param("partId") partId: string, - @Param("claimRequestID") requestId: string, - @UploadedFile("file") file: Express.Multer.File, - ) { - if (!file) { - throw new BadRequestException("Image file is required."); - } - return await this.claimRequestManagementService.setDamageImage( - requestId, - partId, - file, - ); - } - - // @ApiBody({ - // schema: { - // type: "object", - // properties: { - // file: { type: "string", format: "binary" }, - // }, - // }, - // }) - @UseInterceptors( - FileInterceptor("file", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/car-capture-videos/", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `claim-video-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - // @ApiConsumes("multipart/form-data") - // @ApiParam({ name: "claimRequestID" }) - // @ApiOperation({ deprecated: true }) - @Patch("car-capture/:claimRequestID") - async captureVideoCapture( - @Param("claimRequestID") requestId: string, - @UploadedFile("file") file: Express.Multer.File, - ) { - return await this.claimRequestManagementService.setVideoCapture( - requestId, - file, - ); - } - - // @ApiOperation({ deprecated: true }) - @Get("requests/") - async getRequest(@CurrentUser() currentUser) { - return await this.claimRequestManagementService.myRequests(currentUser); - } - - // @ApiOperation({ deprecated: true }) - @Get("request/:claimRequestId") - // @ApiParam({ name: "claimRequestId" }) - myRequests(@Param("claimRequestId") requestId: string, @CurrentUser() user) { - return this.claimRequestManagementService.requestDetails(requestId, user); - } - - // @ApiOperation({ deprecated: true }) - @Put("request/reply/:claimRequestId") - // @ApiParam({ name: "claimRequestId" }) - @UseInterceptors( - FileInterceptor("file", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/claim-sign", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `${file.originalname.split(" ")[0]}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - // @ApiBody({ - // type: UserCommentDto, - // description: "if partId null , you can upload video capture", - // }) - // @ApiConsumes("multipart/form-data") - // @ApiParam({ name: "claimRequestId" }) - async submitReply( - @Param("claimRequestId") requestId, - @Body() body, - @UploadedFile() file: Express.Multer.File, - @CurrentUser() user, - ) { - // return await this.claimRequestManagementService.submitUserReply( - // requestId, - // body, - // file, - // user, - // ); - } - - // @ApiOperation({ deprecated: true }) - @Put("request/resend/:claimRequestId/objection") - // @ApiParam({ name: "claimRequestId" }) - // @ApiConsumes("application/json") - // @ApiBody({ - // type: UserObjectionDto, - // description: "Objection details with optional new parts", - // }) - async handleUserObjection( - @Param("claimRequestId") claimRequestId: string, - @Body() userObjectionDto: UserObjectionDto, - ) { - return await this.claimRequestManagementService.handleUserObjectionAndParts( - claimRequestId, - userObjectionDto, - ); - } - - // @ApiOperation({ deprecated: true }) - @Patch("request/resend/:claimRequestId") - // @ApiConsumes("multipart/form-data") - // @ApiParam({ name: "claimRequestId" }) - // @ApiQuery({ name: "fields", enum: ["resendDocuments", "resendCarParts"] }) - // @ApiQuery({ name: "partId", required: false }) - // @ApiQuery({ name: "documentName", required: false }) - // @ApiQuery({ name: "side", required: false }) - // @ApiBody({ - // schema: { - // type: "object", - // properties: { - // file: { - // type: "string", - // format: "binary", - // }, - // }, - // }, - // }) - @UseInterceptors( - FileInterceptor("file", { - storage: diskStorage({ - destination: "./files/claim-resend-documents", - filename: (req, file, callback) => { - const unique = Date.now(); - const ext = extname(file.originalname); - const filename = `${file.originalname.split(" ")[0]}-${unique}${ext}`; - callback(null, filename); - }, - }), - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - }), - ) - async uploadDocuments( - @Param("claimRequestId") claimId: string, - @Query() query: string, - @UploadedFile() file: Express.Multer.File, - @CurrentUser() user, - ) { - return await this.claimRequestManagementService.resendFiles( - claimId, - file, - query, - user, - ); - } - - /** - * User satisfaction rating for a completed claim file. - * Only the damaged user (claim owner) can rate their claim after it is closed. - */ - // @ApiOperation({ deprecated: true }) - @Put("request/:claimRequestId/user-rating") - // @ApiParam({ name: "claimRequestId" }) - // @ApiBody({ type: UserRatingDto }) - async addUserRating( - @Param("claimRequestId") claimRequestId: string, - @Body() ratingDto: UserRatingDto, - @CurrentUser() user, - ) { - return await this.claimRequestManagementService.addUserRating( - claimRequestId, - user, - ratingDto, - ); - } - - // @ApiOperation({ deprecated: true }) - @Patch("request/reply/:claimRequestId/:partId/upload-factor") - // @ApiConsumes("multipart/form-data") - // @ApiParam({ name: "claimRequestId" }) - // @ApiParam({ name: "partId" }) - // @ApiBody({ - // schema: { - // type: "object", - // properties: { - // file: { - // type: "string", - // format: "binary", - // }, - // }, - // }, - // }) - @UseInterceptors( - FileInterceptor("file", { - storage: diskStorage({ - destination: "./files/claim-factors", - filename: (req, file, callback) => { - const unique = Date.now(); - const filename = `-${unique}-${file.originalname}`; - callback(null, filename); - }, - }), - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - }), - ) - async uploadFactorForPart( - @Param("claimRequestId") claimId: string, - @Param("partId") partId: string, - @UploadedFile() file: Express.Multer.File, - @CurrentUser() user, - ) { - return await this.claimRequestManagementService.uploadClaimFactor( - claimId, - partId, - file, - user, - ); - } - - // @ApiParam({ name: "id" }) - // @ApiOperation({ deprecated: true }) - @Patch(":id/visit") - async inPersonVisit( - @Param("id") requestId: string, - @CurrentUser() actor, - ) { - return await this.claimRequestManagementService.inPersonVisit(requestId, actor); - } - - // Legacy V1 owner branch picker — intentionally disabled. - // A claim is handled by an expert assigned to the insurer branch, so the - // owner must not choose an insurer branch while signing. This does not apply - // to the separate expert-only `daghi.branchId` choice in pricing flows. - // - // @Get("branches/:insuranceId") - // async insuranceBranches(@Param("insuranceId") insuranceId: string) { - // return await this.claimRequestManagementService.retrieveInsuranceBranches( - // insuranceId, - // ); - // } - - // @ApiOperation({ deprecated: true }) - @Get("fanavaran-submit/:claimRequestId") - // @ApiParam({ name: "claimRequestId" }) - async fanavaranSubmit(@Param("claimRequestId") claimRequestId: string) { - return await this.claimRequestManagementService.fanavaranSubmit( - claimRequestId, - ); - } - - // @ApiOperation({ deprecated: true }) - @Post("fanavaran-submit/:claimRequestId") - // @ApiParam({ name: "claimRequestId" }) - async submitToFanavaran(@Param("claimRequestId") claimRequestId: string) { - return await this.claimRequestManagementService.submitToFanavaran( - claimRequestId, - ); - } } diff --git a/src/claim-request-management/claim-request-management.module.ts b/src/claim-request-management/claim-request-management.module.ts index 552c58f..7bae105 100644 --- a/src/claim-request-management/claim-request-management.module.ts +++ b/src/claim-request-management/claim-request-management.module.ts @@ -9,11 +9,9 @@ import { RequestManagementModule } from "src/request-management/request-manageme import { UsersModule } from "src/users/users.module"; import { ClaimRequestManagementController } from "./claim-request-management.controller"; import { ClaimRequestManagementV2Controller } from "./claim-request-management.v2.controller"; -import { RegistrarClaimV1Controller } from "./registrar-claim.v1.controller"; import { ExpertInitiatedClaimMirrorController } from "./expert-initiated-claim.mirror.controller"; import { RegistrarClaimMirrorController } from "./registrar-claim.mirror.controller"; import { ClaimRequestManagementService } from "./claim-request-management.service"; -import { CarGreenCardDbService } from "./entites/db-service/car-green-card.db.service"; import { ClaimRequestManagementDbService } from "./entites/db-service/claim-request-management.db.service"; import { ClaimCaseDbService } from "./entites/db-service/claim-case.db.service"; import { @@ -21,7 +19,6 @@ import { ClaimCaseSchema, } from "./entites/schema/claim-cases.schema"; import { ClaimSignDbService } from "./entites/db-service/claim-sign.db.service"; -import { DamageImageDbService } from "./entites/db-service/damage-image.db.service"; import { ClaimFactorsImageDbService } from "./entites/db-service/factor-image.db.service"; import { VideoCaptureDbService } from "./entites/db-service/video-capture.db.service"; import { ClaimRequiredDocumentDbService } from "./entites/db-service/claim-required-document.db.service"; @@ -98,9 +95,9 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz ClaimRequestManagementService, ClaimRequestManagementDbService, ClaimCaseDbService, - CarGreenCardDbService, + ClaimCaseDbService, - DamageImageDbService, + ClaimSignDbService, ClaimFactorsImageDbService, VideoCaptureDbService, @@ -110,7 +107,6 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz controllers: [ ClaimRequestManagementController, ClaimRequestManagementV2Controller, - RegistrarClaimV1Controller, ExpertInitiatedClaimMirrorController, RegistrarClaimMirrorController, ], @@ -118,7 +114,7 @@ import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normaliz ClaimRequestManagementService, ClaimRequestManagementDbService, ClaimCaseDbService, - DamageImageDbService, + VideoCaptureDbService, ClaimRequiredDocumentDbService, ClaimSignDbService, diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index bdc7869..b22c89d 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -1,183 +1,61 @@ import { BadGatewayException, BadRequestException, + ConflictException, ForbiddenException, HttpException, HttpStatus, Injectable, + InternalServerErrorException, Logger, NotFoundException, - ConflictException, - InternalServerErrorException, } from "@nestjs/common"; -import { Types } from "mongoose"; import { isAxiosError } from "axios"; -import { unlink } from "node:fs/promises"; +import { Types } from "mongoose"; import { createReadStream, existsSync } from "node:fs"; import { basename, resolve } from "node:path"; -import FormData = require("form-data"); -import { AiService } from "src/ai/ai.service"; -import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; -import { RequestManagementDbService } from "src/request-management/entities/db-service/request-management.db.service"; -import { ReqBlameStatus } from "src/Types&Enums/blame-request-management/status.enum"; +import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; +import { CaseStatus as BlameCaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; +import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; +import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; +import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum"; +import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum"; +import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum"; import { ReqClaimStatus } from "src/Types&Enums/claim-request-management/status.enum"; import { ClaimStepsEnum } from "src/Types&Enums/claim-request-management/steps.enum"; -import { RequestManagementModel } from "src/request-management/entities/schema/request-management.schema"; -import { UserDbService } from "src/users/entities/db-service/user.db.service"; -import { CarDamagePartDto } from "./dto/car-part.dto"; -import { ClaimPartUploadDetail } from "./dto/claim-detail"; -import { CreateClaimRequestDtoRs } from "./dto/create-claim.dto"; -import { ClaimRequestDtoRs } from "./dto/claim-rs-dto"; -import { ImageRequiredDto } from "./dto/image-required.dto"; -import { MyRequestsDto } from "./dto/my-request.dto"; -import { UserObjectionDto } from "./dto/user-objection.dto"; -import { UserObjectionV2Dto } from "./dto/user-objection-v2.dto"; -import { CarGreenCardDbService } from "./entites/db-service/car-green-card.db.service"; -import { ClaimRequestManagementDbService } from "./entites/db-service/claim-request-management.db.service"; -import { ClaimCaseDbService } from "./entites/db-service/claim-case.db.service"; -import { fanavaranClaimReferences } from "./fanavaran-claim-references"; -import { - FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, - fanavaranClaimProductFromBlameType, - fanavaranClaimsBaseUrl, - fanavaranClaimStageUrl, - fanavaranHasDamageCaseStage, - fanavaranInsuranceLineIdForProduct, - fanavaranPartyInquirySources, - isFanavaranSubmitSupportedBlameType, - pickCarBodyPolicyNationalCode, - pickStoredCarBodyPolicyId, - type FanavaranClaimProduct, -} from "./fanavaran-claim-product"; -import { - actualPremiumFromHullPolicyRecord, - authorityCulpritIdFromDetectionRows, - customerIdFromHullPolicyRecord, - FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID, - FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, - fanavaranHullNestedClaimId, - toFanavaranHullBaseClaimPayload, -} from "./fanavaran-hull-base-claim"; -import { - activeStageLookupRows, applyFanavaranStageFieldReview, - fanavaranFieldStageSent, fanavaranStageFields, - type FanavaranFieldValues, -} from "./fanavaran-stage-fields"; -import { - collectFanavaranExpertiseReadinessWarnings, - hullExpertiseAssertFields, - mergeHullVehicleIdentityFromFanavaranVehicle, - pickHullVehicleIdentity, - toFanavaranHullExpertiseDmgSection, - toFanavaranHullExpertisePayload, - vehicleCurrentValueFromHullPolicyRecord, - FANAVARAN_DEFAULT_HULL_REPAIR_DURATION, -} from "./fanavaran-hull-expertise"; -import { - FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID, - FANAVARAN_DEFAULT_HULL_DMG_KIND_ID, - FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID, - FANAVARAN_HULL_DMG_COST_KIND_CAPTION, - FANAVARAN_HULL_DMG_KIND_CAPTION, - findLookupIdByCaption, -} from "./fanavaran-hull-expertise-lookups"; -import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; -import { CreateClaimFromBlameResponseDto } from "./dto/create-claim-v2.dto"; -import { - OuterPartCatalogItemDto, - SelectOuterPartsV2Dto, - SelectOuterPartsV2ResponseDto, -} from "./dto/select-outer-parts-v2.dto"; -import { - SelectOtherPartsV2Dto, - SelectOtherPartsV2ResponseDto, -} from "./dto/select-other-parts-v2.dto"; -import { SelectOtherPartsV3Dto } from "./dto/select-other-parts-v3.dto"; -import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-v2.dto"; -import { - UploadRequiredDocumentV2Dto, - UploadRequiredDocumentV2ResponseDto, -} from "./dto/upload-document-v2.dto"; -import { - CapturePartV2Dto, - CapturePartV2ResponseDto, - VideoCaptureV2ResponseDto, -} from "./dto/capture-part-v2.dto"; -import { - GetMyClaimsV2ResponseDto, - ClaimListItemV2Dto, -} from "./dto/my-claims-v2.dto"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { AiService } from "src/ai/ai.service"; +import { BranchDbService } from "src/client/entities/db-service/branch.db.service"; +import { InquiryParticipantRole } from "src/common/dto/inquiry-participants.dto"; import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; -import { toPublicListItems } from "src/helpers/public-list-response"; -import { - applyListQueryV2, - isInListDateRange, - parseListDateRange, -} from "src/helpers/list-query-v2"; -import { resolveUnifiedFileStatus } from "src/helpers/unified-file-status"; -import { partyPersonMatchesUser } from "src/helpers/iran-mobile"; -import { - buildBlamePartyAccessOrConditions, - collectUserIdVariants, -} from "src/helpers/party-access-queries"; -import { - buildOwnerUserIdAccessFilter, - ownerUserIdMatchesActor, - resolveLinkedUserIdStrings, -} from "src/helpers/user-access-resolver"; -import { - blameDamagedPartyMatchesUser, - resolveClaimOwnerFieldsFromBlame, - resolveClaimOwnerParty, - resolveDamagedPartyRow, - resolveDamagedPartyUserId, -} from "src/helpers/blame-damaged-party"; -import { claimCaseInitiatedByFieldExpert } from "src/helpers/tenant-scope"; -import { ClaimDetailsV2ResponseDto } from "./dto/claim-details-v2.dto"; -import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; -import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum"; -import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum"; -import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; -import { CaseStatus as BlameCaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; -import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; -import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; -import { ClaimSignDbService } from "./entites/db-service/claim-sign.db.service"; -import { DamageImageDbService } from "./entites/db-service/damage-image.db.service"; -import { ClaimFactorsImageDbService } from "./entites/db-service/factor-image.db.service"; -import { VideoCaptureDbService } from "./entites/db-service/video-capture.db.service"; -import { ClaimRequiredDocumentDbService } from "./entites/db-service/claim-required-document.db.service"; -import { - ClaimRequestManagementModel, - UserClaimRating, -} from "./entites/schema/claim-request-management.schema"; -import { PublicIdService } from "src/utils/public-id/public-id.service"; -import { ImageRequiredModel } from "./entites/schema/image-required.schema"; -import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; -import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; -import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; import { assertFileMakerCanCreateBlameType, assertFileReviewerCanReviewBlameType, resolveFileMakerStageOneExpertId, resolveFileReviewerExpertiseExpertId, } from "src/fanavaran/fanavaran-file-role-expert-ids"; -import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service"; -import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service"; -import { SandHubService } from "src/sand-hub/sand-hub.service"; import { - ExpertFileActivityType, - ExpertFileKind, -} from "src/users/entities/schema/expert-file-activity.schema"; -import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum"; -import { BranchDbService } from "src/client/entities/db-service/branch.db.service"; -import { CreationMethod } from "src/request-management/entities/schema/request-management.schema"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; -import { InquiryParticipantRole } from "src/common/dto/inquiry-participants.dto"; -import { participantForStoredPartyRole } from "src/request-management/inquiry-participant-resolver"; -import type { InquiryParticipantRoleAssignments } from "src/request-management/inquiry-participant-resolver"; -import { UserRatingDto } from "./dto/user-rating.dto"; + canUserCreateClaim, + resolveClaimBeneficiary, +} from "src/helpers/blame-claim-eligibility"; +import { + resolveClaimOwnerFieldsFromBlame, + resolveClaimOwnerParty, + resolveDamagedPartyRow, + resolveDamagedPartyUserId, +} from "src/helpers/blame-damaged-party"; +import { + canonicalizeClaimCarAngleKey, + getClaimCarAngleCaptureBlob, + getDamagedPartCaptureBlob, + hasClaimCarAngleCapture, + hasDamagedPartCapture, + legacyAngleDamagedPartFieldKeysToUnset, + type ClaimCarAngleKey, +} from "src/helpers/claim-car-angle-media"; +import { serializeDamagedPartSelectionHistory } from "src/helpers/claim-damaged-part-audit"; +import { buildClaimDetailsV2OwnerGuidance } from "src/helpers/claim-details-v2-owner-guidance"; import { canFinalizeExpertResend, documentKeyAllowedForExpertResend, @@ -193,37 +71,168 @@ import { getActiveV2ExpertReply, objectionDisallowedDueToOutstandingFactorWorkflow, } from "src/helpers/claim-v2-expert-reply-workflow"; -import { buildClaimDetailsV2OwnerGuidance } from "src/helpers/claim-details-v2-owner-guidance"; +import { partyPersonMatchesUser } from "src/helpers/iran-mobile"; import { - canonicalizeClaimCarAngleKey, - getClaimCarAngleCaptureBlob, - getDamagedPartCaptureBlob, - hasClaimCarAngleCapture, - hasDamagedPartCapture, - legacyAngleDamagedPartFieldKeysToUnset, - type ClaimCarAngleKey, -} from "src/helpers/claim-car-angle-media"; -import { - ClaimVehicleTypeV2, - FANAVARAN_CAR_PARTS_CATALOG, - OuterPartCatalogItem, -} from "src/static/outer-car-parts-catalog"; + applyListQueryV2, + isInListDateRange, + parseListDateRange, +} from "src/helpers/list-query-v2"; import { carPartDamageLabelForFactorRecord, catalogItemToSelectedPart, catalogLikeKeyFromPart, coerceDamagedPartsMediaToArray, - type DamageSelectedPartV2, migrateExpertReplyCarPartDamageToUnified, normalizeDamageSelectedParts, parseCatalogPartIdInput, partLookupKey, resolvePartCaptureIndex, + type DamageSelectedPartV2, } from "src/helpers/outer-damage-parts"; -import { serializeDamagedPartSelectionHistory } from "src/helpers/claim-damaged-part-audit"; -import { normalizeMoneyAmountString } from "src/utils/unicode-digits"; +import { + buildBlamePartyAccessOrConditions, + collectUserIdVariants, +} from "src/helpers/party-access-queries"; +import { toPublicListItems } from "src/helpers/public-list-response"; +import { claimCaseInitiatedByFieldExpert } from "src/helpers/tenant-scope"; +import { resolveUnifiedFileStatus } from "src/helpers/unified-file-status"; +import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; +import { + buildOwnerUserIdAccessFilter, + ownerUserIdMatchesActor, + resolveLinkedUserIdStrings, +} from "src/helpers/user-access-resolver"; +import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; + +import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; +import { CreationMethod } from "src/request-management/entities/schema/request-management.schema"; +import type { InquiryParticipantRoleAssignments } from "src/request-management/inquiry-participant-resolver"; +import { participantForStoredPartyRole } from "src/request-management/inquiry-participant-resolver"; +import { SandHubService } from "src/sand-hub/sand-hub.service"; +import { + ClaimVehicleTypeV2, + FANAVARAN_CAR_PARTS_CATALOG, + OuterPartCatalogItem, +} from "src/static/outer-car-parts-catalog"; + +import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; +import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; +import { UserDbService } from "src/users/entities/db-service/user.db.service"; import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service"; +import { normalizeMoneyAmountString } from "src/utils/unicode-digits"; +import { + CapturePartV2Dto, + CapturePartV2ResponseDto, + VideoCaptureV2ResponseDto, +} from "./dto/capture-part-v2.dto"; +import { GetCaptureRequirementsV2ResponseDto } from "./dto/capture-requirements-v2.dto"; +import { CarDamagePartDto } from "./dto/car-part.dto"; +import { ClaimDetailsV2ResponseDto } from "./dto/claim-details-v2.dto"; +import { CreateClaimFromBlameResponseDto } from "./dto/create-claim-v2.dto"; +import { + ClaimListItemV2Dto, + GetMyClaimsV2ResponseDto, +} from "./dto/my-claims-v2.dto"; +import { + SelectOtherPartsV2Dto, + SelectOtherPartsV2ResponseDto, +} from "./dto/select-other-parts-v2.dto"; +import { SelectOtherPartsV3Dto } from "./dto/select-other-parts-v3.dto"; +import { + OuterPartCatalogItemDto, + SelectOuterPartsV2Dto, + SelectOuterPartsV2ResponseDto, +} from "./dto/select-outer-parts-v2.dto"; +import { + UploadRequiredDocumentV2Dto, + UploadRequiredDocumentV2ResponseDto, +} from "./dto/upload-document-v2.dto"; +import { UserObjectionV2Dto } from "./dto/user-objection-v2.dto"; +import { UserRatingDto } from "./dto/user-rating.dto"; + +import { ClaimCaseDbService } from "./entites/db-service/claim-case.db.service"; +import { ClaimRequestManagementDbService } from "./entites/db-service/claim-request-management.db.service"; +import { ClaimRequiredDocumentDbService } from "./entites/db-service/claim-required-document.db.service"; +import { ClaimSignDbService } from "./entites/db-service/claim-sign.db.service"; + +import { ClaimFactorsImageDbService } from "./entites/db-service/factor-image.db.service"; +import { VideoCaptureDbService } from "./entites/db-service/video-capture.db.service"; +import { UserClaimRating } from "./entites/schema/claim-request-management.schema"; +import { ImageRequiredModel } from "./entites/schema/image-required.schema"; +import { + FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, + fanavaranClaimProductFromBlameType, + fanavaranClaimsBaseUrl, + fanavaranClaimStageUrl, + fanavaranHasDamageCaseStage, + fanavaranInsuranceLineIdForProduct, + fanavaranPartyInquirySources, + isFanavaranSubmitSupportedBlameType, + pickCarBodyPolicyNationalCode, + pickStoredCarBodyPolicyId, + type FanavaranClaimProduct, +} from "./fanavaran-claim-product"; +import { fanavaranClaimReferences } from "./fanavaran-claim-references"; +import { + actualPremiumFromHullPolicyRecord, + authorityCulpritIdFromDetectionRows, + customerIdFromHullPolicyRecord, + FANAVARAN_DEFAULT_HULL_AUTHORITY_CULPRIT_ID, + FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, + fanavaranHullNestedClaimId, + toFanavaranHullBaseClaimPayload, +} from "./fanavaran-hull-base-claim"; +import { + collectFanavaranExpertiseReadinessWarnings, + FANAVARAN_DEFAULT_HULL_REPAIR_DURATION, + hullExpertiseAssertFields, + mergeHullVehicleIdentityFromFanavaranVehicle, + pickHullVehicleIdentity, + toFanavaranHullExpertiseDmgSection, + toFanavaranHullExpertisePayload, + vehicleCurrentValueFromHullPolicyRecord, +} from "./fanavaran-hull-expertise"; +import { + FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID, + FANAVARAN_DEFAULT_HULL_DMG_KIND_ID, + FANAVARAN_DEFAULT_HULL_VEHICLE_ACCESSORY_ID, + FANAVARAN_HULL_DMG_COST_KIND_CAPTION, + FANAVARAN_HULL_DMG_KIND_CAPTION, + findLookupIdByCaption, +} from "./fanavaran-hull-expertise-lookups"; +import { + activeStageLookupRows, + applyFanavaranStageFieldReview, + fanavaranFieldStageSent, + fanavaranStageFields, + type FanavaranFieldValues, +} from "./fanavaran-stage-fields"; +import FormData = require("form-data"); + +import { HttpService } from "@nestjs/axios"; +import { firstValueFrom } from "rxjs"; +import { + fanavaranSubmitPath, + getFanavaranClientProfile, + resolveFanavaranClientKey, + resolveFanavaranProductContractId, + type FanavaranClientKey, +} from "src/core/config/fanavaran-client.config"; +import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher"; +import { FanavaranAuditService } from "src/fanavaran/fanavaran-audit.service"; +import type { FanavaranAuditSession } from "src/fanavaran/fanavaran-audit.types"; +import { FanavaranAuthService } from "src/fanavaran/fanavaran-auth.service"; +import { + FANAVARAN_LOOKUP_BASE_URL, + FANAVARAN_REMOTE_LOOKUPS, +} from "src/fanavaran/fanavaran-lookup.config"; +import { FanavaranLookupService } from "src/fanavaran/fanavaran-lookup.service"; +import { + FanavaranAuditSource, + FanavaranAuditStatus, + FanavaranAuditStep, +} from "src/fanavaran/schema/fanavaran-audit-log.schema"; import { CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS, capturePhaseSequenceMessage, @@ -233,30 +242,26 @@ import { isClaimCaptureStepComplete, OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5, } from "src/helpers/claim-capture-phase"; -import { HttpService } from "@nestjs/axios"; -import { firstValueFrom } from "rxjs"; -import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher"; import { - type FanavaranClientKey, - fanavaranSubmitPath, - getFanavaranClientProfile, - resolveFanavaranClientKey, - resolveFanavaranProductContractId, -} from "src/core/config/fanavaran-client.config"; -import { FanavaranAuditService } from "src/fanavaran/fanavaran-audit.service"; -import { FanavaranAuthService } from "src/fanavaran/fanavaran-auth.service"; -import { FanavaranLookupService } from "src/fanavaran/fanavaran-lookup.service"; -import { - FANAVARAN_LOOKUP_BASE_URL, - FANAVARAN_REMOTE_LOOKUPS, -} from "src/fanavaran/fanavaran-lookup.config"; -import type { FanavaranAuditSession } from "src/fanavaran/fanavaran-audit.types"; -import { - FanavaranAuditSource, - FanavaranAuditStatus, - FanavaranAuditStep, -} from "src/fanavaran/schema/fanavaran-audit-log.schema"; -import { selectLatestActiveFanavaranPolicy } from "./fanavaran-policy-selection"; + applyFanavaranManualPayloadOverrides, + asObjectRecord, + asVehicleInquiryRows, + collectPartyVinCandidates, + completePlaqueParts, + FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS, + FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS, + FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS, + fanavaranVehicleMatchesDamagedIdentity, + normalizeVin, + parseFanavaranId, + pickFanavaranPlaqueLookupFields, + pickFanavaranVehicleFromInquiry, + pickVehicleId, + pickVinFromPartyVehicle, + resolveDamageCasePlaqueLookupIds, + selectFanavaranVehicleForDamageCase, + type FanavaranDamagedVehicleIdentity, +} from "src/lookups/fanavaran-last-car-policy"; import { selectAccidentVehicleUsedId, vehicleGroupIdForKind, @@ -271,6 +276,10 @@ import { selectFanavaranDriverId, selectFanavaranOwnerId, } from "./fanavaran-driver-inquiry"; +import { + buildFanavaranOtherPeoplePayload, + pickFanavaranRecordId, +} from "./fanavaran-other-people"; import { resolveDriverFromParty, resolveDriverIsOwner, @@ -280,30 +289,7 @@ import { resolvePolicyholderFromParty, resolveThirdPartyCulpritTypeId, } from "./fanavaran-party-roles"; -import { - buildFanavaranOtherPeoplePayload, - pickFanavaranRecordId, -} from "./fanavaran-other-people"; -import { - asObjectRecord, - asVehicleInquiryRows, - collectPartyVinCandidates, - completePlaqueParts, - fanavaranVehicleMatchesDamagedIdentity, - normalizeVin, - applyFanavaranManualPayloadOverrides, - FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS, - FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS, - FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS, - parseFanavaranId, - pickFanavaranPlaqueLookupFields, - pickFanavaranVehicleFromInquiry, - pickVehicleId, - pickVinFromPartyVehicle, - resolveDamageCasePlaqueLookupIds, - selectFanavaranVehicleForDamageCase, - type FanavaranDamagedVehicleIdentity, -} from "src/lookups/fanavaran-last-car-policy"; +import { selectLatestActiveFanavaranPolicy } from "./fanavaran-policy-selection"; export interface FanavaranAutoSubmitResult { attempted: boolean; @@ -366,9 +352,18 @@ interface FanavaranAttachmentCandidate { */ function jalaliDateToInt(d: Date): number { const parts = d - .toLocaleDateString("fa-IR", { year: "numeric", month: "2-digit", day: "2-digit" }) + .toLocaleDateString("fa-IR", { + year: "numeric", + month: "2-digit", + day: "2-digit", + }) .split("/") - .map((p) => parseInt(p.replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0)), 10)); + .map((p) => + parseInt( + p.replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0)), + 10, + ), + ); return parts[0] * 10000 + parts[1] * 100 + parts[2]; } @@ -437,20 +432,6 @@ const FANAVARAN_PLATE_LETTER_CODE: Record = { export class ClaimRequestManagementService { private readonly logger = new Logger(ClaimRequestManagementService.name); - // Legacy Tejaratno third-party URL. V2 stages use fanavaranClaimsBaseUrl(product). - private readonly FANAVARAN_SUBMIT_URL = fanavaranClaimsBaseUrl("third-party"); - - // Authentication credentials - private readonly APP_NAME = "fanhab"; - private readonly SECRET = "5Fa@N#A2B"; - private readonly USERNAME = "fanhabUser"; - private readonly PASSWORD = "Fan#@2U$3er"; - - // API headers (legacy Tejaratno — prefer getFanavaranClientProfile) - private readonly CORP_ID = "3539"; - private readonly CONTRACT_ID = "263"; - private readonly LOCATION = "100"; - private readonly PARSIAN_FANAVARAN_CONFIG = { appName: "ParsianService", secret: "P@r30@n$erv!ce", @@ -477,27 +458,21 @@ export class ClaimRequestManagementService { /** Prevent concurrent auto/manual runs of the same claim stage. */ private readonly fanavaranInFlightStages = new Set(); - private readonly MAP_IR_API_KEY = - "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImI5ZDZjMThkNDRjZjc2OWI2Yjk1ODcyMGFjYmEzMmRiN2NhZjg0Zjk4OTRlMjZiZDg0Yzg3YjVlMzhlMTAyZDlkMWYxOGM5NjNmOTk4YjY2In0.eyJhdWQiOiIyMTcxOCIsImp0aSI6ImI5ZDZjMThkNDRjZjc2OWI2Yjk1ODcyMGFjYmEzMmRiN2NhZjg0Zjk4OTRlMjZiZDg0Yzg3YjVlMzhlMTAyZDlkMWYxOGM5NjNmOTk4YjY2IiwiaWF0IjoxNjgwNjA4NTkxLCJuYmYiOjE2ODA2MDg1OTEsImV4cCI6MTY4MzIwMDU5MSwic3ViIjoiIiwic2NvcGVzIjpbImJhc2ljIl19.rTviLd8b5yTHUDa3ODZyva593eMnL0d3XPg3sKkZxMOf_jNIH6lFQyIfbId-wsd1EAdsOdsL3CME_Y8t332PWJbxMNgnEq4Rf2IkClkvkSx6Sb5_4bmlhBM75zw2SmccvgbFUn4xkTOw0FT4vABC2Y3-MKctjMpmO8QOrVULSKt4psrmQhr7hBu7YRDnAAEc6muZ1VpRvdB1kqNKddoSIrfDaq6aDRJ-BNbGRAaFFvP_kH4cgSCKV4dU0TknL3mRKUiVy6_TDkjtzAN8fE2wsdvNo2pGTJPzKFsR2ipgGNTvB__g3bOnVpKsgFXPBH0e_Qa7ff1tZ3VGWy3jRNh9Lg"; - constructor( - private readonly blameDbService: RequestManagementDbService, private readonly claimDbService: ClaimRequestManagementDbService, private readonly claimCaseDbService: ClaimCaseDbService, private readonly blameRequestDbService: BlameRequestDbService, - private readonly carGreenCardDbService: CarGreenCardDbService, - private readonly damageImageDbService: DamageImageDbService, + private readonly userDbService: UserDbService, private readonly videoCaptureDbService: VideoCaptureDbService, private readonly claimSignDbService: ClaimSignDbService, private readonly aiService: AiService, private readonly claimRequestManagementDbService: ClaimRequestManagementDbService, private readonly claimFactorsImageDbService: ClaimFactorsImageDbService, - private readonly damageExpertDbService: DamageExpertDbService, - private readonly expertFileActivityDbService: ExpertFileActivityDbService, + private readonly branchDbService: BranchDbService, private readonly claimRequiredDocumentDbService: ClaimRequiredDocumentDbService, - private readonly publicIdService: PublicIdService, + private readonly sandHubService: SandHubService, private readonly httpService: HttpService, private readonly fanavaranAuditService: FanavaranAuditService, @@ -505,7 +480,7 @@ export class ClaimRequestManagementService { private readonly fanavaranLookupService: FanavaranLookupService, private readonly fileMakerDbService: FileMakerDbService, private readonly fileReviewerDbService: FileReviewerDbService, - private readonly fieldExpertDbService: FieldExpertDbService, + private readonly plateNormalizer: PlateNormalizerService, private readonly fanavaranLocationService: FanavaranLocationService, ) {} @@ -578,7 +553,11 @@ export class ClaimRequestManagementService { skipMetalPlate?: boolean, ): boolean { for (const k of this.v3PreCaptureDocumentKeys(isCarBody)) { - if (skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)) continue; + if ( + skipMetalPlate && + OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any) + ) + continue; const ok = k === assumeUploadedKey ? true @@ -604,7 +583,11 @@ export class ClaimRequestManagementService { ): number { let n = 0; for (const k of this.v3PreCaptureDocumentKeys(isCarBody)) { - if (skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)) continue; + if ( + skipMetalPlate && + OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any) + ) + continue; const ok = k === assumeUploadedKey ? true @@ -659,7 +642,9 @@ export class ClaimRequestManagementService { const ir = Number(irRaw); const leftDigits = Number(leftRaw); const centerDigits = Number(centerRaw); - const centerAlphabet = this.plateNormalizer.normalizePlateText(String(alphaRaw || "")); + const centerAlphabet = this.plateNormalizer.normalizePlateText( + String(alphaRaw || ""), + ); if ( !Number.isFinite(ir) || !Number.isFinite(leftDigits) || @@ -690,7 +675,9 @@ export class ClaimRequestManagementService { ) { return { leftDigits: Number(p.leftDigits), - centerAlphabet: this.plateNormalizer.normalizePlateText(String(p.centerAlphabet)), + centerAlphabet: this.plateNormalizer.normalizePlateText( + String(p.centerAlphabet), + ), centerDigits: Number(p.centerDigits), ir: Number(p.ir), }; @@ -761,7 +748,9 @@ export class ClaimRequestManagementService { * rows for internal use (e.g. validating selectedPartIds). * Falls back to the static snapshot when the remote lookup is unavailable. */ - private async getLiveFanavaranCatalogItems(): Promise { + private async getLiveFanavaranCatalogItems(): Promise< + OuterPartCatalogItem[] + > { const clientKey = resolveFanavaranClientKey(); const rows = await this.getFanavaranLookupRows(clientKey, "car-components"); if (!rows.length) { @@ -778,227 +767,14 @@ export class ClaimRequestManagementService { typeof (r as any).Id === "number" && typeof (r as any).Caption === "string", ) - .map((r): OuterPartCatalogItem => ({ - id: r.Id, - key: String(r.Id), - titleFa: r.Caption, - side: "", - })); - } - - private userDamageDetail(blRequest: RequestManagementModel) { - const { firstPartyDetails: first, secondPartyDetails: second } = blRequest; - switch (blRequest.expertSubmitReply.guiltyUserId) { - case first.firstPartyId: - return { isGuilty: first, isNotGuilty: second }; - case second.secondPartyId: - return { isGuilty: second, isNotGuilty: first }; - } - } - - /** - * Helper method to get the effective user ID for claim operations. - * For experts accessing IN_PERSON claim files, returns the claim file's userId. - * For regular users, returns their own ID. - */ - private async getEffectiveUserId( - claimRequestId: string, - actor: any, - ): Promise { - // If actor is a user, return their ID - if (actor.role === RoleEnum.USER) { - return actor.sub; - } - - // If actor is an expert, verify they're accessing an IN_PERSON claim file - // and return the claim file's userId - const expertRoles = [ - RoleEnum.EXPERT, - RoleEnum.DAMAGE_EXPERT, - RoleEnum.FIELD_EXPERT, - ]; - if (expertRoles.includes(actor.role)) { - const claim = await this.claimDbService.findOne(claimRequestId); - if (!claim) { - throw new NotFoundException("Claim file not found"); - } - - const blameFile = claim.blameFile; - if ( - blameFile?.expertInitiated && - blameFile?.creationMethod === "IN_PERSON" && - String(blameFile.initiatedBy) === actor.sub - ) { - // Expert is accessing IN_PERSON file they initiated - use claim's userId - return String(claim.userId); - } - - throw new ForbiddenException( - "Experts can only access IN_PERSON claim files they initiated", + .map( + (r): OuterPartCatalogItem => ({ + id: r.Id, + key: String(r.Id), + titleFa: r.Caption, + side: "", + }), ); - } - - throw new ForbiddenException("Invalid role"); - } - - async createClaimRequest( - requestId: string, - CurrentUserId?: string, - actor?: any, - ) { - try { - const blameRequest = await this.blameDbService.findOne(requestId); - if (!blameRequest) { - throw new NotFoundException("Source blame request not found."); - } - - // Ensure the blame request has a shared human-friendly id. - // For legacy records, generate it lazily exactly once. - let publicId = (blameRequest as any).publicId as string | undefined; - if (!publicId) { - publicId = await this.publicIdService.generateRequestPublicId(); - await this.blameDbService.findAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { $set: { publicId } }, - ); - } - - const existingClaimCount = await this.claimDbService.countByFilter({ - "blameFile._id": new Types.ObjectId(requestId), - blameRequestId: new Types.ObjectId(requestId), - publicId, - }); - if (existingClaimCount > 0) { - throw new ForbiddenException( - "A claim request for this blame file already exists.", - ); - } - - const isStatusValid = - blameRequest.blameStatus === ReqBlameStatus.CloseRequest; - - if (!isStatusValid) { - throw new HttpException( - `Blame request must be 'CloseRequest', but is currently '${blameRequest.blameStatus}'.`, - HttpStatus.BAD_REQUEST, - ); - } - - if (!blameRequest.expertSubmitReply) { - throw new HttpException( - "Cannot create a claim file until the expert has submitted a reply.", - HttpStatus.GONE, - ); - } - - // Determine the damaged user (non-guilty party) - const guiltyUserId = String(blameRequest.expertSubmitReply.guiltyUserId); - let damagedUserId: string; - - // For IN_PERSON expert-initiated files, expert creates the claim - // For LINK method or regular files, user creates their own claim - const expertRoles = [ - RoleEnum.EXPERT, - RoleEnum.DAMAGE_EXPERT, - RoleEnum.FIELD_EXPERT, - ]; - if ( - blameRequest.expertInitiated && - blameRequest.creationMethod === "IN_PERSON" && - actor && - expertRoles.includes(actor.role) - ) { - // Expert is creating claim for IN_PERSON file - // Verify expert is the initiating expert - if (String(blameRequest.initiatedBy) !== actor.sub) { - throw new ForbiddenException( - "Only the initiating expert can create claim files for IN_PERSON files.", - ); - } - - // Determine damaged user (the one who is NOT guilty) - if ( - String(blameRequest.firstPartyDetails.firstPartyId) === guiltyUserId - ) { - damagedUserId = String(blameRequest.secondPartyDetails.secondPartyId); - } else { - damagedUserId = String(blameRequest.firstPartyDetails.firstPartyId); - } - } else { - // Regular user flow - if (!CurrentUserId) { - throw new BadRequestException("User ID is required."); - } - if (guiltyUserId === CurrentUserId) { - throw new HttpException( - "You cannot submit a claim file as you are the guilty party.", - HttpStatus.FORBIDDEN, - ); - } - damagedUserId = CurrentUserId; - } - - const userDetail = await this.userDbService.findOne({ - _id: new Types.ObjectId(damagedUserId), - }); - if (!userDetail) { - throw new NotFoundException("User details could not be found."); - } - - const carDetail = - String(blameRequest.firstPartyDetails.firstPartyId) === damagedUserId - ? blameRequest.firstPartyDetails.firstPartyCarDetail - : blameRequest.secondPartyDetails.secondPartyCarDetail; - - const carPlate = - String(blameRequest.firstPartyDetails.firstPartyId) === damagedUserId - ? blameRequest.firstPartyDetails.firstPartyPlate - : blameRequest.secondPartyDetails.secondPartyPlate; - - const newClaimPayload = { - blameFile: blameRequest, - userId: new Types.ObjectId(damagedUserId), - claimStatus: ReqClaimStatus.WaitingForUserCompleted, - steps: [ClaimStepsEnum.CreateClaimFile], - currentStep: ClaimStepsEnum.CreateClaimFile, - nextStep: ClaimStepsEnum.SelectDamagePart, - fullName: userDetail.fullName, - carDetail, - carPlate, - userClientKey: new Types.ObjectId(userDetail.clientKey), - createdAt: new Date(), - }; - - const response = await this.claimDbService.create(newClaimPayload as any); - - return new CreateClaimRequestDtoRs( - response["_id"], - "Claim file created successfully.", - ); - } catch (er) { - this.logger.error(er); - - if (er instanceof HttpException) { - throw er; - } - - if ( - typeof er === "object" && - er !== null && - "code" in er && - er.code === 11000 - ) { - throw new HttpException( - "Duplicate claim file reference.", - HttpStatus.CONFLICT, - ); - } - - throw new HttpException( - "An internal server error occurred.", - HttpStatus.INTERNAL_SERVER_ERROR, - ); - } } private findTrueItems(userPartSelect: CarDamagePartDto) { @@ -1184,51 +960,6 @@ export class ClaimRequestManagementService { return cl.imageRequired; } - async selectCarPartDamage( - requestId: string, - userPartSelect: CarDamagePartDto, - actor: any, - ): Promise { - try { - const cl = await this.claimDbService.findOne(requestId); - - if (!cl) { - throw new HttpException("Claim file not found", HttpStatus.NOT_FOUND); - } - - // Verify access: user must own the claim, or expert must be accessing IN_PERSON file - const effectiveUserId = await this.getEffectiveUserId(requestId, actor); - if (String(cl.userId) !== effectiveUserId) { - throw new ForbiddenException( - "You do not have access to this claim file", - ); - } - - if (cl.carPartDamage) { - throw new HttpException( - "car damage part has exist", - HttpStatus.CONFLICT, - ); - } - - const trueItems = this.findTrueItems(userPartSelect); - const damageParts = this.setCarPartDamageAndImage(cl, trueItems); - - await this.claimDbService.findAndUpdate(requestId, { - currentStep: ClaimStepsEnum.SelectDamagePart, - nextStep: ClaimStepsEnum.SelectOtherParts, - $push: { - steps: ClaimStepsEnum.SelectDamagePart, - }, - }); - - return damageParts; - } catch (error) { - this.logger.error(error); - throw error; - } - } - /** * Field expert completes claim-needed data for expert-initiated IN_PERSON files. * Only the initiating field expert can call this. Accepts car part damage and/or sheba, nationalCodeOfInsurer, otherParts. @@ -1547,548 +1278,6 @@ export class ClaimRequestManagementService { return { success: true, claimRequestId }; } - async selectCarOtherPartDamage( - requestId: string, - body: any, // Use your DTO for better type safety - file: Express.Multer.File, - actor: any, - ) { - try { - // 1. Fetch the claim request and perform initial validation - const claimRequest = await this.claimDbService.findOne(requestId); - if (!claimRequest) { - throw new NotFoundException("Claim file not found"); - } - - // Verify access: user must own the claim, or expert must be accessing IN_PERSON file - const effectiveUserId = await this.getEffectiveUserId(requestId, actor); - if (String(claimRequest.userId) !== effectiveUserId) { - throw new ForbiddenException( - "You do not have access to this claim file", - ); - } - - if ( - String(claimRequest.blameFile.expertSubmitReply?.guiltyUserId) === - effectiveUserId - ) { - throw new ForbiddenException( - "User access denied. You are the guilty party in the blame file.", - ); - } - - if (!claimRequest.carPlate) { - throw new BadRequestException( - "Cannot validate ownership: Plate information is missing from the claim file.", - ); - } - - // await this.sandHubService.getCarOwnershipInfo( - // claimRequest.carPlate, - // body.nationalCodeOfInsurer, - // ); - - // await this.sandHubService.getShebaValidation( - // body.nationalCodeOfInsurer, - // body.sheba, - // ); - - const greenCard = await this.carGreenCardDbService.create({ - path: file.path, - fileName: file.filename, - claimId: requestId, - }); - if (!greenCard) { - throw new BadGatewayException( - "Failed to save car green card document.", - ); - } - - const updatePayload = { - $set: { - otherParts: JSON.parse(body.otherParts as any), - nationalCodeOfInsurer: body.nationalCodeOfInsurer, - sheba: body.sheba, - carGreenCard: { - path: buildFileLink(greenCard.path), - fileName: greenCard.fileName, - claimId: requestId, - }, - currentStep: ClaimStepsEnum.SelectOtherParts, - nextStep: ClaimStepsEnum.ImageRequired, - claimStatus: ReqClaimStatus.WaitingForUserCompleted, - }, - $push: { - steps: ClaimStepsEnum.SelectOtherParts, - }, - }; - - this.logger.log( - `[CLAIM] Moving to ImageRequired step for claim ${requestId}. Status set to: ${ReqClaimStatus.WaitingForUserCompleted}`, - ); - - const updatedClaim = await this.claimDbService.findByIdAndUpdate( - requestId, - updatePayload, - ); - - // 6. Return the successful response - return new ClaimPartUploadDetail([updatedClaim]); - } catch (error) { - this.logger.error( - `Error in selectCarOtherPartDamage: ${error instanceof Error ? error.message : String(error)}`, - error instanceof Error ? error.stack : undefined, - ); - // Re-throw the specific error from the validation steps or a generic one. - throw error; - } - } - - /** - * Get the list of required document types based on claim type and whether there's a second party car - * For CAR_BODY type with accident with another object (not a car), only require 7 damaged party documents - * Otherwise, require all 12 documents (7 damaged + 5 guilty party) - */ - private getRequiredDocumentTypes( - claimRequest: any, - ): ClaimRequiredDocumentType[] { - const allTypes = Object.values(ClaimRequiredDocumentType).filter( - (type) => type !== ClaimRequiredDocumentType.ACCIDENT_SKETCH, - ); - - // Check if it's CAR_BODY type - const isCarBody = claimRequest.blameFile?.type === "CAR_BODY"; - - if (isCarBody) { - // Accident with object (not another car): v2 uses parties[0].carBodyFirstForm.object, v1 uses carBodyForm.carBodyForm.car === false - const firstPartyCarBody = - claimRequest.blameFile?.parties?.[0]?.carBodyFirstForm; - const isAccidentWithOtherObject = - (firstPartyCarBody && firstPartyCarBody.object === true) || - claimRequest.blameFile?.carBodyForm?.carBodyForm?.car === false || - !claimRequest.blameFile?.secondPartyDetails?.secondPartyCarDetail; - - if (isAccidentWithOtherObject) { - this.logger.debug( - `[getRequiredDocumentTypes] CAR_BODY claim with other object detected. ` + - `Requiring only 7 damaged party documents for claim ${claimRequest._id}`, - ); - // Only require damaged party documents (7 documents) - return allTypes.filter((type) => type.startsWith("damaged_")); - } - } - - // Default: require all 12 documents - return allTypes; - } - - async uploadRequiredDocument( - requestId: string, - documentType: ClaimRequiredDocumentType, - file: Express.Multer.File, - actor: any, - ) { - try { - const claimRequest = await this.claimDbService.findOne(requestId); - if (!claimRequest) { - throw new NotFoundException("Claim file not found"); - } - - // Verify access: user must own the claim, or expert must be accessing IN_PERSON file - const effectiveUserId = await this.getEffectiveUserId(requestId, actor); - if (String(claimRequest.userId) !== effectiveUserId) { - throw new ForbiddenException( - "You do not have access to this claim file", - ); - } - - if ( - String(claimRequest.blameFile.expertSubmitReply?.guiltyUserId) === - effectiveUserId - ) { - throw new ForbiddenException( - "User access denied. You are the guilty party in the blame file.", - ); - } - - if (claimRequest.currentStep !== ClaimStepsEnum.UploadRequiredDocuments) { - throw new BadRequestException( - `Claim is not in the required documents upload step. Current step: ${claimRequest.currentStep}`, - ); - } - - if (!file) { - throw new BadRequestException("File is required"); - } - - // Check if this document type has already been uploaded - const existingDocuments = - await this.claimRequiredDocumentDbService.findAll({ - claimId: new Types.ObjectId(requestId), - documentType: documentType, - }); - - // If document exists, delete the old one first (allow replacement) - if (existingDocuments.length > 0) { - for (const existingDoc of existingDocuments) { - // Delete the file from filesystem - try { - if (existingDoc.path && existsSync(existingDoc.path)) { - await unlink(existingDoc.path); - this.logger.log( - `Deleted old file: ${existingDoc.path} for document type ${documentType}`, - ); - } - } catch (fileError) { - this.logger.warn( - `Failed to delete file ${existingDoc.path}: ${fileError instanceof Error ? fileError.message : String(fileError)}`, - ); - // Continue even if file deletion fails - } - - // Delete from the separate collection - await this.claimRequiredDocumentDbService.delete( - existingDoc._id.toString(), - ); - // Remove from claim's requiredDocuments map - await this.claimDbService.findOneAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { - $unset: { - [`requiredDocuments.${documentType}`]: "", - }, - }, - ); - } - } - - // Create the document record - const documentRecord = await this.claimRequiredDocumentDbService.create({ - path: file.path, - fileName: file.filename, - claimId: new Types.ObjectId(requestId), - documentType: documentType, - uploadedAt: new Date(), - }); - - // Add document ID to claim's requiredDocuments map using documentType as key - await this.claimDbService.findOneAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { - $set: { - [`requiredDocuments.${documentType}`]: documentRecord._id, - }, - }, - ); - - // Check if all required documents have been uploaded - // For CAR_BODY with other object, only require 7 documents instead of 12 - const allRequiredTypes = this.getRequiredDocumentTypes(claimRequest); - const uploadedDocuments = - await this.claimRequiredDocumentDbService.findAll({ - claimId: new Types.ObjectId(requestId), - }); - - const uploadedTypes = uploadedDocuments.map((doc) => doc.documentType); - const allUploaded = allRequiredTypes.every((type) => - uploadedTypes.includes(type), - ); - - // If all documents are uploaded, move to next step - if (allUploaded) { - await this.claimDbService.findAndUpdate(requestId, { - $set: { - currentStep: ClaimStepsEnum.UploadRequiredDocuments, - nextStep: ClaimStepsEnum.waitForDamageExpertComment, - claimStatus: ReqClaimStatus.UnChecked, - }, - $push: { - steps: ClaimStepsEnum.UploadRequiredDocuments, - }, - }); - } else { - // Ensure status is set when entering this step (first document upload) - const currentClaim = await this.claimDbService.findOne(requestId); - if ( - currentClaim?.claimStatus !== - ReqClaimStatus.UploadingRequiredDocuments - ) { - await this.claimDbService.findOneAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { - $set: { - currentStep: ClaimStepsEnum.UploadRequiredDocuments, - nextStep: ClaimStepsEnum.UploadRequiredDocuments, - claimStatus: ReqClaimStatus.UploadingRequiredDocuments, - }, - }, - ); - } - } - - return { - message: "Document uploaded successfully", - documentId: documentRecord._id, - documentType: documentType, - allDocumentsUploaded: allUploaded, - nextStep: allUploaded - ? ClaimStepsEnum.waitForDamageExpertComment - : null, - }; - } catch (error) { - this.logger.error( - `Error in uploadRequiredDocument: ${error instanceof Error ? error.message : String(error)}`, - error instanceof Error ? error.stack : undefined, - ); - throw error; - } - } - - async getRequiredDocumentsStatus(requestId: string) { - try { - const claimRequest = await this.claimDbService.findOne(requestId); - if (!claimRequest) { - throw new NotFoundException("Claim file not found"); - } - - // Get required document types based on claim type - const allRequiredTypes = this.getRequiredDocumentTypes(claimRequest); - const uploadedDocuments = - await this.claimRequiredDocumentDbService.findAll({ - claimId: new Types.ObjectId(requestId), - }); - - const uploadedTypes = uploadedDocuments.map((doc) => doc.documentType); - const status = allRequiredTypes.map((type) => { - const doc = uploadedDocuments.find((d) => d.documentType === type); - return { - documentType: type, - uploaded: !!doc, - documentId: doc?._id || null, - fileName: doc?.fileName || null, - uploadedAt: doc?.uploadedAt || null, - }; - }); - - return { - claimId: requestId, - currentStep: claimRequest.currentStep, - nextStep: claimRequest.nextStep, - allUploaded: allRequiredTypes.every((type) => - uploadedTypes.includes(type), - ), - documents: status, - totalRequired: allRequiredTypes.length, - totalUploaded: uploadedDocuments.length, - }; - } catch (error) { - this.logger.error( - `Error in getRequiredDocumentsStatus: ${error instanceof Error ? error.message : String(error)}`, - error instanceof Error ? error.stack : undefined, - ); - throw error; - } - } - - async getImageRequiredList(requestId: string) { - return await new Promise((resolve, reject) => { - this.claimDbService - .findOne(requestId) - .then((cl) => { - if (!cl) { - throw new HttpException( - "Claim File Not Found", - HttpStatus.NOT_FOUND, - ); - } - - // Allow access if: - // 1. Currently in ImageRequired step (currentStep or nextStep is ImageRequired) - // 2. OR has completed ImageRequired and moved to next step (to allow viewing data after completion) - const isInImageRequiredStep = - cl.currentStep === ClaimStepsEnum.ImageRequired || - cl.nextStep === ClaimStepsEnum.ImageRequired; - - const hasCompletedImageRequired = - cl.steps && - Array.isArray(cl.steps) && - cl.steps.includes(ClaimStepsEnum.ImageRequired); - - if (isInImageRequiredStep || hasCompletedImageRequired) { - this.logger.debug( - `[getImageRequiredList] Allowing access for claim ${requestId}. ` + - `currentStep: ${cl.currentStep}, nextStep: ${cl.nextStep}, ` + - `hasCompletedImageRequired: ${hasCompletedImageRequired}`, - ); - if ( - cl.imageRequired.aroundTheCar && - Array.isArray(cl.imageRequired.aroundTheCar) - ) { - cl.imageRequired.aroundTheCar.forEach((carPart) => { - //@ts-ignore - delete carPart?.aiReport; - }); - cl.imageRequired.selectPartOfCar.forEach((part) => { - delete part.aiReport; - }); - } - resolve(new ImageRequiredDto(cl)); - } else { - this.logger.warn( - `[getImageRequiredList] Access denied for claim ${requestId}. ` + - `currentStep: ${cl.currentStep}, nextStep: ${cl.nextStep}, ` + - `steps: ${JSON.stringify(cl.steps)}`, - ); - throw new HttpException( - "This File is Not in ImageRequired Step", - HttpStatus.FORBIDDEN, - ); - } - }) - .catch((er) => { - this.logger.error(er); - if (er instanceof Error) { - reject(er); - } else { - reject(new Error(`Promise rejected with non-error value: ${er}`)); - } - }); - }); - } - - async setImageRequiredList( - requestId: string, - partOfDamageId: string, - fileDetail: any, - ) { - try { - const document = await this.claimDbService.findOneDocument(requestId); - - if (!document) { - throw new HttpException("Claim file not found", HttpStatus.NOT_FOUND); - } - - let result = []; - const imageRequiredKeys = Object.keys(document.imageRequired); - - if (partOfDamageId === undefined) { - if (document.videoCaptureId) { - throw new HttpException("Video already exists", HttpStatus.CONFLICT); - } - - const videoId = await this.createVideoCapture(fileDetail, requestId); - await this.updateClaimWithVideoCapture(requestId, videoId); - throw new HttpException("Video capture uploaded", HttpStatus.ACCEPTED); - } else if (partOfDamageId) { - await this.processDamageImages( - document, - requestId, - partOfDamageId, - fileDetail, - imageRequiredKeys, - result, - ); - result.forEach((item) => { - if (item.aroundTheCar && Array.isArray(item.aroundTheCar)) { - item.aroundTheCar.forEach((carPart) => { - delete carPart.aiReport; - }); - item.selectPartOfCar.forEach((part) => { - delete part.aiReport; - }); - } - }); - } - - return result; - } catch (error) { - this.handleError(error); - } - } - - async setDamageImage( - requestId: string, - partOfDamageId: string, - fileDetail: Express.Multer.File, - ) { - try { - const document = await this.claimDbService.findOneDocument(requestId); - if (!document) { - throw new HttpException("Claim file not found", HttpStatus.NOT_FOUND); - } - if (!fileDetail) { - throw new BadRequestException("Image file is required."); - } - - if ( - document.currentStep !== ClaimStepsEnum.ImageRequired && - document.nextStep !== ClaimStepsEnum.ImageRequired - ) { - throw new BadRequestException( - `Claim is not in the ImageRequired step. Current step: ${document.currentStep}, Status: ${document.claimStatus}`, - ); - } - - const result = []; - const imageRequiredKeys = Object.keys(document.imageRequired); - - // Process images - AI will be processed in background - await this.processDamageImages( - document, - requestId, - partOfDamageId, - fileDetail, - imageRequiredKeys, - result, - ); - - // Clean up the response - remove AI reports since they're processing in background - result.forEach((item) => { - if (item.aroundTheCar && Array.isArray(item.aroundTheCar)) { - item.aroundTheCar.forEach((carPart) => delete carPart.aiReport); - item.selectPartOfCar.forEach((part) => delete part.aiReport); - } - }); - - this.logger.log( - `[setDamageImage] Image uploaded successfully for part ${partOfDamageId}, request ${requestId}. AI processing started in background.`, - ); - - return result; - } catch (error) { - this.handleError(error); - } - } - - async setVideoCapture(requestId: string, fileDetail: Express.Multer.File) { - try { - const document = await this.claimDbService.findOneDocument(requestId); - if (!document) { - throw new HttpException("Claim file not found", HttpStatus.NOT_FOUND); - } - if (!fileDetail) { - throw new BadRequestException("Video file is required."); - } - if (document.videoCaptureId) { - throw new HttpException( - "A video has already been uploaded for this claim.", - HttpStatus.CONFLICT, - ); - } - - const videoId = await this.createVideoCapture(fileDetail, requestId); - await this.updateClaimWithVideoCapture(requestId, videoId); - - return { - statusCode: HttpStatus.ACCEPTED, - message: "Video capture uploaded successfully.", - videoId: videoId, - }; - } catch (error) { - this.handleError(error); - } - } - private async createVideoCapture(fileDetail: any, requestId: string) { const videoId = await this.videoCaptureDbService.create({ path: fileDetail.path, @@ -2098,340 +1287,6 @@ export class ClaimRequestManagementService { return videoId; } - private async updateClaimWithVideoCapture(requestId: string, videoId: any) { - if ( - await this.claimDbService.findOneAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { - $set: { videoCaptureId: videoId }, - }, - ) - ) { - throw new HttpException("Video capture uploaded", HttpStatus.ACCEPTED); - } - } - - private async processDamageImages( - document: any, - requestId: string, - partOfDamageId: string, - fileDetail: any, - imageRequiredKeys: string[], - result: any[], - ) { - for (const key of imageRequiredKeys) { - const images = document.imageRequired[key]; - for (const img of images) { - if (img.partId === partOfDamageId) { - const newImageDoc = await this.createDamageImage( - fileDetail, - requestId, - ); - - // Update the document immediately with the uploaded image - await this.updateImageRequiredDocument( - requestId, - key, - partOfDamageId, - newImageDoc, - ); - if (key === "selectPartOfCar") { - await this.aiService.enqueue(requestId, newImageDoc); - } - const updatedDocs = - await this.claimDbService.findOneDocument(requestId); - this.handleImageUpdateResult(result, updatedDocs, requestId); - } - } - } - - } - - private async updateImageRequiredDocument( - requestId, - key, - partOfDamageId, - newImageDoc, - ) { - await this.claimDbService.findOneAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { - $set: { - [`imageRequired.${key}.$[elem].upload`]: true, - [`imageRequired.${key}.$[elem].imageId`]: newImageDoc._id, - }, - }, - { - arrayFilters: [{ "elem.partId": partOfDamageId }], - }, - ); - } - - private async createDamageImage(fileDetail, requestId) { - return await this.damageImageDbService.create({ - path: fileDetail.path, - fileName: fileDetail.filename, - claimId: requestId, - }); - } - - private async handleImageUpdateResult(result, updatedDocs, requestId) { - const aroundCarChecked = updatedDocs.imageRequired.aroundTheCar.filter( - (r) => !r.upload, - ); - const selectPartOfCar = updatedDocs.imageRequired.selectPartOfCar.filter( - (r) => !r.upload, - ); - - result.push(updatedDocs.imageRequired); - if (aroundCarChecked.length === 0 && selectPartOfCar.length === 0) { - await this.claimDbService.findOneAndUpdate( - { _id: new Types.ObjectId(requestId) }, - { - $push: { - steps: ClaimStepsEnum.ImageRequired, - }, - $set: { - currentStep: ClaimStepsEnum.UploadRequiredDocuments, - nextStep: ClaimStepsEnum.UploadRequiredDocuments, - claimStatus: ReqClaimStatus.UploadingRequiredDocuments, - }, - }, - ); - } - } - - async myRequests(currentUser) { - // For users, return their own claim files - if (currentUser.role === RoleEnum.USER) { - const claimFile = await this.claimDbService.findAllByAnyFilter({ - userId: new Types.ObjectId(currentUser.sub), - }); - if (!claimFile) throw new NotFoundException("claim file not found"); - return new MyRequestsDto(claimFile); - } - - // For experts, return IN_PERSON claim files they initiated - const expertRoles = [ - RoleEnum.EXPERT, - RoleEnum.DAMAGE_EXPERT, - RoleEnum.FIELD_EXPERT, - ]; - if (expertRoles.includes(currentUser.role)) { - const allClaims = await this.claimDbService.findAllByAnyFilter({}); - const expertClaims = allClaims.filter((claim) => { - const blameFile = claim.blameFile; - return ( - blameFile?.expertInitiated && - blameFile?.creationMethod === "IN_PERSON" && - String(blameFile.initiatedBy) === currentUser.sub - ); - }); - if (expertClaims.length === 0) { - throw new NotFoundException("No IN_PERSON claim files found"); - } - return new MyRequestsDto(expertClaims); - } - - throw new ForbiddenException("Invalid role"); - } - - private waitingForUserResendRS(req: ClaimRequestManagementModel) { - if (req.damageExpertResend) { - return new ClaimRequestDtoRs( - req.damageExpertResend as any, - "این درخواست نیاز به ارسال مدارک مجدد دارد ", - ReqClaimStatus.WaitingForUserToResend, - ); - } else { - throw new ForbiddenException("damageExpertResend doesnt exist"); - } - } - - private closeRequestRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "این درخواست بسته شده است ", - ReqClaimStatus.CloseRequest, - ); - } - - private checkAgainRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "در انتظار پاسخ مجدد کارشناس", - ReqClaimStatus.CheckAgain, - ); - } - - private userPendingRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "این پرونده از طرف شما کامل نشده میباشد", - ReqClaimStatus.UserPending, - ); - } - - private reviewRequestRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - `درخواست درحال برسی توسط کارشناس میباشد ${req.unlockTime} - زمان باقی مانده لطفا صبر کنید`, - ReqClaimStatus.ReviewRequest, - ); - } - - private checkedRequestRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "این درخواست بررسی شده است", - ReqClaimStatus.CheckedRequest, - ); - } - - private uncheckedRequestRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "این درخواست در انتظار بررسی می باشد.", - ReqClaimStatus.UnChecked, - ); - } - - private waitingForUserCompletedRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "این درخواست نیازمند تکمیل توسط کاربر می باشد.", - ReqClaimStatus.WaitingForUserCompleted, - ); - } - - private inPersonVisitRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "مراجعه حضوری", - ReqClaimStatus.InPersonVisit, - ); - } - - private responseController(request: ClaimRequestManagementModel) { - switch (request.claimStatus) { - case ReqClaimStatus.WaitingForUserCompleted: - return this.waitingForUserCompletedRS(request); - case ReqClaimStatus.UnChecked: - return this.uncheckedRequestRS(request); - case ReqClaimStatus.CheckedRequest: - return this.checkedRequestRS(request); - case ReqClaimStatus.ReviewRequest: - return this.reviewRequestRS(request); - case ReqClaimStatus.UserPending: - return this.userPendingRS(request); - case ReqClaimStatus.CloseRequest: - return this.closeRequestRS(request); - case ReqClaimStatus.WaitingForUserToResend: - return this.waitingForUserResendRS(request); - case ReqClaimStatus.CheckAgain: - return this.checkAgainRS(request); - case ReqClaimStatus.InPersonVisit: - return this.inPersonVisitRS(request); - case ReqClaimStatus.PendingFactorValidation: - return this.pendingFactorValidationRS(request); - case ReqClaimStatus.FactorRejected: - return this.factorRejectedRS(request); - case ReqClaimStatus.PendingFactorUpload: - return this.pendingFactorUploadRS(request); - case ReqClaimStatus.UploadingRequiredDocuments: - return this.uploadingRequiredDocumentsRS(request); - default: - return "Unknown status"; - } - } - - private pendingFactorUploadRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "منتظر آپلود فاکتور توسط کاربر", - ReqClaimStatus.PendingFactorUpload, - ); - } - - private pendingFactorValidationRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "منتظر تایید فاکتور توسط کارشناس", - ReqClaimStatus.PendingFactorValidation, - ); - } - - private factorRejectedRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "فاکتور ریجکت شده و باید دوباره ارسال شود", - ReqClaimStatus.FactorRejected, - ); - } - - private uploadingRequiredDocumentsRS(req: ClaimRequestManagementModel) { - return new ClaimRequestDtoRs( - req, - "منتظر آپلود مدارک مورد نیاز توسط کاربر", - ReqClaimStatus.UploadingRequiredDocuments, - ); - } - - async requestDetails(requestId: string, user?: any) { - const request = await this.claimDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Claim request not found"); - } - - // Verify access if user is provided - if (user) { - const effectiveUserId = await this.getEffectiveUserId(requestId, user); - if (String(request.userId) !== effectiveUserId) { - throw new ForbiddenException( - "You do not have access to this claim file", - ); - } - } - - if (request.imageRequired) { - request.imageRequired.selectPartOfCar.forEach((r) => { - delete r.aiReport; - }); - - request.imageRequired.aroundTheCar.forEach((r) => { - //@ts-ignore - delete r.aiReport; - }); - } - - // Populate factorLink ObjectIds with actual file URLs - await this.populateFactorLinks(request.damageExpertReply); - await this.populateFactorLinks(request.damageExpertReplyFinal); - - return this.responseController(request); - } - - /** - * Converts factorLink ObjectIds to file URLs - */ - private async populateFactorLinks(reply: any): Promise { - if (!reply || !Array.isArray(reply.parts)) { - return; - } - - for (const part of reply.parts) { - if (part.factorLink && Types.ObjectId.isValid(part.factorLink)) { - const factorDoc = await this.claimFactorsImageDbService.findById( - part.factorLink.toString(), - ); - - if (factorDoc) { - part.factorLink = buildFileLink(factorDoc.path); - } - } - } - } - /** * V2 response mapper: * - convert factorLink ObjectId -> public URL @@ -2531,7 +1386,11 @@ export class ClaimRequestManagementService { ? objectionRaw.toObject() : { ...objectionRaw } : undefined; - if (objection && Array.isArray(objection.invoices) && objection.invoices.length > 0) { + if ( + objection && + Array.isArray(objection.invoices) && + objection.invoices.length > 0 + ) { objection = { ...objection, invoices: objection.invoices.map((inv: any) => ({ @@ -2549,321 +1408,6 @@ export class ClaimRequestManagementService { }; } - // async submitUserReply( - // requestId: string, - // body: UserCommentDto, - // file?: Express.Multer.File, - // actor?: any, - // ) { - // try { - // const request = await this.claimDbService.findOne(requestId); - - // if (!this.isValidRequest(request)) { - // throw new HttpException("Invalid request", HttpStatus.NOT_ACCEPTABLE); - // } - - // // Verify access if actor is provided - // if (actor) { - // const effectiveUserId = await this.getEffectiveUserId(requestId, actor); - // if (String(request.userId) !== effectiveUserId) { - // throw new ForbiddenException( - // "You do not have access to this claim file", - // ); - // } - // } - - // const finalReply = - // request.damageExpertReplyFinal || request.damageExpertReply; - - // const replyFieldKey = request.damageExpertReplyFinal - // ? "damageExpertReplyFinal" - // : "damageExpertReply"; - - // const parts = finalReply?.parts || []; - // const missingFactors = parts - // .filter((p) => p.factorNeeded === true && !p.factorLink) - // .map( - // (p) => carPartDamageLabelForFactorRecord(p.carPartDamage) || p.partId, - // ); - - // if (missingFactors.length > 0) { - // throw new HttpException( - // `Missing factor images for parts: ${missingFactors.join(", ")}`, - // HttpStatus.BAD_REQUEST, - // ); - // } - - // const userComment = { - // ...body, - // ...(file ? { fileLink: buildFileLink(file.path) } : {}), - // }; - - // await this.claimDbService.findAndUpdate(requestId, { - // $set: { - // [`${replyFieldKey}.userComment`]: { - // ...userComment, - // time: Date.now(), - // }, - // }, - // }); - - // if (body.isAccept) { - // const { partsFactorDetail, partsNeedFactor } = - // await this.processAcceptance(request, file, requestId, body); - - // await this.claimDbService.findAndUpdate(requestId, { - // $set: { - // claimStatus: ReqClaimStatus.CloseRequest, - // }, - // }); - - // return new SubmitUserReplyDtoRs( - // request, - // partsFactorDetail, - // partsNeedFactor, - // ); - // } else { - // this.handleRejection(request, body.isAccept, requestId); - // return { requestId, isAccept: body.isAccept }; - // } - // } catch (error) { - // this.handleError(error); - // } - // } - - private isValidRequest(request: any): boolean { - return ( - request.damageExpertReply && - request.claimStatus === ReqClaimStatus.CheckedRequest - ); - } - - // private async processAcceptance( - // request: any, - // file: any, - // requestId: string, - // body: UserCommentDto, - // ): Promise<{ partsFactorDetail: any[]; partsNeedFactor: boolean }> { - // const partsFactorDetail = []; - // let partsNeedFactor = false; - - // for (let i = 0; i < request.damageExpertReply.parts.length; i++) { - // const part = request.damageExpertReply.parts[i]; - - // if (!part || part.partCost === undefined) continue; - - // if (part.partCost === "FACTOR") { - // partsNeedFactor = await this.handleFactorPart( - // requestId, - // i, - // part, - // partsFactorDetail, - // partsNeedFactor, - // ); - // } else { - // await this.handleNonFactorPart(requestId, file, body.isAccept, part); - // } - // } - - // return { partsFactorDetail, partsNeedFactor }; - // } - - // private async handleFactorPart( - // requestId: string, - // i: number, - // part: any, - // partsFactorDetail: any[], - // partsNeedFactor: boolean, - // ): Promise { - // if (part.needFactor === undefined) { - // const uId = uuidv4(); - // partsNeedFactor = true; - - // await this.claimDbService.findAndUpdate(requestId, { - // $set: { - // [`damageExpertReply.parts.${i}.needFactor`]: true, - // [`damageExpertReply.parts.${i}.partId`]: uId, - // }, - // }); - - // partsFactorDetail.push({ partId: uId, ...part }); - // } else { - // partsFactorDetail.push(part); - // } - - // return partsNeedFactor; - // } - - // private async handleNonFactorPart( - // requestId: string, - // file: any, - // isAccept: boolean, - // part: any, - // ): Promise { - // const sign = await this.claimSignDbService.create(file); - - // await this.claimDbService.findAndUpdate(requestId, { - // $set: { - // "damageExpertReply.userComment.isAccept": isAccept, - // "damageExpertReply.userComment.signId": sign["_id"], - // }, - // }); - // } - - private async handleRejection( - request: any, - isAccept: boolean, - requestId: string, - ): Promise { - await this.claimDbService.findAndUpdate(requestId, { - $set: { - "damageExpertReply.userComment.isAccept": isAccept, - "damageExpertReply.userComment.signId": null, - }, - }); - } - - /** - * Allows the damaged user to rate their claim file after completion. - * Only the claim owner (damaged user) can submit this rating and only - * when the claim is in CloseRequest status. - */ - async addUserRating( - claimRequestId: string, - actor: any, - ratingDto: UserRatingDto, - ): Promise { - const claim = await this.claimDbService.findOne(claimRequestId); - - if (!claim) { - throw new NotFoundException("Claim file not found"); - } - - // Only the damaged user (claim owner) can rate the claim - const actorId = actor?.sub; - if (!actorId || String(claim.userId) !== actorId) { - throw new ForbiddenException( - "Only the claim owner can submit a satisfaction rating.", - ); - } - - // Rating is only allowed after the claim is fully closed - if (claim.claimStatus !== ReqClaimStatus.CloseRequest) { - throw new BadRequestException( - "You can only rate a claim after it has been closed.", - ); - } - - const userRating: UserClaimRating = { - progressSpeed: ratingDto.progressSpeed, - registrationEase: ratingDto.registrationEase, - overallEvaluation: ratingDto.overallEvaluation, - comment: ratingDto.comment, - createdAt: new Date(), - }; - - await this.claimDbService.findAndUpdate(claimRequestId, { - $set: { userRating }, - }); - - return userRating; - } - - async uploadClaimFactor( - claimId: string, - partId: string, - file: Express.Multer.File, - actor: any, - ) { - try { - if (!file) { - throw new BadRequestException("A factor file is required for upload."); - } - - const claim = await this.claimRequestManagementDbService.findOne(claimId); - if (!claim) { - throw new NotFoundException("Claim not found"); - } - - // Verify access: user must own the claim, or expert must be accessing IN_PERSON file - const effectiveUserId = await this.getEffectiveUserId(claimId, actor); - if (String(claim.userId) !== effectiveUserId) { - throw new ForbiddenException( - "You do not have access to this claim file", - ); - } - - const finalReply = - claim.damageExpertReplyFinal || claim.damageExpertReply; - const replyFieldKey = claim.damageExpertReplyFinal - ? "damageExpertReplyFinal" - : "damageExpertReply"; - - if (!finalReply) { - throw new BadRequestException("No expert reply found in this claim."); - } - - const part = finalReply.parts?.find((p) => p.partId === String(partId)); - if (!part) { - throw new BadRequestException( - "The specified part was not found in the expert's reply.", - ); - } - - const factorRecord = await this.claimFactorsImageDbService.create({ - claimId, - partId, - partName: carPartDamageLabelForFactorRecord(part.carPartDamage), - path: file.path, - fileName: file.filename, - uploadedAt: new Date(), - }); - - const updatedClaim = - await this.claimRequestManagementDbService.findOneAndUpdate( - { - _id: new Types.ObjectId(claimId), - [`${replyFieldKey}.parts.partId`]: partId, - }, - { - $set: { - [`${replyFieldKey}.parts.$.factorLink`]: factorRecord._id, - [`${replyFieldKey}.parts.$.factorStatus`]: FactorStatus.PENDING, - }, - }, - ); - - if (!updatedClaim) { - throw new NotFoundException( - "Could not find the specific part to update in the database.", - ); - } - - await this.checkAndTransitionStatusAfterUpload(claimId); - - return { - message: "Factor uploaded successfully. Awaiting expert validation.", - factorId: factorRecord._id, - factorLink: buildFileLink(file.path), - url: buildFileLink(file.path), - }; - } catch (error) { - this.logger.error( - `Error during factor upload for claim ${claimId}:`, - error instanceof Error ? error.stack : String(error), - ); - - if (error instanceof HttpException) { - throw error; - } - - throw new HttpException( - "An internal server error occurred during factor upload.", - HttpStatus.INTERNAL_SERVER_ERROR, - ); - } - } - /** * V2: Upload repair factor file for a part marked `factorNeeded` on the expert reply (ClaimCase). * Same behavior as v1 {@link uploadClaimFactor} but uses `evaluation.damageExpertReply` / `damageExpertReplyFinal`. @@ -3072,92 +1616,6 @@ export class ClaimRequestManagementService { }); } - private async checkAndTransitionStatusAfterUpload( - claimId: string, - ): Promise { - // Re-fetch the latest state of the claim - const claim = await this.claimRequestManagementDbService.findOne(claimId); - const finalReply = claim.damageExpertReplyFinal || claim.damageExpertReply; - - if (!finalReply?.parts) { - return; - } - - const requiredFactorParts = finalReply.parts.filter( - (p) => p.factorNeeded === true, - ); - - if (requiredFactorParts.length === 0) { - return; - } - - const allFactorsAreUploaded = requiredFactorParts.every( - (p) => !!p.factorLink, - ); - - if (allFactorsAreUploaded) { - this.logger.log( - `All required factors for claim ${claimId} have been uploaded. Updating status.`, - ); - await this.claimRequestManagementDbService.findByIdAndUpdate(claimId, { - $set: { - claimStatus: ReqClaimStatus.PendingFactorValidation, - }, - }); - } - } - - private async resendDocumentsController(claimFile, query, file) { - if (!Object.keys(query).includes("documentName")) { - throw new HttpException("use documentName", HttpStatus.BAD_REQUEST); - } - - const fileRequired = claimFile.damageExpertResend.resendDocuments; - if (!fileRequired.includes(query.documentName)) { - throw new HttpException("wrong required file", HttpStatus.BAD_REQUEST); - } - - try { - const updated = await this.claimRequestManagementDbService.findAndUpdate( - String(claimFile._id), - { - $push: { - "userResendDocuments.documents": { - [query.documentName]: buildFileLink(file.path), - }, - }, - }, - { new: true }, - ); - - const existingKeys = updated.userResendDocuments.documents.flatMap( - Object.keys, - ); - const allExist = fileRequired.every((key) => existingKeys.includes(key)); - - if (allExist) { - await this.claimRequestManagementDbService.findAndUpdate( - String(claimFile._id), - { $set: { claimStatus: ReqClaimStatus.CheckAgain } }, - ); - } - - return { - allExist, - updated: updated.userResendDocuments.documents, - fileRequired, - }; - } catch (err) { - this.logger.error(err); - return new HttpException( - err instanceof HttpException ? err.message : String(err), - err instanceof HttpException - ? err.getStatus() - : HttpStatus.INTERNAL_SERVER_ERROR, - ); - } - } - private async resendCarParts(claimFile, query, file) { if (!Object.keys(query).includes("partId")) { throw new HttpException( @@ -3222,115 +1680,10 @@ export class ClaimRequestManagementService { } } - async resendFiles(claimId, file, query, actor) { - let claimFile = await this.claimRequestManagementDbService.findOne(claimId); - if (!claimFile) { - throw new NotFoundException("Claim file not found"); - } - - // Verify access: user must own the claim, or expert must be accessing IN_PERSON file - const effectiveUserId = await this.getEffectiveUserId(claimId, actor); - if (String(claimFile.userId) !== effectiveUserId) { - throw new ForbiddenException("You do not have access to this claim file"); - } - - switch (query.fields) { - case "resendDocuments": - return this.resendDocumentsController(claimFile, query, file); - case "resendCarParts": - return this.resendCarParts(claimFile, query, file); - default: - return new HttpException("wrong query string", HttpStatus.BAD_REQUEST); - } - } - - async handleUserObjectionAndParts( - claimRequestId: string, - userObjectionDto: UserObjectionDto, - ) { - const claimRequest = await this.claimDbService.findOne(claimRequestId); - if (!claimRequest) { - throw new NotFoundException("Claim request not found"); - } - - if ( - claimRequest.claimStatus !== ReqClaimStatus.WaitingForUserToResend && - claimRequest.claimStatus !== ReqClaimStatus.CheckedRequest - ) { - throw new BadRequestException( - "درخواست شما در این حالت نمی تواند انجام شود", - ); - } - - if (claimRequest.objection) - throw new BadRequestException("Objection already exists!"); - - const updatePayload: any = { - objection: userObjectionDto, - }; - - if (userObjectionDto.newParts?.length) { - const newPartsWithIds = userObjectionDto.newParts.map((part) => ({ - ...part, - partId: part.partId || new Types.ObjectId(), - })); - - updatePayload["newParts"] = newPartsWithIds; - } - - const updated = await this.claimDbService.findAndUpdate( - claimRequestId, - { - ...updatePayload, - claimStatus: ReqClaimStatus.CheckAgain, - }, - { new: true }, - ); - - return updated.objection; - } - - async inPersonVisit(requestId: string, actorDetail: any) { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Claim not found"); - } - - const updated = await this.claimRequestManagementDbService.findAndUpdate( - requestId, - { - claimStatus: ReqClaimStatus.InPersonVisit, - }, - ); - - if ( - Types.ObjectId.isValid(String(actorDetail.sub)) && - Types.ObjectId.isValid(String(request.userClientKey)) && - Types.ObjectId.isValid(String(requestId)) - ) { - await this.expertFileActivityDbService.recordEvent({ - expertId: String(actorDetail.sub), - tenantId: String(request.userClientKey), - fileId: String(requestId), - fileType: ExpertFileKind.CLAIM, - eventType: ExpertFileActivityType.HANDLED, - idempotencyKey: `claim:${requestId}:handled:inperson:${actorDetail.sub}`, - }); - } - - return updated; - } - async retrieveInsuranceBranches(insuranceId: string) { return await this.branchDbService.findAll(insuranceId); } - private handleError(error) { - this.logger.error(error); - throw error; - } - /** * Convert Gregorian date to Persian date format (1404/08/13) */ @@ -3375,32 +1728,6 @@ export class ClaimRequestManagementService { return `${hours}:${minutes}`; } - /** - * Call reverse geocoding API to get address from lat/lon - */ - private async getAddressFromCoordinates( - lat: number, - lon: number, - ): Promise { - try { - const response = await firstValueFrom( - this.httpService.get( - `https://map.ir/fast-reverse?lat=${lat}&lon=${lon}`, - { - headers: { - accept: "application/json", - "x-api-key": this.MAP_IR_API_KEY, - }, - }, - ), - ); - return response.data?.address_compact || ""; - } catch (error) { - this.logger.error("Failed to get address from coordinates", error); - return ""; - } - } - /** * Calculate EstimateAmount from damageExpertReply parts */ @@ -3420,28 +1747,13 @@ export class ClaimRequestManagementService { return amount > 0 ? amount : FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT; } - private getTejaratnoFanavaranConfig() { - return { - appName: this.APP_NAME, - secret: this.SECRET, - username: this.USERNAME, - password: this.PASSWORD, - corpId: this.CORP_ID, - contractId: this.CONTRACT_ID, - location: this.LOCATION, - }; - } - /** * Extract digits-only licence number from a possibly-null/empty value. * Returns `null` when the value is "null", "undefined", "", '' or whitespace. */ - private extractNonEmptyLicenceDigits( - value: unknown, - ): string | null { + private extractNonEmptyLicenceDigits(value: unknown): string | null { if (value === null || value === undefined) return null; - const asString = - typeof value === "number" ? String(value) : String(value); + const asString = typeof value === "number" ? String(value) : String(value); const trimmed = asString.trim(); if (!trimmed) return null; const lowered = trimmed.toLowerCase(); @@ -3623,7 +1935,10 @@ export class ClaimRequestManagementService { const normalized = this.plateNormalizer.normalizePlateText(raw); const asNumber = Number(normalized); if (Number.isFinite(asNumber)) return asNumber; - return this.plateNormalizer.resolvePlateLetterCode(normalized, FANAVARAN_PLATE_LETTER_CODE); + return this.plateNormalizer.resolvePlateLetterCode( + normalized, + FANAVARAN_PLATE_LETTER_CODE, + ); } private formatFanavaranPlateNo( @@ -3793,7 +2108,10 @@ export class ClaimRequestManagementService { this.logger.log( `VIN inquiry ${vin} VehicleId=${pickVehicleId(vehicle) ?? "none"} VehicleKindId=${parseFanavaranId(vehicle.VehicleKindId) ?? "none"} UsedId=${parseFanavaranId(vehicle.UsedId) ?? "none"} PlaqueKindId=${parseFanavaranId(vehicle.PlaqueKindId) ?? "none"}`, ); - return this.resolveAccidentVehicleUsedFromVehicleRecord(clientKey, vehicle); + return this.resolveAccidentVehicleUsedFromVehicleRecord( + clientKey, + vehicle, + ); } catch (error) { this.logger.warn( `Failed to resolve AccidentVehicleUsedId from VIN=${vin}: ${ @@ -3951,7 +2269,10 @@ export class ClaimRequestManagementService { this.logger.log( `Policy ${policyId} VehicleId=${vehicleId} version=${versionNo ?? "latest"} VehicleKindId=${parseFanavaranId(vehicle?.VehicleKindId) ?? "none"} UsedId=${parseFanavaranId(vehicle?.UsedId) ?? "none"}`, ); - return this.resolveAccidentVehicleUsedFromVehicleRecord(clientKey, vehicle); + return this.resolveAccidentVehicleUsedFromVehicleRecord( + clientKey, + vehicle, + ); } catch (error) { this.logger.warn( `Failed to resolve AccidentVehicleUsedId from PolicyId=${policyId}: ${ @@ -3975,7 +2296,8 @@ export class ClaimRequestManagementService { }> { const guiltyParty = (input.parties ?? []).find( (party: any) => - String(party?.person?.userId ?? "") === String(input.guiltyPartyId ?? ""), + String(party?.person?.userId ?? "") === + String(input.guiltyPartyId ?? ""), ); const vin = pickVinFromPartyVehicle(guiltyParty); @@ -4036,15 +2358,13 @@ export class ClaimRequestManagementService { ); try { - const response = await this.fanavaranLookupService.inquiryByUniqueIdentifier( - clientKey, - { + const response = + await this.fanavaranLookupService.inquiryByUniqueIdentifier(clientKey, { nationalCode, birthYear: parsed.year, birthMonth: parsed.month, birthDay: parsed.day, - }, - ); + }); this.logger.log( `[resolveDriverFanavaranId] RESPONSE: ${JSON.stringify(response)}`, @@ -4063,7 +2383,10 @@ export class ClaimRequestManagementService { this.logger.warn( `[resolveDriverFanavaranId] NO acceptable RoleId 161/166 for nationalCode=${nationalCode} driverIsInsurer=${driverIsInsurer}. ` + `Available entries: ${asPartyInquiryRows(response) - .map((e) => `{Id=${e.Id}, RoleId=${e.RoleId}, Name=${e.Name} ${e.LastName}}`) + .map( + (e) => + `{Id=${e.Id}, RoleId=${e.RoleId}, Name=${e.Name} ${e.LastName}}`, + ) .join("; ")} — submit will register GEN.44 other-people`, ); return null; @@ -4085,15 +2408,13 @@ export class ClaimRequestManagementService { const parsed = this.parseJalaliBirthday(birthday); if (!parsed) return null; try { - const response = await this.fanavaranLookupService.inquiryByUniqueIdentifier( - clientKey, - { + const response = + await this.fanavaranLookupService.inquiryByUniqueIdentifier(clientKey, { nationalCode, birthYear: parsed.year, birthMonth: parsed.month, birthDay: parsed.day, - }, - ); + }); const ownerId = selectFanavaranOwnerId(response); if (ownerId != null) { this.logger.log( @@ -4181,9 +2502,7 @@ export class ClaimRequestManagementService { const nationalCode = driverIdentity.nationalCode ?? pickPersonNationalCode(person) ?? - pickCarBodyPolicyNationalCode( - input.blameCase as { parties?: unknown[] }, - ); + pickCarBodyPolicyNationalCode(input.blameCase as { parties?: unknown[] }); const birthday = driverIdentity.birthday ?? pickPersonBirthday(person); let accidentCulpritId: number | null = null; @@ -4241,7 +2560,10 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, claimCase: { fanavaranSync?: { - baseClaim?: { policyId?: unknown; lastPayload?: { PolicyId?: unknown } }; + baseClaim?: { + policyId?: unknown; + lastPayload?: { PolicyId?: unknown }; + }; }; }, ): Promise { @@ -4252,16 +2574,12 @@ export class ClaimRequestManagementService { if (policyId == null) return null; try { const policy = asObjectRecord( - await this.fanavaranLookupService.bodyPolicyById( - clientKey, - policyId, - { - contractIdOverride: resolveFanavaranProductContractId( - clientKey, - "car-body", - ), - }, - ), + await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId, { + contractIdOverride: resolveFanavaranProductContractId( + clientKey, + "car-body", + ), + }), ); return vehicleCurrentValueFromHullPolicyRecord(policy); } catch (error) { @@ -4310,21 +2628,20 @@ export class ClaimRequestManagementService { ), }; - const [dmgKindRows, dmgCostKindRows, policyRecord] = - await Promise.all([ - this.getFanavaranLookupRows(input.clientKey, "vehicle-hull-dmg-kind"), - this.getFanavaranLookupRows( - input.clientKey, - "vehicle-hull-dmg-cost-kinds", - ), - policyId != null - ? this.fanavaranLookupService.bodyPolicyById( - input.clientKey, - policyId, - contractOptions, - ) - : Promise.resolve(null), - ]); + const [dmgKindRows, dmgCostKindRows, policyRecord] = await Promise.all([ + this.getFanavaranLookupRows(input.clientKey, "vehicle-hull-dmg-kind"), + this.getFanavaranLookupRows( + input.clientKey, + "vehicle-hull-dmg-cost-kinds", + ), + policyId != null + ? this.fanavaranLookupService.bodyPolicyById( + input.clientKey, + policyId, + contractOptions, + ) + : Promise.resolve(null), + ]); const dmgKindId = findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION) ?? @@ -4400,8 +2717,12 @@ export class ClaimRequestManagementService { vehicleCurrentValue = vehicleCurrentValueFromHullPolicyRecord(policy); } - vehicleCurrentValue = input.claimCase?.fanavaranFieldReview?.values?.VehicleCurrentValue ?? vehicleCurrentValue; - const repairDuration = input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ?? FANAVARAN_DEFAULT_HULL_REPAIR_DURATION; + vehicleCurrentValue = + input.claimCase?.fanavaranFieldReview?.values?.VehicleCurrentValue ?? + vehicleCurrentValue; + const repairDuration = + input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ?? + FANAVARAN_DEFAULT_HULL_REPAIR_DURATION; return { replyKey: input.replyKey, @@ -4515,20 +2836,23 @@ export class ClaimRequestManagementService { "ModelField", "ModelCii", ]); - const builtYearFromInquiry = builtYearRaw ? Number(builtYearRaw) || null : null; + const builtYearFromInquiry = builtYearRaw + ? Number(builtYearRaw) || null + : null; const damagedVin = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ "VIN", "vin", "VinNumberField", - ]) ?? collectPartyVinCandidates(damagedParty)[0] ?? + ]) ?? + collectPartyVinCandidates(damagedParty)[0] ?? null; - const damagedChassis = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "ShsNum", - "ChassisNumberField", - "shsNam", - ]); + const damagedChassis = this.pickPartyInquiryField( + inquiryMapped, + inquiryRaw, + ["ShsNum", "ChassisNumberField", "shsNam"], + ); const damagedIdentity: FanavaranDamagedVehicleIdentity = { vin: damagedVin, chassis: damagedChassis, @@ -4585,18 +2909,21 @@ export class ClaimRequestManagementService { const approvedVehicleKindId = this.firstPositiveFanavaranId( input.claimCase?.fanavaranVehicleReview?.vehicleKind?.id, ); - let vehicleKindId = approvedVehicleKindId ?? this.firstPositiveFanavaranId(apiVehicle?.VehicleKindId); - let vehicleKindSource: "expert-review" | "vehicle-inquiry" | "car-type-lookup" | null = + let vehicleKindId = + approvedVehicleKindId ?? + this.firstPositiveFanavaranId(apiVehicle?.VehicleKindId); + let vehicleKindSource: + | "expert-review" + | "vehicle-inquiry" + | "car-type-lookup" + | null = approvedVehicleKindId != null ? "expert-review" : parseFanavaranId(apiVehicle?.VehicleKindId) != null ? "vehicle-inquiry" : null; if (vehicleKindId == null) { - vehicleKindId = await this.resolveVehicleKindId( - input.clientKey, - carType, - ); + vehicleKindId = await this.resolveVehicleKindId(input.clientKey, carType); if (vehicleKindId != null) vehicleKindSource = "car-type-lookup"; } @@ -4617,7 +2944,9 @@ export class ClaimRequestManagementService { input.claimCase, ); } - let otherPersonId = this.firstPositiveFanavaranId(cachedDamage.otherPersonId); + let otherPersonId = this.firstPositiveFanavaranId( + cachedDamage.otherPersonId, + ); if (driverFanavaranId) { this.logger.log( @@ -4696,14 +3025,20 @@ export class ClaimRequestManagementService { if (driverFanavaranId && input.blameCase?._id && damagedParty) { const partyIndex = (input.blameCase.parties ?? []).findIndex( - (p: any) => p === damagedParty || + (p: any) => + p === damagedParty || String(p?.person?.userId ?? "") === String(damagedParty?.person?.userId ?? ""), ); if (partyIndex >= 0) { await this.blameRequestDbService.findByIdAndUpdate( String(input.blameCase._id), - { $set: { [`parties.${partyIndex}.person.fanavaranDriverId`]: driverFanavaranId } }, + { + $set: { + [`parties.${partyIndex}.person.fanavaranDriverId`]: + driverFanavaranId, + }, + }, ); this.logger.log( `[buildFanavaranDamageCasePayload] stored DriverId=${driverFanavaranId} on blameCase=${input.blameCase._id} party[${partyIndex}]`, @@ -4712,16 +3047,18 @@ export class ClaimRequestManagementService { } const insuranceCorpId = - await this.fanavaranLookupService.resolveInsuranceCorpId( - input.clientKey, - ); + await this.fanavaranLookupService.resolveInsuranceCorpId(input.clientKey); const approvedVehicleUseTypeId = this.firstPositiveFanavaranId( input.claimCase?.fanavaranVehicleReview?.vehicleUseType?.id, ); let accidentVehicleUsedId: number | null = approvedVehicleUseTypeId; - let usedSource: "expert-review" | "vin-inquiry" | "policy-vehicle" | "vehicle-inquiry" | null = - approvedVehicleUseTypeId != null ? "expert-review" : null; + let usedSource: + | "expert-review" + | "vin-inquiry" + | "policy-vehicle" + | "vehicle-inquiry" + | null = approvedVehicleUseTypeId != null ? "expert-review" : null; if (accidentVehicleUsedId == null && apiVehicle) { const fromDamagedVehicle = await this.resolveAccidentVehicleUsedFromVehicleRecord( @@ -4732,11 +3069,12 @@ export class ClaimRequestManagementService { if (accidentVehicleUsedId != null) usedSource = "vehicle-inquiry"; } if (accidentVehicleUsedId == null) { - accidentVehicleUsedId = await this.resolveAccidentVehicleUsedFromVehicleKind( - input.clientKey, - vehicleKindId, - parseFanavaranId(apiVehicle?.UsedId), - ); + accidentVehicleUsedId = + await this.resolveAccidentVehicleUsedFromVehicleKind( + input.clientKey, + vehicleKindId, + parseFanavaranId(apiVehicle?.UsedId), + ); if (accidentVehicleUsedId != null && usedSource == null) { usedSource = apiVehicle ? "vehicle-inquiry" : null; } @@ -4762,8 +3100,12 @@ export class ClaimRequestManagementService { "ChassisNumberField", "shsNam", ]) ?? - (typeof apiVehicle?.ChassisNo === "string" ? apiVehicle.ChassisNo : null), - DmgHistoryStatus: input.claimCase?.fanavaranFieldReview?.values?.DmgHistoryStatus ?? input.defaults.DmgHistoryStatus, + (typeof apiVehicle?.ChassisNo === "string" + ? apiVehicle.ChassisNo + : null), + DmgHistoryStatus: + input.claimCase?.fanavaranFieldReview?.values?.DmgHistoryStatus ?? + input.defaults.DmgHistoryStatus, Desc: this.formatFanavaranSelectedPartsDesc(input.selectedParts), DmgCaseTypeId: input.defaults.DmgCaseTypeId, DriverId: driverFanavaranId ?? null, @@ -4789,7 +3131,8 @@ export class ClaimRequestManagementService { "MtrNum", "EngineNumberField", "mtrnum", - ]) ?? (typeof apiVehicle?.MotorNo === "string" ? apiVehicle.MotorNo : null), + ]) ?? + (typeof apiVehicle?.MotorNo === "string" ? apiVehicle.MotorNo : null), OwnerId: ownerFanavaranId, PlaqueCityId: apiPlaque.cityId, PlaqueKindId: plaqueKindId, @@ -4823,219 +3166,52 @@ export class ClaimRequestManagementService { // Persist Fanavaran-sourced IDs + last payload for reuse on later preview/submit if (input.claimCase?._id) { - await this.claimCaseDbService.findByIdAndUpdate(String(input.claimCase._id), { - $set: { - "fanavaranSync.damageCase.lastPayload": persistedPayload, - "fanavaranSync.damageCase.lastPayloadBuiltAt": new Date(), - ...(driverFanavaranId != null - ? { "fanavaranSync.damageCase.driverId": driverFanavaranId } - : {}), - ...(otherPersonId != null - ? { "fanavaranSync.damageCase.otherPersonId": otherPersonId } - : {}), - ...(vehicleKindId != null - ? { - "fanavaranSync.damageCase.vehicleKindId": vehicleKindId, - "fanavaranSync.damageCase.vehicleKindSource": - vehicleKindSource ?? "car-type-lookup", - } - : {}), - "fanavaranSync.damageCase.plaqueKindId": plaqueKindId, - "fanavaranSync.damageCase.plaqueKindSource": plaqueKindSource, - "fanavaranSync.damageCase.plaqueSampleId": plaqueSampleId, - "fanavaranSync.damageCase.plaqueSampleSource": plaqueSampleSource, - ...(accidentVehicleUsedId != null - ? { - "fanavaranSync.damageCase.accidentVehicleUsedId": - accidentVehicleUsedId, - ...(usedSource - ? { - "fanavaranSync.damageCase.accidentVehicleUsedSource": - usedSource, - } - : {}), - } - : {}), - ...(insuranceCorpId != null - ? { "fanavaranSync.damageCase.insuranceCorpId": insuranceCorpId } - : {}), + await this.claimCaseDbService.findByIdAndUpdate( + String(input.claimCase._id), + { + $set: { + "fanavaranSync.damageCase.lastPayload": persistedPayload, + "fanavaranSync.damageCase.lastPayloadBuiltAt": new Date(), + ...(driverFanavaranId != null + ? { "fanavaranSync.damageCase.driverId": driverFanavaranId } + : {}), + ...(otherPersonId != null + ? { "fanavaranSync.damageCase.otherPersonId": otherPersonId } + : {}), + ...(vehicleKindId != null + ? { + "fanavaranSync.damageCase.vehicleKindId": vehicleKindId, + "fanavaranSync.damageCase.vehicleKindSource": + vehicleKindSource ?? "car-type-lookup", + } + : {}), + "fanavaranSync.damageCase.plaqueKindId": plaqueKindId, + "fanavaranSync.damageCase.plaqueKindSource": plaqueKindSource, + "fanavaranSync.damageCase.plaqueSampleId": plaqueSampleId, + "fanavaranSync.damageCase.plaqueSampleSource": plaqueSampleSource, + ...(accidentVehicleUsedId != null + ? { + "fanavaranSync.damageCase.accidentVehicleUsedId": + accidentVehicleUsedId, + ...(usedSource + ? { + "fanavaranSync.damageCase.accidentVehicleUsedSource": + usedSource, + } + : {}), + } + : {}), + ...(insuranceCorpId != null + ? { "fanavaranSync.damageCase.insuranceCorpId": insuranceCorpId } + : {}), + }, }, - }); + ); } return persistedPayload; } - /** - * Fanavaran Submit - Map data from claim-request-management and request-management to third-party-car-financial-claims format - */ - async fanavaranSubmit(claimRequestId: string): Promise { - try { - // Query claim-request-management with only needed fields using aggregate for field selection - const claimRequestResult = - await this.claimRequestManagementDbService.aggregate([ - { $match: { _id: new Types.ObjectId(claimRequestId) } }, - { - $project: { - blameFile: 1, - damageExpertReply: 1, - damageExpertReplyFinal: 1, - }, - }, - ]); - - if (!claimRequestResult || claimRequestResult.length === 0) { - throw new NotFoundException("Claim request not found"); - } - - const claimRequest = claimRequestResult[0]; - - if (!claimRequest) { - throw new NotFoundException("Claim request not found"); - } - - if (!claimRequest.blameFile || !claimRequest.blameFile._id) { - throw new BadRequestException("Blame file not found in claim request"); - } - - const blameRequestId = claimRequest.blameFile._id.toString(); - - // Query request-management with only needed fields using aggregate for field selection - const blameRequestResult = await this.blameDbService.aggregate([ - { $match: { _id: new Types.ObjectId(blameRequestId) } }, - { - $project: { - expertSubmitReplyFinal: 1, - expertSubmitReply: 1, - createdAt: 1, - firstPartyLocation: 1, - "firstPartyDetails.firstPartyId": 1, - "firstPartyDetails.nationalCodeOfInsurer": 1, - "secondPartyDetails.secondPartyId": 1, - "secondPartyDetails.nationalCodeOfInsurer": 1, - }, - }, - ]); - - if (!blameRequestResult || blameRequestResult.length === 0) { - throw new NotFoundException("Blame request not found"); - } - - const blameRequest = blameRequestResult[0]; - - if (!blameRequest) { - throw new NotFoundException("Blame request not found"); - } - - // Start building the response object - const result: any = { - AccidentCityId: 701, - AccidentReportTypeId: 155, - AccidentVehicleUsedId: 1, - ClaimExpertId: 4543092, - CompensationReferenceId: 167, - CulpritLicenceTypeId: 2, - CulpritTypeId: 337, - AccidentCauseId: FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID, - }; - - if ( - !blameRequest.expertSubmitReplyFinal && - !blameRequest.expertSubmitReply - ) { - this.logger.error( - `[Fanavaran Submit] Both expertSubmitReplyFinal and expertSubmitReply are null/undefined`, - ); - } - - // AccidentDate: Convert createdAt to Persian date - if (blameRequest.createdAt) { - result.AccidentDate = this.convertToPersianDate(blameRequest.createdAt); - result.AnnouncementDate = result.AccidentDate; - result.DocReceivedDate = result.AccidentDate; - } - - // AccidentTime: Extract time from createdAt in 24-hour format - if (blameRequest.createdAt) { - result.AccidentTime = this.getTime24Hour(blameRequest.createdAt); - } - - result.AccidentLocationAddress = FANAVARAN_ACCIDENT_LOCATION_ADDRESS; - - // EstimateAmount: Sum of totalPayment from damageExpertReply parts - const damageReply = - claimRequest.damageExpertReplyFinal || claimRequest.damageExpertReply; - if (damageReply?.parts) { - result.EstimateAmount = this.normalizeFanavaranEstimateAmount( - this.calculateEstimateAmount(damageReply.parts), - ); - } else { - result.EstimateAmount = FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT; - } - - // Keep other fields from template with default values - this.applyFanavaranDefaultFields(result); - - // Get PolicyId from external API - try { - const policyId = await this.getPolicyIdFromExternalApi( - blameRequest, - claimRequestId, - ); - if (!policyId) { - throw new BadRequestException( - `[Fanavaran Submit] PolicyId is required for Fanavaran submit. Policy inquiry returned no valid policy; contact the administrator.`, - ); - } - result.PolicyId = policyId; - } catch (error) { - this.logger.error( - `[Fanavaran Submit] Failed to get PolicyId from external API:`, - error, - ); - throw error; - } - - return result; - } catch (error) { - this.logger.error("Error in fanavaranSubmit", error); - throw error; - } - } - - /** - * Resolve Fanavaran authenticationToken via shared tenant cache (TTL). - * Prefer clientKey overload — config-based overload keeps legacy Tejaratno callers working. - */ - private async getAppToken( - config: { - appName: string; - secret: string; - } = this.getTejaratnoFanavaranConfig(), - auditSession?: FanavaranAuditSession, - ): Promise { - const clientKey = this.resolveClientKeyFromAuthConfig(config); - // App token is internal to FanavaranAuthService; return auth token for legacy callers - // that only needed a successful login chain. Prefer getFanavaranAuthHeaders. - return this.fanavaranAuthService.getAuthenticationToken(clientKey, { - auditSession, - }); - } - - private async login( - _appToken: string, - config: { - username: string; - password: string; - } = this.getTejaratnoFanavaranConfig(), - auditSession?: FanavaranAuditSession, - ): Promise { - const clientKey = this.resolveClientKeyFromLoginConfig(config); - return this.fanavaranAuthService.getAuthenticationToken(clientKey, { - auditSession, - }); - } - private resolveClientKeyFromAuthConfig(config: { appName: string; }): FanavaranClientKey { @@ -5045,15 +3221,6 @@ export class ClaimRequestManagementService { return resolveFanavaranClientKey(); } - private resolveClientKeyFromLoginConfig(config: { - username: string; - }): FanavaranClientKey { - if (config.username === this.PARSIAN_FANAVARAN_CONFIG.username) { - return "parsian"; - } - return resolveFanavaranClientKey(); - } - private async resolveFanavaranClaimProduct( claimCaseId?: string, blameCase?: { type?: string } | null, @@ -5318,8 +3485,7 @@ export class ClaimRequestManagementService { const errorMessage = error instanceof Error ? error.message : "unknown policy inquiry error"; if (auditSession) { - const exchange = - this.fanavaranAuditService.captureAxiosExchange(error); + const exchange = this.fanavaranAuditService.captureAxiosExchange(error); await this.fanavaranAuditService.recordStep({ session: auditSession, step: FanavaranAuditStep.POLICY_INQUIRY, @@ -5344,70 +3510,6 @@ export class ClaimRequestManagementService { } } - /** - * Get PolicyId from external API - */ - private async getPolicyIdFromExternalApi( - blameRequest: any, - claimRequestId: string, - ): Promise { - try { - // Get guiltyUserId from expertSubmitReplyFinal or expertSubmitReply - let guiltyUserId: string | null = null; - if (blameRequest.expertSubmitReplyFinal?.guiltyUserId) { - guiltyUserId = blameRequest.expertSubmitReplyFinal.guiltyUserId; - } else if (blameRequest.expertSubmitReply?.guiltyUserId) { - guiltyUserId = blameRequest.expertSubmitReply.guiltyUserId; - } - - if (!guiltyUserId) { - this.logger.warn( - `[Fanavaran Submit] guiltyUserId not found in expertSubmitReplyFinal or expertSubmitReply`, - ); - return null; - } - - // Find the nationalCodeOfInsurer by matching guiltyUserId with firstPartyId or secondPartyId - let nationalCodeOfInsurer: string | null = null; - - if ( - blameRequest.firstPartyDetails?.firstPartyId?.toString() === - guiltyUserId.toString() - ) { - nationalCodeOfInsurer = - blameRequest.firstPartyDetails?.nationalCodeOfInsurer; - } else if ( - blameRequest.secondPartyDetails?.secondPartyId?.toString() === - guiltyUserId.toString() - ) { - nationalCodeOfInsurer = - blameRequest.secondPartyDetails?.nationalCodeOfInsurer; - } - - if (!nationalCodeOfInsurer) { - this.logger.warn( - `[Fanavaran Submit] nationalCodeOfInsurer not found for guiltyUserId: ${guiltyUserId}`, - ); - return null; - } - - return await this.getPolicyIdFromNationalCode( - nationalCodeOfInsurer, - this.getTejaratnoFanavaranConfig(), - `[Fanavaran Submit] claimRequestId=${claimRequestId}`, - ); - } catch (error) { - this.logger.error( - `[Fanavaran Submit] Error getting PolicyId from external API:`, - error, - ); - if (error instanceof BadRequestException) { - throw error; - } - return null; - } - } - private firstPositiveFanavaranId(...values: unknown[]): number | null { for (const value of values) { const id = parseFanavaranId(value); @@ -5416,33 +3518,20 @@ export class ClaimRequestManagementService { return null; } - private keepPreviousPositiveIds( - previous: Record | null, - next: Record, - keys: string[], - ): Record { - const merged = { ...previous, ...next }; - for (const key of keys) { - if (this.firstPositiveFanavaranId(next[key]) != null) continue; - const previousId = this.firstPositiveFanavaranId(previous?.[key]); - if (previousId != null) { - merged[key] = previousId; - } - } - return merged; - } - private async resolveDriverFanavaranIdFromPerson( clientKey: FanavaranClientKey, - person: { - driverIsInsurer?: boolean; - nationalCodeOfDriver?: unknown; - nationalCodeOfInsurer?: unknown; - nationalCode?: unknown; - driverBirthday?: unknown; - birthday?: unknown; - insurerBirthday?: unknown; - } | null | undefined, + person: + | { + driverIsInsurer?: boolean; + nationalCodeOfDriver?: unknown; + nationalCodeOfInsurer?: unknown; + nationalCode?: unknown; + driverBirthday?: unknown; + birthday?: unknown; + insurerBirthday?: unknown; + } + | null + | undefined, ): Promise { const codes = collectPersonNationalCodes(person); const birthdays = collectPersonBirthdays(person); @@ -5619,12 +3708,9 @@ export class ClaimRequestManagementService { `[registerFanavaranOtherPerson] inquiry seed Id=${seedRow.Id} RoleId=${roleId} — creating GEN.44 سایر (adds RoleId 166 entry; existing roles stay)`, ); inquirySeed = { - name: - typeof seedRow.Name === "string" ? seedRow.Name : undefined, + name: typeof seedRow.Name === "string" ? seedRow.Name : undefined, lastName: - typeof seedRow.LastName === "string" - ? seedRow.LastName - : undefined, + typeof seedRow.LastName === "string" ? seedRow.LastName : undefined, fatherName: typeof seedRow.FatherName === "string" ? seedRow.FatherName @@ -5765,8 +3851,7 @@ export class ClaimRequestManagementService { const ownerId = claimCase?.owner?.userId; if (ownerId) { const byOwner = parties.find( - (party) => - String(party?.person?.userId ?? "") === String(ownerId), + (party) => String(party?.person?.userId ?? "") === String(ownerId), ); if (byOwner) return byOwner; } @@ -5915,8 +4000,7 @@ export class ClaimRequestManagementService { estimateAmount: null as number | null, }, failureReason: null as string | null, - note: - "HTTP preview/submit always re-inquire PolicyId and AccidentVehicleUsedId. Auth token is shared until Tehran midnight.", + note: "HTTP preview/submit always re-inquire PolicyId and AccidentVehicleUsedId. Auth token is shared until Tehran midnight.", }; const claimCase = await this.claimCaseDbService.findById(claimCaseId); @@ -5975,8 +4059,7 @@ export class ClaimRequestManagementService { const accidentAt = blameCase.type === BlameRequestType.CAR_BODY ? ((firstParty as { statement?: { accidentDate?: Date } })?.statement - ?.accidentDate ?? - (blameCase as { createdAt?: Date }).createdAt) + ?.accidentDate ?? (blameCase as { createdAt?: Date }).createdAt) : (blameCase as { createdAt?: Date }).createdAt; const payload = await this.buildFanavaranSubmitPayload({ @@ -6116,8 +4199,9 @@ export class ClaimRequestManagementService { payload.CulpritLicenceIssuDate = resolveFanavaranLicenceIssuDate(culpritDriver); if (blameCase.type !== BlameRequestType.CAR_BODY) { - payload.CulpritTypeId = - resolveThirdPartyCulpritTypeId(culpritParty as any); + payload.CulpritTypeId = resolveThirdPartyCulpritTypeId( + culpritParty as any, + ); } } @@ -6147,7 +4231,11 @@ export class ClaimRequestManagementService { cachedUsedSource === "policy-vehicle"); delete payload.AccidentVehicleUsedId; - let usedSource: "expert-review" | "vin-inquiry" | "policy-vehicle" | null = null; + let usedSource: + | "expert-review" + | "vin-inquiry" + | "policy-vehicle" + | null = null; if (canReuseApiUsedId) { payload.AccidentVehicleUsedId = Number(cachedUsedId); usedSource = cachedUsedSource; @@ -6179,8 +4267,7 @@ export class ClaimRequestManagementService { } if (parseFanavaranId(payload.AccidentVehicleUsedId) == null) { - payload.AccidentVehicleUsedId = - profile.defaults.AccidentVehicleUsedId; + payload.AccidentVehicleUsedId = profile.defaults.AccidentVehicleUsedId; this.logger.log( `${logPrefix} AccidentVehicleUsedId API miss; using config default ${payload.AccidentVehicleUsedId}`, ); @@ -6195,15 +4282,27 @@ export class ClaimRequestManagementService { logPrefix, claimCaseId, }); - applyFanavaranStageFieldReview(payload, claimCase, "car-body", "baseClaim"); + applyFanavaranStageFieldReview( + payload, + claimCase, + "car-body", + "baseClaim", + ); delete payload.IsLicenseReplacement; const hull = toFanavaranHullBaseClaimPayload(payload); for (const key of Object.keys(payload)) delete payload[key]; Object.assign(payload, hull); } - if (fanavaranClaimProductFromBlameType(blameCase.type) === "third-party") { - applyFanavaranStageFieldReview(payload, claimCase, "third-party", "baseClaim"); + if ( + fanavaranClaimProductFromBlameType(blameCase.type) === "third-party" + ) { + applyFanavaranStageFieldReview( + payload, + claimCase, + "third-party", + "baseClaim", + ); } const fileRoleExpertIds = @@ -6261,14 +4360,6 @@ export class ClaimRequestManagementService { } } - /** @deprecated Use previewFanavaranSubmitV2(claimCaseId, "parsian", options) */ - async fanavaranSubmitParsianV2( - claimCaseId: string, - options?: { debug?: boolean }, - ): Promise { - return this.previewFanavaranSubmitV2(claimCaseId, "parsian", options); - } - /** * Submit Fanavaran data (V2 claimCases + blameCases) for a specific client. */ @@ -6294,11 +4385,6 @@ export class ClaimRequestManagementService { } } - /** @deprecated Use submitFanavaranV2(claimCaseId, "parsian") */ - async submitToFanavaranParsianV2(claimCaseId: string): Promise { - return this.submitFanavaranV2(claimCaseId, "parsian"); - } - async previewFanavaranDamageCaseV2( claimCaseId: string, clientKey: FanavaranClientKey, @@ -6868,7 +4954,9 @@ export class ClaimRequestManagementService { auditSession, ); - this.logger.log(`${logPrefix} Fanavaran response: ${JSON.stringify(response.data)}`); + this.logger.log( + `${logPrefix} Fanavaran response: ${JSON.stringify(response.data)}`, + ); const fileId = response.data?.Id; const exchange = @@ -7093,7 +5181,11 @@ export class ClaimRequestManagementService { definition.cacheFile, ); let rows: unknown = data; - for (let level = 0; level < 3 && rows && !Array.isArray(rows) && typeof rows === "object"; level++) { + for ( + let level = 0; + level < 3 && rows && !Array.isArray(rows) && typeof rows === "object"; + level++ + ) { rows = (rows as { data?: unknown }).data; } return Array.isArray(rows) ? rows : []; @@ -7105,73 +5197,6 @@ export class ClaimRequestManagementService { } } - private normalizeFanavaranLookupText(value: unknown): string { - return String(value ?? "") - .toLowerCase() - .replace(/[ي]/g, "ی") - .replace(/[ك]/g, "ک") - .replace(/[\u200c\s_\-\/]+/g, "") - .replace(/[^\p{L}\p{N}]/gu, ""); - } - - private lookupRowId(row: unknown): number | null { - if (!row || typeof row !== "object") return null; - const raw = - (row as { Id?: unknown; id?: unknown; Code?: unknown }).Id ?? - (row as { id?: unknown }).id ?? - (row as { Code?: unknown }).Code; - const id = Number(raw); - return Number.isFinite(id) ? id : null; - } - - private lookupRowTextCandidates(row: unknown): string[] { - if (!row || typeof row !== "object") return []; - const r = row as Record; - return [ - r.Caption, - r.caption, - r.Title, - r.title, - r.Name, - r.name, - r.Text, - r.text, - r.Description, - r.description, - r.Value, - r.value, - ] - .filter((value): value is string => typeof value === "string") - .filter(Boolean); - } - - private findLookupIdByText(rows: unknown[], texts: unknown[]): number | null { - const wanted = texts - .map((text) => this.normalizeFanavaranLookupText(text)) - .filter(Boolean); - if (!wanted.length) return null; - - for (const row of rows) { - const rowTexts = this.lookupRowTextCandidates(row).map((text) => - this.normalizeFanavaranLookupText(text), - ); - if ( - rowTexts.some((rowText) => - wanted.some( - (want) => - rowText === want || - rowText.includes(want) || - want.includes(rowText), - ), - ) - ) { - return this.lookupRowId(row); - } - } - - return null; - } - private parseFanavaranMoney(value: unknown): number { if (value == null || value === "") return 0; if (typeof value === "number" && Number.isFinite(value)) return value; @@ -7200,22 +5225,6 @@ export class ClaimRequestManagementService { return String(damage ?? part?.partId ?? ""); } - private fanavaranPartLookupTexts(part: any): unknown[] { - const damage = part?.carPartDamage; - if (damage && typeof damage === "object") { - const d = damage as Record; - return [ - d.label_fa, - d.part, - d.name, - d.catalogKey, - part.partId, - this.fanavaranPartLabel(part), - ]; - } - return [damage, part?.partId, this.fanavaranPartLabel(part)]; - } - private fanavaranDaghiWasteValue(daghi: unknown): number { if (!daghi || typeof daghi !== "object") return this.parseFanavaranMoney(daghi); @@ -7223,28 +5232,6 @@ export class ClaimRequestManagementService { return this.parseFanavaranMoney(d.price); } - private findPriceDropLineForPart(priceDrop: any, part: any): any { - const lines = Array.isArray(priceDrop?.partLines) - ? priceDrop.partLines - : []; - return lines.find((line: any) => { - const linePartId = parseCatalogPartIdInput(line?.partId); - const partId = parseCatalogPartIdInput(part?.partId); - return linePartId != null && partId != null && linePartId === partId; - }); - } - - private findDropAmountStatusId( - rows: unknown[], - priceDropTotal: number, - ): number | null { - const positiveTexts = - priceDropTotal > 0 - ? ["مشمول", "دارد", "افت", "has", "yes"] - : ["فاقد", "ندارد", "عدم", "بدون", "no"]; - return this.findLookupIdByText(rows, positiveTexts); - } - private buildFanavaranExpertiseDmgSection(input: { part: any; warnings: string[]; @@ -7260,9 +5247,7 @@ export class ClaimRequestManagementService { const label = this.fanavaranPartLabel(input.part); if (partId == null) { - input.warnings.push( - `No DmgSectionId (partId) for part "${label}".`, - ); + input.warnings.push(`No DmgSectionId (partId) for part "${label}".`); } return { @@ -7331,17 +5316,15 @@ export class ClaimRequestManagementService { warnings.push("No submit-ready expert pricing lines exist yet."); } - const [ - inspectionPlaces, - dropAmountStatuses, - ] = await Promise.all([ + const [inspectionPlaces, dropAmountStatuses] = await Promise.all([ this.getFanavaranLookupRows(input.clientKey, "inspection-place"), this.getFanavaranLookupRows(input.clientKey, "drop-amount-status"), ]); const priceDrop = input.claimCase.evaluation?.priceDrop ?? {}; const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total); - const inspectionPlaceId = input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282; + const inspectionPlaceId = + input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282; const dropAmountStatus = 5458; const dmgSections = parts.map((part) => @@ -7386,20 +5369,20 @@ export class ClaimRequestManagementService { } const payload: Record = { - ClaimExpertId: claimExpertId, - ComponentReplacementCost: componentReplacementCost, - DmgAssessmentDate: this.convertToPersianDate(submittedAt), - InspectionPlaceId: inspectionPlaceId, - InspectionTime: this.getTime24Hour(submittedAt), - RepairWage: repairWage, - WasteValue: wasteValue, - WentDistanceByExpert: null, - DropAmountStatus: dropAmountStatus, - DropAmountAdditionsDeductions: priceDropTotal || 0, - ComponentReplacementTaxAndToll: 0, - DamagedVehicleCurrentPrice: - this.parseFanavaranMoney(priceDrop?.carPrice) || null, - DmgSections: dmgSections, + ClaimExpertId: claimExpertId, + ComponentReplacementCost: componentReplacementCost, + DmgAssessmentDate: this.convertToPersianDate(submittedAt), + InspectionPlaceId: inspectionPlaceId, + InspectionTime: this.getTime24Hour(submittedAt), + RepairWage: repairWage, + WasteValue: wasteValue, + WentDistanceByExpert: null, + DropAmountStatus: dropAmountStatus, + DropAmountAdditionsDeductions: priceDropTotal || 0, + ComponentReplacementTaxAndToll: 0, + DamagedVehicleCurrentPrice: + this.parseFanavaranMoney(priceDrop?.carPrice) || null, + DmgSections: dmgSections, }; payload.DmgCaseId = input.claimCase.dmgCaseId ?? null; @@ -7413,7 +5396,10 @@ export class ClaimRequestManagementService { private assertFanavaranExpertisePayloadReady( payload: Record, warnings: string[], - options?: { requireDmgCaseId?: boolean; requireThirdPartyLookups?: boolean }, + options?: { + requireDmgCaseId?: boolean; + requireThirdPartyLookups?: boolean; + }, ): void { const readyWarnings = collectFanavaranExpertiseReadinessWarnings( payload, @@ -7517,11 +5503,7 @@ export class ClaimRequestManagementService { !claimCase?.claimId || (fanavaranHasDamageCaseStage(product) && claimCase.dmgCaseId == null) ) { - await this.ensureFanavaranDamageCase( - claimCaseId, - clientKey, - auditSource, - ); + await this.ensureFanavaranDamageCase(claimCaseId, clientKey, auditSource); claimCase = await this.claimCaseDbService.findById(claimCaseId); } if (!claimCase?.claimId) { @@ -7770,11 +5752,20 @@ export class ClaimRequestManagementService { private assertFanavaranVehicleReviewApproved(claimCase: any): void { const review = claimCase?.fanavaranVehicleReview; - const ids = [review?.vehicleGroup?.id, review?.vehicleUseType?.id, review?.vehicleSystem?.id, review?.vehicleKind?.id]; - if (review?.approved !== true || ids.some((id) => !Number.isInteger(Number(id)) || Number(id) <= 0)) { + const ids = [ + review?.vehicleGroup?.id, + review?.vehicleUseType?.id, + review?.vehicleSystem?.id, + review?.vehicleKind?.id, + ]; + if ( + review?.approved !== true || + ids.some((id) => !Number.isInteger(Number(id)) || Number(id) <= 0) + ) { throw new ConflictException({ code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED", - message: "An expert must review and approve the vehicle group, use type, system, and kind before any data can be sent to Fanavaran.", + message: + "An expert must review and approve the vehicle group, use type, system, and kind before any data can be sent to Fanavaran.", }); } } @@ -8056,7 +6047,9 @@ export class ClaimRequestManagementService { `-F 'Param=${JSON.stringify(content)}'`, ...files.map((f) => `-F 'Param1=@${f.path};filename=${f.fileName}'`), ]; - this.logger.log(`\n====== COPY THIS CURL ======\n${curlParts.join(" \\\n ")}\n====== END CURL ======\n`); + this.logger.log( + `\n====== COPY THIS CURL ======\n${curlParts.join(" \\\n ")}\n====== END CURL ======\n`, + ); const logPrefix = `[Fanavaran Multipart]`; this.logger.log( @@ -8176,7 +6169,9 @@ export class ClaimRequestManagementService { ); // Guardrail: never send empty/null licence fields even if manual overrides arrive. - payload.LicenceNo = this.ensureFanavaranNonEmptyLicenceNo(payload.LicenceNo); + payload.LicenceNo = this.ensureFanavaranNonEmptyLicenceNo( + payload.LicenceNo, + ); this.logger.log( `[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? "NULL"} payload keys=${Object.keys(payload).join(", ")}`, @@ -8332,7 +6327,8 @@ export class ClaimRequestManagementService { submitted: false, skipped: true, skipReason: - fanavaranResponse.skipReason ?? FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, + fanavaranResponse.skipReason ?? + FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, claimId: claimCase.claimId, }; } @@ -8425,103 +6421,109 @@ export class ClaimRequestManagementService { claimCaseId, "baseClaim", async () => { - try { - const claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) { - return { - attempted: false, - submitted: false, - warning: - "Claim case not found for Fanavaran early submit. Retry manually when available.", - }; - } + try { + const claimCase = await this.claimCaseDbService.findById(claimCaseId); + if (!claimCase) { + return { + attempted: false, + submitted: false, + warning: + "Claim case not found for Fanavaran early submit. Retry manually when available.", + }; + } - const skipReason = await this.getFanavaranAutoSubmitSkipReason(claimCase); - if (skipReason) { - return { - attempted: false, - submitted: false, - skipped: true, - skipReason, - claimId: claimCase.claimId, - claimNo: claimCase.claimNo, - }; - } + const skipReason = + await this.getFanavaranAutoSubmitSkipReason(claimCase); + if (skipReason) { + return { + attempted: false, + submitted: false, + skipped: true, + skipReason, + claimId: claimCase.claimId, + claimNo: claimCase.claimNo, + }; + } - const fanavaranResponse = await this.executeFanavaranV2Submit( - claimCaseId, - clientKey, - undefined, - FanavaranAuditSource.AUTO_SUBMIT, - ); + const fanavaranResponse = await this.executeFanavaranV2Submit( + claimCaseId, + clientKey, + undefined, + FanavaranAuditSource.AUTO_SUBMIT, + ); - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $push: { - history: { - type: "FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { - clientKey, - claimNo: fanavaranResponse?.ClaimNo, - claimId: fanavaranResponse?.Id, + await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { + $push: { + history: { + type: "FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED", + actor: { actorType: "system" }, + timestamp: new Date(), + metadata: { + clientKey, + claimNo: fanavaranResponse?.ClaimNo, + claimId: fanavaranResponse?.Id, + }, + }, }, - }, - }, - }); + }); - return { - attempted: true, - submitted: true, - claimNo: fanavaranResponse?.ClaimNo, - claimId: fanavaranResponse?.Id, - fanavaranResponse, - }; - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - this.logger.warn(`${logPrefix} Early auto-submit failed: ${warning}`); + return { + attempted: true, + submitted: true, + claimNo: fanavaranResponse?.ClaimNo, + claimId: fanavaranResponse?.Id, + fanavaranResponse, + }; + } catch (error) { + const warning = this.extractFanavaranErrorMessage(error); + this.logger.warn(`${logPrefix} Early auto-submit failed: ${warning}`); - try { - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - "fanavaranSync.baseClaim.status": "failed", - "fanavaranSync.baseClaim.lastTriedAt": new Date(), - "fanavaranSync.baseClaim.lastError": warning, - }, - $push: { - history: { - type: "FANAVARAN_EARLY_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, - timestamp: new Date(), - metadata: { clientKey, error: warning }, - }, - }, - }); - } catch (historyError) { - this.logger.error( - `${logPrefix} Failed to record Fanavaran early auto-submit failure history`, - historyError, - ); - } + try { + await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { + $set: { + "fanavaranSync.baseClaim.status": "failed", + "fanavaranSync.baseClaim.lastTriedAt": new Date(), + "fanavaranSync.baseClaim.lastError": warning, + }, + $push: { + history: { + type: "FANAVARAN_EARLY_AUTO_SUBMIT_FAILED", + actor: { actorType: "system" }, + timestamp: new Date(), + metadata: { clientKey, error: warning }, + }, + }, + }); + } catch (historyError) { + this.logger.error( + `${logPrefix} Failed to record Fanavaran early auto-submit failure history`, + historyError, + ); + } - await this.scheduleFanavaranRetry( - claimCaseId, - "baseClaim", - () => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId), - logPrefix, - { error, clientKey }, - ); + await this.scheduleFanavaranRetry( + claimCaseId, + "baseClaim", + () => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId), + logPrefix, + { error, clientKey }, + ); - return { - attempted: true, - submitted: false, - warning: `${warning} Initial case was not sent to Fanavaran. Retry manually via POST ${fanavaranSubmitPath(clientKey, claimCaseId)}.`, - }; - } + return { + attempted: true, + submitted: false, + warning: `${warning} Initial case was not sent to Fanavaran. Retry manually via POST ${fanavaranSubmitPath(clientKey, claimCaseId)}.`, + }; + } }, ); - if (locked && typeof locked === "object" && "skipped" in locked && locked.skipped) { + if ( + locked && + typeof locked === "object" && + "skipped" in locked && + locked.skipped + ) { return { attempted: false, submitted: false, @@ -8670,13 +6672,6 @@ export class ClaimRequestManagementService { } } - /** @deprecated Use autoSubmitToFanavaranV2OnClaimCompleted */ - async autoSubmitToFanavaranParsianV2OnClaimCompleted( - claimCaseId: string, - ): Promise { - return this.autoSubmitToFanavaranV2OnClaimCompleted(claimCaseId); - } - private extractFanavaranErrorMessage(error: unknown): string { if (isAxiosError(error)) { return ( @@ -8768,10 +6763,7 @@ export class ClaimRequestManagementService { const existingNext = syncStage?.nextRetryAt ? new Date(syncStage.nextRetryAt).getTime() : 0; - if ( - syncStage?.status === "pending" && - existingNext > Date.now() + 5_000 - ) { + if (syncStage?.status === "pending" && existingNext > Date.now() + 5_000) { this.logger.log( `${logPrefix} Retry already pending for ${stage} at ${new Date(existingNext).toISOString()}; skipping duplicate schedule.`, ); @@ -8877,14 +6869,13 @@ export class ClaimRequestManagementService { claimCaseId, }; - const built = - await this.previewFanavaranSubmitV2(claimCaseId, clientKey, { - requirePolicyId: true, - auditSession, - persistPayload: true, - forceRefreshPolicy: true, - forceRefreshUsedId: true, - }); + const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, { + requirePolicyId: true, + auditSession, + persistPayload: true, + forceRefreshPolicy: true, + forceRefreshUsedId: true, + }); const fanavaranData = applyFanavaranManualPayloadOverrides( built, bodyOverride, @@ -9028,205 +7019,6 @@ export class ClaimRequestManagementService { } } - /** @deprecated Use executeFanavaranV2Submit(claimCaseId, "parsian") */ - private async executeFanavaranParsianV2Submit( - claimCaseId: string, - ): Promise { - return this.executeFanavaranV2Submit(claimCaseId, "parsian"); - } - - /** - * Submit fanavaran data to external API - */ - async submitToFanavaran(claimRequestId: string): Promise { - try { - // First, get the mapped data - this.logger.log( - `[Fanavaran Submit] Starting submission for claimRequestId: ${claimRequestId}`, - ); - const fanavaranData = await this.fanavaranSubmit(claimRequestId); - this.logger.log( - `[Fanavaran Submit] Mapped data prepared:`, - JSON.stringify(fanavaranData, null, 2), - ); - - // Validate required fields before submission - if ( - fanavaranData.AccidentCauseId === undefined || - fanavaranData.AccidentCauseId === null - ) { - this.logger.error( - `[Fanavaran Submit] CRITICAL: AccidentCauseId is missing or null!`, - ); - this.logger.error( - `[Fanavaran Submit] This field is required by the API. Request will likely fail.`, - ); - this.logger.error( - `[Fanavaran Submit] Available fields in result:`, - Object.keys(fanavaranData), - ); - } else { - this.logger.log( - `[Fanavaran Submit] AccidentCauseId validated: ${fanavaranData.AccidentCauseId}`, - ); - } - - // Step 1: Get appToken - this.logger.log(`[Fanavaran Submit] Step 1: Getting appToken`); - const appToken = await this.getAppToken(); - this.logger.log(`[Fanavaran Submit] AppToken obtained: ${appToken}`); - - // Step 2: Login to get authenticationToken - this.logger.log( - `[Fanavaran Submit] Step 2: Logging in to get authenticationToken`, - ); - const authenticationToken = await this.login(appToken); - this.logger.log( - `[Fanavaran Submit] AuthenticationToken obtained: ${authenticationToken}`, - ); - - // Step 3: Submit data to Fanavaran API - this.logger.log( - `[Fanavaran Submit] Step 3: Submitting data to Fanavaran API`, - ); - this.logger.log(`[Fanavaran Submit] URL: ${this.FANAVARAN_SUBMIT_URL}`); - this.logger.log(`[Fanavaran Submit] Request headers:`, { - authenticationToken: authenticationToken, - CorpId: this.CORP_ID, - ContractId: this.CONTRACT_ID, - Location: this.LOCATION, - "Content-Type": "application/json", - }); - this.logger.log( - `[Fanavaran Submit] Request body:`, - JSON.stringify(fanavaranData, null, 2), - ); - - const response = await firstValueFrom( - this.httpService.post(this.FANAVARAN_SUBMIT_URL, fanavaranData, { - headers: { - authenticationToken: authenticationToken, - CorpId: this.CORP_ID, - ContractId: this.CONTRACT_ID, - Location: this.LOCATION, - "Content-Type": "application/json", - }, - }), - ); - - this.logger.log( - `[Fanavaran Submit] API Response Status: ${response.status}`, - ); - this.logger.log( - `[Fanavaran Submit] API Response Headers:`, - JSON.stringify(response.headers, null, 2), - ); - this.logger.log( - `[Fanavaran Submit] API Response Data:`, - JSON.stringify(response.data, null, 2), - ); - this.logger.log("Successfully submitted data to Fanavaran API"); - - // Step 4: Save ClaimNo and Id from response to claim-request-management document - if (response.data) { - const claimNo = response.data.ClaimNo; - const claimId = response.data.Id; - - this.logger.log( - `[Fanavaran Submit] Extracted from response - ClaimNo: ${claimNo}, Id: ${claimId}`, - ); - - if (claimNo !== undefined || claimId !== undefined) { - const updateData: any = { - $set: {}, - }; - if (claimNo !== undefined) { - updateData.$set.claimNo = claimNo; - } - if (claimId !== undefined) { - updateData.$set.claimId = claimId; - } - - this.logger.log( - `[Fanavaran Submit] Updating document with:`, - JSON.stringify(updateData, null, 2), - ); - await this.claimRequestManagementDbService.findAndUpdate( - claimRequestId, - updateData, - ); - - this.logger.log( - `Updated claim-request-management document with claimNo: ${claimNo}, claimId: ${claimId}`, - ); - } else { - this.logger.warn( - `[Fanavaran Submit] No ClaimNo or Id found in response data`, - ); - } - } else { - this.logger.warn(`[Fanavaran Submit] No response data received`); - } - - return response.data; - } catch (error) { - this.logger.error("[Fanavaran Submit] Error submitting to Fanavaran"); - this.logger.error( - "[Fanavaran Submit] Error type:", - error?.constructor?.name, - ); - - if (isAxiosError(error)) { - this.logger.error("[Fanavaran Submit] Axios Error Details:"); - this.logger.error( - "[Fanavaran Submit] Error Status:", - error.response?.status, - ); - this.logger.error( - "[Fanavaran Submit] Error Status Text:", - error.response?.statusText, - ); - this.logger.error( - "[Fanavaran Submit] Error Response Headers:", - JSON.stringify(error.response?.headers, null, 2), - ); - this.logger.error( - "[Fanavaran Submit] Error Response Data:", - JSON.stringify(error.response?.data, null, 2), - ); - this.logger.error("[Fanavaran Submit] Request URL:", error.config?.url); - this.logger.error( - "[Fanavaran Submit] Request Method:", - error.config?.method, - ); - this.logger.error( - "[Fanavaran Submit] Request Headers:", - JSON.stringify(error.config?.headers, null, 2), - ); - this.logger.error( - "[Fanavaran Submit] Request Data:", - JSON.stringify(error.config?.data, null, 2), - ); - - const errorMessage = - error.response?.data?.message || - error.response?.data?.Message || - error.response?.data || - error.message || - "Failed to submit data to Fanavaran API"; - - this.logger.error( - "[Fanavaran Submit] Extracted Error Message:", - errorMessage, - ); - throw new BadGatewayException(errorMessage); - } else { - this.logger.error("[Fanavaran Submit] Non-Axios Error:", error); - throw new BadGatewayException("Failed to submit data to Fanavaran API"); - } - } - } - /** * V2: Create claim request from completed blame case * Only damaged party can create claim after both parties accept expert decision @@ -9243,92 +7035,30 @@ export class ClaimRequestManagementService { throw new NotFoundException("Blame request not found"); } - // 2. Validate blame status is COMPLETED - // if (blameRequest.status !== BlameCaseStatus.COMPLETED) { - // throw new BadRequestException( - // `Blame request must be COMPLETED. Current status: ${blameRequest.status}`, - // ); - // } - - const parties = blameRequest.parties || []; - const isCarBody = blameRequest.type === BlameRequestType.CAR_BODY; - - if (isCarBody) { - // CAR_BODY: single party, no expert; first party is the damaged one who creates the claim - if (parties.length < 1) { - throw new BadRequestException("Blame request has no party"); - } - const firstParty = parties.find((p) => p.role === "FIRST"); - if ( - !firstParty || - String(firstParty.person?.userId) !== currentUserId - ) { - throw new ForbiddenException( - "Only the first party (damaged) can create a claim from this CAR_BODY blame request", - ); - } - } else { - // THIRD_PARTY: require expert decision and both parties signed - if (!blameRequest.expert?.decision) { - throw new BadRequestException( - "Cannot create claim until expert has made a decision", - ); - } - - const guiltyPartyId = String( - blameRequest.expert.decision.guiltyPartyId, + if (blameRequest.status !== BlameCaseStatus.COMPLETED) { + throw new BadRequestException( + "Blame request must be completed before creating a claim", ); - - if (parties.length < 2) { - throw new BadRequestException( - "Both parties must be present in the blame request", - ); - } - - const allPartiesSigned = parties.every( - (p) => p.confirmation !== undefined && p.confirmation !== null, - ); - - if (!allPartiesSigned) { - throw new BadRequestException( - "Both parties must sign the expert decision before creating a claim", - ); - } - - const allPartiesAccepted = parties.every( - (p) => p.confirmation?.accepted === true, - ); - - if (!allPartiesAccepted) { - throw new BadRequestException( - "Both parties must accept the expert decision. If rejected, in-person resolution is required.", - ); - } - - const guiltyParty = parties.find((p) => { - return String(p.person?.userId) === guiltyPartyId; - }); - - if ( - guiltyParty && - String(guiltyParty.person?.userId) === currentUserId - ) { - throw new ForbiddenException( - "You cannot create a claim as you are the guilty party", - ); - } } - // 5. Validate current user is a party (and for THIRD_PARTY not the guilty one) - const currentUserParty = parties.find( - (p) => String(p.person?.userId) === currentUserId, - ); - - if (!currentUserParty) { + const beneficiary = resolveClaimBeneficiary(blameRequest); + if (!beneficiary) { + throw new BadRequestException( + "The damaged party could not be determined from this blame request", + ); + } + if (String(beneficiary.person!.userId) !== currentUserId) { throw new ForbiddenException( - "You are not a party in this blame request", + "Only the damaged party can create a claim from this blame request", ); } + if (!canUserCreateClaim(blameRequest, currentUserId)) { + throw new BadRequestException( + "Both parties must sign and accept the decision before creating a claim", + ); + } + + const currentUserParty = beneficiary; // 6. Validate no existing claim for this blame const existingClaim = await this.claimCaseDbService.findOne({ @@ -9351,13 +7081,7 @@ export class ClaimRequestManagementService { "Could not resolve claim owner from blame parties", ); } - const damagedUserId = (() => { - const oid = String(ownerParty.person.userId); - const dp = (blameRequest.parties || []).find( - (p: any) => p.person?.userId && String(p.person.userId) !== oid, - ); - return dp?.person?.userId ? String(dp.person.userId) : null; - })(); + const damagedUserId = String(beneficiary.person!.userId); const newClaim = await this.claimCaseDbService.create({ requestNo: claimNo, publicId: blameRequest.publicId, @@ -9378,8 +7102,8 @@ export class ClaimRequestManagementService { owner: (() => { const cid = ownerParty.person.clientId; return { - userId: new Types.ObjectId(String(ownerParty.person.userId)), - userRole: ownerParty.role as any, + userId: new Types.ObjectId(String(beneficiary.person!.userId)), + userRole: beneficiary.role as any, fullName: currentUserParty.person?.fullName, userClientKey: cid ? String(cid) : undefined, ...(cid ? { clientId: new Types.ObjectId(String(cid)) } : {}), @@ -9488,7 +7212,11 @@ export class ClaimRequestManagementService { blameRequestNo: blameRequest.requestNo, initiatedByFieldExpertId: new Types.ObjectId(expert.sub), ...((blameRequest as any).branchId - ? { branchId: new Types.ObjectId(String((blameRequest as any).branchId)) } + ? { + branchId: new Types.ObjectId( + String((blameRequest as any).branchId), + ), + } : {}), status: ClaimCaseStatus.SELECTING_OUTER_PARTS, claimStatus: ClaimStatus.PENDING, @@ -9594,38 +7322,40 @@ export class ClaimRequestManagementService { }); const actorCtx = { sub: effectiveUserId, username: actor?.username }; - // 0. damagedPartyUserId stored directly on the claim (fastest, most reliable) - if (ownerUserIdMatchesActor(claimCase?.damagedPartyUserId, linkedUserIds)) { - return; - } - - // 1. Owner (= guilty party for THIRD_PARTY) — kept for backward compat - // on CAR_BODY where owner IS the damaged party. - if (ownerUserIdMatchesActor(claimCase?.owner?.userId, linkedUserIds)) { - return; - } - - // 2. Blame-based resolution (primary path for THIRD_PARTY) + // The linked blame decision is authoritative for historical claims whose + // owner.userId may still point to the guilty party. if (claimCase?.blameRequestId) { const blame = await this.blameRequestDbService.findById( - claimCase.blameRequestId.toString(), + String(claimCase.blameRequestId), ); - if ( - blame && - blameDamagedPartyMatchesUser(blame, actorCtx, linkedUserIds) - ) { - return; + if (blame) { + const beneficiary = resolveClaimBeneficiary(blame); + if ( + beneficiary && + partyPersonMatchesUser(beneficiary.person, actorCtx, linkedUserIds) + ) + return; + throw new ForbiddenException(message); } } - // 3. Snapshot-party fallback: claim.snapshot.parties is written at creation - // and is reliable even when blame lookup fails or userId mapping differs. + // A persisted beneficiary is authoritative when the source is unavailable. + if (ownerUserIdMatchesActor(claimCase?.damagedPartyUserId, linkedUserIds)) { + return; + } + if (claimCase?.damagedPartyUserId) throw new ForbiddenException(message); + + // Standalone legacy claims have no blame source; their owner is the beneficiary. if ( - this.claimSnapshotPartyMatchesAsDamagedParty(claimCase, linkedUserIds) + !claimCase?.blameRequestId && + !claimCase?.snapshot?.parties?.length && + ownerUserIdMatchesActor(claimCase?.owner?.userId, linkedUserIds) ) { return; } + // Snapshot party membership alone cannot establish liability: some older + // claims used the guilty party as owner, while in-person claims use the beneficiary. throw new ForbiddenException(message); } @@ -9757,7 +7487,10 @@ export class ClaimRequestManagementService { ); if (!blameRequest || blameRequest.creationMethod !== "IN_PERSON") return currentUserId; - if (actorRole === RoleEnum.FIELD_EXPERT || actorRole === RoleEnum.FILE_MAKER) { + if ( + actorRole === RoleEnum.FIELD_EXPERT || + actorRole === RoleEnum.FILE_MAKER + ) { if ( !blameRequest.expertInitiated || !blameRequest.initiatedByFieldExpertId || @@ -9880,108 +7613,6 @@ export class ClaimRequestManagementService { }; } - /** - * V2: Registrar creates a claim from a registrar-initiated IN_PERSON completed blame. - * Mirrors createClaimFromBlameForRegistrarV1 but uses V2 naming conventions. - */ - async createClaimFromBlameForRegistrarV2( - blameRequestId: string, - registrar: { sub: string; firstName?: string; lastName?: string }, - ): Promise { - const blameRequest = - await this.blameRequestDbService.findById(blameRequestId); - if (!blameRequest) throw new NotFoundException("Blame request not found"); - if (blameRequest.status !== BlameCaseStatus.COMPLETED) { - throw new BadRequestException( - `Blame request must be COMPLETED. Current status: ${blameRequest.status}`, - ); - } - if ( - !blameRequest.registrarInitiated || - blameRequest.creationMethod !== "IN_PERSON" || - !blameRequest.initiatedByRegistrarId - ) { - throw new BadRequestException( - "This endpoint is only for registrar-initiated IN_PERSON blame files.", - ); - } - if (String(blameRequest.initiatedByRegistrarId) !== String(registrar.sub)) { - throw new ForbiddenException( - "Only the registrar who created this blame file can create the claim.", - ); - } - const ownerFields = resolveClaimOwnerFieldsFromBlame(blameRequest); - if (!ownerFields) { - throw new BadRequestException( - "Could not resolve claim owner (damaged party) from blame", - ); - } - const existingClaim = await this.claimCaseDbService.findOne({ - blameRequestId: new Types.ObjectId(blameRequestId), - }); - if (existingClaim) - throw new ConflictException("A claim for this blame case already exists"); - const claimNo = await this.generateUniqueClaimNumber(); - const newClaim = await this.claimCaseDbService.create({ - requestNo: claimNo, - publicId: blameRequest.publicId, - blameRequestId: new Types.ObjectId(blameRequestId), - blameRequestNo: blameRequest.requestNo, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - claimStatus: ClaimStatus.PENDING, - inquiries: (blameRequest as any).inquiries ?? {}, - workflow: { - currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS, - nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS, - completedSteps: [ClaimWorkflowStep.CLAIM_CREATED], - locked: false, - }, - damagedPartyUserId: new Types.ObjectId(ownerFields.userId), - owner: { - userId: new Types.ObjectId(ownerFields.userId), - userRole: ownerFields.userRole as any, - ...(ownerFields.clientId - ? { - clientId: new Types.ObjectId(ownerFields.clientId), - userClientKey: ownerFields.clientId, - } - : {}), - }, - createdByRegistrarId: new Types.ObjectId(registrar.sub), - history: [ - { - type: "CLAIM_CREATED", - actor: { - actorId: new Types.ObjectId(registrar.sub), - actorName: - `${registrar.firstName || ""} ${registrar.lastName || ""}`.trim(), - actorType: "registrar", - }, - timestamp: new Date(), - metadata: { - blameRequestId, - blamePublicId: blameRequest.publicId, - createdByRegistrar: true, - }, - }, - ], - } as any); - const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated( - String(newClaim._id), - ); - const message = this.withFanavaranAutoSubmitMessage( - "Claim created successfully. Registrar can now fill claim data on behalf of the damaged party.", - fanavaran, - ); - return { - claimRequestId: String(newClaim._id), - publicId: blameRequest.publicId, - status: ClaimCaseStatus.SELECTING_OUTER_PARTS, - message, - fanavaran, - }; - } - /** * V2 API: Select damaged outer car parts for claim (Step 2 of claim workflow) * @@ -10038,8 +7669,7 @@ export class ClaimRequestManagementService { // For FILE_REVIEWER re-reviewing after a FileMaker rejection, the existing // selection from the prior cycle is intentionally overwritten — skip this // guard so the reviewer can update the damaged parts list. - const isFileReviewerReselect = - actor?.role === RoleEnum.FILE_REVIEWER; + const isFileReviewerReselect = actor?.role === RoleEnum.FILE_REVIEWER; if ( !isFileReviewerReselect && claimCase.damage?.selectedParts && @@ -10655,9 +8285,7 @@ export class ClaimRequestManagementService { }); // Calculate progress - const requiredDocumentItems = requiredDocuments.filter( - (d) => d.required, - ); + const requiredDocumentItems = requiredDocuments.filter((d) => d.required); const documentsUploaded = requiredDocumentItems.filter( (d) => d.uploaded, ).length; @@ -10835,7 +8463,12 @@ export class ClaimRequestManagementService { file: Express.Multer.File, currentUserId: string, actor?: { sub: string; role?: string }, - options?: { v3InPersonFlow?: boolean; skipMetalPlate?: boolean; requiresFileMakerApproval?: boolean; includeGuiltyDamageArea?: boolean }, + options?: { + v3InPersonFlow?: boolean; + skipMetalPlate?: boolean; + requiresFileMakerApproval?: boolean; + includeGuiltyDamageArea?: boolean; + }, ): Promise { try { const claimCase = await this.claimCaseDbService.findById(claimRequestId); @@ -11019,10 +8652,16 @@ export class ClaimRequestManagementService { this.isRequiredDocumentUploadedOnClaim(claimCase, k); const captureKeysForCount: string[] = [ ...CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS, - ...(options?.includeGuiltyDamageArea ? [GUILTY_DAMAGE_AREA_DOC_KEY] : []), + ...(options?.includeGuiltyDamageArea + ? [GUILTY_DAMAGE_AREA_DOC_KEY] + : []), ]; remaining = captureKeysForCount.filter((k) => { - if (options?.skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)) return false; + if ( + options?.skipMetalPlate && + OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any) + ) + return false; return !afterThis(k); }).length; @@ -11045,8 +8684,10 @@ export class ClaimRequestManagementService { // setVideoCaptureV3 (car-capture), which is the last FileReviewer // action before handing off to the damage expert. $set["status"] = ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS; - $set["workflow.currentStep"] = ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS; - $set["workflow.nextStep"] = ClaimWorkflowStep.USER_SUBMISSION_COMPLETE; + $set["workflow.currentStep"] = + ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS; + $set["workflow.nextStep"] = + ClaimWorkflowStep.USER_SUBMISSION_COMPLETE; completedStepsEntries.push( ClaimWorkflowStep.CAPTURE_PART_DAMAGES, @@ -11166,10 +8807,7 @@ export class ClaimRequestManagementService { undefined, options?.skipMetalPlate, ) - : this.countRemainingV2OwnerDocuments( - claimCase, - isCarBodyUpload, - ); + : this.countRemainingV2OwnerDocuments(claimCase, isCarBodyUpload); } // Build the final MongoDB update — all operators explicit and clean @@ -11200,20 +8838,34 @@ export class ClaimRequestManagementService { // the stale snapshot we read earlier missed it — or vice-versa), we apply // WAITING_FOR_FILE_REVIEWER atomically using findOneAndUpdate with a status // condition, so exactly one writer wins regardless of concurrency. - if (options?.v3InPersonFlow && !isResendUpload && !isCapturePhaseDocUpload) { - const afterWrite = await this.claimCaseDbService.findById(claimRequestId); + if ( + options?.v3InPersonFlow && + !isResendUpload && + !isCapturePhaseDocUpload + ) { + const afterWrite = + await this.claimCaseDbService.findById(claimRequestId); if (afterWrite) { const blameForRecheck = afterWrite.blameRequestId ? await this.blameRequestDbService.findById( afterWrite.blameRequestId.toString(), ) : null; - const isCarBodyRecheck = blameForRecheck?.type === BlameRequestType.CAR_BODY; - const skipMetalPlateRecheck = !!(blameForRecheck as any)?.isMadeByFileMaker; + const isCarBodyRecheck = + blameForRecheck?.type === BlameRequestType.CAR_BODY; + const skipMetalPlateRecheck = !!(blameForRecheck as any) + ?.isMadeByFileMaker; const allDoneNow = - afterWrite.status === ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS && - afterWrite.workflow?.currentStep === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && - this.allV3PreCaptureDocumentsComplete(afterWrite, isCarBodyRecheck, undefined, skipMetalPlateRecheck); + afterWrite.status === + ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS && + afterWrite.workflow?.currentStep === + ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && + this.allV3PreCaptureDocumentsComplete( + afterWrite, + isCarBodyRecheck, + undefined, + skipMetalPlateRecheck, + ); if (allDoneNow) { // Atomic conditional update: only succeeds when status is still @@ -11229,7 +8881,8 @@ export class ClaimRequestManagementService { "workflow.nextStep": ClaimWorkflowStep.SELECT_OUTER_PARTS, }, $push: { - "workflow.completedSteps": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, + "workflow.completedSteps": + ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, history: { type: "STEP_COMPLETED", actor: { @@ -11258,7 +8911,9 @@ export class ClaimRequestManagementService { if (blameId) { await this.blameRequestDbService.findByIdAndUpdate( String(blameId), - { $set: { status: BlameCaseStatus.WAITING_FOR_FILE_REVIEWER } }, + { + $set: { status: BlameCaseStatus.WAITING_FOR_FILE_REVIEWER }, + }, ); } } @@ -11282,8 +8937,13 @@ export class ClaimRequestManagementService { !isResendUpload && !options?.v3InPersonFlow ) { - this.submitFanavaranAttachmentsV2(claimRequestId, resolveFanavaranClientKey()).catch( - (err) => this.logger.warn(`Fanavaran attachments auto-submit failed: ${err?.message}`), + this.submitFanavaranAttachmentsV2( + claimRequestId, + resolveFanavaranClientKey(), + ).catch((err) => + this.logger.warn( + `Fanavaran attachments auto-submit failed: ${err?.message}`, + ), ); } @@ -11324,22 +8984,22 @@ export class ClaimRequestManagementService { const message = isOptionalDocument ? "Optional accident sketch uploaded successfully." : isCapturePhaseDocUpload - ? captureStepCompletedOnThisUpload - ? options?.v3InPersonFlow - ? "Capture-phase documents and all damage captures are complete. Upload the walk-around video (car-capture) to finalise." - : "Capture-phase documents and all damage captures are complete. Please proceed to upload the remaining required documents." - : remaining > 0 - ? `Document saved. ${remaining} capture-phase document(s) still required (chassis, engine, metal plate).` - : capturePhaseSequenceMessage( - getClaimCaptureProgress(claimCase, { - assumeCapturePhaseDocKey: body.documentKey, - }).sequencePhase, - ) - : allDocumentsUploaded - ? options?.v3InPersonFlow - ? "All FileMaker documents uploaded. File is sealed and ready for FileReviewer pickup." - : "All documents uploaded successfully. Your claim is now ready for damage expert review." - : `Document uploaded successfully. ${remaining} documents remaining.`; + ? captureStepCompletedOnThisUpload + ? options?.v3InPersonFlow + ? "Capture-phase documents and all damage captures are complete. Upload the walk-around video (car-capture) to finalise." + : "Capture-phase documents and all damage captures are complete. Please proceed to upload the remaining required documents." + : remaining > 0 + ? `Document saved. ${remaining} capture-phase document(s) still required (chassis, engine, metal plate).` + : capturePhaseSequenceMessage( + getClaimCaptureProgress(claimCase, { + assumeCapturePhaseDocKey: body.documentKey, + }).sequencePhase, + ) + : allDocumentsUploaded + ? options?.v3InPersonFlow + ? "All FileMaker documents uploaded. File is sealed and ready for FileReviewer pickup." + : "All documents uploaded successfully. Your claim is now ready for damage expert review." + : `Document uploaded successfully. ${remaining} documents remaining.`; return { claimRequestId: claimCase._id.toString(), @@ -11349,14 +9009,14 @@ export class ClaimRequestManagementService { currentStep: isOptionalDocument ? step || ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS : isCapturePhaseDocUpload - ? captureStepCompletedOnThisUpload - ? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - : ClaimWorkflowStep.CAPTURE_PART_DAMAGES - : allDocumentsUploaded - ? options?.v3InPersonFlow + ? captureStepCompletedOnThisUpload ? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS - : ClaimWorkflowStep.USER_SUBMISSION_COMPLETE - : ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, + : ClaimWorkflowStep.CAPTURE_PART_DAMAGES + : allDocumentsUploaded + ? options?.v3InPersonFlow + ? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS + : ClaimWorkflowStep.USER_SUBMISSION_COMPLETE + : ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, message, fanavaranAttachment: await this.autoSubmitFanavaranAttachment( claimRequestId, @@ -11595,8 +9255,7 @@ export class ClaimRequestManagementService { } // Re-read so capture-progress sees sibling concurrent part/angle writes. const updatedClaim = - (await this.claimCaseDbService.findById(claimRequestId)) ?? - claimCase; + (await this.claimCaseDbService.findById(claimRequestId)) ?? claimCase; if (isResendCapture) { await this.tryFinalizeExpertResendAfterUserAction( @@ -12563,7 +10222,11 @@ export class ClaimRequestManagementService { const blamesForList = blameIdsForList.length > 0 ? ((await this.blameRequestDbService.find( - { _id: { $in: blameIdsForList.map((id) => new Types.ObjectId(id)) } }, + { + _id: { + $in: blameIdsForList.map((id) => new Types.ObjectId(id)), + }, + }, { lean: true, select: "type creationMethod status" }, )) as any[]) : []; @@ -12650,7 +10313,7 @@ export class ClaimRequestManagementService { async getClaimDetailsV2( claimRequestId: string, currentUserId: string, - actor?: { sub: string; role?: string }, + actor?: { sub: string; role?: string; username?: string }, ): Promise { try { const claim = await this.claimCaseDbService.findById(claimRequestId); @@ -12787,6 +10450,22 @@ export class ClaimRequestManagementService { const isExpertViewer = actor?.role === RoleEnum.FIELD_EXPERT || actor?.role === RoleEnum.REGISTRAR; + let canAct = false; + try { + const effectiveUserId = await this.resolveClaimEffectiveUserId( + claim, + currentUserId, + actor?.role, + ); + await this.assertEffectiveUserIsDamagedPartyOnClaim( + claim, + effectiveUserId, + actor, + ); + canAct = true; + } catch (error) { + if (!(error instanceof ForbiddenException)) throw error; + } const ownerData = claim.owner ? { userId: claim.owner.userId?.toString(), @@ -12819,6 +10498,7 @@ export class ClaimRequestManagementService { return { claimRequestId: claim._id.toString(), + canAct, publicId: claim.publicId, requestNo: claim.requestNo, status: claim.status, @@ -12849,7 +10529,7 @@ export class ClaimRequestManagementService { damageExpertReplyFinal: mappedEvaluation.damageExpertReplyFinal, } : undefined, - ...(!isExpertViewer + ...(!isExpertViewer && canAct ? { ownerGuidance: buildClaimDetailsV2OwnerGuidance( claim, @@ -12893,17 +10573,6 @@ export class ClaimRequestManagementService { ); } - private hasPartyInquiriesOnBlame( - blame: any, - role: "FIRST" | "SECOND", - ): boolean { - const step = - role === "FIRST" - ? WorkflowStep.FIRST_INITIAL_FORM - : WorkflowStep.SECOND_INITIAL_FORM; - return (blame.workflow?.completedSteps ?? []).includes(step); - } - private partyHasSignedOnBlame(blame: any, role: "FIRST" | "SECOND"): boolean { const party = (blame.parties ?? []).find((p: any) => p?.role === role); return !!party?.confirmation; @@ -13164,7 +10833,10 @@ export class ClaimRequestManagementService { const capturePhaseDocs = base.requiredDocuments.filter( (d) => d.preferUploadDuringCapture && - !(skipMetalPlate && OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(d.key as any)), + !( + skipMetalPlate && + OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(d.key as any) + ), ); // V4 THIRD_PARTY only: guilty_damage_area is uploaded via upload-document @@ -13196,7 +10868,8 @@ export class ClaimRequestManagementService { totalRemaining: captureProgress.capturePhaseDocsRemaining, progress: { ...base.progress, - capturePhaseDocsRemaining: captureProgress.capturePhaseDocsRemaining, + capturePhaseDocsRemaining: + captureProgress.capturePhaseDocsRemaining, }, }; } @@ -13271,7 +10944,8 @@ export class ClaimRequestManagementService { !isCarBodyBlame; const isCaptureDoc = - isCapturePhaseDamagedPartyDocKey(body.documentKey) || isGuiltyDamageAreaDoc; + isCapturePhaseDamagedPartyDocKey(body.documentKey) || + isGuiltyDamageAreaDoc; if (isCaptureDoc) { this.assertV3ClaimPartsPhase(blame); @@ -13330,7 +11004,8 @@ export class ClaimRequestManagementService { { v3InPersonFlow: true, skipMetalPlate, - requiresFileMakerApproval: !!(claimCase as any).requiresFileMakerApproval, + requiresFileMakerApproval: !!(claimCase as any) + .requiresFileMakerApproval, includeGuiltyDamageArea, }, ); @@ -13390,7 +11065,12 @@ export class ClaimRequestManagementService { "Select outer parts after accident fields and required documents.", ); - const result = await this.selectOuterPartsV2(claimRequestId, body, currentUserId, actor); + const result = await this.selectOuterPartsV2( + claimRequestId, + body, + currentUserId, + actor, + ); return result; } @@ -13529,7 +11209,10 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { $unset: { "media.videoCaptureId": "" }, }); - claimCase.media = { ...(claimCase.media ?? {}), videoCaptureId: undefined } as any; + claimCase.media = { + ...(claimCase.media ?? {}), + videoCaptureId: undefined, + } as any; } else { throw new ConflictException( "A walk-around video has already been uploaded for this claim.", @@ -13546,7 +11229,9 @@ export class ClaimRequestManagementService { ); } - const captureProgress = getClaimCaptureProgress(claimCase, { skipMetalPlate }); + const captureProgress = getClaimCaptureProgress(claimCase, { + skipMetalPlate, + }); if (!captureProgress.partsComplete) { throw new BadRequestException( "Upload photos for all selected damaged parts before the walk-around video.", @@ -13585,7 +11270,8 @@ export class ClaimRequestManagementService { "workflow.nextStep": undefined, }, $push: { - "workflow.completedSteps": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, + "workflow.completedSteps": + ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, history: { type: "STEP_COMPLETED", actor: { @@ -13621,12 +11307,16 @@ export class ClaimRequestManagementService { actor: { actorId: new Types.ObjectId(currentUserId), actorName: claimCase.owner?.fullName || "User", - actorType: actor?.role === RoleEnum.FILE_REVIEWER ? "file_reviewer" : "user", + actorType: + actor?.role === RoleEnum.FILE_REVIEWER + ? "file_reviewer" + : "user", }, timestamp: new Date(), metadata: { stepKey: ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - description: "V4/V5 walk-around video uploaded. Claim ready for damage expert review.", + description: + "V4/V5 walk-around video uploaded. Claim ready for damage expert review.", v3InPersonFlow: true, }, }, diff --git a/src/claim-request-management/dto/claim-detail.ts b/src/claim-request-management/dto/claim-detail.ts deleted file mode 100644 index eaae5ca..0000000 --- a/src/claim-request-management/dto/claim-detail.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { ClaimRequestManagementModel } from "src/claim-request-management/entites/schema/claim-request-management.schema"; - -export class ClaimPartUploadDetail { - list: any; - constructor(claimFile: ClaimRequestManagementModel[]) { - this.list = claimFile - .map((c) => { - return { - carPartDamage: c.carPartDamage, - carOtherPartDamage: c.otherParts, - greenCardUpload: !!c.carGreenCard.path, - }; - }) - .flat(2); - } -} diff --git a/src/claim-request-management/dto/claim-details-v2.dto.ts b/src/claim-request-management/dto/claim-details-v2.dto.ts index 744254c..40ad3d7 100644 --- a/src/claim-request-management/dto/claim-details-v2.dto.ts +++ b/src/claim-request-management/dto/claim-details-v2.dto.ts @@ -1,61 +1,65 @@ -import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { DamageSelectedPartV2BodyDto } from './damage-selected-part-v2.dto'; +import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; +import { DamageSelectedPartV2BodyDto } from "./damage-selected-part-v2.dto"; /** Suggested HTTP call for the owner UI (`pathTemplate`: replace placeholders). */ export class ClaimDetailsOwnerNextActionV2Dto { - @ApiProperty({ description: 'Stable UI key', example: 'FINAL_SIGN' }) + @ApiProperty({ description: "Stable UI key", example: "FINAL_SIGN" }) key: string; - @ApiPropertyOptional({ description: 'HTTP verb', example: 'PUT' }) + @ApiPropertyOptional({ description: "HTTP verb", example: "PUT" }) method?: string; @ApiPropertyOptional({ - description: 'Path under API root', - example: 'v2/claim-request-management/request/{claimRequestId}/owner-insurer-approval/sign', + description: "Path under API root", + example: + "v2/claim-request-management/request/{claimRequestId}/owner-insurer-approval/sign", }) pathTemplate?: string; - @ApiProperty({ description: 'What this endpoint does for the user' }) + @ApiProperty({ description: "What this endpoint does for the user" }) description: string; } /** Server-derived hints: which phase the claim is in and what to offer next (owners only). */ export class ClaimDetailsOwnerGuidanceV2Dto { @ApiProperty({ - description: 'Machine-readable phase', + description: "Machine-readable phase", enum: [ - 'COMPLETED', - 'REJECTED', - 'CANCELLED', - 'EXPERT_RESEND', - 'WAITING_DAMAGE_EXPERT', - 'EXPERT_REVIEWING', - 'USER_FLOW', - 'UPLOAD_FACTORS', - 'EXPERT_VALIDATING_FACTORS', - 'SIGN_PRICED_LINES', - 'INSURER_REVIEW_NEEDS_REVISION', - 'FINAL_SIGN_OR_REJECT', - 'INSURER_APPROVAL_FALLBACK', + "COMPLETED", + "REJECTED", + "CANCELLED", + "EXPERT_RESEND", + "WAITING_DAMAGE_EXPERT", + "EXPERT_REVIEWING", + "USER_FLOW", + "UPLOAD_FACTORS", + "EXPERT_VALIDATING_FACTORS", + "SIGN_PRICED_LINES", + "INSURER_REVIEW_NEEDS_REVISION", + "FINAL_SIGN_OR_REJECT", + "INSURER_APPROVAL_FALLBACK", ], }) phaseKey: string; - @ApiProperty({ description: 'Short headline for the current phase' }) + @ApiProperty({ description: "Short headline for the current phase" }) headline: string; - @ApiPropertyOptional({ description: 'Longer UX copy' }) + @ApiPropertyOptional({ description: "Longer UX copy" }) detail?: string; @ApiProperty({ type: [ClaimDetailsOwnerNextActionV2Dto] }) nextActions: ClaimDetailsOwnerNextActionV2Dto[]; @ApiPropertyOptional({ - description: 'Whether PUT objection is permitted (see server validation for exact rules)', + description: + "Whether PUT objection is permitted (see server validation for exact rules)", }) objectionAllowed?: boolean; - @ApiPropertyOptional({ description: 'How objection relates to priced vs factor-only lines' }) + @ApiPropertyOptional({ + description: "How objection relates to priced vs factor-only lines", + }) objectionHint?: string; } @@ -86,18 +90,26 @@ export class ExpertResendDetailsV2Dto { fileName?: string; }>; - @ApiPropertyOptional({ description: 'Set when the owner satisfied the resend request' }) + @ApiPropertyOptional({ + description: "Set when the owner satisfied the resend request", + }) fulfilledAt?: Date; } export class ClaimDetailsV2ResponseDto { - @ApiProperty({ description: 'Claim case ID' }) + @ApiProperty({ + description: + "Whether this authorized viewer may act for the claim beneficiary. False means read-only access.", + }) + canAct: boolean; + + @ApiProperty({ description: "Claim case ID" }) claimRequestId: string; - @ApiProperty({ description: 'Public ID' }) + @ApiProperty({ description: "Public ID" }) publicId: string; - @ApiProperty({ description: 'Request number' }) + @ApiProperty({ description: "Request number" }) requestNo: string; @ApiProperty({ @@ -107,35 +119,36 @@ export class ClaimDetailsV2ResponseDto { }) status: string; - @ApiProperty({ description: 'Claim damage status' }) + @ApiProperty({ description: "Claim damage status" }) claimStatus: string; - @ApiProperty({ description: 'Current workflow step' }) + @ApiProperty({ description: "Current workflow step" }) currentStep: string; - @ApiPropertyOptional({ description: 'Next workflow step' }) + @ApiPropertyOptional({ description: "Next workflow step" }) nextStep?: string; - @ApiPropertyOptional({ description: 'Blame request ID' }) + @ApiPropertyOptional({ description: "Blame request ID" }) blameRequestId?: string; - @ApiPropertyOptional({ description: 'Blame request number' }) + @ApiPropertyOptional({ description: "Blame request number" }) blameRequestNo?: string; @ApiPropertyOptional({ - description: 'Blame file type: THIRD_PARTY or CAR_BODY', - example: 'THIRD_PARTY', + description: "Blame file type: THIRD_PARTY or CAR_BODY", + example: "THIRD_PARTY", }) blameType?: string; @ApiPropertyOptional({ - description: 'How the blame file was initiated: IN_PERSON or LINK', - example: 'IN_PERSON', + description: "How the blame file was initiated: IN_PERSON or LINK", + example: "IN_PERSON", }) creationMethod?: string; @ApiPropertyOptional({ - description: 'Claim owner (damaged party): ids for the user and their insurer client scope', + description: + "Claim owner (damaged party): ids for the user and their insurer client scope", }) owner?: { userId: string; @@ -144,7 +157,7 @@ export class ClaimDetailsV2ResponseDto { fullName?: string; }; - @ApiPropertyOptional({ description: 'Vehicle snapshot' }) + @ApiPropertyOptional({ description: "Vehicle snapshot" }) vehicle?: { carName?: string; carModel?: string; @@ -153,42 +166,45 @@ export class ClaimDetailsV2ResponseDto { }; @ApiPropertyOptional({ - description: 'Selected outer damaged parts (ordered objects with id, name, side, label_fa)', + description: + "Selected outer damaged parts (ordered objects with id, name, side, label_fa)", type: [DamageSelectedPartV2BodyDto], }) selectedParts?: DamageSelectedPartV2BodyDto[]; - @ApiPropertyOptional({ description: 'Selected other damaged parts' }) + @ApiPropertyOptional({ description: "Selected other damaged parts" }) otherParts?: string[]; - @ApiPropertyOptional({ description: 'Bank info (masked)' }) + @ApiPropertyOptional({ description: "Bank info (masked)" }) money?: { sheba?: string; nationalCodeOfOwner?: string; }; - @ApiPropertyOptional({ description: 'Required documents status (link instead of id)' }) + @ApiPropertyOptional({ + description: "Required documents status (link instead of id)", + }) requiredDocuments?: Record; - @ApiPropertyOptional({ description: 'Car angles captured' }) + @ApiPropertyOptional({ description: "Car angles captured" }) carAngles?: Record; @ApiPropertyOptional({ description: - 'Per-part capture status and URLs (array index aligns with selectedParts; includes id, name, side, label_fa)', - type: 'array', + "Per-part capture status and URLs (array index aligns with selectedParts; includes id, name, side, label_fa)", + type: "array", items: { - type: 'object', + type: "object", properties: { - index: { type: 'number' }, - id: { type: 'number', nullable: true }, - name: { type: 'string' }, - side: { type: 'string' }, - label_fa: { type: 'string' }, - captured: { type: 'boolean' }, - url: { type: 'string' }, - path: { type: 'string' }, - fileName: { type: 'string' }, + index: { type: "number" }, + id: { type: "number", nullable: true }, + name: { type: "string" }, + side: { type: "string" }, + label_fa: { type: "string" }, + captured: { type: "boolean" }, + url: { type: "string" }, + path: { type: "string" }, + fileName: { type: "string" }, }, }, }) @@ -206,16 +222,16 @@ export class ClaimDetailsV2ResponseDto { @ApiPropertyOptional({ description: - 'Append-only expert damaged-part revisions. Removed rows retain their original capture URL.', - type: 'array', + "Append-only expert damaged-part revisions. Removed rows retain their original capture URL.", + type: "array", items: { - type: 'object', + type: "object", properties: { - revisionId: { type: 'string' }, - changedAt: { type: 'string', format: 'date-time' }, - changedBy: { type: 'object' }, - removedParts: { type: 'array', items: { type: 'object' } }, - addedParts: { type: 'array', items: { type: 'object' } }, + revisionId: { type: "string" }, + changedAt: { type: "string", format: "date-time" }, + changedBy: { type: "object" }, + removedParts: { type: "array", items: { type: "object" } }, + addedParts: { type: "array", items: { type: "object" } }, }, }, }) @@ -233,7 +249,7 @@ export class ClaimDetailsV2ResponseDto { @ApiPropertyOptional({ description: - 'Damage expert resend instructions and progress (when status is WAITING_FOR_USER_RESEND).', + "Damage expert resend instructions and progress (when status is WAITING_FOR_USER_RESEND).", }) expertResend?: ExpertResendDetailsV2Dto; @@ -255,7 +271,8 @@ export class ClaimDetailsV2ResponseDto { }; @ApiPropertyOptional({ - description: "Damage expert opinion(s): initial and final (after objection).", + description: + "Damage expert opinion(s): initial and final (after objection).", type: Object, }) evaluation?: { @@ -266,11 +283,13 @@ export class ClaimDetailsV2ResponseDto { @ApiPropertyOptional({ type: ClaimDetailsOwnerGuidanceV2Dto, description: - 'Owner-only: derived headline, suggested API routes, and whether objection is plausible. Omitted when the actor is FIELD_EXPERT.', + "Owner-only: derived headline, suggested API routes, and whether objection is plausible. Omitted when the actor is FIELD_EXPERT.", }) ownerGuidance?: ClaimDetailsOwnerGuidanceV2Dto; - @ApiPropertyOptional({ description: 'User satisfaction rating (if submitted)' }) + @ApiPropertyOptional({ + description: "User satisfaction rating (if submitted)", + }) userRating?: { progressSpeed: number; registrationEase: number; @@ -279,9 +298,9 @@ export class ClaimDetailsV2ResponseDto { createdAt?: Date; }; - @ApiProperty({ description: 'Created at' }) + @ApiProperty({ description: "Created at" }) createdAt: string; - @ApiProperty({ description: 'Updated at' }) + @ApiProperty({ description: "Updated at" }) updatedAt: string; } diff --git a/src/claim-request-management/dto/claim-rs-dto.ts b/src/claim-request-management/dto/claim-rs-dto.ts deleted file mode 100644 index af30a7e..0000000 --- a/src/claim-request-management/dto/claim-rs-dto.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { ClaimRequestManagementModel } from "src/claim-request-management/entites/schema/claim-request-management.schema"; -import { ReqClaimStatus } from "src/Types&Enums/claim-request-management/status.enum"; - -export class ClaimRequestDtoRs { - requestDetail: any; - messsage: string; - status: ReqClaimStatus; - constructor( - req: ClaimRequestManagementModel, - message: string, - status: ReqClaimStatus, - ) { - this.requestDetail = req; - this.messsage = message; - this.status = status; - } -} diff --git a/src/claim-request-management/dto/create-claim.dto.ts b/src/claim-request-management/dto/create-claim.dto.ts deleted file mode 100644 index b207cce..0000000 --- a/src/claim-request-management/dto/create-claim.dto.ts +++ /dev/null @@ -1,8 +0,0 @@ -export class CreateClaimRequestDtoRs { - message: string; - requestId: string; - constructor(requestId: string, message: string) { - this.requestId = requestId; - this.message = message; - } -} diff --git a/src/claim-request-management/dto/image-required.dto.ts b/src/claim-request-management/dto/image-required.dto.ts deleted file mode 100644 index 6b2f21f..0000000 --- a/src/claim-request-management/dto/image-required.dto.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { ClaimRequestManagementModel } from "src/claim-request-management/entites/schema/claim-request-management.schema"; - -export class ImageRequiredDto { - public list: {} = {}; - constructor(imageModel: ClaimRequestManagementModel) { - this.list = imageModel.imageRequired; - } -} diff --git a/src/claim-request-management/dto/my-request.dto.ts b/src/claim-request-management/dto/my-request.dto.ts deleted file mode 100644 index c6fe62f..0000000 --- a/src/claim-request-management/dto/my-request.dto.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { Types } from "mongoose"; -import { ClaimRequestManagementModel } from "src/claim-request-management/entites/schema/claim-request-management.schema"; -import { ReqClaimStatus } from "src/Types&Enums/claim-request-management/status.enum"; - -export class MyRequestsDtoList { - status: ReqClaimStatus; - submitDate: string; - numberOfRequest: number; - _id: Types.ObjectId; - constructor(request: ClaimRequestManagementModel) { - this._id = request["_id"]; - this.status = request.claimStatus; - this.submitDate = new Date(request.createdAt).toLocaleString("fa-IR"); - this.numberOfRequest = request.requestNumber; - } -} - -export class MyRequestsDto { - public list = []; - constructor(requests: ClaimRequestManagementModel[]) { - this.list = requests.map((r) => new MyRequestsDtoList(r)); - } -} diff --git a/src/claim-request-management/dto/submit-reply.dto.ts b/src/claim-request-management/dto/submit-reply.dto.ts deleted file mode 100644 index 01e3ff2..0000000 --- a/src/claim-request-management/dto/submit-reply.dto.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ClaimRequestManagementModel } from "src/claim-request-management/entites/schema/claim-request-management.schema"; -import { UserCommentDto } from "src/claim-request-management/dto/user-comment.dto"; - -export class SubmitUserReplyDtoRs { - requestId: string; - partsNeedFactorDetail: object; - partsNeedFactor: boolean; - userComment: UserCommentDto; - constructor( - claim: ClaimRequestManagementModel, - partsFactorDetail?, - partsNeedFactor?, - ) { - this.requestId = claim["_id"]; - this.partsNeedFactorDetail = partsFactorDetail; - this.partsNeedFactor = partsNeedFactor; - this.userComment = claim.damageExpertReply.userComment; - } -} diff --git a/src/claim-request-management/dto/user-comment.dto.ts b/src/claim-request-management/dto/user-comment.dto.ts deleted file mode 100644 index 705e279..0000000 --- a/src/claim-request-management/dto/user-comment.dto.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { ApiProperty } from "@nestjs/swagger"; - -export class UserCommentDto { - @ApiProperty({ type: Boolean }) - isAccept: boolean; - - @ApiProperty({ type: "string", format: "binary", required: false }) - file?: Express.Multer.File; - - @ApiProperty({ type: String }) - branch?: string; -} diff --git a/src/claim-request-management/dto/user-reply.dto.ts b/src/claim-request-management/dto/user-reply.dto.ts deleted file mode 100644 index 88eba59..0000000 --- a/src/claim-request-management/dto/user-reply.dto.ts +++ /dev/null @@ -1,4 +0,0 @@ -export class UserReplyDtoRs { - requestId: string; - isAccept: string; -} diff --git a/src/claim-request-management/entites/db-service/car-green-card.db.service.ts b/src/claim-request-management/entites/db-service/car-green-card.db.service.ts deleted file mode 100644 index 4a10162..0000000 --- a/src/claim-request-management/entites/db-service/car-green-card.db.service.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { InjectModel } from "@nestjs/mongoose"; -import { FilterQuery, Model } from "mongoose"; -import { CarGreenCardModel } from "src/claim-request-management/entites/schema/car-green-card.schema"; - -export class CarGreenCardDbService { - constructor( - @InjectModel(CarGreenCardModel.name) - private readonly model: Model, - ) {} - async create(greenCard): Promise { - return await this.model.create(greenCard); - } - - async findOne( - filter: FilterQuery, - ): Promise { - return await this.model.findOne({ filter }); - } -} diff --git a/src/claim-request-management/entites/db-service/claim-case.db.service.ts b/src/claim-request-management/entites/db-service/claim-case.db.service.ts index 60f23cf..d55f80a 100644 --- a/src/claim-request-management/entites/db-service/claim-case.db.service.ts +++ b/src/claim-request-management/entites/db-service/claim-case.db.service.ts @@ -14,11 +14,15 @@ export class ClaimCaseDbService { return this.claimCaseModel.create(payload); } - async findById(id: string | Types.ObjectId): Promise { + async findById( + id: string | Types.ObjectId, + ): Promise { return this.claimCaseModel.findById(id); } - async findOne(filter: FilterQuery): Promise { + async findOne( + filter: FilterQuery, + ): Promise { return this.claimCaseModel.findOne(filter); } @@ -54,8 +58,4 @@ export class ClaimCaseDbService { : this.claimCaseModel.find(filter); return query.exec() as Promise; } - - async countByFilter(filter: FilterQuery): Promise { - return this.claimCaseModel.countDocuments(filter); - } } diff --git a/src/claim-request-management/entites/db-service/claim-request-management.db.service.ts b/src/claim-request-management/entites/db-service/claim-request-management.db.service.ts index 00bc32b..9c67588 100644 --- a/src/claim-request-management/entites/db-service/claim-request-management.db.service.ts +++ b/src/claim-request-management/entites/db-service/claim-request-management.db.service.ts @@ -11,16 +11,6 @@ export class ClaimRequestManagementDbService { private readonly model: Model, ) {} - async create( - claimRequest: ClaimRequestManagementModel, - ): Promise { - const uniqueRequestNumber = await this.generateUniqueNumbers(); - return this.model.create({ - ...claimRequest, - requestNumber: uniqueRequestNumber, - }); - } - async findOne( id?: string, filter?: FilterQuery, @@ -45,31 +35,6 @@ export class ClaimRequestManagementDbService { return await this.model.findOneAndUpdate(filter, update, option); } - async findAllByStatus(filter: FilterQuery) { - return await this.model.find(filter); - } - - async findAndDelete( - filter: FilterQuery, - option, - ) { - return await this.model.deleteMany(filter, option); - } - - async findAllAndPagination( - filter: FilterQuery, - currentPage: number, - countPerPage: number, - ) { - const responsePerPage = countPerPage | 1; - const skipPge = responsePerPage * (Number(currentPage) - 1); - return await this.model.find(filter).limit(responsePerPage).skip(skipPge); - } - - async aggregate(filter?) { - return await this.model.aggregate(filter); - } - async findAndUpdate( id: string, update: UpdateQuery, @@ -81,41 +46,4 @@ export class ClaimRequestManagementDbService { option, ); } - - async findAllByAnyFilter( - filter: FilterQuery, - ): Promise { - return await this.model.find(filter); - } - - async countByFilter( - filter: FilterQuery, - ): Promise { - return await this.model.countDocuments(filter); - } - async findAll(): Promise { - return await this.model.find(); - } - async generateUniqueNumbers(digits = 5) { - try { - const max = Math.pow(10, digits); - const randomBytes = crypto.randomBytes(Math.ceil(digits / 2)); - const randomNumber = parseInt(randomBytes.toString("hex"), 16) % max; - return randomNumber.toString().padStart(digits, "0"); - } catch (error) { - console.error("Error generating unique numbers:", error); - throw error; - } - } - - async findAllWithFilter(filter?: FilterQuery) { - return await this.model.find(filter); - } - - async findByIdAndUpdate( - id: string, - updateDto: UpdateQuery, - ): Promise { - return this.model.findByIdAndUpdate(id, updateDto, { new: true }).lean(); - } } diff --git a/src/claim-request-management/entites/db-service/claim-required-document.db.service.ts b/src/claim-request-management/entites/db-service/claim-required-document.db.service.ts index 73b8250..04042ef 100644 --- a/src/claim-request-management/entites/db-service/claim-required-document.db.service.ts +++ b/src/claim-request-management/entites/db-service/claim-required-document.db.service.ts @@ -1,6 +1,6 @@ import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; -import { FilterQuery, Model, Types } from "mongoose"; +import { Model, Types } from "mongoose"; import { ClaimRequiredDocument } from "src/claim-request-management/entites/schema/claim-required-document.schema"; @Injectable() @@ -10,32 +10,13 @@ export class ClaimRequiredDocumentDbService { private readonly model: Model, ) {} - async create(document: Partial): Promise { + async create( + document: Partial, + ): Promise { return await this.model.create(document); } - async findOne( - filter: FilterQuery, - ): Promise { - return await this.model.findOne(filter); - } - - async findAll( - filter: FilterQuery, - ): Promise { - return await this.model.find(filter); - } - - async findById(id: string): Promise { - return this.model.findById(id).lean(); - } - async findByClaimId(claimId: string): Promise { return this.model.find({ claimId: new Types.ObjectId(claimId) }); } - - async delete(id: string): Promise { - await this.model.findByIdAndDelete(id); - } } - diff --git a/src/claim-request-management/entites/db-service/damage-image.db.service.ts b/src/claim-request-management/entites/db-service/damage-image.db.service.ts deleted file mode 100644 index 4a9b139..0000000 --- a/src/claim-request-management/entites/db-service/damage-image.db.service.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { InjectModel } from "@nestjs/mongoose"; -import { Model, Types } from "mongoose"; -import { DamagePartImageModel } from "src/claim-request-management/entites/schema/damage-image-part.schema"; - -export class DamageImageDbService { - constructor( - @InjectModel(DamagePartImageModel.name) - private readonly model: Model, - ) {} - - async create(image): Promise { - return await this.model.create(image); - } - - async findOne(id: string): Promise { - return await this.model.findById(new Types.ObjectId(id)); - } -} diff --git a/src/claim-request-management/entites/db-service/factor-image.db.service.ts b/src/claim-request-management/entites/db-service/factor-image.db.service.ts index 1d6f52f..5348448 100644 --- a/src/claim-request-management/entites/db-service/factor-image.db.service.ts +++ b/src/claim-request-management/entites/db-service/factor-image.db.service.ts @@ -1,6 +1,6 @@ import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; -import { FilterQuery, Model } from "mongoose"; +import { Model } from "mongoose"; import { ClaimFactorsImage } from "src/claim-request-management/entites/schema/factor-image.schema"; @Injectable() @@ -13,12 +13,6 @@ export class ClaimFactorsImageDbService { return await this.model.create(image); } - async findOne( - filter: FilterQuery, - ): Promise { - return await this.model.findOne({ filter }); - } - async findById(id: string): Promise { return this.model.findById(id).lean(); } diff --git a/src/claim-request-management/entites/db-service/video-capture.db.service.ts b/src/claim-request-management/entites/db-service/video-capture.db.service.ts index ec00cff..8efcc9e 100644 --- a/src/claim-request-management/entites/db-service/video-capture.db.service.ts +++ b/src/claim-request-management/entites/db-service/video-capture.db.service.ts @@ -1,6 +1,6 @@ import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; -import { FilterQuery, Model } from "mongoose"; +import { Model } from "mongoose"; import { VideoCaptureModel } from "src/claim-request-management/entites/schema/video-capture.schema"; @Injectable() @@ -13,12 +13,6 @@ export class VideoCaptureDbService { return await this.videoCapture.create(video); } - async findOne( - filter: FilterQuery, - ): Promise { - return await this.videoCapture.findOne(filter); - } - async findById(id: string): Promise { return this.videoCapture.findById(id); } diff --git a/src/claim-request-management/entites/schema/action-user.schema.ts b/src/claim-request-management/entites/schema/action-user.schema.ts deleted file mode 100644 index 4f3f22b..0000000 --- a/src/claim-request-management/entites/schema/action-user.schema.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { Prop, Schema, SchemaFactory } from "@nestjs/mongoose"; -import mongoose, { Types } from "mongoose"; - -@Schema({ versionKey: false }) -export class ActionUserModel extends mongoose.Document { - @Prop({ required: true, type: Types.ObjectId }) - userId: Types.ObjectId; - - @Prop({ required: true, type: Date }) - date: Date; -} - -export const ActionActorSchema = SchemaFactory.createForClass(ActionUserModel); diff --git a/src/claim-request-management/entites/schema/claim-base.schema.ts b/src/claim-request-management/entites/schema/claim-base.schema.ts deleted file mode 100644 index aff96de..0000000 --- a/src/claim-request-management/entites/schema/claim-base.schema.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Prop } from "@nestjs/mongoose"; -import mongoose, { Types } from "mongoose"; -import { ActionUserModel } from "./action-user.schema"; - -export class ClaimBaseModel extends mongoose.Document { - @Prop() - readonly _id: Types.ObjectId; - - @Prop() - readonly created: Date; - - @Prop({ - required: false, - type: ActionUserModel, - }) - createdBy: ActionUserModel; - - @Prop({ required: false }) - readonly updated: Date; - - @Prop({ - required: false, - type: [ActionUserModel], - }) - updatedBy: ActionUserModel[]; - - @Prop() - readonly deleted: boolean; -} diff --git a/src/claim-request-management/registrar-claim.v1.controller.ts b/src/claim-request-management/registrar-claim.v1.controller.ts deleted file mode 100644 index 472f21d..0000000 --- a/src/claim-request-management/registrar-claim.v1.controller.ts +++ /dev/null @@ -1,137 +0,0 @@ -import { Body, Controller, Get, Param, Patch, Post, UploadedFile, UseGuards, UseInterceptors } from "@nestjs/common"; -import { FileInterceptor } from "@nestjs/platform-express"; -import { diskStorage } from "multer"; -import { extname } from "path"; -import { ApiBearerAuth, ApiConsumes, ApiExcludeController } from "@nestjs/swagger"; -import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; -import { RolesGuard } from "src/auth/guards/role.guard"; -import { Roles } from "src/decorators/roles.decorator"; -import { CurrentUser } from "src/decorators/user.decorator"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service"; -import { SelectOuterPartsV2Dto } from "./dto/select-outer-parts-v2.dto"; -import { SelectOtherPartsV2Dto } from "./dto/select-other-parts-v2.dto"; -import { UploadRequiredDocumentV2Dto } from "./dto/upload-document-v2.dto"; -import { CapturePartV2Dto } from "./dto/capture-part-v2.dto"; -import { ClaimRequestManagementService } from "./claim-request-management.service"; - -@ApiExcludeController() -// @ApiTags("registrar-claim (v1)") -@Controller("registrar-claim") -@ApiBearerAuth() -@UseGuards(LocalActorAuthGuard, RolesGuard) -@Roles(RoleEnum.REGISTRAR) -export class RegistrarClaimV1Controller { - constructor(private readonly claimRequestManagementService: ClaimRequestManagementService) {} - - @Post("create-from-blame/:blameRequestId") - // @ApiParam({ name: "blameRequestId" }) - createFromBlame(@Param("blameRequestId") blameRequestId: string, @CurrentUser() registrar: any) { - return this.claimRequestManagementService.createClaimFromBlameForRegistrarV1( - blameRequestId, - registrar, - ); - } - - @Get("request/:claimRequestId") - getClaim(@Param("claimRequestId") claimRequestId: string, @CurrentUser() registrar: any) { - return this.claimRequestManagementService.getClaimDetailsV2( - claimRequestId, - registrar.sub, - registrar, - ); - } - - @Patch("select-outer-parts/:claimRequestId") - // @ApiBody({ type: SelectOuterPartsV2Dto }) - selectOuter( - @Param("claimRequestId") claimRequestId: string, - @Body() body: SelectOuterPartsV2Dto, - @CurrentUser() registrar: any, - ) { - return this.claimRequestManagementService.selectOuterPartsV2( - claimRequestId, - body, - registrar.sub, - registrar, - ); - } - - @Patch("select-other-parts/:claimRequestId") - // @ApiBody({ type: SelectOtherPartsV2Dto }) - selectOther( - @Param("claimRequestId") claimRequestId: string, - @Body() body: SelectOtherPartsV2Dto, - @CurrentUser() registrar: any, - ) { - return this.claimRequestManagementService.selectOtherPartsV2( - claimRequestId, - body, - registrar.sub, - registrar, - ); - } - - @Get("capture-requirements/:claimRequestId") - getCapture(@Param("claimRequestId") claimRequestId: string, @CurrentUser() registrar: any) { - return this.claimRequestManagementService.getCaptureRequirementsV2( - claimRequestId, - registrar.sub, - registrar, - ); - } - - @Post("upload-document/:claimRequestId") - @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("file", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/claim-documents", - filename: (req, file, cb) => cb(null, `${Date.now()}${extname(file.originalname)}`), - }), - }), - ) - // @ApiOperation({ summary: "Registrar uploads required claim document" }) - uploadDoc( - @Param("claimRequestId") claimRequestId: string, - @Body() body: UploadRequiredDocumentV2Dto, - @UploadedFile() file: Express.Multer.File, - @CurrentUser() registrar: any, - ) { - return this.claimRequestManagementService.uploadRequiredDocumentV2( - claimRequestId, - body, - file, - registrar.sub, - registrar, - ); - } - - @Post("capture-part/:claimRequestId") - // @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("file", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/claim-captures", - filename: (req, file, cb) => cb(null, `${Date.now()}${extname(file.originalname)}`), - }), - }), - ) - capturePart( - @Param("claimRequestId") claimRequestId: string, - @Body() body: CapturePartV2Dto, - @UploadedFile() file: Express.Multer.File, - @CurrentUser() registrar: any, - ) { - return this.claimRequestManagementService.capturePartV2( - claimRequestId, - body, - file, - registrar.sub, - registrar, - ); - } -} - diff --git a/src/client/client.service.ts b/src/client/client.service.ts index 73f4d08..ae56e07 100644 --- a/src/client/client.service.ts +++ b/src/client/client.service.ts @@ -1,22 +1,24 @@ import { - BadGatewayException, BadRequestException, GoneException, Injectable, NotFoundException, } from "@nestjs/common"; import { Types } from "mongoose"; +import { + type ClientSettingsPanelResponseDto, + UpdateClientSettingsDto, +} from "src/client/dto/client-settings.dto"; import { ClientDto, ClientDtoRs, ClientLists, } from "src/client/dto/create-client.dto"; import { - type ClientSettingsPanelResponseDto, - UpdateClientSettingsDto, -} from "src/client/dto/client-settings.dto"; -import type { ClientMediaLimits } from "./entities/schema/client.schema"; -import { ClientDbService } from "./entities/db-service/client.db.service"; + EXTERNAL_INQUIRY_TYPES, + mergeExternalInquiryFlags, +} from "src/common/types/external-inquiry.types"; +import { SystemSettingsService } from "src/system-settings/system-settings.service"; import { ClientExternalInquiriesCatalogDto, ClientExternalInquiriesListDto, @@ -24,12 +26,9 @@ import { toClientExternalInquiriesView, UpdateClientExternalInquiriesDto, } from "./dto/client-external-inquiries.dto"; -import { - EXTERNAL_INQUIRY_TYPES, - mergeExternalInquiryFlags, -} from "src/common/types/external-inquiry.types"; +import { ClientDbService } from "./entities/db-service/client.db.service"; +import type { ClientMediaLimits } from "./entities/schema/client.schema"; import { ExternalInquirySettingsService } from "./external-inquiry-settings.service"; -import { SystemSettingsService } from "src/system-settings/system-settings.service"; /** * System-wide default applied when a client document has no @@ -150,14 +149,6 @@ export class ClientService { return this.clientDbService.findOne(filter); } - async findClientWithPersianName(filter: string) { - return await this.clientDbService.find({ "clientName.persian": filter }); - } - - async findClientWithCompanyCode(companyCode: number) { - return await this.clientDbService.find({ clientCode: companyCode }); - } - /** * Resolve a client by insurer company code from an external inquiry. * Creates the client when missing so inquiry flows don't fail on unknown codes. @@ -413,7 +404,8 @@ export class ClientService { getExternalInquiriesCatalog(): ClientExternalInquiriesCatalogDto { return { inquiryTypes: [...EXTERNAL_INQUIRY_TYPES], - globalSettingPath: "/system-settings (PATCH externalApis.sandHubUseLiveApi)", + globalSettingPath: + "/system-settings (PATCH externalApis.sandHubUseLiveApi)", perClientSettingPath: "/client/{clientId}/external-inquiries", }; } @@ -439,7 +431,9 @@ export class ClientService { body: UpdateClientExternalInquiriesDto, ): Promise { const client = await this.loadClientOrThrow(clientKey); - const flags = mergeExternalInquiryFlags(body as Partial>); + const flags = mergeExternalInquiryFlags( + body as Partial>, + ); const $set: Record = {}; for (const key of EXTERNAL_INQUIRY_TYPES) { $set[`settings.externalInquiries.${key}`] = flags[key]; diff --git a/src/client/entities/db-service/branch.db.service.ts b/src/client/entities/db-service/branch.db.service.ts index 8e40fa3..8ab6675 100644 --- a/src/client/entities/db-service/branch.db.service.ts +++ b/src/client/entities/db-service/branch.db.service.ts @@ -1,7 +1,7 @@ import { Injectable } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { FilterQuery, Model, Types } from "mongoose"; -import { BranchModel, BranchDocument } from "../schema/branch.schema"; +import { BranchDocument, BranchModel } from "../schema/branch.schema"; @Injectable() export class BranchDbService { @@ -81,14 +81,10 @@ export class BranchDbService { return this.branchModel.find(filter).lean(); } - async findByIds(ids: Types.ObjectId[]) { - return this.branchModel - .find({ _id: { $in: ids } }) - .select({ _id: 1, name: 1, code: 1, city: 1, state: 1, address: 1, phoneNumber: 1, isActive: 1, activityStartDate: 1, createdAt: 1, updatedAt: 1 }) - .lean(); - } - - async findByIdAndUpdate(id: string, update: any): Promise { + async findByIdAndUpdate( + id: string, + update: any, + ): Promise { return this.branchModel.findByIdAndUpdate(id, update, { new: true }).lean(); } diff --git a/src/client/external-inquiry-settings.service.ts b/src/client/external-inquiry-settings.service.ts index 9a5cf26..781be16 100644 --- a/src/client/external-inquiry-settings.service.ts +++ b/src/client/external-inquiry-settings.service.ts @@ -1,7 +1,6 @@ -import { Injectable, Logger } from "@nestjs/common"; +import { Injectable } from "@nestjs/common"; import { Types } from "mongoose"; import { - DEFAULT_EXTERNAL_INQUIRY_FLAGS, ExternalInquiryFlags, ExternalInquiryType, mergeExternalInquiryFlags, @@ -12,7 +11,6 @@ import { ClientDbService } from "./entities/db-service/client.db.service"; @Injectable() export class ExternalInquirySettingsService { - private readonly logger = new Logger(ExternalInquirySettingsService.name); private clientCache = new Map(); private readonly cacheTtlMs = 15_000; @@ -92,9 +90,7 @@ export class ExternalInquirySettingsService { const name = typeof client.clientName === "string" ? client.clientName - : client.clientName?.persian || - client.clientName?.english || - ""; + : client.clientName?.persian || client.clientName?.english || ""; return { companyId: String(client.clientCode ?? process.env.CLIENT_ID ?? "15"), companyName: name || process.env.CLIENT_NAME || "بیمه", @@ -105,16 +101,4 @@ export class ExternalInquirySettingsService { companyName: process.env.CLIENT_NAME ?? "بیمه سامان", }; } - - async getEffectiveLiveFlags( - clientRef?: string | Types.ObjectId | null, - ): Promise { - const global = await this.systemSettingsService.isSandHubLiveEnabled(); - const flags = await this.getFlagsForClient(clientRef); - const effective = { ...DEFAULT_EXTERNAL_INQUIRY_FLAGS }; - for (const key of Object.keys(effective) as ExternalInquiryType[]) { - effective[key] = global && flags[key] === true; - } - return effective; - } } diff --git a/src/common/auth/constants/hash.constants.ts b/src/common/auth/constants/hash.constants.ts deleted file mode 100644 index a96d14c..0000000 --- a/src/common/auth/constants/hash.constants.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { ScryptOptions } from "node:crypto"; - -export const CURRENT_ALGORITHM = "scrypt"; -export const CURRENT_VERSION = 1; // 0 = legacy salt:hash ; 1 = scrypt with different salt and hash and differnet format of salt:hash! - -export const KEY_LENGTH = 64; -export const SCRYPT_PARAMS: ScryptOptions = { - N: 19456, // CPU/memory cost - r: 8, // block size - p: 1, // parallelization -}; - -export const KEY_LENGTH_FOR_OTP = 32; -export const SCRYPT_PARAMS_FOR_OTP: ScryptOptions = { - N: 1024, - r: 8, - p: 1, -}; diff --git a/src/common/auth/constants/index.ts b/src/common/auth/constants/index.ts deleted file mode 100644 index 2d76186..0000000 --- a/src/common/auth/constants/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export { - CURRENT_ALGORITHM, - CURRENT_VERSION, - KEY_LENGTH, - KEY_LENGTH_FOR_OTP, - SCRYPT_PARAMS, - SCRYPT_PARAMS_FOR_OTP, -} from "./hash.constants"; diff --git a/src/core/api-route-contract.spec.ts b/src/core/api-route-contract.spec.ts new file mode 100644 index 0000000..bbece9f --- /dev/null +++ b/src/core/api-route-contract.spec.ts @@ -0,0 +1,78 @@ +import "reflect-metadata"; +import { RequestMethod } from "@nestjs/common"; +import { + GUARDS_METADATA, + METHOD_METADATA, + PATH_METADATA, +} from "@nestjs/common/constants"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; + +type RouteContract = { + controller: string; + method: string; + path: string; + guards: string[]; + roles: string[]; +}; +function controllerFiles(dir: string): string[] { + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const file = join(dir, entry.name); + return entry.isDirectory() + ? controllerFiles(file) + : entry.name.endsWith(".controller.ts") + ? [file] + : []; + }); +} + +describe("retained API surface after legacy retirement", () => { + it("keeps every retained route, authentication guard and role contract", () => { + // Captured from the pre-cleanup controllers, excluding explicitly retired routes. + // This is the public routing/access contract, not a snapshot of service implementation. + const expected: RouteContract[] = JSON.parse( + readFileSync( + join(__dirname, "../../test/contracts/api-routes.json"), + "utf8", + ), + ); + const actual: RouteContract[] = []; + for (const file of controllerFiles(join(__dirname, ".."))) { + const exports = require(file) as Record; + for (const controller of Object.values(exports)) { + if (typeof controller !== "function") continue; + const prefix = Reflect.getMetadata(PATH_METADATA, controller); + if (prefix === undefined) continue; + for (const name of Object.getOwnPropertyNames(controller.prototype)) { + if (name === "constructor") continue; + const handler = controller.prototype[name]; + const method = Reflect.getMetadata(METHOD_METADATA, handler); + if (method === undefined) continue; + const route = Reflect.getMetadata(PATH_METADATA, handler); + actual.push({ + controller: controller.name, + method: RequestMethod[method], + path: + ("/" + prefix + "/" + route) + .replace(/\/+/g, "/") + .replace(/\/$/, "") || "/", + guards: [ + ...(Reflect.getMetadata(GUARDS_METADATA, controller) || []), + ...(Reflect.getMetadata(GUARDS_METADATA, handler) || []), + ].map((guard) => guard.name), + roles: + Reflect.getMetadata("role", handler) || + Reflect.getMetadata("role", controller) || + [], + }); + } + } + } + actual.sort((a, b) => + (a.method + " " + a.path + " " + a.controller).localeCompare( + b.method + " " + b.path + " " + b.controller, + ), + ); + expect(actual).toEqual(expected); + }); +}); diff --git a/src/expert-claim/dto/claim-list-perId-rs.dto.ts b/src/expert-claim/dto/claim-list-perId-rs.dto.ts deleted file mode 100644 index f52b4fb..0000000 --- a/src/expert-claim/dto/claim-list-perId-rs.dto.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { UserObjectionDto } from "src/claim-request-management/dto/user-objection.dto"; -import { - ClaimRequestManagementModel, - SubmitReply, - UserComment, - UserResendDocuments, - PriceDrop, -} from "src/claim-request-management/entites/schema/claim-request-management.schema"; - -export class ClaimPerIdRs { - requestDetail: any; - bankDamageUserInformation: {}; - accidentLocation: {}; - blameFile: any; - aiImages: any; - carPartDamage: any; - imageRequired: any; - carGreenCard: any; - nationalCodeOfInsurer: string; - otherParts: any; - sheba: any; - expertSubmitReply: any; - damageExpertResend: any; - damageExpertReply: SubmitReply; - damageExpertReplyFinal: SubmitReply; - lockFile: boolean; - videoCaptureId: any; - signDetails: UserComment; - lockTime: string | number | Date; - unlockTime: number | Date; - userResendDocuments: UserResendDocuments; - objection: UserObjectionDto; - dropPrice: PriceDrop; - type: string; - requiredDocuments: any; - constructor(request: ClaimRequestManagementModel) { - request.imageRequired.aroundTheCar = request.imageRequired.aroundTheCar.map( - (v) => { - //@ts-ignore - delete v.aiReport; - return v; - }, - ); - request.imageRequired.aroundTheCar = - request.imageRequired.selectPartOfCar.map((v) => { - //@ts-ignore - delete v.aiReport; - return v; - }); - this.requestDetail = { - createdDate: request.createdAt.toLocaleDateString("fa-IR"), - createdTime: request.createdAt.toLocaleTimeString("fa-IR"), - status: request.claimStatus, - }; - delete request.blameFile.actorsChecker; - this.bankDamageUserInformation = { - fullName: request.fullName, - numberOfSheba: request.sheba, - }; - this.blameFile = request.blameFile; - this.videoCaptureId = request?.videoCaptureId; - this.damageExpertResend = request.damageExpertResend; - this.damageExpertReply = request.damageExpertReply; - this.damageExpertReplyFinal = request.damageExpertReplyFinal; - this.lockFile = request.lockFile; - this.lockTime = request.lockTime; - this.unlockTime = request.unlockTime; - this.userResendDocuments = request.userResendDocuments; - this.objection = request.objection as UserObjectionDto; - this.carPartDamage = request.carPartDamage; - this.imageRequired = request.imageRequired; - this.carGreenCard = request.carGreenCard; - this.nationalCodeOfInsurer = request.nationalCodeOfInsurer; - this.otherParts = request.otherParts; - this.sheba = request.sheba; - this.dropPrice = request.priceDrop; - this.type = request.blameFile?.type || "THIRD_PARTY"; // Include type field from blameFile - this.requiredDocuments = request.requiredDocuments; - } -} diff --git a/src/expert-claim/dto/claim-list-rs.dto.ts b/src/expert-claim/dto/claim-list-rs.dto.ts deleted file mode 100644 index ef0fbe3..0000000 --- a/src/expert-claim/dto/claim-list-rs.dto.ts +++ /dev/null @@ -1,22 +0,0 @@ -export class ClaimListDtoRs { - public data: any[]; - constructor(claimFile) { - this.data = claimFile.map((i) => { - return { - requestId: i._id, - lockFile: i.isLocked, - claimStatus: i.claimStatus, - requestCode: i.blameFile?.requestNumber, - firstPartyCar: - i.blameFile.firstPartyDetails.firstPartyCarDetail.carName, - secondPartyCar: - i.blameFile.secondPartyDetails?.secondPartyCarDetail.carName, - date: new Date(i.createdAt).toLocaleDateString("fa-IR"), - time: new Date(i.createdAt).toLocaleTimeString("fa-IR"), - status: i.status, - effectedUserReply: i.effectedUserReply?.reply, - type: i.blameFile?.type || "THIRD_PARTY", // Include type field from blameFile - }; - }); - } -} diff --git a/src/expert-claim/dto/reply.dto.ts b/src/expert-claim/dto/reply.dto.ts deleted file mode 100644 index ee0a9a1..0000000 --- a/src/expert-claim/dto/reply.dto.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { ApiProperty } from "@nestjs/swagger"; -import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-damage.enum"; -import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum"; - -export class CarPartDamageDto { - @ApiProperty({ type: String }) - side: string; - - @ApiProperty({ type: String }) - part: string; -} - -export class DaghiDetailsDto { - @ApiProperty({ - required: true, - enum: DaghiOption, - description: "Daghi option: ارزش لوازم بازیافتی, تحویل داغی, فاقد ارزش, با احتساب داغی", - }) - option: DaghiOption; - - @ApiProperty({ - required: false, - type: String, - description: "Price field required when option is 'ارزش لوازم بازیافتی'", - }) - price?: string; - -} - -export class PartsList { - @ApiProperty({ required: true, type: String }) - partId: string; - - @ApiProperty({ required: true, type: CarPartDamageDto }) - carPartDamage: CarPartDamageDto; - - @ApiProperty({ required: true, type: String }) - typeOfDamage: TypeOfDamage; - - @ApiProperty({ required: true, type: String }) - price: string; - - @ApiProperty({ required: true, type: String }) - salary: string; - - @ApiProperty({ required: true, type: String }) - totalPayment: string; - - @ApiProperty({ required: true, type: DaghiDetailsDto }) - daghi: DaghiDetailsDto; - - @ApiProperty({ required: true, type: Boolean }) - factorNeeded: boolean; -} - -export class ClaimSubmitReplyDto { - @ApiProperty({ required: true }) - description: string; - - @ApiProperty({ required: true, type: [PartsList] }) - parts: PartsList[]; -} - -export class ResendCarPartsDto { - @ApiProperty({ required: true }) - partId: string; - - @ApiProperty({ required: true }) - partName: string; - - @ApiProperty({ required: false }) - side?: string; -} - -class InPersonDocuments { - NationalCertificate: string; - CarCertificate: string; - DrivingLicense: string; - CarGreenCard: string; -} - -export class ClaimSubmitResendDto { - @ApiProperty({ required: true }) - resendDescription: string; - - @ApiProperty({ required: true, examples: InPersonDocuments }) - resendDocuments: InPersonDocuments[]; - - @ApiProperty({ required: true, type: [ResendCarPartsDto] }) - resendCarParts: ResendCarPartsDto[]; -} diff --git a/src/expert-claim/expert-claim.controller.ts b/src/expert-claim/expert-claim.controller.ts index dbcb1f0..f4882fa 100644 --- a/src/expert-claim/expert-claim.controller.ts +++ b/src/expert-claim/expert-claim.controller.ts @@ -1,41 +1,13 @@ -import { - Body, - Controller, - Get, - Header, - Param, - Put, - Query, - Res, - UseGuards, - Headers, - Patch, -} from "@nestjs/common"; -import { - ApiBearerAuth, - ApiBody, - ApiParam, - ApiQuery, - ApiTags, - ApiOperation, - ApiExcludeController, -} from "@nestjs/swagger"; +import { Controller, Get, Param, UseGuards } from "@nestjs/common"; +import { ApiBearerAuth, ApiExcludeController } from "@nestjs/swagger"; import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; import { RolesGuard } from "src/auth/guards/role.guard"; -import { ClientKey } from "src/decorators/clientKey.decorator"; import { Roles } from "src/decorators/roles.decorator"; import { CurrentUser } from "src/decorators/user.decorator"; -import { - ClaimSubmitReplyDto, - ClaimSubmitResendDto, -} from "src/expert-claim/dto/reply.dto"; import { RoleEnum } from "src/Types&Enums/role.enum"; -import { ParseJsonPipe } from "src/utils/pipes/parse-json.pipe"; import { ExpertClaimService } from "./expert-claim.service"; -import { FactorValidationDto } from "./dto/factor-validation.dto"; @ApiExcludeController() -// @ApiTags("expert-claim-panel") @Controller("expert-claim") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) @@ -43,153 +15,13 @@ import { FactorValidationDto } from "./dto/factor-validation.dto"; export class ExpertClaimController { constructor(private readonly expertClaimService: ExpertClaimService) {} - // @ApiOperation({ deprecated: true }) - @Get() - async getAllClaimRequests(@CurrentUser() actor, @ClientKey() client) { - return await this.expertClaimService.getClaimRequestsListForExpert(actor); - } - - // @ApiOperation({ deprecated: true }) - @Get("/:id") - // @ApiParam({ name: "id" }) - // @ApiQuery({ - // name: "updateDropPrice", - // required: false, - // description: "A stringified JSON object with price drop override values.", - // }) - async getClaimRequestPerId( - @Param("id") id: string, - @CurrentUser() currentUser, - @Query("updateDropPrice", new ParseJsonPipe()) priceDrop?: any, - ) { - return await this.expertClaimService.requestPerId( - id, - currentUser, - priceDrop, - ); - } - - // @ApiOperation({ deprecated: true }) @Get("imageRequired/:id") - // @ApiParam({ name: "id" }) async getImageRequired(@Param("id") id: string, @CurrentUser() currentUser) { return await this.expertClaimService.imageRequired(id, currentUser); } - // @ApiOperation({ deprecated: true }) - @Get("required-documents/:id") - // @ApiParam({ name: "id" }) - async getRequiredDocuments( - @Param("id") id: string, - @CurrentUser() currentUser, - ) { - return await this.expertClaimService.getRequiredDocuments(id, currentUser); - } - - // @ApiOperation({ deprecated: true }) - @Put("lock/:id") - async lockClaimRequest(@Param("id") requestId: string, @CurrentUser() actor) { - return await this.expertClaimService.lockClaimRequest(requestId, actor); - } - - @ApiOperation({ deprecated: true }) - @Put("reply/submit/:id") - // @ApiParam({ name: "id" }) - async submitReplyRequest( - @Param("id") requestId, - @Body() body: ClaimSubmitReplyDto, - @CurrentUser() actor, - ) { - return await this.expertClaimService.submitReplyRequest( - requestId, - body, - actor, - ); - } - - // @ApiOperation({ deprecated: true }) - @Put("resend/submit/:id") - // @ApiParam({ name: "id" }) - async submitResend( - @Param("id") requestId, - @Body() body: ClaimSubmitResendDto, - @CurrentUser() actor, - ) { - return await this.expertClaimService.submitResend( - requestId, - body, - actor.sub, - ); - } - - // @ApiQuery({ - // name: "query", - //enum: ["car-capture", "accident"], - //required: true, - //}) - // @ApiOperation({ deprecated: true }) - @Get("stream/:id/video") - @Header("Accept-Ranges", "bytes") - @Header("Content-Type", "video/mp4") - async claimStream( - @Headers() headers, - @Param("id") id: string, - @Query("query") query: "car-capture" | "accident", - @Res() res, - ) { - return this.expertClaimService.streamService(id, query, res, headers); - } - - @ApiQuery({ - name: "query", - enum: ["car-capture", "accident"], - required: true, - }) - // @ApiOperation({ deprecated: true }) - @Get("link/:id/video") - @ApiParam({ name: "id" }) - async getClaimVideoLink( - @Param("id") id: string, - @Query("query") query: "car-capture" | "accident", - ) { - return this.expertClaimService.getVideoLink(id, query); - } - - // @ApiOperation({ deprecated: true }) @Get("stream/:id/voice") - // @ApiParam({ name: "id" }) async getClaimVoiceLink(@Param("id") id: string) { return await this.expertClaimService.getVoiceLink(id); } - - // @ApiOperation({ deprecated: true }) - @Patch("validate-factors/:claimId") - // @ApiParam({ name: "claimId" }) - // @ApiBody({ type: FactorValidationDto }) - @Roles(RoleEnum.DAMAGE_EXPERT) - async validateFactors( - @Param("claimId") claimId: string, - @Body() validationData: FactorValidationDto, - @CurrentUser() user, - ) { - return this.expertClaimService.validateClaimFactors( - claimId, - validationData.decisions, - user.sub, - ); - } - - // @ApiParam({ name: "id" }) - // @ApiOperation({ deprecated: true }) - @Patch(":id/visit") - async inPersonVisit(@Param("id") requestId: string, @CurrentUser() actor) { - return await this.expertClaimService.inPersonVisit(requestId, actor); - } - - // @ApiOperation({ deprecated: true }) - @Get("branches/:insuranceId") - // @ApiParam({ name: "insuranceId" }) - async getInsuranceBranches(@Param("insuranceId") insuranceId: string) { - return await this.expertClaimService.retrieveInsuranceBranches(insuranceId); - } } diff --git a/src/expert-claim/expert-claim.service.spec.ts b/src/expert-claim/expert-claim.service.spec.ts index cd4baca..b6d7559 100644 --- a/src/expert-claim/expert-claim.service.spec.ts +++ b/src/expert-claim/expert-claim.service.spec.ts @@ -302,28 +302,6 @@ describe("ExpertClaimService expert-reply pricing", () => { ]); }); - it("rejects a blank pricing line on the legacy submit endpoint before changing status", async () => { - const service = createService() as any; - const findAndUpdate = jest.fn(); - service.claimRequestManagementDbService = { - findOne: jest.fn().mockResolvedValue({ - _id: "legacy-claim", - actorLocked: { actorId: "expert-1" }, - unlockTime: new Date(Date.now() + 60_000), - lockFile: true, - }), - findAndUpdate, - }; - - await expect( - service.submitReplyRequest("legacy-claim", blankPricingReply, { - sub: "expert-1", - }), - ).rejects.toBeInstanceOf(BadRequestException); - - expect(findAndUpdate).not.toHaveBeenCalled(); - }); - it("rejects a blank pricing line on the V2 submit endpoint before completion", async () => { const service = createService() as any; const findByIdAndUpdate = jest.fn(); diff --git a/src/expert-claim/expert-claim.service.ts b/src/expert-claim/expert-claim.service.ts index ac8d9df..eff55f7 100644 --- a/src/expert-claim/expert-claim.service.ts +++ b/src/expert-claim/expert-claim.service.ts @@ -1,7 +1,5 @@ "use strict"; -import { createReadStream, existsSync, statSync } from "node:fs"; -import { join } from "node:path"; -import { HttpService } from "@nestjs/axios"; + import { BadRequestException, ConflictException, @@ -12,64 +10,56 @@ import { Logger, NotFoundException, } from "@nestjs/common"; -import { - BusinessErrorCode, - BusinessRuleException, -} from "./exceptions/business-rule.exception"; -import { distance as stringDistance } from "fastest-levenshtein"; // حتما نصب بشه import { Types } from "mongoose"; -import { lastValueFrom } from "rxjs"; +import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; +import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service"; -import { - ClaimRequestManagementService, - FanavaranAutoSubmitResult, - FanavaranExpertiseSubmitResult, -} from "src/claim-request-management/claim-request-management.service"; -import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service"; + import { ClaimSignDbService } from "src/claim-request-management/entites/db-service/claim-sign.db.service"; -import { DamageImageDbService } from "src/claim-request-management/entites/db-service/damage-image.db.service"; + +import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.db.service"; import { VideoCaptureDbService } from "src/claim-request-management/entites/db-service/video-capture.db.service"; -import { ClientDbService } from "src/client/entities/db-service/client.db.service"; -import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; -import { toJalaliDateAndTime } from "src/helpers/date-jalali"; -import { BlameDocumentDbService } from "src/request-management/entities/db-service/blame-document.db.service"; -import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service"; -import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service"; -import { SandHubService } from "src/sand-hub/sand-hub.service"; -import { ReqClaimStatus } from "src/Types&Enums/claim-request-management/status.enum"; -import { ClaimStepsEnum } from "src/Types&Enums/claim-request-management/steps.enum"; -import { UserType } from "src/Types&Enums/userType.enum"; -import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; -import { UserDbService } from "src/users/entities/db-service/user.db.service"; +import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references"; +import { BranchDbService } from "src/client/entities/db-service/branch.db.service"; + import { ExpertFileAssignResultDto, ExpertFileAssignStatus, } from "src/common/dto/expert-file-assign-result.dto"; +import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service"; import { - CLAIM_REVIEW_ASSIGNED_HISTORY_TYPE, - claimWorkflowAssigneeToPersistOnLockExpiry, - buildExpertAssignConflictForOtherReviewer, - resolvePersistentReviewAssigneeId, -} from "src/helpers/expert-workflow-review-assignee"; + buildMutualAgreementExpertDecision, + enrichBlamePartiesForAgreementView, +} from "src/helpers/blame-party-agreement-decision"; import { - EXPERT_WORKFLOW_LOCK_TTL_MS, - expertWorkflowLockExpiredAt, -} from "src/helpers/expert-workflow-lock"; -import { ClaimPerIdRs } from "./dto/claim-list-perId-rs.dto"; -import { ClaimListDtoRs } from "./dto/claim-list-rs.dto"; -import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; -import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references"; -import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; -import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum"; -import { RoleEnum } from "src/Types&Enums/role.enum"; + getClaimCarAngleCaptureBlob, + getDamagedPartCaptureBlob, + hasDamagedPartCapture, + type ClaimCarAngleKey, +} from "src/helpers/claim-car-angle-media"; import { - assertClaimCaseForTenant, - assertClaimCaseForExpertActor, - blameCaseTouchesClient, - claimCaseInitiatedByFieldExpert, - claimCaseTouchesClient, - requireActorClientKey, -} from "src/helpers/tenant-scope"; + buildDamagedPartSelectionRevision, + serializeDamagedPartSelectionHistory, +} from "src/helpers/claim-damaged-part-audit"; +import { + normalizeResendCarPartsForStorage, + normalizeResendDocumentKeys, + resendRequestHasPayload, +} from "src/helpers/claim-expert-resend"; +import { + buildCoefficientsFromPartSeverities, + buildDamagedPartsPriceDropLines, + buildPriceDropCatalogForApi, + calculateClaimPriceDrop, + PRICE_DROP_SEVERITY_OPTIONS, + resolveVehicleModelYearFromBlame, +} from "src/helpers/claim-price-drop"; +import { + claimCaseStatusAfterExpertReplyV2, + claimIsAwaitingExpertFactorValidationV2, + classifyV2ExpertPricingParts, +} from "src/helpers/claim-v2-expert-reply-workflow"; +import { toJalaliDateAndTime } from "src/helpers/date-jalali"; import { claimCaseStatusToReportBucket, initialClaimExpertReportBuckets, @@ -79,116 +69,113 @@ import { expertPortfolioFileIdsFromActivityEvents, objectIdsFromStringSet, } from "src/helpers/expert-portfolio"; +import { snapshotFromDamageExpert } from "src/helpers/expert-profile-snapshot"; +import { EXPERT_WORKFLOW_LOCK_TTL_MS } from "src/helpers/expert-workflow-lock"; import { - buildCoefficientsFromPartSeverities, - buildDamagedPartsPriceDropLines, - buildPriceDropCatalogForApi, - calculateClaimPriceDrop, - PRICE_DROP_SEVERITY_OPTIONS, - resolveVehicleModelYearFromBlame, -} from "src/helpers/claim-price-drop"; -import { UpsertClaimPriceDropV2Dto } from "./dto/claim-price-drop-v2.dto"; -import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; -import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum"; -import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; -import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; -import { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver"; -import { - GetClaimListV2ResponseDto, - ClaimListItemV2Dto, -} from "./dto/claim-list-v2.dto"; -import { ClaimDetailV2ResponseDto } from "./dto/claim-detail-v2.dto"; -import { ClaimSubmitReplyDto, ClaimSubmitResendDto } from "./dto/reply.dto"; -import { UpdateClaimDamagedPartsV2Dto } from "./dto/update-claim-damaged-parts-v2.dto"; -import { ClaimFactorsImageDbService } from "src/claim-request-management/entites/db-service/factor-image.db.service"; -import { ClaimRequiredDocumentDbService } from "src/claim-request-management/entites/db-service/claim-required-document.db.service"; -import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum"; -import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum"; -import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-damage.enum"; -import { BranchDbService } from "src/client/entities/db-service/branch.db.service"; -import { ClaimSubmitResendV2Dto } from "./dto/expert-claim-v2.dto"; -import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; -import { FactorValidationV2Dto } from "./dto/factor-validation.dto"; -import { - buildMutualAgreementExpertDecision, - enrichBlamePartiesForAgreementView, -} from "src/helpers/blame-party-agreement-decision"; -import { - normalizeResendDocumentKeys, - resendRequestHasPayload, -} from "src/helpers/claim-expert-resend"; -import { - claimCaseStatusAfterExpertReplyV2, - classifyV2ExpertPricingParts, - claimIsAwaitingExpertFactorValidationV2, -} from "src/helpers/claim-v2-expert-reply-workflow"; -import { - getClaimCarAngleCaptureBlob, - getDamagedPartCaptureBlob, - hasDamagedPartCapture, - type ClaimCarAngleKey, -} from "src/helpers/claim-car-angle-media"; + buildExpertAssignConflictForOtherReviewer, + CLAIM_REVIEW_ASSIGNED_HISTORY_TYPE, + claimWorkflowAssigneeToPersistOnLockExpiry, + resolvePersistentReviewAssigneeId, +} from "src/helpers/expert-workflow-review-assignee"; import { catalogLikeKeyFromPart, + catalogPartIdFromCarPartDamage, coerceDamagedPartsMediaToArray, normalizeCarPartDamageForExpertReply, normalizeDamageSelectedParts, - catalogPartIdFromCarPartDamage, - catalogPartIdFromSelectedPart, partLookupKey, resolvePartForExpertReply, sameCatalogPartId, sanitizeDamageSelectedPartV2, type DamageSelectedPartV2, } from "src/helpers/outer-damage-parts"; -import { normalizeResendCarPartsForStorage } from "src/helpers/claim-expert-resend"; -import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog"; import { - buildDamagedPartSelectionRevision, - serializeDamagedPartSelectionHistory, -} from "src/helpers/claim-damaged-part-audit"; -import { snapshotFromDamageExpert } from "src/helpers/expert-profile-snapshot"; -import { DamageExpertModel } from "src/users/entities/schema/damage-expert.schema"; + assertClaimCaseForExpertActor, + assertClaimCaseForTenant, + blameCaseTouchesClient, + claimCaseInitiatedByFieldExpert, + claimCaseTouchesClient, + requireActorClientKey, +} from "src/helpers/tenant-scope"; +import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; + +import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; +import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service"; +import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service"; +import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; +import { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver"; + import { SmsOrchestrationService } from "src/sms-orchestration/sms-orchestration.service"; +import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog"; +import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; +import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; +import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; +import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum"; +import { DaghiOption } from "src/Types&Enums/claim-request-management/daghi-option.enum"; +import { FactorStatus } from "src/Types&Enums/claim-request-management/factor-status.enum"; +import { ClaimRequiredDocumentType } from "src/Types&Enums/claim-request-management/required-document-type.enum"; +import { ReqClaimStatus } from "src/Types&Enums/claim-request-management/status.enum"; +import { TypeOfDamage } from "src/Types&Enums/claim-request-management/type-of-damage.enum"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service"; +import { UserDbService } from "src/users/entities/db-service/user.db.service"; +import { DamageExpertModel } from "src/users/entities/schema/damage-expert.schema"; import { ExpertFileActivityType, ExpertFileKind, } from "src/users/entities/schema/expert-file-activity.schema"; +import { ClaimDetailV2ResponseDto } from "./dto/claim-detail-v2.dto"; +import { + ClaimListItemV2Dto, + GetClaimListV2ResponseDto, +} from "./dto/claim-list-v2.dto"; +import { UpsertClaimPriceDropV2Dto } from "./dto/claim-price-drop-v2.dto"; +import { ClaimSubmitResendV2Dto } from "./dto/expert-claim-v2.dto"; +import { FactorValidationV2Dto } from "./dto/factor-validation.dto"; +import { UpdateClaimDamagedPartsV2Dto } from "./dto/update-claim-damaged-parts-v2.dto"; +import { + BusinessErrorCode, + BusinessRuleException, +} from "./exceptions/business-rule.exception"; /** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */ -import { getClaimV2TotalPaymentCapToman } from "src/constants/repair-amount-limits"; +/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */ +/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */ +/** Configured V1 maximum sum of line `totalPayment` across the claim (Rial). */ +import { + fanavaranFieldStageSent, + type FanavaranFieldReview, + type FanavaranFieldValues, +} from "src/claim-request-management/fanavaran-stage-fields"; import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; -import { toPublicListItems } from "src/helpers/public-list-response"; import { UnifiedFileStatusReportDto, UnifiedFileStatusReportQueryDto, } from "src/common/dto/unified-file-status-report.dto"; +import { getClaimV2TotalPaymentCapToman } from "src/constants/repair-amount-limits"; +import { claimPriceCapAppliesToBlame } from "src/helpers/claim-price-cap"; +import { canonicalizeResendDocumentKey } from "src/helpers/claim-resend-document-keys"; +import { getExpertReplyPricingValidationError } from "src/helpers/expert-reply-pricing"; import { applyListQueryV2, isInListDateRange, parseListDateRange, } from "src/helpers/list-query-v2"; +import { toPublicListItems } from "src/helpers/public-list-response"; import { countUnifiedFileStatuses, getUnifiedFileStatusCatalog, resolveUnifiedFileStatus, } from "src/helpers/unified-file-status"; -import { buildEnrichedDamagedParts } from "./dto/claim-damaged-part.enricher"; -import { canonicalizeResendDocumentKey } from "src/helpers/claim-resend-document-keys"; -import { getExpertReplyPricingValidationError } from "src/helpers/expert-reply-pricing"; +import { LookupsService } from "src/lookups/lookups.service"; import { normalizeMoneyAmountString, parseMoneyAmountToman, } from "src/utils/unicode-digits"; -import { claimPriceCapAppliesToBlame } from "src/helpers/claim-price-cap"; -import { LookupsService } from "src/lookups/lookups.service"; -import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto"; +import { buildEnrichedDamagedParts } from "./dto/claim-damaged-part.enricher"; import { UpdateFanavaranStageFieldsDto } from "./dto/fanavaran-stage-fields.dto"; -import { - fanavaranFieldStageSent, type FanavaranFieldReview, - type FanavaranFieldValues, -} from "src/claim-request-management/fanavaran-stage-fields"; +import { ApproveFanavaranVehicleReviewDto } from "./dto/fanavaran-vehicle-review.dto"; import { buildFanavaranVehicleSuggestion, collectFanavaranVehicleInquiryRecords, @@ -198,119 +185,21 @@ import { export class ExpertClaimService { private readonly logger = new Logger(ExpertClaimService.name); - private readonly priceDropPart = { - backFender: { - Minor: 2, - Moderate: 3, - Severe: 5, - }, - backDoor: { - Minor: 1, - Moderate: 2, - Severe: 3, - }, - frontDoor: { - Minor: 1, - Moderate: 2, - Severe: 3, - }, - frontFender: { - Minor: 1, - Moderate: 2, - Severe: 3, - }, - frontBumper: { - Minor: 1, - Moderate: 2, - Severe: 3, - }, - Hood: { - Minor: 2, - moderate: 3, - Severe: 4, - }, - Trunk: { - minor: 1, - moderate: 3, - Severe: 5, - }, - Roof: { - Minor: 3, - Moderate: 5, - Severe: 7, - }, - coil: { - Minor: 2, - Moderate: 3, - Severe: 4, - }, - column: { - Minor: 2, - Moderate: 3, - Severe: 4, - }, - frontTray: { - Minor: 1, - Moderate: 2, - Severe: 3, - }, - backTray: { - Minor: 2, - moderate: 4, - Severe: 5, - }, - frontChassis: { - Minor: 3, - Moderate: 5, - Severe: 7, - }, - backChassis: { - Minor: 2, - Moderate: 4, - Severe: 6, - }, - carFootrest: { - Minor: 1, - Moderate: 2, - Severe: 3, - }, - carFloor: { - Minor: 4, - moderate: 6, - Severe: 8, - }, - }; - - private readonly yearCoefficient = { - 1393: 2.05, - 1394: 2.1, - 1395: 2.2, - 1396: 2.3, - 1397: 2.4, - 1398: 2.5, - 1399: 2.6, - 1400: 2.7, - 1401: 2.8, - 1402: 2.9, - 1403: 3, - 1404: 3, - }; - constructor( private readonly blameVoiceDbService: BlameVoiceDbService, - private readonly blameDocumentDbService: BlameDocumentDbService, + private readonly claimRequestManagementDbService: ClaimRequestManagementDbService, - private readonly damageImageDbService: DamageImageDbService, + private readonly blameVideoDbService: BlameVideoDbService, private readonly claimVideoCaptureDbService: VideoCaptureDbService, - private readonly httpService: HttpService, + private readonly claimCaseDbService: ClaimCaseDbService, private readonly blameRequestDbService: BlameRequestDbService, - private readonly sandHubService: SandHubService, + private readonly damageExpertDbService: DamageExpertDbService, - private readonly clientDbService: ClientDbService, + private readonly claimFactorsImageDbService: ClaimFactorsImageDbService, - private readonly claimRequiredDocumentDbService: ClaimRequiredDocumentDbService, + private readonly branchDbService: BranchDbService, private readonly smsOrchestrationService: SmsOrchestrationService, private readonly userDbService: UserDbService, @@ -321,19 +210,6 @@ export class ExpertClaimService { private readonly lookupsService: LookupsService, ) {} - private appendFanavaranAutoSubmitToMessage( - baseMessage: string, - fanavaran: FanavaranAutoSubmitResult | FanavaranExpertiseSubmitResult, - ): string { - if (fanavaran.submitted) { - return `${baseMessage} The claim was sent to Fanavaran successfully.`; - } - if (fanavaran.warning) { - return `${baseMessage} ${fanavaran.warning}`; - } - return baseMessage; - } - /** * Resolve a `claim-sign` document id to a downloadable file URL. * Mirrors the helper used in `ExpertInsurerService` so signature links are @@ -842,245 +718,6 @@ export class ExpertClaimService { return out; } - private isVisibleToClientType(client: any, actor: any): boolean { - if (actor.userType === UserType.GENUINE) { - return true; - } - if ( - actor.userType === UserType.LEGAL && - String(client._id) === actor.clientKey - ) { - return true; - } - return false; - } - - private wasHandledByActor(request: any, actorSub: string): boolean { - type ActorCheckerEntry = { CheckedRequest?: { actorId: string } }; - const actorChecker = request.actorsChecker as ActorCheckerEntry[]; - - if (!Array.isArray(actorChecker)) { - return false; - } - - const matchingEntry = actorChecker.find( - (entry) => String(entry?.CheckedRequest?.actorId) === actorSub, - ); - - return !!matchingEntry; - } - - async getClaimRequestsListForExpert(actor): Promise { - // const requests = await this.claimRequestManagementDbService.findAllByStatus( - // { - // claimStatus: { - // $in: [ - // ReqClaimStatus.UnChecked, - // ReqClaimStatus.ReviewRequest, - // ReqClaimStatus.CheckAgain, - // ReqClaimStatus.CloseRequest, - // ReqClaimStatus.InPersonVisit, - // ReqClaimStatus.CheckedRequest, - // ReqClaimStatus.PendingFactorValidation, - // ], - // }, - // "damageExpertReply.actorDetail.actorId":actor.sub - // }, - // ); - - const requests = await this.claimRequestManagementDbService.findAllByStatus( - { - $or: [ - { - claimStatus: ReqClaimStatus.UnChecked, - }, - { - claimStatus: { - $in: [ - ReqClaimStatus.ReviewRequest, - ReqClaimStatus.CheckAgain, - ReqClaimStatus.CloseRequest, - ReqClaimStatus.InPersonVisit, - ReqClaimStatus.CheckedRequest, - ReqClaimStatus.PendingFactorValidation, - ], - }, - "damageExpertReply.actorDetail.actorId": actor.sub, - }, - ], - }, - ); - - const filteredRequests = []; - - for (const r of requests) { - // For expert-initiated blame files, only show to the initiating expert - if (r.blameFile?.expertInitiated && r.blameFile?.initiatedBy) { - if (String(r.blameFile.initiatedBy) !== actor.sub) { - continue; // Skip if not the initiating expert - } - // Expert-initiated claim files are always visible to the initiating expert - filteredRequests.push(r); - continue; - } - - const client = await this.clientDbService.findOne({ - _id: r.userClientKey, - }); - - if (!client) { - this.logger.warn( - `Client not found for claim request with ID: ${r._id}. Skipping.`, - ); - continue; - } - - const specialHandlingStatuses = [ - ReqClaimStatus.CheckAgain, - ReqClaimStatus.ReviewRequest, - ReqClaimStatus.PendingFactorValidation, - ]; - - const requiresSpecificActorCheck = specialHandlingStatuses.includes( - r.claimStatus, - ); - - if (requiresSpecificActorCheck) { - if (this.wasHandledByActor(r, actor.sub)) { - filteredRequests.push(r); - } - } else { - if (this.isVisibleToClientType(client, actor)) { - filteredRequests.push(r); - } - } - } - - if (filteredRequests.length === 0) { - throw new NotFoundException( - "No claim requests found for you at this time.", - ); - } - - return new ClaimListDtoRs(filteredRequests); - } - - public unlockApi(request, timer) { - // ADD to project - return setTimeout(() => { - this.claimRequestManagementDbService.findOne(request._id).then((r) => { - const updateExp = { - lockFile: false, - unlockTime: null, - actorLocked: {}, - }; - if (r?.claimStatus == ReqClaimStatus.ReviewRequest) { - Object.assign(updateExp, { - claimStatus: ReqClaimStatus.UnChecked, - }); - } - this.claimRequestManagementDbService.findOneAndUpdate(request._id, { - ...updateExp, - }); - }); - this.logger.log(`unlock this request : ${request._id}`); - // TODO enum request claimStatus create - }, timer); - } - - async lockClaimRequest(requestId: string, actorDetail) { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - if (!request) throw new BadRequestException("Claim request not found"); - - const isLocked = !!request.lockFile; - const lockedByCurrent = - String(request?.actorLocked?.actorId || "") === String(actorDetail.sub); - const isLockExpired = - !!request.unlockTime && - Date.now() >= new Date(request.unlockTime).getTime(); - - // Idempotent behavior: same expert can re-enter their locked file. - if (isLocked && lockedByCurrent && !isLockExpired) { - return { _id: requestId, lock: true, message: "Already locked by you" }; - } - if (isLocked && !lockedByCurrent && !isLockExpired) { - throw new BadRequestException( - "Claim request is locked by another expert", - ); - } - - if (request.claimStatus === ReqClaimStatus.UserPending) { - throw new BadRequestException( - "Cannot lock request because claimStatus is UserPending", - ); - } - - if ( - request.damageExpertReplyFinal && - request.claimStatus === ReqClaimStatus.CheckedRequest - ) { - throw new BadRequestException("Request has damage expert reply"); - } - - const lockExpiresAt = expertWorkflowLockExpiredAt(); - const lockSnapshot = await this.snapshotDamageExpert(actorDetail.sub); - - await this.claimRequestManagementDbService.findOneAndUpdate( - new Types.ObjectId(requestId), - { - lockFile: true, - claimStatus: ReqClaimStatus.ReviewRequest, - unlockTime: lockExpiresAt, - lockTime: Date.now(), - $set: { - actorLocked: { - actorId: new Types.ObjectId(actorDetail.sub), - fullName: actorDetail.fullName, - ...(lockSnapshot && { expertProfileSnapshot: lockSnapshot }), - }, - }, - $push: { - actorsChecker: { - [ReqClaimStatus.ReviewRequest]: { - fullName: actorDetail.fullName, - actorId: new Types.ObjectId(actorDetail.sub), - }, - Date: new Date(), - }, - }, - }, - ); - - await this.recordClaimExpertActivity({ - expertId: String(actorDetail.sub), - tenantId: String(request.userClientKey ?? actorDetail.clientKey ?? ""), - claimId: String(requestId), - eventType: ExpertFileActivityType.CHECKED, - idempotencyKey: `claim:${requestId}:checked:${actorDetail.sub}`, - }); - - this.unlockApi(request, lockExpiresAt.getTime() - Date.now()); - - return { _id: requestId, lock: true }; - } - - private normalizeText(str: string) { - if (!str || typeof str !== "string") { - return ""; - } - return str - .replace(/[٠-٩۰-۹]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 1728)) - .replace(/[\u064B-\u065F]/g, "") - .replace(/\s+/g, " ") - .trim() - .toLowerCase(); - } - - normalizeKey(str: string): string { - return str.toLowerCase().replace(/[^a-z0-9]/g, ""); - } - parsePersianNumber(input: string): number { return Number( input @@ -1179,492 +816,6 @@ export class ExpertClaimService { }); } - private findClosestCar(input: string, cars: { carName: string }[]) { - if (!input || !cars || cars.length === 0) { - this.logger.debug( - `[PriceDrop] findClosestCar: Invalid input. input: ${input}, cars length: ${cars?.length || 0}`, - ); - return null; - } - const normalizedInput = this.normalizeText(input); - if (!normalizedInput) { - this.logger.debug( - `[PriceDrop] findClosestCar: Could not normalize input "${input}"`, - ); - return null; - } - let bestMatch = null; - let minDistance = Infinity; - let validCarsChecked = 0; - - for (const car of cars) { - if (!car || !car.carName) { - continue; - } - const normalizedCarName = this.normalizeText(car.carName); - if (!normalizedCarName) { - continue; - } - validCarsChecked++; - const dist = stringDistance(normalizedInput, normalizedCarName); - if (dist < minDistance) { - minDistance = dist; - bestMatch = car; - } - } - - if (!bestMatch) { - this.logger.debug( - `[PriceDrop] findClosestCar: No match found for "${input}" after checking ${validCarsChecked} valid cars out of ${cars.length} total`, - ); - } else { - this.logger.debug( - `[PriceDrop] findClosestCar: Best match for "${input}" is "${bestMatch.carName}" with distance ${minDistance}`, - ); - } - - return bestMatch; - } - - private priceDropFormula( - carPrice: number | string, - carModel: number, - carValue: number[], - ) { - let normalizePrice: number; - - if (typeof carPrice === "string") { - normalizePrice = this.parsePersianNumber(carPrice); - } else if (typeof carPrice === "number") { - normalizePrice = carPrice; - } else { - this.logger.warn( - `Invalid carPrice type received in formula: ${typeof carPrice}`, - ); - normalizePrice = 0; - } - - const coefficient = this.yearCoefficient[carModel] || 1; - const sumOfSeverity = carValue.reduce((a, c) => a + c, 0); - const totalDrop = (normalizePrice * coefficient * sumOfSeverity) / 400; - - return { - carPrice: normalizePrice, - carModel: carModel || null, - carValue: carValue || [], - sumOfSeverity: sumOfSeverity || 0, - coefficientYear: coefficient || 1, - total: totalDrop || 0, - }; - } - - async calculatePriceDrop(request: any, carPartsAi: any, query?: any) { - const requestId = request?._id?.toString() || "unknown"; - - try { - // Step 1: Check SandHub data - if (!request?.blameFile?.sanHubId) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Missing sanHubId in blameFile. Cannot calculate price drop.`, - ); - return; - } - - const sandHubData = await this.sandHubService.getSandHubDataFromId( - request.blameFile.sanHubId, - ); - if (!sandHubData) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Could not retrieve SandHub data for sanHubId: ${request.blameFile.sanHubId}. Cannot calculate price drop.`, - ); - return; - } - - if ( - sandHubData.MapTypNam === undefined || - sandHubData.MapTypNam === null - ) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: SandHub data missing ModelCii. Cannot calculate price drop.`, - ); - return; - } - - const existingPriceDrop = request.priceDrop || {}; - const manualOverride = query || {}; - - // Step 2: Check car parts and get severity values - if ( - !carPartsAi || - (Array.isArray(carPartsAi) && carPartsAi.length === 0) - ) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: No car parts data provided. Cannot calculate severity values.`, - ); - } - - const severityValues = this.getSeverityValues(carPartsAi); - let autoCalculatedData: any = {}; - - if (severityValues.length === 0) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: No severity values found from car parts. Price drop calculation will use existing data or manual override only.`, - ); - } - - // Step 3: Check car detail and find closest car - if (!request?.carDetail) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Missing carDetail in request. Cannot find car price.`, - ); - } else if (!request.carDetail.carName) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Missing carName in carDetail. Cannot find car price.`, - ); - } else if (severityValues.length > 0) { - // Only fetch car prices if we have severity values to calculate - const carPrices = await this.fetchCarPrices(); - - if (!carPrices || carPrices.length === 0) { - this.logger.error( - `[PriceDrop] Request ${requestId}: Failed to fetch car prices or car prices list is empty. Cannot find matching car.`, - ); - } else { - this.logger.debug( - `[PriceDrop] Request ${requestId}: Fetched ${carPrices.length} car prices. Searching for: "${request.carDetail.carName}"`, - ); - - const closestCar = this.findClosestCar( - request.carDetail.carName, - carPrices, - ); - - if (!closestCar) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Could not find closest matching car for "${request.carDetail.carName}". Available cars: ${carPrices.length}. Cannot determine car price.`, - ); - } else if (!closestCar.marketPrice) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Found matching car "${closestCar.carName}" but marketPrice is missing. Cannot calculate price drop.`, - ); - } else { - this.logger.debug( - `[PriceDrop] Request ${requestId}: Found matching car "${closestCar.carName}" with marketPrice: ${closestCar.marketPrice}`, - ); - autoCalculatedData = { - carPrice: closestCar.marketPrice, - carValue: severityValues, - }; - } - } - } - - // Step 4: Merge and recalculate - const finalPriceDropData = this.mergeAndRecalculatePriceDrop( - existingPriceDrop, - autoCalculatedData, - manualOverride, - sandHubData.ModelCii, - ); - - if (!finalPriceDropData) { - this.logger.error( - `[PriceDrop] Request ${requestId}: Failed to generate final price drop data.`, - ); - return; - } - - // Step 5: Log calculation result - if ( - !finalPriceDropData.carPrice || - !finalPriceDropData.carValue || - finalPriceDropData.carValue.length === 0 - ) { - this.logger.warn( - `[PriceDrop] Request ${requestId}: Price drop calculated but missing critical data. ` + - `carPrice: ${finalPriceDropData.carPrice}, ` + - `carValue length: ${finalPriceDropData.carValue?.length || 0}, ` + - `total: ${finalPriceDropData.total}`, - ); - } else { - this.logger.debug( - `[PriceDrop] Request ${requestId}: Successfully calculated price drop. ` + - `carPrice: ${finalPriceDropData.carPrice}, ` + - `sumOfSeverity: ${finalPriceDropData.sumOfSeverity}, ` + - `total: ${finalPriceDropData.total}`, - ); - } - - // Step 6: Save to database - await this.claimRequestManagementDbService.findOneAndUpdate( - { _id: new Types.ObjectId(request._id) }, - { $set: { priceDrop: finalPriceDropData } }, - ); - - this.logger.log( - `[PriceDrop] Request ${requestId}: Price drop calculation completed and saved.`, - ); - } catch (err) { - this.logger.error( - `[PriceDrop] Request ${requestId}: An error occurred during the price drop calculation: ${err.message}`, - err.stack, - ); - } - } - - private mergeAndRecalculatePriceDrop( - existingData: any, - autoCalculatedData: any, - manualOverride: any, - carModel: number, - ) { - const mergedInputs = { - ...existingData, - ...autoCalculatedData, - ...manualOverride, - }; - - if (!mergedInputs.carPrice || !mergedInputs.carValue) { - return { - carPrice: mergedInputs.carPrice || null, - carModel: carModel, - carValue: mergedInputs.carValue || [], - sumOfSeverity: 0, - coefficientYear: this.yearCoefficient[carModel] || 1, - total: 0, - }; - } - - return this.priceDropFormula( - mergedInputs.carPrice, - carModel, - mergedInputs.carValue, - ); - } - - private getSeverityValues(carPartsAi: any[]): number[] { - const severities: number[] = []; - - const knownPartKeyMap = new Map(); - for (const originalKey of Object.keys(this.priceDropPart)) { - if (typeof originalKey === "string") { - knownPartKeyMap.set(this.normalizeKey(originalKey), originalKey); - } - } - - for (const part of carPartsAi) { - const damagedPartTable = part?.aiReport?.damaged_part_table; - if (Array.isArray(damagedPartTable) && damagedPartTable.length > 0) { - for (const damagedPartInfo of damagedPartTable) { - if (damagedPartInfo && typeof damagedPartInfo.name === "string") { - const normalizedAiPartName = this.normalizeKey( - damagedPartInfo.name, - ); - - if (knownPartKeyMap.has(normalizedAiPartName)) { - const originalPriceDropKey = - knownPartKeyMap.get(normalizedAiPartName); - - const severityValue = - this.priceDropPart[originalPriceDropKey]?.[ - damagedPartInfo.severity - ]; - - if (severityValue !== undefined) { - severities.push(severityValue); - } - } - } - } - } - } - return severities; - } - - private async fetchCarPrices(): Promise< - { carName: string; marketPrice: number }[] - > { - const carPrices: { carName: string; marketPrice: number }[] = []; - const endpoints = ["akharin", "hamrah"]; - - for (const item of endpoints) { - try { - const url = `${process.env.CW_URL}price?${item}`; - const response = await lastValueFrom(this.httpService.get(url)); - if (Array.isArray(response.data)) { - let validEntries = 0; - for (const r of response.data) { - if (r?.carName && r?.marketPrice) { - carPrices.push({ - carName: r.carName, - marketPrice: r.marketPrice, - }); - validEntries++; - } - } - this.logger.debug( - `[PriceDrop] Fetched ${validEntries} valid car prices from endpoint '${item}' (total entries: ${response.data.length})`, - ); - } else { - this.logger.warn( - `[PriceDrop] Endpoint '${item}' returned non-array data: ${typeof response.data}`, - ); - } - } catch (err) { - this.logger.error( - `[PriceDrop] Error fetching car prices for endpoint '${item}': ${err.message}`, - err.stack, - ); - } - } - - if (carPrices.length === 0) { - this.logger.error( - `[PriceDrop] No car prices fetched from any endpoint. Endpoints tried: ${endpoints.join(", ")}`, - ); - } else { - this.logger.debug( - `[PriceDrop] Total car prices fetched: ${carPrices.length}`, - ); - } - - return carPrices; - } - - private calculateFinalDropPrice( - closestCar: { marketPrice: number } | null, - carModel: any, - severities: number[], - query?: any, - ) { - if (query?.carPrice && query?.carValue) { - return this.priceDropFormula(query.carPrice, carModel, query.carValue); - } - if (closestCar?.marketPrice && severities.length > 0) { - return this.priceDropFormula( - closestCar.marketPrice, - carModel, - severities, - ); - } - return null; - } - - async requestPerId(requestId: string, currentUser: any, query?: any) { - try { - // 1. Fetch the initial request document and perform calculations - const initialRequest = - await this.claimRequestManagementDbService.findOneDocument(requestId); - - if (!initialRequest) { - throw new HttpException( - { responseCode: 1006, message: "Request not found" }, - HttpStatus.NOT_FOUND, - ); - } - - await this.calculatePriceDrop( - initialRequest, - initialRequest.imageRequired.selectPartOfCar, - query, - ); - - const requestUpdated = - await this.claimRequestManagementDbService.findOneDocument(requestId); - - await this.populateFactorLinks(requestUpdated.damageExpertReply); - await this.populateFactorLinks(requestUpdated.damageExpertReplyFinal); - - // 2. Populate required documents with file links - if ( - requestUpdated.requiredDocuments && - Object.keys(requestUpdated.requiredDocuments).length > 0 - ) { - for (const documentType in requestUpdated.requiredDocuments) { - const documentId = requestUpdated.requiredDocuments[documentType]; - if (documentId) { - try { - const doc = await this.claimRequiredDocumentDbService.findById( - documentId.toString(), - ); - if (doc && doc.path) { - // Replace ID with file URL - requestUpdated.requiredDocuments[documentType] = buildFileLink( - doc.path, - ) as any; - } - } catch (error) { - this.logger.warn( - `Failed to populate required document ${documentType}: ${error.message}`, - ); - // Keep the ID if population fails - } - } - } - } - - // 3. Populate the resent document and voice links from the nested blameFile. - if (requestUpdated.blameFile?.expertResendReply) { - // Helper function to avoid repeating code - const populatePartyLinks = async ( - partyKey: "firstParty" | "secondParty", - ) => { - const partyReply = - requestUpdated.blameFile.expertResendReply[partyKey]; - if (!partyReply) return; - - // Populate the voice link - if (partyReply.voice) { - const voiceDoc = await this.blameVoiceDbService.findOne( - partyReply.voice.toString(), - ); - if (voiceDoc) { - partyReply.voice = buildFileLink(voiceDoc.path); - } - } - - // Populate the document links - if (partyReply.documents) { - for (const docType in partyReply.documents) { - const docId = partyReply.documents[docType]; - if (docId) { - // This line will now work correctly after you inject the service. - const doc = await this.blameDocumentDbService.findById( - docId.toString(), - ); - if (doc) { - partyReply.documents[docType] = buildFileLink(doc.path); // Replace ID with URL - } - } - } - } - }; - - // Run the population for both parties - await populatePartyLinks("firstParty"); - await populatePartyLinks("secondParty"); - } - - // 4. Perform authorization checks (as before) - if (this.isCurrentUserAllowed(requestUpdated, currentUser)) { - return new ClaimPerIdRs(requestUpdated); - } - - // Check if locked by someone else (allow if locked by current user) - if (this.isRequestLocked(requestUpdated, currentUser)) { - throw new HttpException( - { responseCode: 1007, message: "Request is locked" }, - HttpStatus.FORBIDDEN, - ); - } - - // 5. Return the fully populated response - return new ClaimPerIdRs(requestUpdated); - } catch (error) { - this.globalErrHandler(error); - } - } - async imageRequired(requestId, currentUser) { const request = await this.claimRequestManagementDbService.findOneDocument(requestId); @@ -1710,60 +861,6 @@ export class ExpertClaimService { } } - async getRequiredDocuments(requestId: string, currentUser: any) { - try { - const request = - await this.claimRequestManagementDbService.findOneDocument(requestId); - - if (!request) { - throw new HttpException( - { responseCode: 1006, message: "Request not found" }, - HttpStatus.NOT_FOUND, - ); - } - - // Perform authorization checks - allow if locked by current user - if (this.isRequestLocked(request, currentUser)) { - throw new HttpException( - { responseCode: 1007, message: "Request is locked" }, - HttpStatus.FORBIDDEN, - ); - } - - // Fetch all required documents for this claim - const documents = - await this.claimRequiredDocumentDbService.findByClaimId(requestId); - - // Populate with file URLs - const populatedDocuments = documents.map((doc) => ({ - _id: doc._id, - documentType: doc.documentType, - fileName: doc.fileName, - fileUrl: buildFileLink(doc.path), - uploadedAt: doc.uploadedAt, - })); - - return { - claimId: requestId, - totalDocuments: populatedDocuments.length, - documents: populatedDocuments, - }; - } catch (error) { - this.globalErrHandler(error); - } - } - - private async processAiImages( - imageRequired: any, - ): Promise<{ aroundTheCar: any[]; damagePartOfCar: any[] }> { - const aiImages = { aroundTheCar: [], damagePartOfCar: [] }; - return aiImages; - } - - private async processImage(imageId: string) { - return this.damageImageDbService.findOne(imageId); - } - private isCurrentUserAllowed(request: any, currentUser: any): boolean { // Check if locked by current user and lock is still active const isLockedByCurrentUser = @@ -1818,256 +915,6 @@ export class ExpertClaimService { return true; } - async submitReplyRequest( - requestId: string, - reply: ClaimSubmitReplyDto, - userId: any, - ) { - try { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - - if (!request) { - throw new NotFoundException("Request not found"); - } - if ( - String(request?.actorLocked?.actorId) !== userId.sub && - !request?.objection - ) { - throw new ForbiddenException("Access denied to this request"); - } - - // Check if lock has expired (unlockTime has passed) - if (request?.unlockTime && !request?.objection) { - const unlockTime = new Date(request.unlockTime).getTime(); - const now = Date.now(); - if (now >= unlockTime) { - throw new ForbiddenException("Your time has expired"); - } - } else if (request?.unlockTime == null && !request?.objection) { - throw new ForbiddenException("Your time has expired"); - } - - if (!request.lockFile && !request?.objection) { - throw new ForbiddenException( - "For submit reply you must lock the request", - ); - } - - const pricingValidationError = getExpertReplyPricingValidationError( - reply.parts, - ); - if (pricingValidationError) { - throw new BadRequestException(pricingValidationError); - } - - // The total cap is a V1-only rule. Legacy claims embed their blame file. - const configuredPriceCap = getClaimV2TotalPaymentCapToman(); - const priceCap = - configuredPriceCap !== null && - claimPriceCapAppliesToBlame(request.blameFile) - ? configuredPriceCap - : null; - if (priceCap !== null && reply.parts && reply.parts.length > 0) { - let totalPrice = 0; - - for (const part of reply.parts) { - if (part.totalPayment) { - let partPrice: number; - if (typeof part.totalPayment === "string") { - // Handle Persian numbers and remove commas - partPrice = this.parsePersianNumber(part.totalPayment); - } else if (typeof part.totalPayment === "number") { - partPrice = part.totalPayment; - } else { - this.logger.warn( - `Invalid totalPayment type for part ${part.partId}: ${typeof part.totalPayment}`, - ); - partPrice = 0; - } - - if (isNaN(partPrice)) { - this.logger.warn( - `Could not parse totalPayment for part ${part.partId}: ${part.totalPayment}`, - ); - partPrice = 0; - } - - totalPrice += partPrice; - } - } - - if (totalPrice > priceCap) { - throw new BadRequestException({ - message: `You have reached the maximum acceptable total price (Rial). The sum of priced parts and factor lines (${totalPrice.toLocaleString()}) exceeds the limit (${priceCap.toLocaleString()}).`, - error: "PRICE_CAP_ERROR", - code: "PRICE_CAP_ERROR", - totalPrice: totalPrice, - priceCap, - }); - } - } - - // Validate daghi fields - if (reply.parts && reply.parts.length > 0) { - for (const part of reply.parts) { - if (part.typeOfDamage === TypeOfDamage.Repair) continue; - if (!part.daghi || !part.daghi.option) { - throw new BadRequestException( - `Daghi option is required for part ${part.partId}`, - ); - } - - // Validate based on option - if (part.daghi.option === DaghiOption.RECYCLED_PARTS_VALUE) { - if (!part.daghi.price) { - throw new BadRequestException( - `Price is required for part ${part.partId} when option is '${DaghiOption.RECYCLED_PARTS_VALUE}'`, - ); - } - } - // For NO_VALUE and WITH_DAMAGED_PART_CALCULATION, no additional fields needed - } - } - - const isObjection = !!request.objection; - const replyFieldKey = isObjection - ? "damageExpertReplyFinal" - : "damageExpertReply"; - - const needsFactorUpload = - reply.parts?.some((part) => part.factorNeeded === true) ?? false; - - const nextStatus = needsFactorUpload - ? ReqClaimStatus.PendingFactorUpload - : ReqClaimStatus.CheckedRequest; - - const nextStep = needsFactorUpload - ? ClaimStepsEnum.WaitingForFactorUpload - : ClaimStepsEnum.WaitingForUserToReact; - - // Branch selection is no longer part of claim pricing. - const processedParts = reply.parts.map((part) => { - if (part.typeOfDamage === TypeOfDamage.Repair) { - const { daghi: _daghi, ...repairPart } = part; - return repairPart; - } - return { - ...part, - daghi: { - option: part.daghi!.option, - ...(part.daghi!.price && { price: part.daghi!.price }), - }, - }; - }); - - const expertProfileSnapshot = await this.snapshotDamageExpert(userId.sub); - - const replyPayload = { - description: reply.description, - parts: processedParts, - submitTime: new Date(), - actorDetail: { - actorName: userId.fullName, - actorId: userId.sub, - }, - ...(expertProfileSnapshot && { expertProfileSnapshot }), - }; - - const updatePayload = { - $set: { - lockFile: false, - claimStatus: nextStatus, - currentStep: nextStep, - [replyFieldKey]: replyPayload, - }, - $push: { - actorsChecker: { - [ReqClaimStatus.CheckedRequest]: request.actorLocked, - Date: new Date(), - }, - steps: nextStep, - }, - }; - - await this.claimRequestManagementDbService.findAndUpdate( - requestId, - updatePayload, - ); - - if (!isObjection) { - await this.recordClaimExpertActivity({ - expertId: String(userId.sub), - tenantId: String(request.userClientKey ?? userId.clientKey ?? ""), - claimId: String(requestId), - eventType: ExpertFileActivityType.HANDLED, - idempotencyKey: `claim:${requestId}:handled:${userId.sub}`, - }); - } - - return { - requestId: request._id, - claimStatus: nextStatus, - }; - } catch (error) { - this.logger.error( - `Error in submitReplyRequest for claim ${requestId}:`, - error.stack, - ); - if (error instanceof HttpException) { - throw error; - } - throw new HttpException( - "An internal server error occurred.", - HttpStatus.INTERNAL_SERVER_ERROR, - ); - } - } - - async submitResend( - requestId: string, - body: ClaimSubmitResendDto, - userId: any, - ) { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - - if (!request) throw new NotFoundException("request_not_found"); - if (String(request?.actorLocked?.actorId) !== userId) - throw new ForbiddenException("access_denied_please_lock"); - if (request.unlockTime == null) - throw new ForbiddenException("time_expired"); - if (!request.lockFile) - throw new ForbiddenException( - "for submit reply you must lock the request", - ); - if (request.damageExpertResend) - throw new ForbiddenException("request already has resend reply"); - if (request.damageExpertReplyFinal) - throw new ForbiddenException("request already has final reply"); - - const resendSnapshot = await this.snapshotDamageExpert(userId); - - await this.claimRequestManagementDbService.findAndUpdate(requestId, { - lockFile: false, - claimStatus: ReqClaimStatus.WaitingForUserToResend, - damageExpertResend: { - resendDescription: body.resendDescription, - resendDocuments: body.resendDocuments, - resendCarParts: body.resendCarParts, - ...(resendSnapshot && { expertProfileSnapshot: resendSnapshot }), - }, - $push: { - actorsChecker: { - [ReqClaimStatus.WaitingForUserToResend]: request.actorLocked, - }, - Date: new Date(), - }, - }); - - return request; - } - async streamServiceV2(requestId, query, res, header) { const request = await this.claimCaseDbService.findById(requestId); // const blameCase = await this.blameCaseDbService @@ -2127,138 +974,6 @@ export class ExpertClaimService { // } } - async streamService(requestId, query, res, header) { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - let videoPath: string = ""; - switch (query) { - case "accident": - videoPath = await this.getAccidentVideoPath( - String( - request?.blameFile?.firstPartyDetails?.firstPartyFile - ?.firstPartyVideoId, - ), - ); - break; - case "car-capture": - videoPath = await this.getCarCapture(requestId); - break; - default: - throw new NotFoundException("Invalid query type"); - } - if (!videoPath) throw new NotFoundException("video_not_found"); - - const absolutePath = join(process.cwd(), videoPath.replace(/^\/+/, "")); - - if (!existsSync(absolutePath)) { - throw new NotFoundException( - `Video file not found at path: ${absolutePath}`, - ); - } - - const { size } = statSync(absolutePath); - const range = header.range; - - if (range) { - const [startStr, endStr] = range.replace(/bytes=/, "").split("-"); - const start = parseInt(startStr, 10); - const end = endStr ? parseInt(endStr, 10) : size - 1; - const chunkSize = end - start + 1; - - const file = createReadStream(absolutePath, { start, end }); - - res.writeHead(206, { - "Content-Range": `bytes ${start}-${end}/${size}`, - "Accept-Ranges": "bytes", - "Content-Length": chunkSize, - "Content-Type": "video/mp4", - }); - - file.pipe(res); - } else { - res.writeHead(200, { - "Content-Length": size, - "Content-Type": "video/mp4", - }); - - createReadStream(absolutePath).pipe(res); - } - } - - async getVideoLink( - requestId: string, - query: "car-capture" | "accident", - ): Promise<{ url: string }> { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Claim request not found"); - } - - let videoPath: string = ""; - switch (query) { - case "accident": - videoPath = await this.getAccidentVideoPath( - String( - request?.blameFile?.firstPartyDetails?.firstPartyFile - ?.firstPartyVideoId, - ), - ); - break; - case "car-capture": - videoPath = await this.getCarCapture(requestId); - break; - default: - throw new BadRequestException("Invalid query type specified"); - } - - if (!videoPath) { - throw new NotFoundException( - "Video file not found for the specified type.", - ); - } - - // Use your existing helper to build the full, public URL - const fileUrl = buildFileLink(videoPath); - - // Return the URL in a clean JSON object - return { url: fileUrl }; - } - - async voiceStream(id, res, headers) { - // audio/mpeg - const voice = await this.blameVoiceDbService.findOne(id); - if (!voice) throw new NotFoundException("video_not_found"); - const { size } = statSync(voice.path); - const voicePath = voice.path; - const VoiceRange = headers.range; - if (VoiceRange) { - const parts = VoiceRange?.replace(/bytes=/, "").split("-"); - const end = parts[1] ? parseInt(parts[1], 16) : size - 1; - const start = parseInt(parts[0], 10); - const chunksize = end - start + 1; - - const file = createReadStream(voicePath, { start, end }); - - const header = { - "Content-Range": `bytes ${start}-${end}/${size}`, - "Accept-Ranges": "bytes", - "Content-Length": chunksize, - "Content-Type": "audio/mpeg", - }; - - res.writeHead(206, header); - file.pipe(res); - } else { - const head = { - "Content-Length": size, - "Content-Type": "audio/mpeg", - }; - res.writeHead(200, head); - createReadStream(voicePath).pipe(res); - } - } - async getVoiceLink(id: string): Promise<{ url: string }> { const voice = await this.blameVoiceDbService.findOne(id); if (!voice) { @@ -2270,146 +985,6 @@ export class ExpertClaimService { return { url: fileUrl }; } - async getCarCapture(requestId): Promise { - const video = await this.claimVideoCaptureDbService.findOne({ - claimId: new Types.ObjectId(requestId), - }); - - if (!video?.path) { - throw new NotFoundException("Car capture video not found"); - } - - return String(video.path); - } - - async getAccidentVideoPath(requestId: string): Promise { - const video = await this.blameVideoDbService.findOneByRequestId(requestId); - if (!video?.path) { - throw new NotFoundException("Accident video not found"); - } - - return video.path; - } - - async validateClaimFactors( - claimId: string, - decisions: { - partId: string; - status: FactorStatus; - rejectionReason?: string; - }[], - expertId: string, - ) { - const claim = await this.claimRequestManagementDbService.findOne(claimId); - if (!claim) { - throw new NotFoundException("Claim not found"); - } - - const finalReply = claim.damageExpertReplyFinal || claim.damageExpertReply; - const replyFieldKey = claim.damageExpertReplyFinal - ? "damageExpertReplyFinal" - : "damageExpertReply"; - - if (!finalReply) { - throw new BadRequestException("No expert reply found in this claim."); - } - - for (const decision of decisions) { - const partIndex = finalReply.parts.findIndex( - (p) => p.partId === decision.partId, - ); - if (partIndex === -1) { - this.logger.warn( - `Part with ID ${decision.partId} not found in claim ${claimId}. Skipping.`, - ); - continue; - } - - await this.claimRequestManagementDbService.findOneAndUpdate( - { _id: new Types.ObjectId(claimId) }, - { - $set: { - [`${replyFieldKey}.parts.${partIndex}.factorStatus`]: - decision.status, - [`${replyFieldKey}.parts.${partIndex}.rejectionReason`]: - decision.rejectionReason || null, - }, - }, - ); - } - - const factorSnap = await this.snapshotDamageExpert(expertId); - if (factorSnap && decisions.length > 0) { - await this.claimRequestManagementDbService.findOneAndUpdate( - { _id: new Types.ObjectId(claimId) }, - { - $set: { factorValidationExpertProfileSnapshot: factorSnap }, - }, - ); - } - - const updatedClaim = - await this.claimRequestManagementDbService.findOne(claimId); - const updatedReply = - updatedClaim.damageExpertReplyFinal || updatedClaim.damageExpertReply; - - const requiredFactors = updatedReply.parts.filter((p) => p.factorNeeded); - - const anyRejected = requiredFactors.some( - (p) => p.factorStatus === FactorStatus.REJECTED, - ); - const anyStillPending = requiredFactors.some( - (p) => p.factorStatus === FactorStatus.PENDING || !p.factorStatus, - ); - - let newStatus: ReqClaimStatus | null = null; - let responseMessage = "Factor validation complete."; - - if (anyRejected) { - // At least one factor is rejected → stay in factor flow and ask user to re-upload - newStatus = ReqClaimStatus.FactorRejected; - responseMessage = - "Factors reviewed. Some factors were rejected, awaiting user resubmission."; - // TODO: Send an SMS or notification to the user here. - } else if (anyStillPending) { - // Some factors still pending (e.g. not validated in this batch) - responseMessage = - "Some factors were approved, but others are still pending validation."; - } else { - // All required factors are approved: - // Move claim into a state where the user can review the final decision and object if needed. - newStatus = ReqClaimStatus.CheckedRequest; - responseMessage = - "All required factors have been approved. The claim is now ready for user review and possible objection."; - } - - if (newStatus) { - const update: any = { - $set: { claimStatus: newStatus }, - }; - - // When factors are fully approved, also move the step to WaitingForUserToReact, - // just like the non-factor flow in submitReplyRequest. - if (newStatus === ReqClaimStatus.CheckedRequest) { - update.$set.currentStep = ClaimStepsEnum.WaitingForUserToReact; - update.$set.nextStep = ClaimStepsEnum.WaitingForUserToReact; - update.$push = { - steps: ClaimStepsEnum.WaitingForUserToReact, - }; - } - - await this.claimRequestManagementDbService.findByIdAndUpdate( - claimId, - update, - ); - } - - return { - message: responseMessage, - newStatus: newStatus || updatedClaim.claimStatus, - }; - } - /** * Close the claim after factor validation without a second insurer-review signature. * Owner already uploaded factor files; mixed replies already have priced-line acceptance on file. @@ -2684,40 +1259,6 @@ export class ExpertClaimService { }; } - async inPersonVisit(requestId: string, actorDetail: any) { - const request = - await this.claimRequestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Blame not found"); - } - - const visitSnapshot = await this.snapshotDamageExpert(actorDetail.sub); - - const updated = await this.claimRequestManagementDbService.findAndUpdate( - requestId, - { - claimStatus: ReqClaimStatus.InPersonVisit, - ...(visitSnapshot && { - damageExpertInPersonVisitProfileSnapshot: visitSnapshot, - }), - }, - ); - - await this.recordClaimExpertActivity({ - expertId: String(actorDetail.sub), - tenantId: String(request.userClientKey ?? actorDetail.clientKey ?? ""), - claimId: String(requestId), - eventType: ExpertFileActivityType.HANDLED, - idempotencyKey: `claim:${requestId}:handled:${actorDetail.sub}`, - }); - - return updated; - } - - async retrieveInsuranceBranches(insuranceId: string) { - return await this.branchDbService.findAll(insuranceId); - } - /** * V2: branches for the damage expert's insurer tenant (JWT `clientKey`). * Same data as v1 `GET expert-claim/branches/:insuranceId` without passing client id. @@ -2727,11 +1268,6 @@ export class ExpertClaimService { return await this.branchDbService.findAll(clientKey); } - private globalErrHandler(error) { - this.logger.error(error.response?.responseCode, error.response); - throw new HttpException(error.response, error.claimStatus); - } - /** * FILE_REVIEWER path: atomically assign this reviewer to the linked V4 blame * file. Operates on the blame document (not the claim workflow lock). @@ -4959,18 +3495,6 @@ export class ExpertClaimService { }; } - private claimHasDamageExpertReply(claim: { - evaluation?: { - damageExpertReply?: unknown; - damageExpertReplyFinal?: unknown; - }; - }): boolean { - return !!( - claim.evaluation?.damageExpertReply || - claim.evaluation?.damageExpertReplyFinal - ); - } - /** * True while a workflow lock is still within its window (`expiredAt` when set, else lockedAt + TTL). * Missing both timestamps on old documents: treat lock as enforced until cleared. diff --git a/src/expert-insurer/expert-insurer.service.ts b/src/expert-insurer/expert-insurer.service.ts index 591e585..0e91e46 100644 --- a/src/expert-insurer/expert-insurer.service.ts +++ b/src/expert-insurer/expert-insurer.service.ts @@ -7,8 +7,69 @@ import { } from "@nestjs/common"; import { Types } from "mongoose"; import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; +import { ClaimSignDbService } from "src/claim-request-management/entites/db-service/claim-sign.db.service"; +import { VideoCaptureDbService } from "src/claim-request-management/entites/db-service/video-capture.db.service"; +import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references"; import { CreateBranchDto } from "src/client/dto/create-branch.dto"; import { BranchDbService } from "src/client/entities/db-service/branch.db.service"; +import { ClientDbService } from "src/client/entities/db-service/client.db.service"; +import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; +import { + UnifiedFileStatusReportDto, + UnifiedFileStatusReportQueryDto, +} from "src/common/dto/unified-file-status-report.dto"; +import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher"; +import { enrichBlamePartiesForAgreementView } from "src/helpers/blame-party-agreement-decision"; +import { + getClaimCarAngleCaptureBlob, + getDamagedPartCaptureBlob, + hasDamagedPartCapture, + type ClaimCarAngleKey, +} from "src/helpers/claim-car-angle-media"; +import { serializeDamagedPartSelectionHistory } from "src/helpers/claim-damaged-part-audit"; +import { toJalaliDateAndTime } from "src/helpers/date-jalali"; +import { + applyListQueryV2, + isInListDateRange, + parseListDateRange, +} from "src/helpers/list-query-v2"; +import { + catalogLikeKeyFromPart, + normalizeDamageSelectedParts, +} from "src/helpers/outer-damage-parts"; +import { + blameCaseTouchesClient, + claimCaseTouchesClient, +} from "src/helpers/tenant-scope"; +import { + countUnifiedFileStatuses, + getUnifiedFileStatusCatalog, + resolveUnifiedFileStatus, +} from "src/helpers/unified-file-status"; +import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; +import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; +import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service"; +import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service"; +import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; +import { FileRating } from "src/request-management/entities/schema/request-management.schema"; +import { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver"; +import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog"; +import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; +import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; +import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { UserType } from "src/Types&Enums/userType.enum"; +import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service"; +import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; +import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service"; +import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; +import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; +import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; +import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; +import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service"; +import { UserDbService } from "src/users/entities/db-service/user.db.service"; +import { ExpertFileActivityType } from "src/users/entities/schema/expert-file-activity.schema"; +import { HashService } from "src/utils/hash/hash.service"; import { CreateBlameExpertByInsurerDto, CreateClaimExpertByInsurerDto, @@ -16,65 +77,6 @@ import { CreateFileReviewerByInsurerDto, CreateInsurerExpertDto, } from "./dto/create-insurer-expert.dto"; -import { - blameCaseTouchesClient, - claimCaseTouchesClient, -} from "src/helpers/tenant-scope"; -import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; -import { FileRating } from "src/request-management/entities/schema/request-management.schema"; -import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; -import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; -import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; -import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; -import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; -import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; -import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; -import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service"; -import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service"; -import { UserDbService } from "src/users/entities/db-service/user.db.service"; -import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service"; -import { ExpertFileActivityType } from "src/users/entities/schema/expert-file-activity.schema"; -import { HashService } from "src/utils/hash/hash.service"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { UserType } from "src/Types&Enums/userType.enum"; -import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service"; -import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service"; -import { VideoCaptureDbService } from "src/claim-request-management/entites/db-service/video-capture.db.service"; -import { ClientDbService } from "src/client/entities/db-service/client.db.service"; -import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; -import { toJalaliDateAndTime } from "src/helpers/date-jalali"; -import { enrichBlamePartiesForAgreementView } from "src/helpers/blame-party-agreement-decision"; -import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; -import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; -import { sanitizeStoredInquiryParticipants } from "src/request-management/inquiry-participant-resolver"; -import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; -import { - UnifiedFileStatusReportDto, - UnifiedFileStatusReportQueryDto, -} from "src/common/dto/unified-file-status-report.dto"; -import { - applyListQueryV2, - isInListDateRange, - parseListDateRange, -} from "src/helpers/list-query-v2"; -import { - countUnifiedFileStatuses, - getUnifiedFileStatusCatalog, - resolveUnifiedFileStatus, -} from "src/helpers/unified-file-status"; -import { - getClaimCarAngleCaptureBlob, - getDamagedPartCaptureBlob, - hasDamagedPartCapture, - type ClaimCarAngleKey, -} from "src/helpers/claim-car-angle-media"; -import { - catalogLikeKeyFromPart, - normalizeDamageSelectedParts, - type DamageSelectedPartV2, -} from "src/helpers/outer-damage-parts"; -import { ClaimVehicleTypeV2 } from "src/static/outer-car-parts-catalog"; -import { ClaimSignDbService } from "src/claim-request-management/entites/db-service/claim-sign.db.service"; import { extractExpertNamesFromBlame, extractExpertNamesFromClaim, @@ -84,9 +86,6 @@ import { getEventFaLabel, localizeTimelineMetadata, } from "./helper/timeline-fa-labels"; -import { buildEnrichedDamagedParts } from "src/expert-claim/dto/claim-damaged-part.enricher"; -import { serializeDamagedPartSelectionHistory } from "src/helpers/claim-damaged-part-audit"; -import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references"; @Injectable() export class ExpertInsurerService { @@ -150,54 +149,6 @@ export class ExpertInsurerService { return { $or: [{ clientKey: oid }, { clientKey: str }] }; } - private async buildExpertActivityStatsMap( - tenantId: Types.ObjectId, - expertIds: string[], - ): Promise> { - const events = - await this.expertFileActivityDbService.findByTenantAndExperts( - tenantId, - expertIds, - ); - const stateByExpertFile = new Map< - string, - { checked: boolean; handled: boolean } - >(); - - for (const e of events) { - const key = `${String(e.expertId)}:${String(e.fileId)}`; - const prev = stateByExpertFile.get(key) ?? { - checked: false, - handled: false, - }; - if (e.eventType === ExpertFileActivityType.CHECKED) { - if (!prev.handled) prev.checked = true; - } else if (e.eventType === ExpertFileActivityType.UNCHECKED) { - prev.checked = false; - } else if (e.eventType === ExpertFileActivityType.HANDLED) { - prev.handled = true; - prev.checked = false; - } - stateByExpertFile.set(key, prev); - } - - const result: Record< - string, - { totalHandled: number; totalChecked: number } - > = {}; - for (const expertId of expertIds) { - result[expertId] = { totalHandled: 0, totalChecked: 0 }; - } - for (const [key, st] of stateByExpertFile.entries()) { - const [expertId] = key.split(":"); - if (!result[expertId]) - result[expertId] = { totalHandled: 0, totalChecked: 0 }; - if (st.handled) result[expertId].totalHandled += 1; - else if (st.checked) result[expertId].totalChecked += 1; - } - return result; - } - private parseObjectId(value: string, label: string): Types.ObjectId { if (!Types.ObjectId.isValid(value)) { throw new BadRequestException(`Invalid ${label}`); @@ -338,14 +289,6 @@ export class ExpertInsurerService { }; } - private sanitizePartyForInsurerView(party: any) { - if (!party || typeof party !== "object") return party; - return { - ...party, - vehicle: this.sanitizeVehicleInquiry(party.vehicle), - }; - } - private serializeBlameExpertDecisionForInsurer( decision: unknown, ): Record | undefined { @@ -488,39 +431,6 @@ export class ExpertInsurerService { } } - private insurerDamagedPartRowFromCapture( - sp: DamageSelectedPartV2, - index: number, - damagedPartsDataExpert: unknown, - selectedNormExpert: DamageSelectedPartV2[], - ) { - const ck = sp.catalogKey ?? catalogLikeKeyFromPart(sp); - const cap = getDamagedPartCaptureBlob( - damagedPartsDataExpert, - ck, - selectedNormExpert, - ) as { url?: string; path?: string; fileName?: string } | undefined; - const url = resolveStoredFileUrl(cap); - const link = url; - return { - index, - id: sp.id, - name: sp.name, - side: sp.side, - label_fa: sp.label_fa, - catalogKey: sp.catalogKey, - captured: hasDamagedPartCapture( - damagedPartsDataExpert, - ck, - selectedNormExpert, - ), - path: cap?.path, - fileName: cap?.fileName, - url, - link, - }; - } - private sanitizeDamageForInsurerDetail(damage: unknown): unknown { if (!damage || typeof damage !== "object") return damage; const d = { ...(damage as Record) }; @@ -945,12 +855,15 @@ export class ExpertInsurerService { }; } - private resolveReportDateRange(opts: { - from?: string; - to?: string; - periodDays?: string | number; - } = {}) { - const hasFrom = typeof opts.from === "string" && opts.from.trim().length > 0; + private resolveReportDateRange( + opts: { + from?: string; + to?: string; + periodDays?: string | number; + } = {}, + ) { + const hasFrom = + typeof opts.from === "string" && opts.from.trim().length > 0; const hasTo = typeof opts.to === "string" && opts.to.trim().length > 0; const periodDays = this.parseReportPeriodDays(opts.periodDays); const now = new Date(); @@ -1020,7 +933,8 @@ export class ExpertInsurerService { })) .filter( (event) => - !Number.isNaN(event.occurredAt.getTime()) && event.occurredAt <= cutoff, + !Number.isNaN(event.occurredAt.getTime()) && + event.occurredAt <= cutoff, ) .sort((a, b) => a.occurredAt.getTime() - b.occurredAt.getTime()); @@ -1097,15 +1011,21 @@ export class ExpertInsurerService { const clientObjectId = this.getClientId(actor); const ckFilter = this.clientKeyScopeFilter(clientObjectId); const range = this.resolveReportDateRange(opts); - const [experts, damageExperts, fieldExperts, blameFiles, claimFiles, activityEvents] = - await Promise.all([ - this.expertDbService.findAll(ckFilter as never), - this.damageExpertDbService.findAll(ckFilter as never), - this.fieldExpertDbService.findAll(ckFilter as never), - this.getClientBlameFiles(clientObjectId), - this.getClientClaimFiles(clientObjectId), - this.expertFileActivityDbService.findByTenant(clientObjectId), - ]); + const [ + experts, + damageExperts, + fieldExperts, + blameFiles, + claimFiles, + activityEvents, + ] = await Promise.all([ + this.expertDbService.findAll(ckFilter as never), + this.damageExpertDbService.findAll(ckFilter as never), + this.fieldExpertDbService.findAll(ckFilter as never), + this.getClientBlameFiles(clientObjectId), + this.getClientClaimFiles(clientObjectId), + this.expertFileActivityDbService.findByTenant(clientObjectId), + ]); const roster = [ ...(experts as any[]).map((expert) => ({ @@ -1135,9 +1055,15 @@ export class ExpertInsurerService { ]; const rosterById = new Map( - roster.map((expert) => [expert._id, { ...expert, ...this.emptyExpertCaseBreakdown() }]), + roster.map((expert) => [ + expert._id, + { ...expert, ...this.emptyExpertCaseBreakdown() }, + ]), + ); + const fileState = this.buildExpertFileStateMap( + activityEvents as any[], + range.toDate, ); - const fileState = this.buildExpertFileStateMap(activityEvents as any[], range.toDate); const blameFilesInRange = blameFiles.filter((file) => this.isInDateRange(file?.createdAt, range.fromDate, range.toDate), @@ -1147,8 +1073,8 @@ export class ExpertInsurerService { ); for (const file of blameFilesInRange as any[]) { - const expertIds = this.blameFieldExpertIdCandidates(file).filter((expertId) => - rosterById.has(expertId), + const expertIds = this.blameFieldExpertIdCandidates(file).filter( + (expertId) => rosterById.has(expertId), ); for (const expertId of new Set(expertIds)) { const row = rosterById.get(expertId); @@ -1295,14 +1221,18 @@ export class ExpertInsurerService { async getTopFilesForClient( insurerId: string, opts: { from?: string; to?: string; periodDays?: string | number } = {}, - ): Promise> { + ): Promise< + Array<{ + publicId: string; + createdAt: string; + combinedScore: number; + userRating: { comment: string | null; overallEvaluation: number | null }; + }> + > { const range = this.resolveReportDateRange(opts); - let claimFiles = await this.getClientClaimFiles(this.getClientId(insurerId)); + let claimFiles = await this.getClientClaimFiles( + this.getClientId(insurerId), + ); claimFiles = claimFiles.filter((file) => this.isInDateRange(file.createdAt, range.fromDate, range.toDate), @@ -1403,7 +1333,11 @@ export class ExpertInsurerService { } const handledAt = this.portfolioFileHandledAt(file, handledAtByFileId); - if (!handledAt || handledAt < range.fromDate || handledAt > range.toDate) { + if ( + !handledAt || + handledAt < range.fromDate || + handledAt > range.toDate + ) { continue; } if (Number.isNaN(createdAt.getTime())) continue; @@ -1512,9 +1446,11 @@ export class ExpertInsurerService { // files they handled is the correct scope. const [allBlames, allClaims] = await Promise.all([ onBlameRoster - ? (this.blameRequestDbService.find({}, { lean: true }) as Promise) + ? (this.blameRequestDbService.find({}, { lean: true }) as Promise< + any[] + >) : Promise.resolve([] as any[]), - (this.claimCaseDbService.find({}, { lean: true }) as Promise), + this.claimCaseDbService.find({}, { lean: true }) as Promise, ]); const result: any[] = []; @@ -1801,11 +1737,12 @@ export class ExpertInsurerService { let files = await this.buildMergedInsurerFiles(id); if (query.unifiedStatus) { - files = files.filter( - (f) => f.unifiedFileStatus === query.unifiedStatus, - ); + files = files.filter((f) => f.unifiedFileStatus === query.unifiedStatus); } - const { fromDate, toDate } = parseListDateRange(query.startDate, query.endDate); + const { fromDate, toDate } = parseListDateRange( + query.startDate, + query.endDate, + ); if (fromDate || toDate) { files = files.filter((f) => isInListDateRange(f.createdAt, fromDate, toDate), @@ -2167,7 +2104,9 @@ export class ExpertInsurerService { const email = payload.email.trim().toLowerCase(); const existing = await this.fileMakerDbService.findOne({ email }); if (existing) { - throw new ConflictException("A FileMaker with this email already exists."); + throw new ConflictException( + "A FileMaker with this email already exists.", + ); } const nationalCode = payload.nationalCode.trim(); @@ -2304,8 +2243,9 @@ export class ExpertInsurerService { thirdPartyFiles: summary.thirdPartyFiles, carBodyFiles: summary.carBodyFiles, totalFiles: summary.totalFiles, - activeExperts: expertReport.experts.filter((expert) => expert.totalFiles > 0) - .length, + activeExperts: expertReport.experts.filter( + (expert) => expert.totalFiles > 0, + ).length, reviewedFiles: summary.reviewedFiles, unreviewedFiles: summary.unreviewedFiles, thirdPartyReviewedFiles: summary.thirdPartyReviewedFiles, @@ -2501,17 +2441,18 @@ export class ExpertInsurerService { }; } - private static readonly TIMELINE_PERFORMER_FA_LABELS: Record = { - user: "کاربر", - field_expert: "کارشناس میدانی", - damage_expert: "کارشناس خسارت", - file_maker: "پرونده‌ساز", - file_reviewer: "بازبین پرونده", - registrar: "ثبت‌کننده", - call_center: "اپراتور کال‌سنتر", - system: "سیستم", - expert: "کارشناس", - }; + private static readonly TIMELINE_PERFORMER_FA_LABELS: Record = + { + user: "کاربر", + field_expert: "کارشناس میدانی", + damage_expert: "کارشناس خسارت", + file_maker: "پرونده‌ساز", + file_reviewer: "بازبین پرونده", + registrar: "ثبت‌کننده", + call_center: "اپراتور کال‌سنتر", + system: "سیستم", + expert: "کارشناس", + }; /** * Returns the most specific actor role recorded in history so the frontend can @@ -2527,7 +2468,8 @@ export class ExpertInsurerService { private static resolveTimelinePerformedByCategory( actorType: string | undefined, ): "user" | "expert" | "staff" | "system" | null { - const performedBy = ExpertInsurerService.resolveTimelinePerformedBy(actorType); + const performedBy = + ExpertInsurerService.resolveTimelinePerformedBy(actorType); if (!performedBy) return null; if (performedBy === "user") return "user"; if (performedBy === "system") return "system"; @@ -2544,7 +2486,8 @@ export class ExpertInsurerService { private static resolveTimelinePerformedByFaLabel( actorType: string | undefined, ): string | null { - const performedBy = ExpertInsurerService.resolveTimelinePerformedBy(actorType); + const performedBy = + ExpertInsurerService.resolveTimelinePerformedBy(actorType); if (!performedBy) return null; return ( ExpertInsurerService.TIMELINE_PERFORMER_FA_LABELS[performedBy] ?? @@ -2581,7 +2524,9 @@ export class ExpertInsurerService { return combined || null; } - private static isMeaningfulTimelineActorName(name: string | undefined): boolean { + private static isMeaningfulTimelineActorName( + name: string | undefined, + ): boolean { const trimmed = typeof name === "string" ? name.trim() : ""; if (!trimmed) return false; return !ExpertInsurerService.TIMELINE_PLACEHOLDER_ACTOR_NAMES.has( @@ -2589,7 +2534,10 @@ export class ExpertInsurerService { ); } - private static resolveBlamePartyName(sourceDoc: any, partyRole?: string): string | null { + private static resolveBlamePartyName( + sourceDoc: any, + partyRole?: string, + ): string | null { const parties = Array.isArray(sourceDoc?.parties) ? sourceDoc.parties : []; const normalizedPartyRole = typeof partyRole === "string" ? partyRole.trim().toUpperCase() : ""; @@ -2597,7 +2545,9 @@ export class ExpertInsurerService { const matchedParty = normalizedPartyRole ? parties.find( (party: any) => - String(party?.role ?? "").trim().toUpperCase() === normalizedPartyRole, + String(party?.role ?? "") + .trim() + .toUpperCase() === normalizedPartyRole, ) : null; @@ -2629,7 +2579,16 @@ export class ExpertInsurerService { } const objectId = new Types.ObjectId(actorId); - const [fileMaker, fileReviewer, registrar, callCenter, fieldExpert, damageExpert, expert, user] = await Promise.all([ + const [ + fileMaker, + fileReviewer, + registrar, + callCenter, + fieldExpert, + damageExpert, + expert, + user, + ] = await Promise.all([ this.fileMakerDbService.findById(actorId), this.fileReviewerDbService.findById(actorId), this.registrarDbService.findById(actorId), @@ -2861,7 +2820,9 @@ export class ExpertInsurerService { actorName, performedBy, performedByCategory: - ExpertInsurerService.resolveTimelinePerformedByCategory(performedBy), + ExpertInsurerService.resolveTimelinePerformedByCategory( + performedBy, + ), performedByFaLabel: ExpertInsurerService.resolveTimelinePerformedByFaLabel(performedBy), metadata: localizeTimelineMetadata(ev), @@ -2899,7 +2860,9 @@ export class ExpertInsurerService { actorName, performedBy, performedByCategory: - ExpertInsurerService.resolveTimelinePerformedByCategory(performedBy), + ExpertInsurerService.resolveTimelinePerformedByCategory( + performedBy, + ), performedByFaLabel: ExpertInsurerService.resolveTimelinePerformedByFaLabel(performedBy), metadata: localizeTimelineMetadata(ev), diff --git a/src/fanavaran/fanavaran-audit.service.ts b/src/fanavaran/fanavaran-audit.service.ts index 6117cff..629b0e8 100644 --- a/src/fanavaran/fanavaran-audit.service.ts +++ b/src/fanavaran/fanavaran-audit.service.ts @@ -1,15 +1,15 @@ import { Injectable, Logger } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { isAxiosError, type AxiosResponse } from "axios"; -import { randomBytes } from "node:crypto"; import { Model, Types } from "mongoose"; +import { randomBytes } from "node:crypto"; +import type { FanavaranAuditSession } from "./fanavaran-audit.types"; import { FanavaranAuditLog, FanavaranAuditLogDocument, FanavaranAuditStatus, FanavaranAuditStep, } from "./schema/fanavaran-audit-log.schema"; -import type { FanavaranAuditSession } from "./fanavaran-audit.types"; export interface RecordFanavaranAuditStepInput { session: FanavaranAuditSession; @@ -104,9 +104,7 @@ export class FanavaranAuditService { const lower = key.toLowerCase(); if (FanavaranAuditService.SENSITIVE_HEADER_KEYS.has(lower)) { out[key] = - typeof rawValue === "string" - ? this.maskToken(rawValue) - : "***"; + typeof rawValue === "string" ? this.maskToken(rawValue) : "***"; continue; } if ( @@ -301,14 +299,6 @@ export class FanavaranAuditService { } } - async findByTrackingCode(trackingCode: string) { - return this.auditModel - .find({ trackingCode }) - .sort({ createdAt: 1 }) - .lean() - .exec(); - } - private maskSensitiveDeep(value: unknown, depth = 0): unknown { if (depth > 8) { return "[max-depth]"; diff --git a/src/fanavaran/fanavaran-auth.service.spec.ts b/src/fanavaran/fanavaran-auth.service.spec.ts index f7e44e7..0184f95 100644 --- a/src/fanavaran/fanavaran-auth.service.spec.ts +++ b/src/fanavaran/fanavaran-auth.service.spec.ts @@ -174,7 +174,6 @@ describe("FanavaranAuthService", () => { "parsian", "کد پیگیری خطا: 1\r\n.لطفا پس از چند لحظه مجدد تلاش فرمایید.", ); - expect(service.isInBackoff("parsian")).toBe(true); expect(() => service.assertNotInBackoff("parsian")).toThrow(/backoff/i); }); diff --git a/src/fanavaran/fanavaran-auth.service.ts b/src/fanavaran/fanavaran-auth.service.ts index 38ea0ec..c34227d 100644 --- a/src/fanavaran/fanavaran-auth.service.ts +++ b/src/fanavaran/fanavaran-auth.service.ts @@ -58,7 +58,10 @@ export class FanavaranAuthService { */ static readonly TOKEN_TIME_ZONE = "Asia/Tehran"; - private readonly tokenCache = new Map(); + private readonly tokenCache = new Map< + FanavaranClientKey, + CachedFanavaranAuth + >(); private readonly inflightLogin = new Map< FanavaranClientKey, Promise @@ -94,12 +97,7 @@ export class FanavaranAuthService { | string | undefined; if (typeof data === "string") return data; - return ( - data?.Message || - data?.message || - errorOrMessage.message || - "" - ); + return data?.Message || data?.message || errorOrMessage.message || ""; } if (errorOrMessage instanceof Error) return errorOrMessage.message; return errorOrMessage == null ? "" : String(errorOrMessage); @@ -145,10 +143,6 @@ export class FanavaranAuthService { return Math.max(0, state.until - Date.now()); } - isInBackoff(clientKey: FanavaranClientKey): boolean { - return this.getBackoffRemainingMs(clientKey) > 0; - } - /** * Call after any Fanavaran HTTP failure. Sets a tenant-wide pause when the * error is the familiar “try again later” overload response. @@ -172,12 +166,15 @@ export class FanavaranAuthService { invalidateToken(clientKey: FanavaranClientKey): void { this.tokenCache.delete(clientKey); - void this.authTokenModel.deleteOne({ clientKey }).exec().catch((error) => { - this.logger.warn( - `[${clientKey}] Failed to clear persisted Fanavaran auth token`, - error, - ); - }); + void this.authTokenModel + .deleteOne({ clientKey }) + .exec() + .catch((error) => { + this.logger.warn( + `[${clientKey}] Failed to clear persisted Fanavaran auth token`, + error, + ); + }); } /** @@ -331,7 +328,10 @@ export class FanavaranAuthService { fingerprint: string, ): Promise { try { - const doc = await this.authTokenModel.findOne({ clientKey }).lean().exec(); + const doc = await this.authTokenModel + .findOne({ clientKey }) + .lean() + .exec(); if (!doc?.authenticationToken || !doc.expiresAt) { return null; } @@ -454,11 +454,10 @@ export class FanavaranAuthService { } if (auditSession) { - const exchange = - this.fanavaranAuditService.captureAxiosExchange( - response, - requestHeaders, - ); + const exchange = this.fanavaranAuditService.captureAxiosExchange( + response, + requestHeaders, + ); await this.fanavaranAuditService.recordStep({ session: auditSession, step: FanavaranAuditStep.GET_APP_TOKEN, @@ -498,7 +497,11 @@ export class FanavaranAuthService { durationMs: Date.now() - startedAt, }); } - throw this.toGatewayError(error, "Failed to get appToken from external API", auditSession); + throw this.toGatewayError( + error, + "Failed to get appToken from external API", + auditSession, + ); } } @@ -551,11 +554,10 @@ export class FanavaranAuthService { } if (auditSession) { - const exchange = - this.fanavaranAuditService.captureAxiosExchange( - response, - requestHeaders, - ); + const exchange = this.fanavaranAuditService.captureAxiosExchange( + response, + requestHeaders, + ); await this.fanavaranAuditService.recordStep({ session: auditSession, step: FanavaranAuditStep.LOGIN, @@ -598,7 +600,11 @@ export class FanavaranAuthService { durationMs: Date.now() - startedAt, }); } - throw this.toGatewayError(error, "Failed to login to external API", auditSession); + throw this.toGatewayError( + error, + "Failed to login to external API", + auditSession, + ); } } diff --git a/src/fanavaran/fanavaran-location.service.ts b/src/fanavaran/fanavaran-location.service.ts index efb6840..7b9aad7 100644 --- a/src/fanavaran/fanavaran-location.service.ts +++ b/src/fanavaran/fanavaran-location.service.ts @@ -36,10 +36,6 @@ export class FanavaranLocationService { return ids; } - primaryLocationId(locations?: LocationEntry[] | null): string | undefined { - return this.extractLocationIds(locations)[0]; - } - /** * Maker primary location → reviewer primary → tenant auth.location. * Non-parsian or non-FileMaker flows always use the tenant default. @@ -57,7 +53,10 @@ export class FanavaranLocationService { return defaultLocation; } - const makerLocation = await this.loadPrimaryLocationId(input.fileMakerId, "maker"); + const makerLocation = await this.loadPrimaryLocationId( + input.fileMakerId, + "maker", + ); if (makerLocation) { this.logger.debug( `Fanavaran Location from file-maker id=${input.fileMakerId} → ${makerLocation}`, @@ -155,9 +154,7 @@ export class FanavaranLocationService { ); } if (!caseBranchId || caseBranchId !== reviewerBranchId) { - throw new ForbiddenException( - "This file belongs to another branch.", - ); + throw new ForbiddenException("This file belongs to another branch."); } } diff --git a/src/helpers/blame-claim-eligibility.ts b/src/helpers/blame-claim-eligibility.ts new file mode 100644 index 0000000..442769a --- /dev/null +++ b/src/helpers/blame-claim-eligibility.ts @@ -0,0 +1,61 @@ +type ClaimParty = { + role?: string; + person?: { + userId?: unknown; + fullName?: string; + clientId?: unknown; + phoneNumber?: string; + }; + confirmation?: { accepted?: boolean; signature?: { fileId?: unknown } }; +}; + +type ClaimSource = { + type?: string; + status?: string; + parties?: ClaimParty[]; + expert?: { decision?: { guiltyPartyId?: unknown } }; +}; + +/** Resolve a specific beneficiary; an unknown guilty id never means everyone is eligible. */ +export function resolveClaimBeneficiary(blame: ClaimSource): ClaimParty | null { + const parties = blame.parties ?? []; + const first = parties.find((party) => party.role === "FIRST"); + if (blame.type === "CAR_BODY") return first?.person?.userId ? first : null; + if (blame.type !== "THIRD_PARTY" || parties.length !== 2) return null; + const second = parties.find((party) => party.role === "SECOND"); + const firstId = first?.person?.userId; + const secondId = second?.person?.userId; + const guiltyId = blame.expert?.decision?.guiltyPartyId; + if ( + !firstId || + !secondId || + !guiltyId || + String(firstId) === String(secondId) + ) + return null; + if (String(guiltyId) === String(firstId)) return second!; + if (String(guiltyId) === String(secondId)) return first!; + return null; +} + +export function canUserCreateClaim( + blame: ClaimSource, + userId: string, +): boolean { + const beneficiary = resolveClaimBeneficiary(blame); + if ( + !beneficiary || + !userId || + blame.status !== "COMPLETED" || + String(beneficiary?.person?.userId ?? "") !== userId + ) + return false; + return ( + blame.type === "CAR_BODY" || + (blame.parties ?? []).every( + (party) => + party.confirmation?.accepted === true && + !!party.confirmation.signature?.fileId, + ) + ); +} diff --git a/src/helpers/blame-user-progress.ts b/src/helpers/blame-user-progress.ts index 5e7e7a8..f0734de 100644 --- a/src/helpers/blame-user-progress.ts +++ b/src/helpers/blame-user-progress.ts @@ -10,7 +10,11 @@ export type BlameUserNextAction = export function resolveBlameUserNextAction( status: string, party: { confirmation?: { accepted?: boolean } } | undefined, - claimCreation: { hasClaim: boolean; shouldGuideToCreateClaim: boolean }, + claimCreation: { + hasClaim: boolean; + shouldGuideToCreateClaim: boolean; + canContinueClaim?: boolean; + }, ): BlameUserNextAction { if (!party) return null; if (status === "WAITING_FOR_SIGNATURES") { @@ -20,7 +24,8 @@ export function resolveBlameUserNextAction( } if (status === "COMPLETED") { if (claimCreation.shouldGuideToCreateClaim) return "CREATE_CLAIM"; - if (claimCreation.hasClaim) return "CONTINUE_CLAIM"; + if (claimCreation.hasClaim && claimCreation.canContinueClaim !== false) + return "CONTINUE_CLAIM"; return "VIEW_RESULT"; } if (status === "STOPPED") return "VIEW_RESULT"; diff --git a/src/helpers/persian-pdf-document.ts b/src/helpers/persian-pdf-document.ts deleted file mode 100644 index 9e31cf1..0000000 --- a/src/helpers/persian-pdf-document.ts +++ /dev/null @@ -1,166 +0,0 @@ -import { existsSync } from "node:fs"; -import { join } from "node:path"; -import type PDFDocumentType from "pdfkit"; -import { - isMostlyAscii, - pdfKitRtlKeyValue, - pdfKitRtlParagraph, -} from "./persian-pdf-text"; - -// pdfkit publishes CJS (`module.exports = PDFDocument`) without a `.default` export. -// eslint-disable-next-line @typescript-eslint/no-require-imports -const PDFDocument = require("pdfkit") as typeof PDFDocumentType; - -const PAGE_WIDTH = 595.28; -const MARGIN = 50; -const CONTENT_WIDTH = PAGE_WIDTH - MARGIN * 2; -const LABEL_COLUMN_WIDTH = CONTENT_WIDTH * 0.44; -const VALUE_COLUMN_WIDTH = CONTENT_WIDTH * 0.5; -const VALUE_COLUMN_X = MARGIN; -const COLON_X = MARGIN + VALUE_COLUMN_WIDTH + 4; -const LABEL_COLUMN_X = COLON_X + 10; - -function resolveFontFile(variant: "regular" | "bold"): string { - const file = - variant === "bold" ? "Vazirmatn-Bold.ttf" : "Vazirmatn-Regular.ttf"; - const candidates = [ - join(process.cwd(), "assets", file), - join(process.cwd(), "assets", "fonts", file), - join(process.cwd(), "dist", "assets", file), - join(process.cwd(), "dist", "assets", "fonts", file), - ]; - for (const path of candidates) { - if (existsSync(path)) return path; - } - throw new Error( - `Persian PDF font not found (${file}). Place it under assets/ or assets/fonts/.`, - ); -} - -export type PersianPdfDocument = InstanceType & { - addTitle: (text: string) => void; - addSection: (text: string) => void; - addKeyValue: (label: string, value?: string | number | null) => void; - addBlank: (lines?: number) => void; -}; - -/** Ensure at least `neededPts` of vertical space remain; add a page if not. */ -function ensureSpace( - doc: InstanceType, - neededPts: number, -): void { - if (doc.y + neededPts > doc.page.maxY()) { - doc.addPage(); - } -} - -function drawRtlLine( - doc: InstanceType, - text: string, - fontSize: number, - bold: boolean, -): void { - const y = doc.y; - doc - .font(bold ? "FaBold" : "FaRegular") - .fontSize(fontSize) - .text(pdfKitRtlParagraph(text), MARGIN, y, { - width: CONTENT_WIDTH, - align: "right", - lineBreak: false, - }); - doc.moveDown(fontSize > 12 ? 0.55 : 0.45); -} - -function drawKeyValueRow( - doc: InstanceType, - label: string, - value: string, -): void { - // Reserve one row height (font 10pt ≈ 14 pts with leading) before drawing. - ensureSpace(doc, 16); - - const y = doc.y; - const { label: faLabel, value: faValue } = pdfKitRtlKeyValue(label, value); - - if (isMostlyAscii(faValue)) { - doc.font("Helvetica").fontSize(10).text(faValue, VALUE_COLUMN_X, y, { - width: VALUE_COLUMN_WIDTH, - align: "left", - lineBreak: false, - }); - } else { - doc.font("FaRegular").fontSize(10).text(faValue, VALUE_COLUMN_X, y, { - width: VALUE_COLUMN_WIDTH, - align: "left", - lineBreak: false, - }); - } - - doc.font("Helvetica").fontSize(10).text(":", COLON_X, y, { - lineBreak: false, - }); - - doc.font("FaRegular").fontSize(10).text(faLabel, LABEL_COLUMN_X, y, { - width: LABEL_COLUMN_WIDTH, - align: "right", - lineBreak: false, - }); - - doc.moveDown(0.5); -} - -export function createPersianPdfDocument(): PersianPdfDocument { - const doc = new PDFDocument({ - size: "A4", - margin: MARGIN, - autoFirstPage: true, - }) as PersianPdfDocument; - - doc.registerFont("FaRegular", resolveFontFile("regular")); - doc.registerFont("FaBold", resolveFontFile("bold")); - doc.font("FaRegular"); - - doc.addTitle = (text: string) => { - doc.moveDown(0.2); - drawRtlLine(doc, text, 16, true); - doc.font("FaRegular").fontSize(10); - doc.moveDown(0.15); - }; - - doc.addSection = (text: string) => { - // Reserve space for the gap + section heading + at least one data row below it, - // so the heading is never stranded alone at the bottom of a page. - ensureSpace(doc, 60); - doc.moveDown(0.5); - drawRtlLine(doc, text, 13, true); - doc.font("FaRegular").fontSize(10); - doc.moveDown(0.1); - }; - - doc.addKeyValue = (label: string, value?: string | number | null) => { - const v = - value === undefined || value === null || value === "" - ? "-" - : String(value); - drawKeyValueRow(doc, label, v); - }; - - doc.addBlank = (lines = 1) => { - doc.moveDown(lines * 0.35); - }; - - return doc; -} - -export function persianPdfToBuffer( - doc: InstanceType, -): Promise { - return new Promise((resolve, reject) => { - const chunks: Buffer[] = []; - doc.on("data", (chunk: Buffer) => chunks.push(chunk)); - doc.on("end", () => resolve(Buffer.concat(chunks))); - doc.on("error", reject); - doc.end(); - }); -} diff --git a/src/helpers/persian-pdf-text.ts b/src/helpers/persian-pdf-text.ts deleted file mode 100644 index 5d08c34..0000000 --- a/src/helpers/persian-pdf-text.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** Strip invisible bidi / ZWNJ chars that render as tofu in embedded Arabic fonts. */ -export function normalizePersianPdfText(text: string): string { - return text - .replace(/\u200c/g, " ") - .replace(/[\u200e\u200f\u202a-\u202e\u2066-\u2069\ufeff]/g, "") - .replace(/\u2014/g, "-") - .replace(/\s+/g, " ") - .trim(); -} - -/** - * pdfkit renders glyphs strictly left-to-right. - * fontkit already reshapes each word's glyphs into visual (LTR) order, - * but it does NOT reorder words — so a multi-word RTL string like - * "نام صاحب خودرو" has its words placed LTR on the page and reads - * backwards. Reversing the word sequence here makes pdfkit emit the - * words in the correct visual order for a right-to-left PDF reader. - */ -function reverseRtlWords(text: string): string { - if (!/[\u0600-\u06FF]/.test(text)) return text; - return text.split(" ").reverse().join(" "); -} - -export function pdfKitRtlKeyValue( - label: string, - value: string, -): { label: string; value: string } { - return { - label: reverseRtlWords(normalizePersianPdfText(label)), - value: reverseRtlWords(normalizePersianPdfText(value)), - }; -} - -export function pdfKitRtlParagraph(text: string): string { - return reverseRtlWords(normalizePersianPdfText(text)); -} - -export function isMostlyAscii(text: string): boolean { - return text.length > 0 && !/[\u0600-\u06FF]/.test(text); -} diff --git a/src/helpers/simple-pdf-writer.ts b/src/helpers/simple-pdf-writer.ts deleted file mode 100644 index 8c24ca9..0000000 --- a/src/helpers/simple-pdf-writer.ts +++ /dev/null @@ -1,166 +0,0 @@ -type PdfTextRun = { - pageIndex: number; - x: number; - y: number; - fontSize: number; - bold: boolean; - text: string; -}; - -/** Minimal PDF 1.4 writer (Helvetica) — no external dependencies. */ -export class SimplePdfWriter { - private readonly pageWidth = 595.28; - private readonly pageHeight = 841.89; - private readonly marginX = 50; - private readonly marginTop = 50; - private readonly marginBottom = 50; - private runs: PdfTextRun[] = []; - private pageCount = 1; - private cursorY = this.pageHeight - this.marginTop; - private pageIndex = 0; - - private ensureSpace(lineHeight: number): void { - if (this.cursorY - lineHeight < this.marginBottom) { - this.pageIndex += 1; - this.pageCount += 1; - this.cursorY = this.pageHeight - this.marginTop; - } - } - - private addRun(text: string, fontSize: number, bold = false): void { - const lineHeight = fontSize + 4; - this.ensureSpace(lineHeight); - this.runs.push({ - pageIndex: this.pageIndex, - x: this.marginX, - y: this.cursorY, - fontSize, - bold, - text, - }); - this.cursorY -= lineHeight; - } - - addTitle(text: string): void { - this.addRun(text, 16, true); - this.cursorY -= 4; - } - - addSection(text: string): void { - this.cursorY -= 6; - this.addRun(text, 13, true); - this.cursorY -= 2; - } - - addLine(text: string): void { - this.addRun(text, 10, false); - } - - addKeyValue(label: string, value?: string | number | null): void { - const v = - value === undefined || value === null || value === "" - ? "-" - : String(value); - this.addLine(`${label}: ${v}`); - } - - addBlank(): void { - this.cursorY -= 8; - } - - toBuffer(): Buffer { - const chunkById: string[] = []; - const offsets: number[] = [0]; - let size = Buffer.byteLength("%PDF-1.4\n", "utf8"); - - const addObj = (content: string): number => { - const id = chunkById.length; - offsets.push(size); - const block = `${id} 0 obj\n${content}\nendobj\n`; - chunkById.push(block); - size += Buffer.byteLength(block, "utf8"); - return id; - }; - - chunkById.push("%PDF-1.4\n"); - - const fontRegularId = addObj( - "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>", - ); - const fontBoldId = addObj( - "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>", - ); - - const contentIds: number[] = []; - for (let p = 0; p < this.pageCount; p++) { - const pageRuns = this.runs.filter((r) => r.pageIndex === p); - const cmds: string[] = []; - for (const run of pageRuns) { - const font = run.bold ? "F2" : "F1"; - cmds.push("BT"); - cmds.push(`/${font} ${run.fontSize} Tf`); - cmds.push(`1 0 0 1 ${run.x.toFixed(2)} ${run.y.toFixed(2)} Tm`); - cmds.push(`${encodePdfText(run.text)} Tj`); - cmds.push("ET"); - } - const stream = cmds.join("\n"); - contentIds.push( - addObj( - `<< /Length ${Buffer.byteLength(stream, "utf8")} >>\nstream\n${stream}\nendstream`, - ), - ); - } - - const pagesKidsToken = "__PAGES_KIDS__"; - const pagesId = addObj( - `<< /Type /Pages /Kids [${pagesKidsToken}] /Count ${this.pageCount} >>`, - ); - const pageIds: number[] = []; - for (let p = 0; p < this.pageCount; p++) { - pageIds.push( - addObj( - `<< /Type /Page /Parent ${pagesId} 0 R /Resources << /Font << /F1 ${fontRegularId} 0 R /F2 ${fontBoldId} 0 R >> >> /MediaBox [0 0 ${this.pageWidth} ${this.pageHeight}] /Contents ${contentIds[p]} 0 R >>`, - ), - ); - } - - const catalogId = addObj(`<< /Type /Catalog /Pages ${pagesId} 0 R >>`); - - chunkById[pagesId] = chunkById[pagesId].replace( - pagesKidsToken, - pageIds.map((id) => `${id} 0 R`).join(" "), - ); - - const body = chunkById.join(""); - const bodyBuf = Buffer.from(body, "utf8"); - const xrefAt = bodyBuf.length; - const xref: string[] = [ - `xref\n0 ${offsets.length}\n0000000000 65535 f \n`, - ]; - for (let i = 1; i < offsets.length; i++) { - xref.push(`${String(offsets[i]).padStart(10, "0")} 00000 n \n`); - } - const trailer = `trailer\n<< /Size ${offsets.length} /Root ${catalogId} 0 R >>\nstartxref\n${xrefAt}\n%%EOF\n`; - return Buffer.concat([bodyBuf, Buffer.from(xref.join("") + trailer, "utf8")]); - } -} - -/** PDF literal string for Helvetica (WinAnsi) — Latin text only. */ -function encodePdfText(input: string): string { - const text = input.normalize("NFC"); - const safe = [...text] - .map((ch) => { - const code = ch.charCodeAt(0); - if (code >= 0x20 && code <= 0x7e) return ch; - if (ch === "—" || ch === "–") return "-"; - if (/\s/.test(ch)) return " "; - return ""; - }) - .join("") - .replace(/\s+/g, " ") - .trim(); - return `(${safe - .replace(/\\/g, "\\\\") - .replace(/\(/g, "\\(") - .replace(/\)/g, "\\)")})`; -} diff --git a/src/lookups/entities/db-service/lookup.db.service.ts b/src/lookups/entities/db-service/lookup.db.service.ts index 3b5e80c..46803c7 100644 --- a/src/lookups/entities/db-service/lookup.db.service.ts +++ b/src/lookups/entities/db-service/lookup.db.service.ts @@ -10,13 +10,7 @@ export class LookupDbService { private readonly lookupModel: Model, ) {} - async create(lookupData: Partial): Promise { - return await this.lookupModel.create(lookupData); - } - - async findOne( - filter: FilterQuery, - ): Promise { + async findOne(filter: FilterQuery): Promise { return await this.lookupModel.findOne(filter).lean(); } @@ -29,9 +23,4 @@ export class LookupDbService { upsert: true, }); } - - async findById(id: string): Promise { - return await this.lookupModel.findById(id).lean(); - } } - diff --git a/src/media-policy/media-policy.service.ts b/src/media-policy/media-policy.service.ts index 6198e37..e0b4563 100644 --- a/src/media-policy/media-policy.service.ts +++ b/src/media-policy/media-policy.service.ts @@ -1,18 +1,14 @@ -import { - BadRequestException, - Injectable, - Logger, -} from "@nestjs/common"; +import { BadRequestException, Injectable, Logger } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; -import { promises as fs } from "node:fs"; import { Model, Types } from "mongoose"; +import { promises as fs } from "node:fs"; +import { ClaimCase } from "src/claim-request-management/entites/schema/claim-cases.schema"; import { ClientService, MediaKind, MediaLimits, } from "src/client/client.service"; -import { ClaimCase } from "src/claim-request-management/entites/schema/claim-cases.schema"; import { BlameRequest } from "src/request-management/entities/schema/blame-cases.schema"; /** @@ -102,23 +98,6 @@ export class MediaPolicyService { await this.assertManyWithClient(provided, clientId, fieldKindMap); } - /** - * Same as `assertForBlameMany` but for claim files. Use this when (and - * if) a multi-field claim upload endpoint is added; today's claim - * controllers only upload one file at a time. - */ - async assertForClaimMany( - files: Partial>, - claimRequestId: string, - fieldKindMap: Record, - ): Promise { - const provided = this.flattenProvidedFiles(files); - if (provided.length === 0) return; - - const clientId = await this.resolveClaimClientId(claimRequestId); - await this.assertManyWithClient(provided, clientId, fieldKindMap); - } - // -- internal helpers --------------------------------------------------- private async assertWithClient( @@ -211,7 +190,8 @@ export class MediaPolicyService { private flattenProvidedFiles( files: Partial>, ): Array<{ field: TKeys; file: NonNullable }> { - const out: Array<{ field: TKeys; file: NonNullable }> = []; + const out: Array<{ field: TKeys; file: NonNullable }> = + []; if (!files) return out; for (const key of Object.keys(files) as TKeys[]) { for (const f of files[key] || []) { @@ -230,7 +210,9 @@ export class MediaPolicyService { .findById(blameRequestId) .select("parties") .lean() - .exec()) as { parties?: Array<{ person?: { clientId?: Types.ObjectId } }> } | null; + .exec()) as { + parties?: Array<{ person?: { clientId?: Types.ObjectId } }>; + } | null; if (!blame?.parties?.length) return null; for (const party of blame.parties) { diff --git a/src/plates/interface/plate.interface.ts b/src/plates/interface/plate.interface.ts deleted file mode 100644 index f50ef87..0000000 --- a/src/plates/interface/plate.interface.ts +++ /dev/null @@ -1,8 +0,0 @@ -export interface PlateType { - nationalCodeOfInsurer: string; - userId: string; - leftDigits: number; - centerAlphabet: string; - centerDigits: number; - ir: number; -} diff --git a/src/plates/plates.service.ts b/src/plates/plates.service.ts index e41695a..61c00a1 100644 --- a/src/plates/plates.service.ts +++ b/src/plates/plates.service.ts @@ -19,7 +19,9 @@ export class PlatesService { async addPlate(currentUser, body: AddPlateDto) { const { plate, nationalCodeOfInsurer } = body; - const normalizedAlphabet = this.plateNormalizer.normalizePlateText(String(plate.centerAlphabet || "")); + const normalizedAlphabet = this.plateNormalizer.normalizePlateText( + String(plate.centerAlphabet || ""), + ); const duplicate = await this.plateDbService.findOne({ userId: currentUser, leftDigits: plate.leftDigits, @@ -45,28 +47,6 @@ export class PlatesService { }; } - private async checkUniquePlate(plate): Promise { - const { - userId, - leftDigits, - centerAlphabet, - centerDigits, - ir, - nationalCodeOfInsurer, - } = plate; - - const found = await this.plateDbService.findOne({ - leftDigits, - centerAlphabet, - centerDigits, - userId, - nationalCodeOfInsurer, - ir, - }); - - return !found; - } - async deletePlate(id: Types.ObjectId) { const deleted = await this.plateDbService.findAndRemove(id); if (!deleted) throw new NotFoundException("Plate not found"); diff --git a/src/profile/dto/actor/profile.dto.ts b/src/profile/dto/actor/profile.dto.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/request-management/dto/claim-creation-hint.dto.ts b/src/request-management/dto/claim-creation-hint.dto.ts deleted file mode 100644 index 1b7ded5..0000000 --- a/src/request-management/dto/claim-creation-hint.dto.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { ApiProperty } from "@nestjs/swagger"; - -/** - * Computed on GET blame v2 for the current viewer — no DB field on BlameRequest. - */ -export class ClaimCreationHintDto { - @ApiProperty({ - description: - "True if a v2 claim case already exists for this blame (by blameRequestId).", - }) - hasClaim: boolean; - - @ApiProperty({ - description: - "True when this viewer is the damaged party, blame is COMPLETED, no claim exists yet, " + - "and for THIRD_PARTY all parties have signed and accepted the expert decision.", - }) - shouldGuideToCreateClaim: boolean; -} diff --git a/src/request-management/dto/expert-complete-car-body-form.dto.ts b/src/request-management/dto/expert-complete-car-body-form.dto.ts deleted file mode 100644 index a05bf36..0000000 --- a/src/request-management/dto/expert-complete-car-body-form.dto.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { ApiProperty } from "@nestjs/swagger"; -import { AddPlateDto } from "src/profile/dto/user/AddPlateDto"; -import { DescriptionDto } from "./create-request-management.dto"; -import { InitialFormDto, CarBodyFormDto } from "./create-request-management.dto"; - -/** - * Comprehensive form for experts to fill all information at once for IN_PERSON CAR_BODY files - */ -export class ExpertCompleteCarBodyFormDto { - // First Party Information - @ApiProperty({ - description: "First party phone number", - example: "09123456789", - }) - firstPartyPhoneNumber: string; - - @ApiProperty({ type: InitialFormDto }) - firstPartyInitialForm: InitialFormDto; - - @ApiProperty({ type: CarBodyFormDto }) - carBodyForm: CarBodyFormDto; - - @ApiProperty({ type: AddPlateDto }) - firstPartyPlate: AddPlateDto; - - @ApiProperty({ type: DescriptionDto }) - firstPartyDescription: DescriptionDto; -} - diff --git a/src/request-management/dto/expert-complete-locations.dto.ts b/src/request-management/dto/expert-complete-locations.dto.ts deleted file mode 100644 index 6dcd28c..0000000 --- a/src/request-management/dto/expert-complete-locations.dto.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; -import { LocationDto } from "./create-request-management.dto"; - -export class ExpertCompleteLocationsDto { - @ApiProperty({ type: LocationDto }) - firstPartyLocation: LocationDto; - - @ApiPropertyOptional({ type: LocationDto }) - secondPartyLocation?: LocationDto; -} - diff --git a/src/request-management/dto/expert-complete-third-party-form.dto.ts b/src/request-management/dto/expert-complete-third-party-form.dto.ts deleted file mode 100644 index 1c5ad02..0000000 --- a/src/request-management/dto/expert-complete-third-party-form.dto.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { ApiProperty } from "@nestjs/swagger"; -import { AddPlateDto } from "src/profile/dto/user/AddPlateDto"; -import { DescriptionDto } from "./create-request-management.dto"; -import { InitialFormDto } from "./create-request-management.dto"; - -/** - * Second party information for expert-completed THIRD_PARTY forms - */ -export class ExpertSecondPartyInfoDto { - @ApiProperty({ - description: "Second party phone number", - example: "09123456789", - }) - phoneNumber: string; - - @ApiProperty({ type: InitialFormDto }) - initialForm: InitialFormDto; - - @ApiProperty({ type: AddPlateDto }) - plate: AddPlateDto; - - @ApiProperty({ type: DescriptionDto }) - description: DescriptionDto; -} - -/** - * Comprehensive form for experts to fill all information at once for IN_PERSON THIRD_PARTY files - */ -export class ExpertCompleteThirdPartyFormDto { - // First Party Information - @ApiProperty({ - description: "First party phone number", - example: "09123456789", - }) - firstPartyPhoneNumber: string; - - @ApiProperty({ type: InitialFormDto }) - firstPartyInitialForm: InitialFormDto; - - @ApiProperty({ type: AddPlateDto }) - firstPartyPlate: AddPlateDto; - - @ApiProperty({ type: DescriptionDto }) - firstPartyDescription: DescriptionDto; - - // Second Party Information - @ApiProperty({ type: ExpertSecondPartyInfoDto }) - secondParty: ExpertSecondPartyInfoDto; - - // Guilty Party - @ApiProperty({ - description: "Phone number of the guilty party. Must match either first or second party phone number.", - example: "09123456789", - }) - guiltyPartyPhoneNumber: string; -} - diff --git a/src/request-management/dto/update-request-management.dto.ts b/src/request-management/dto/update-request-management.dto.ts deleted file mode 100644 index e69de29..0000000 diff --git a/src/request-management/dto/user-reply.dto.ts b/src/request-management/dto/user-reply.dto.ts deleted file mode 100644 index 250381e..0000000 --- a/src/request-management/dto/user-reply.dto.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { ApiProperty } from "@nestjs/swagger"; -import { RequestManagementModel } from "../entities/schema/request-management.schema"; - -export class UserReplyDto { - public _id: string; - - @ApiProperty({ required: true }) - isAccept: boolean; - - @ApiProperty({ required: true }) - signId: string; - - constructor(requestId: string) { - this._id = requestId; - } -} - -export class DetailsReplyDtoRs { - public fields: Object; - public actorFullName: string; - public description: string; - public dateOfReply: string; - public timeOfReply: string; - public isGuiltyUser: boolean; - public firstPartyAccept: boolean; - public secondPartyAccept: boolean; - public status: string; - public expertResendReply: any; - public expertSubmitReply: any; - public expertSubmitReplyFinal: any; - public theParties: any; - public type: string; - - constructor(request: RequestManagementModel, details: any) { - const finalReply = request.expertSubmitReply; - - this.fields = finalReply.fields; - this.description = finalReply.description; - this.firstPartyAccept = finalReply?.firstPartyComment?.isAccept; - this.secondPartyAccept = finalReply?.secondPartyComment?.isAccept; - this.actorFullName = details.actorDetail.CheckedRequest.fullName; - this.dateOfReply = details.actorDetail.Date.toLocaleDateString("fa-IR"); - this.timeOfReply = details.actorDetail.Date.toLocaleTimeString("fa-IR"); - this.isGuiltyUser = details.isGuilty; - this.status = request.blameStatus; - this.expertResendReply = request.expertResendReply; - this.expertSubmitReply = request.expertSubmitReply; - this.expertSubmitReplyFinal = request.expertSubmitReplyFinal; - this.theParties = details.theParties; - this.type = request.type || "THIRD_PARTY"; // Include type field - } -} diff --git a/src/request-management/entities/db-service/blame-document.db.service.ts b/src/request-management/entities/db-service/blame-document.db.service.ts index a156500..16a6315 100644 --- a/src/request-management/entities/db-service/blame-document.db.service.ts +++ b/src/request-management/entities/db-service/blame-document.db.service.ts @@ -1,7 +1,7 @@ -import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { FilterQuery, Model, UpdateQuery } from 'mongoose'; -import { BlameDocumentModel } from '../schema/blame-document.schema'; +import { Injectable } from "@nestjs/common"; +import { InjectModel } from "@nestjs/mongoose"; +import { Model } from "mongoose"; +import { BlameDocumentModel } from "../schema/blame-document.schema"; @Injectable() export class BlameDocumentDbService { @@ -10,27 +10,14 @@ export class BlameDocumentDbService { private readonly blameDocumentModel: Model, ) {} - async create(createDto: Partial): Promise { + async create( + createDto: Partial, + ): Promise { const newDocument = new this.blameDocumentModel(createDto); return newDocument.save(); } - async findOne(filter: FilterQuery): Promise { - return this.blameDocumentModel.findOne(filter).lean(); - } - - async findAll(filter: FilterQuery): Promise { - return this.blameDocumentModel.find(filter).lean(); - } - async findById(id: string): Promise { return this.blameDocumentModel.findById(id).lean(); } - - async findByIdAndUpdate( - id: string, - updateDto: UpdateQuery, - ): Promise { - return this.blameDocumentModel.findByIdAndUpdate(id, updateDto, { new: true }).lean(); - } -} \ No newline at end of file +} diff --git a/src/request-management/entities/db-service/blame-request.db.service.ts b/src/request-management/entities/db-service/blame-request.db.service.ts index c5de222..d9a4c50 100644 --- a/src/request-management/entities/db-service/blame-request.db.service.ts +++ b/src/request-management/entities/db-service/blame-request.db.service.ts @@ -17,12 +17,6 @@ export class BlameRequestDbService { return this.blameRequestModel.create(payload); } - async findOne( - filter: FilterQuery, - ): Promise { - return this.blameRequestModel.findOne(filter); - } - async findById( id: string | Types.ObjectId, ): Promise { diff --git a/src/request-management/entities/db-service/blame-video.db.service.ts b/src/request-management/entities/db-service/blame-video.db.service.ts index 09cbac2..936ed1a 100644 --- a/src/request-management/entities/db-service/blame-video.db.service.ts +++ b/src/request-management/entities/db-service/blame-video.db.service.ts @@ -16,10 +16,6 @@ export class BlameVideoDbService { return await this.blameVideoModel.findOne(new Types.ObjectId(id)); } - async findOneByRequestId(id: string): Promise { - return await this.blameVideoModel.findById(id); - } - async findById(id: string): Promise { return this.blameVideoModel.findById(id).lean(); } diff --git a/src/request-management/entities/db-service/request-management.db.service.ts b/src/request-management/entities/db-service/request-management.db.service.ts index 07f6c0c..b2b095b 100644 --- a/src/request-management/entities/db-service/request-management.db.service.ts +++ b/src/request-management/entities/db-service/request-management.db.service.ts @@ -8,12 +8,6 @@ export class RequestManagementDbService { private readonly requestModel: Model, ) {} - async create( - request: RequestManagementModel, - ): Promise { - return await this.requestModel.create(request); - } - async findOne(id: string) { return await this.requestModel.findOne(new Types.ObjectId(id)); } @@ -22,21 +16,6 @@ export class RequestManagementDbService { return await this.requestModel.find({ ...filter }); } - async findAllAndPagination(query, currentPage, resPerPage?) { - const responsePerPage = resPerPage | 1; - const skipPge = responsePerPage * (Number(currentPage) - 1); - return await this.requestModel - .find(query) - .limit(responsePerPage) - .skip(skipPge); - } - - async countByFilter( - filter: FilterQuery, - ): Promise { - return await this.requestModel.countDocuments(filter); - } - async findAndUpdate( filter: FilterQuery, update: UpdateQuery, @@ -83,12 +62,4 @@ export class RequestManagementDbService { update, ); } - - async aggregate(filter?) { - return await this.requestModel.aggregate(filter); - } - - async updateMany(filter?, update?) { - return await this.requestModel.updateMany(filter, update); - } } diff --git a/src/request-management/entities/db-service/sign.db.service.ts b/src/request-management/entities/db-service/sign.db.service.ts index e1e19c7..1149353 100644 --- a/src/request-management/entities/db-service/sign.db.service.ts +++ b/src/request-management/entities/db-service/sign.db.service.ts @@ -1,5 +1,5 @@ import { InjectModel } from "@nestjs/mongoose"; -import { Model, Types } from "mongoose"; +import { Model } from "mongoose"; import { UserSignModel } from "../schema/sign.schema"; export class UserSignDbService { @@ -12,10 +12,6 @@ export class UserSignDbService { return await this.blameVoiceModel.create(sign); } - async findOne(id: string): Promise { - return await this.blameVoiceModel.findOne(new Types.ObjectId(id)); - } - async findById(id: string): Promise { // Use your correct Model type return this.blameVoiceModel.findById(id).lean(); diff --git a/src/request-management/expert-initiated.controller.ts b/src/request-management/expert-initiated.controller.ts index 8a1f353..6974baf 100644 --- a/src/request-management/expert-initiated.controller.ts +++ b/src/request-management/expert-initiated.controller.ts @@ -1,44 +1,15 @@ -import { extname } from "node:path"; -import { - Controller, - Post, - Body, - Param, - UseGuards, - Get, - UseInterceptors, - UploadedFile, -} from "@nestjs/common"; -import { - FileInterceptor, -} from "@nestjs/platform-express"; -import { diskStorage } from "multer"; -import { - ApiBearerAuth, - ApiBody, - ApiParam, - ApiTags, - ApiOperation, - ApiResponse, - ApiConsumes, - ApiExcludeController, -} from "@nestjs/swagger"; +import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common"; +import { ApiBearerAuth, ApiExcludeController } from "@nestjs/swagger"; import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; import { RolesGuard } from "src/auth/guards/role.guard"; -import { CurrentUser } from "src/decorators/user.decorator"; + import { Roles } from "src/decorators/roles.decorator"; +import { CurrentUser } from "src/decorators/user.decorator"; import { RoleEnum } from "src/Types&Enums/role.enum"; -import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service"; -import { RequestManagementService } from "./request-management.service"; -import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto"; -import { ExpertCompleteThirdPartyFormDto } from "./dto/expert-complete-third-party-form.dto"; -import { ExpertCompleteCarBodyFormDto } from "./dto/expert-complete-car-body-form.dto"; import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto"; -import { ExpertCompleteClaimDataDto } from "./dto/expert-complete-claim-data.dto"; -import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; +import { RequestManagementService } from "./request-management.service"; @ApiExcludeController() -// @ApiTags("expert-initiated-blame") @Controller("expert-initiated-blame") @ApiBearerAuth() @UseGuards(LocalActorAuthGuard, RolesGuard) @@ -46,239 +17,9 @@ import { ClaimRequestManagementService } from "src/claim-request-management/clai export class ExpertInitiatedController { constructor( private readonly requestManagementService: RequestManagementService, - private readonly claimRequestManagementService: ClaimRequestManagementService, ) {} - // @ApiOperation({ deprecated: true }) - @Get("my-files") - // @ApiOperation({ - // summary: "List my expert-initiated files", - // description: - // "Returns all blame files created by the current field expert (their panel).", - // }) - // @ApiResponse({ status: 200, description: "List of expert-initiated files" }) - async getMyFiles(@CurrentUser() expert: any) { - return await this.requestManagementService.getMyExpertInitiatedFiles(expert); - } - - // @ApiOperation({ deprecated: true }) - @Post("complete-blame-data/:requestId") - // @ApiParam({ name: "requestId", description: "ID of the expert-initiated file" }) - // @ApiBody({ - // description: - // "Send ExpertCompleteThirdPartyFormDto for THIRD_PARTY files or ExpertCompleteCarBodyFormDto for CAR_BODY files (according to file type).", - // }) - // @ApiResponse({ status: 200, description: "Blame form completed successfully" }) - async completeBlameData( - @CurrentUser() expert: any, - @Param("requestId") requestId: string, - @Body() formData: any, - ) { - return await this.requestManagementService.completeBlameData( - expert, - requestId, - formData, - ); - } - - // @ApiOperation({ deprecated: true }) - @Post("complete-claim-data/:claimRequestId") - // @ApiOperation({ - // summary: "Submit claim-needed data", - // description: - // "Field expert fills claim data for expert-initiated IN_PERSON files (car part damage, sheba, national code, other parts). " + - // "Only the initiating expert can call this.", - // }) - // @ApiParam({ - // name: "claimRequestId", - // description: "ID of the claim file (created from the expert-initiated blame file)", - // }) - // @ApiBody({ type: ExpertCompleteClaimDataDto }) - // @ApiResponse({ status: 200, description: "Claim data updated successfully" }) - async completeClaimData( - @CurrentUser() expert: any, - @Param("claimRequestId") claimRequestId: string, - @Body() dto: ExpertCompleteClaimDataDto, - ) { - return await this.claimRequestManagementService.expertCompleteClaimData( - claimRequestId, - expert, - dto, - ); - } - - // @ApiOperation({ deprecated: true }) - // @Post("create") - // @ApiOperation({ - // summary: "Create expert-initiated blame file", - // description: - // "Expert creates an initial incomplete blame file. Can be IN_PERSON (expert fills all info) or LINK (expert sends link to users).", - // }) - // @ApiBody({ type: CreateExpertInitiatedFileDto }) - // @ApiResponse({ - // status: 201, - // description: "File created successfully", - // schema: { - // type: "object", - // properties: { - // requestId: { type: "string" }, - // }, - // }, - // }) - // async createExpertInitiatedFile( - // @CurrentUser() expert: any, - // @Body() dto: CreateExpertInitiatedFileDto, - // ) { - // return await this.requestManagementService.createExpertInitiatedFile( - // expert, - // dto, - // ); - // } - - // @ApiOperation({ deprecated: true }) - @Post("complete-form-third-party/:requestId") - // @ApiParam({ name: "requestId" }) - // @ApiBody({ type: ExpertCompleteThirdPartyFormDto }) - // @ApiResponse({ status: 200, description: "Form completed successfully. File is now ready for user signatures." }) - async completeThirdPartyForm( - @CurrentUser() expert: any, - @Param("requestId") requestId: string, - @Body() formData: ExpertCompleteThirdPartyFormDto, - ) { - return await this.requestManagementService.expertCompleteThirdPartyForm( - expert, - requestId, - formData, - ); - } - - // @ApiOperation({ deprecated: true }) - @Post("complete-form-car-body/:requestId") - // @ApiOperation({ - // summary: "Expert completes all information for IN_PERSON CAR_BODY file", - // description: - // "Expert fills all information at once for IN_PERSON CAR_BODY files. " + - // "Includes first party data and carBodyForm. " + - // "Video and voice uploads are handled separately.", - // }) - async completeCarBodyForm( - @CurrentUser() expert: any, - @Param("requestId") requestId: string, - @Body() formData: ExpertCompleteCarBodyFormDto, - ) { - return await this.requestManagementService.expertCompleteCarBodyForm( - expert, - requestId, - formData, - ); - } - - // @ApiOperation({ deprecated: true }) - @Post("upload-video/:requestId") - // @ApiParam({ name: "requestId" }) - // @ApiConsumes("multipart/form-data") - // @ApiBody({ - // schema: { - // type: "object", - // properties: { file: { type: "string", format: "binary" } }, - // }, - // }) - @UseInterceptors( - FileInterceptor("file", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/video", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `expert-${file.originalname}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - // @ApiResponse({ - // status: 200, - // description: "Video uploaded successfully", - // }) - async uploadVideo( - @CurrentUser() expert: any, - @Param("requestId") requestId: string, - @UploadedFile() file?: Express.Multer.File, - ) { - return await this.requestManagementService.expertUploadVideo( - expert, - requestId, - file, - ); - } - - // @ApiOperation({ deprecated: true }) - @Post("upload-voice/:requestId") - // @ApiOperation({ - // summary: "Expert uploads voice for expert-initiated file", - // description: - // "Expert uploads a single voice file for the entire blame file. " + - // "Only one voice is needed per file (not per party). " + - // "Only works for expert-initiated files.", - // }) - // @ApiParam({ name: "requestId" }) - // @ApiConsumes("multipart/form-data") - // @ApiBody({ - // schema: { - // type: "object", - // properties: { - // voice: { - // type: "string", - // format: "binary", - // }, - // }, - // }, - // }) - @UseInterceptors( - FileInterceptor("voice", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/voice", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const flname = file.originalname.split(".")[0]; - const filename = `expert-${flname}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - // @ApiResponse({ status: 200, description: "Voice uploaded successfully" }) - async uploadVoice( - @CurrentUser() expert: any, - @Param("requestId") requestId: string, - @UploadedFile() voice?: Express.Multer.File, - ) { - return await this.requestManagementService.expertUploadVoice( - expert, - requestId, - voice, - ); - } - - // @ApiOperation({ deprecated: true }) @Post("add-accident-fields/:requestId") - // @ApiOperation({ - // summary: "Expert adds accident fields to expert-initiated file", - // description: - // "Expert adds accident way, reason, and type fields to an expert-initiated file. " + - // "Can be used for both IN_PERSON and LINK-based files. " + - // "If expertSubmitReply already exists, updates the fields. Otherwise, creates a new expertSubmitReply.", - // }) - // @ApiParam({ name: "requestId" }) - // @ApiBody({ type: ExpertAccidentFieldsDto }) - // @ApiResponse({ status: 200, description: "Accident fields added successfully" }) async addAccidentFields( @CurrentUser() expert: any, @Param("requestId") requestId: string, @@ -291,4 +32,3 @@ export class ExpertInitiatedController { ); } } - diff --git a/src/request-management/file-maker-claim-approval-v5.controller.ts b/src/request-management/file-maker-claim-approval-v5.controller.ts index e14aea3..0ee1a32 100644 --- a/src/request-management/file-maker-claim-approval-v5.controller.ts +++ b/src/request-management/file-maker-claim-approval-v5.controller.ts @@ -1,10 +1,4 @@ -import { - Body, - Controller, - Param, - Post, - UseGuards, -} from "@nestjs/common"; +import { Body, Controller, Param, Post, UseGuards } from "@nestjs/common"; import { ApiBearerAuth, ApiBody, @@ -21,12 +15,12 @@ import { Roles } from "src/decorators/roles.decorator"; import { CurrentUser } from "src/decorators/user.decorator"; import { RoleEnum } from "src/Types&Enums/role.enum"; import { RequestManagementService } from "./request-management.service"; -import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; class FileMakerRejectDto { @ApiPropertyOptional({ description: "Reason for rejection (visible to FileReviewer)", - example: "Damage assessment is incorrect — please re-evaluate parts X and Y", + example: + "Damage assessment is incorrect — please re-evaluate parts X and Y", }) @IsOptional() @IsString() @@ -57,7 +51,6 @@ class FileMakerRejectDto { export class FileMakerClaimApprovalV5Controller { constructor( private readonly requestManagementService: RequestManagementService, - private readonly claimRequestManagementService: ClaimRequestManagementService, ) {} @Post("approve/:claimRequestId") diff --git a/src/request-management/file-maker-claim-approval-v5.spec.ts b/src/request-management/file-maker-claim-approval-v5.spec.ts index e8089a4..09388d6 100644 --- a/src/request-management/file-maker-claim-approval-v5.spec.ts +++ b/src/request-management/file-maker-claim-approval-v5.spec.ts @@ -17,23 +17,11 @@ describe("RequestManagementService V5 FileMaker approval", () => { }), findByIdAndUpdate: jest.fn().mockResolvedValue({}), }; - const service = new (RequestManagementService as any)( - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - claimCaseDbService, + const service = Object.assign( + Object.create(RequestManagementService.prototype), + { + claimCaseDbService, + }, ) as RequestManagementService; const result = await service.fileMakerApproveV5( diff --git a/src/request-management/registrar-initiated.controller.ts b/src/request-management/registrar-initiated.controller.ts deleted file mode 100644 index e171f42..0000000 --- a/src/request-management/registrar-initiated.controller.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { extname } from "node:path"; -import { Body, Controller, Get, Param, Post, UploadedFile, UseGuards, UseInterceptors } from "@nestjs/common"; -import { FileInterceptor } from "@nestjs/platform-express"; -import { diskStorage } from "multer"; -import { ApiBearerAuth, ApiBody, ApiConsumes, ApiOperation, ApiParam, ApiTags, ApiExcludeController } from "@nestjs/swagger"; -import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; -import { RolesGuard } from "src/auth/guards/role.guard"; -import { CurrentUser } from "src/decorators/user.decorator"; -import { Roles } from "src/decorators/roles.decorator"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service"; -import { RequestManagementService } from "./request-management.service"; -import { CreateRegistrarInitiatedFileDto } from "./dto/registrar-initiated.dto"; -import { SendPartyOtpsDto } from "./dto/send-party-otps.dto"; -import { VerifyPartyOtpsDto } from "./dto/verify-party-otps.dto"; -import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto"; -import { PartyRole } from "./entities/schema/partyRole.enum"; - -@ApiExcludeController() -// @ApiTags("registrar-initiated-blame (v1)") -@Controller("registrar-initiated-blame") -@ApiBearerAuth() -@UseGuards(LocalActorAuthGuard, RolesGuard) -@Roles(RoleEnum.REGISTRAR) -export class RegistrarInitiatedController { - constructor(private readonly requestManagementService: RequestManagementService) {} - - @Post("create") -// @ApiOperation({ summary: "Registrar creates IN_PERSON blame file" }) -// @ApiBody({ type: CreateRegistrarInitiatedFileDto }) - create(@CurrentUser() registrar: any, @Body() dto: CreateRegistrarInitiatedFileDto) { - return this.requestManagementService.createRegistrarInitiatedBlame(registrar, dto); - } - - @Get("my-files") - myFiles(@CurrentUser() registrar: any) { - return this.requestManagementService.getMyExpertInitiatedFilesV2(registrar); - } - - @Get("blame/:requestId") - getBlame(@Param("requestId") requestId: string, @CurrentUser() registrar: any) { - return this.requestManagementService.getBlameRequestV2(requestId, registrar); - } - - @Post("send-party-otps/:requestId") -// @ApiParam({ name: "requestId" }) -// @ApiBody({ type: SendPartyOtpsDto }) - sendPartyOtps( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @Body() dto: SendPartyOtpsDto, - ) { - return this.requestManagementService.sendPartyOtpsV2(registrar, requestId, dto); - } - - @Post("verify-party-otps/:requestId") -// @ApiParam({ name: "requestId" }) -// @ApiBody({ type: VerifyPartyOtpsDto }) - verifyPartyOtps( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @Body() dto: VerifyPartyOtpsDto, - ) { - return this.requestManagementService.verifyPartyOtpsV2(registrar, requestId, dto); - } - - @Post("complete-blame-data/:requestId") - completeBlameData( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @Body() body: any, - ) { - return this.requestManagementService.expertCompleteBlameDataV2(registrar, requestId, body); - } - - @Post("upload-video/:requestId") -// @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("file", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/video", - filename: (req, file, cb) => cb(null, `registrar-${Date.now()}${extname(file.originalname)}`), - }), - }), - ) - uploadVideo( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @UploadedFile() file?: Express.Multer.File, - ) { - return this.requestManagementService.expertUploadVideoForBlameV2(registrar, requestId, file); - } - - @Post("upload-voice/:requestId") -// @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("voice", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/voice", - filename: (req, file, cb) => cb(null, `registrar-${Date.now()}${extname(file.originalname)}`), - }), - }), - ) - uploadVoice( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @UploadedFile() voice?: Express.Multer.File, - ) { - return this.requestManagementService.expertUploadVoiceForBlameV2(registrar, requestId, voice); - } - - @Post("add-accident-fields/:requestId") -// @ApiBody({ type: ExpertAccidentFieldsDto }) - addAccidentFields( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @Body() fields: ExpertAccidentFieldsDto, - ) { - return this.requestManagementService.expertAddAccidentFieldsForBlameV2( - registrar, - requestId, - fields, - ); - } - - @Post("upload-party-signature/:requestId") -// @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("sign", { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/signs", - filename: (req, file, cb) => cb(null, `registrar-party-${Date.now()}${extname(file.originalname)}`), - }), - }), - ) - uploadPartySignature( - @CurrentUser() registrar: any, - @Param("requestId") requestId: string, - @Body() body: { partyRole?: string; isAccept?: boolean | string }, - @UploadedFile() sign?: Express.Multer.File, - ) { - const role = - body.partyRole === "SECOND" ? PartyRole.SECOND : PartyRole.FIRST; - const isAccept = !(body.isAccept === false || body.isAccept === "false"); - return this.requestManagementService.expertUploadPartySignatureV2( - registrar, - requestId, - role, - isAccept, - sign!, - ); - } -} - diff --git a/src/request-management/request-management.controller.ts b/src/request-management/request-management.controller.ts deleted file mode 100644 index f2cc350..0000000 --- a/src/request-management/request-management.controller.ts +++ /dev/null @@ -1,417 +0,0 @@ -import { extname } from "node:path"; -import { - Controller, - Get, - Post, - Body, - Param, - UseGuards, - UseInterceptors, - UploadedFile, - Req, - Put, - UploadedFiles, -} from "@nestjs/common"; -import { - FileFieldsInterceptor, - FileInterceptor, -} from "@nestjs/platform-express"; -import { - ApiBearerAuth, - ApiBody, - ApiConsumes, - ApiParam, - ApiTags, - ApiOperation, - ApiExcludeController, -} from "@nestjs/swagger"; -import { Request } from "express"; -import { diskStorage } from "multer"; -import { GlobalGuard } from "src/auth/guards/global.guard"; -import { RolesGuard } from "src/auth/guards/role.guard"; -import { CurrentUser } from "src/decorators/user.decorator"; -import { Roles } from "src/decorators/roles.decorator"; -import { AddPlateDto } from "src/profile/dto/user/AddPlateDto"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { DEFAULT_MEDIA_MAX_BYTES } from "src/client/client.service"; -import { BlameDocumentType } from "./entities/schema/blame-document.schema"; -import { - CarBodyFormDto, - CarBodySecondForm, - DescriptionDto, - InitialFormDto, - LocationDto, -} from "./dto/create-request-management.dto"; -import { RequestManagementService } from "./request-management.service"; - -@ApiExcludeController() -@Controller("blame-request-management") -// @ApiTags("blame-request-management") -@ApiBearerAuth() -@UseGuards(GlobalGuard, RolesGuard) -@Roles(RoleEnum.USER) -export class RequestManagementController { - constructor( - private readonly requestManagementService: RequestManagementService, - ) {} - - // @ApiOperation({ deprecated: true }) - // @Post() - // @UseGuards(GlobalGuard) - // async createRequest( - // @CurrentUser() user, - // @Body() createRequestDto: CreateRequestDto, - // ) { - // return await this.requestManagementService.createRequest( - // user, - // createRequestDto.type, - // ); - // } - - @ApiOperation({ deprecated: true }) - @Post("/initial-form/:requestId") - @ApiParam({ name: "requestId" }) - @ApiBody({ type: InitialFormDto }) - @UseGuards(GlobalGuard) - async initialFrom( - @Body() - body: InitialFormDto, - @CurrentUser() user, - @Param("requestId") requestId, - ) { - return await this.requestManagementService.initialFormStep( - body, - user, - requestId, - ); - } - - @ApiBody({ - schema: { - type: "object", - properties: { - file: { - type: "string", - format: "binary", - }, - }, - }, - }) - @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("file", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/video", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `${file.originalname}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - @UseGuards(GlobalGuard) - @ApiParam({ name: "requestId" }) - @ApiOperation({ deprecated: true }) - @Post("upload-video/:requestId") - @UseGuards(GlobalGuard) - async videoUploader( - @Param("requestId") requestId, - @CurrentUser() user, - @UploadedFile() file?: Express.Multer.File, - ) { - return await this.requestManagementService.videoUploadStep( - file, - user, - requestId, - ); - } - - @ApiOperation({ deprecated: true }) - @Post("/add-plate/:requestId") - @ApiParam({ name: "requestId" }) - @ApiBody({ type: AddPlateDto }) - @UseGuards(GlobalGuard) - async addPlate( - @Body() - body: AddPlateDto, - @CurrentUser() user, - @Param("requestId") requestId, - ) { - return await this.requestManagementService.addPlateToRequest( - user, - body, - requestId, - ); - } - - @ApiOperation({ deprecated: true }) - @Post("/carbody-form/:requestId") - @ApiParam({ name: "requestId" }) - @ApiBody({ type: CarBodyFormDto }) - @UseGuards(GlobalGuard) - async carBodyForm( - @Body() - body: CarBodyFormDto, - @CurrentUser() user, - @Param("requestId") requestId, - ) { - return await this.requestManagementService.carBodyFormStep( - body, - user, - requestId, - ); - } - - @ApiOperation({ deprecated: true }) - @Post("/carbody-secondform/:requestId") - @ApiParam({ name: "requestId" }) - @ApiBody({ type: CarBodySecondForm }) - @UseGuards(GlobalGuard) - async carBodySecondForm( - @Body() - body: CarBodySecondForm, - @CurrentUser() user, - @Param("requestId") requestId, - ) { - return await this.requestManagementService.carBodySecondForm( - body, - user, - requestId, - ); - } - - @ApiOperation({ deprecated: true }) - @Post("/add-detail-location/:requestId") - @ApiParam({ name: "requestId" }) - @ApiBody({ type: LocationDto }) - @UseGuards(GlobalGuard) - async addLocation( - @Body() - body: LocationDto, - @CurrentUser() user, - @Param("requestId") requestId, - ) { - return await this.requestManagementService.addDetailToRequestLocation( - user.sub, - body, - requestId, - user, // Pass user object for expert verification - ); - } - - @ApiBody({ - schema: { - type: "object", - properties: { - file: { - type: "string", - format: "binary", - }, - }, - }, - }) - @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("file", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/voice", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const flname = file.originalname.split(".")[0]; - const filename = `${flname}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - @ApiParam({ name: "requestId" }) - @ApiOperation({ deprecated: true }) - @Post("upload-voice/:requestId") - @UseGuards(GlobalGuard) - async voiceUploader( - @Param("requestId") requestId, - @CurrentUser() user, - @UploadedFile() voice?: Express.Multer.File, - ) { - return await this.requestManagementService.voiceUploadStep( - user, - voice, - requestId, - ); - } - - @ApiOperation({ deprecated: true }) - @Post("/add-detail-description/:requestId") - @ApiParam({ name: "requestId" }) - @ApiBody({ type: DescriptionDto }) - @UseGuards(GlobalGuard) - async addDescription( - @Body() - body: DescriptionDto, - @Param("requestId") requestId, - @CurrentUser() user, - ) { - return await this.requestManagementService.addDescriptionToRequest( - user, - body, - requestId, - ); - } - - @ApiOperation({ deprecated: true }) - @Post("add-second-party-details/:phoneNumber/:requestId/:frontendRoutes") - @ApiParam({ name: "phoneNumber" }) - @ApiParam({ name: "requestId" }) - @ApiParam({ name: "frontendRoutes" }) - @UseGuards(GlobalGuard) - async addSecondPartyDetailsToRequest( - @Req() req: Request, - @Param("phoneNumber") phoneNumber, - @Param("requestId") requestId, - @Param("frontendRoutes") frontendRoutes, - @CurrentUser() firstPartyUser, - ) { - return await this.requestManagementService.addSecondPartyDetailsToRequest( - phoneNumber, - requestId, - firstPartyUser, - frontendRoutes, - req, - ); - } - - @ApiOperation({ deprecated: true }) - @Get("requests") - async requests(@CurrentUser() user) { - return await this.requestManagementService.myRequests(user.username); - } - - @ApiOperation({ deprecated: true }) - @Get("creatable-claims") - @UseGuards(GlobalGuard) - async getCreatableClaims(@CurrentUser() user) { - return await this.requestManagementService.getCreatableClaims(user); - } - - @ApiOperation({ deprecated: true }) - @Get("request/:requestId") - @ApiParam({ name: "requestId" }) - @Roles(RoleEnum.USER) - async checkParties(@CurrentUser() user, @Param("requestId") requestId) { - return await this.requestManagementService.requestDetails(user, requestId); - } - - @ApiBody({ - schema: { - type: "object", - properties: { - sign: { - type: "string", - format: "binary", - }, - isAccept: { - type: "Boolean", - }, - }, - }, - }) - @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileInterceptor("sign", { - limits: { - fileSize: DEFAULT_MEDIA_MAX_BYTES, - }, - storage: diskStorage({ - destination: "./files/signs", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `${file.originalname.split(/[.,\s-]/)[0]}-${unique}${ex}`; - callback(null, filename); - }, - }), - }), - ) - @ApiOperation({ deprecated: true }) - @Put("request/reply/:requestId") - @ApiParam({ name: "requestId" }) - @UseGuards(GlobalGuard) - async userReply( - @Body("isAccept") isAccept: boolean, - @Param("requestId") requestId: string, - @CurrentUser() user, - @UploadedFile() sign?: Express.Multer.File, - ) { - const props = { requestId, user }; - return await this.requestManagementService.userReply( - props, - Boolean(isAccept), - sign, - ); - } - - @ApiBody({ - schema: { - type: "object", - properties: { - nationalCertificate: { type: "string", format: "binary" }, - carCertificate: { type: "string", format: "binary" }, - drivingLicense: { type: "string", format: "binary" }, - carGreenCard: { type: "string", format: "binary" }, - voice: { type: "string", format: "binary" }, - description: { type: "string" }, - }, - }, - }) - @ApiConsumes("multipart/form-data") - @UseInterceptors( - FileFieldsInterceptor( - [ - { name: "nationalCertificate", maxCount: 1 }, - { name: "carCertificate", maxCount: 1 }, - { name: "drivingLicense", maxCount: 1 }, - { name: "carGreenCard", maxCount: 1 }, - { name: "voice", maxCount: 1 }, - ], - { - limits: { fileSize: DEFAULT_MEDIA_MAX_BYTES }, - storage: diskStorage({ - destination: "./files/blame-resend-docs", - filename: (req, file, callback) => { - const unique = Date.now(); - const ex = extname(file.originalname); - const filename = `${file.fieldname}-${unique}${ex}`; - callback(null, filename); - }, - }), - }, - ), - ) - @UseGuards(GlobalGuard) - @ApiParam({ name: "requestId" }) - @ApiOperation({ deprecated: true }) - @Put("request/resend/:requestId") - userResendReply( - @Body("description") description: string, - @Param("requestId") requestId: string, - @CurrentUser() user: any, - @UploadedFiles() - files: { [key in BlameDocumentType | "voice"]?: Express.Multer.File[] }, - ) { - return this.requestManagementService.userResend( - files, - user, - requestId, - description, - ); - } -} diff --git a/src/request-management/request-management.file-reviewer.spec.ts b/src/request-management/request-management.file-reviewer.spec.ts index 8424e82..754d1af 100644 --- a/src/request-management/request-management.file-reviewer.spec.ts +++ b/src/request-management/request-management.file-reviewer.spec.ts @@ -39,7 +39,9 @@ describe("RequestManagementService FileReviewer inbox", () => { find: jest.fn().mockResolvedValue([]), }; (service as any).fanavaranLocationService = { - assertMakerReviewerBranchCompatible: jest.fn().mockResolvedValue(undefined), + assertMakerReviewerBranchCompatible: jest + .fn() + .mockResolvedValue(undefined), }; return { service, blameRequestDbService }; } @@ -94,10 +96,11 @@ describe("RequestManagementService FileReviewer inbox", () => { it("does not list an open file from another branch", async () => { const { service } = createService([sealedFile]); - (service as any).fanavaranLocationService - .assertMakerReviewerBranchCompatible.mockRejectedValue( - new Error("This file belongs to another branch."), - ); + ( + service as any + ).fanavaranLocationService.assertMakerReviewerBranchCompatible.mockRejectedValue( + new Error("This file belongs to another branch."), + ); const result = await service.getMyFileReviewerFiles({ sub: String(reviewerId), @@ -137,10 +140,12 @@ describe("RequestManagementService FileReviewer inbox", () => { it("does not expose an open file's details to a reviewer from another tenant", async () => { const { service } = createService([]); - (service as any).blameRequestDbService.findById = jest.fn().mockResolvedValue({ - ...sealedFile, - parties: [{ role: "FIRST", person: { clientId: otherClientId } }], - }); + (service as any).blameRequestDbService.findById = jest + .fn() + .mockResolvedValue({ + ...sealedFile, + parties: [{ role: "FIRST", person: { clientId: otherClientId } }], + }); await expect( service.getMyFileReviewerFileDetail( @@ -225,16 +230,11 @@ describe("RequestManagementService FileReviewer inbox", () => { }), findOneAndUpdate: jest.fn(), }; - const expertClaimService = new (ExpertClaimService as any)( - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - undefined, - blameRequestDbService, + const expertClaimService = Object.assign( + Object.create(ExpertClaimService.prototype), + { + blameRequestDbService, + }, ) as ExpertClaimService; await expect( diff --git a/src/request-management/request-management.module.ts b/src/request-management/request-management.module.ts index 80db63f..99683c9 100644 --- a/src/request-management/request-management.module.ts +++ b/src/request-management/request-management.module.ts @@ -31,19 +31,23 @@ import { BlameVoiceSchema, BlameVoicesModel, } from "./entities/schema/blame-voice.schema"; -import { BlameDocumentModel, BlameDocumentSchema } from "./entities/schema/blame-document.schema"; -import { BlameRequest, BlameRequestSchema } from "./entities/schema/blame-cases.schema"; +import { + BlameDocumentModel, + BlameDocumentSchema, +} from "./entities/schema/blame-document.schema"; +import { + BlameRequest, + BlameRequestSchema, +} from "./entities/schema/blame-cases.schema"; import { RequestManagementModel, RequestManagementSchema, } from "./entities/schema/request-management.schema"; import { RequestManagementService } from "./request-management.service"; -import { RequestManagementController } from "./request-management.controller"; import { RequestManagementV2Controller } from "./request-management.v2.controller"; import { ExpertInitiatedController } from "./expert-initiated.controller"; import { ExpertInitiatedV2Controller } from "./expert-initiated.v2.controller"; import { ExpertInitiatedBlameMirrorController } from "./expert-initiated-blame.mirror.controller"; -import { RegistrarInitiatedController } from "./registrar-initiated.controller"; import { RegistrarBlameMirrorController } from "./registrar-blame.mirror.controller"; import { ExpertInitiatedBlameV3MirrorController } from "./expert-initiated-blame-v3.mirror.controller"; import { FileMakerBlameV4Controller } from "./file-maker-blame-v4.controller"; @@ -85,13 +89,11 @@ import { CallCenterBlameV6Controller } from "./call-center-blame-v6.controller"; MediaPolicyModule, ], controllers: [ - RequestManagementController, RequestManagementV2Controller, ExpertInitiatedController, ExpertInitiatedV2Controller, ExpertInitiatedBlameMirrorController, ExpertInitiatedBlameV3MirrorController, - RegistrarInitiatedController, RegistrarBlameMirrorController, FileMakerBlameV4Controller, FileReviewerBlameV4Controller, diff --git a/src/request-management/request-management.service.ts b/src/request-management/request-management.service.ts index db59559..637164d 100644 --- a/src/request-management/request-management.service.ts +++ b/src/request-management/request-management.service.ts @@ -1,5 +1,4 @@ import { - BadGatewayException, BadRequestException, ConflictException, ForbiddenException, @@ -10,28 +9,11 @@ import { Logger, NotFoundException, } from "@nestjs/common"; -import { ExternalExceptionFilter } from "@nestjs/core/exceptions/external-exception-filter"; import { Types } from "mongoose"; -import { ClientService } from "src/client/client.service"; -import { LookupsService } from "src/lookups/lookups.service"; -import { selectedDrivingLicenceType } from "src/lookups/driving-licence-types"; -import { AddPlateDto } from "src/profile/dto/user/AddPlateDto"; -import { VehicleRegistrationState } from "src/common/dto/inquiry-participants.dto"; -import { - CarBodyFormDto, - CarBodySecondForm, - InitialFormDto, - InitialFormVinDto, -} from "src/request-management/dto/create-request-management.dto"; -import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service"; -import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service"; -import { RequestManagementDbService } from "src/request-management/entities/db-service/request-management.db.service"; -import { - UserResendResponseDto, - UserResendUploadResponseDto, -} from "./dto/user-resend.dto"; -import { UserSignatureResponseDto } from "./dto/user-signature.dto"; -import { ResendItemType } from "src/Types&Enums/blame-request-management/resendItemType.enum"; +import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; +import { BlameStatus } from "src/Types&Enums/blame-request-management/blameStatus.enum"; +import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; +import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; import { buildResendItemsWithUi, cloneResendUploadedDocuments, @@ -39,119 +21,127 @@ import { normalizeResendRequestedItemKey, normalizeResendRequestedItemsList, } from "src/Types&Enums/blame-request-management/resend-item-ui"; -import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; +import { ResendItemType } from "src/Types&Enums/blame-request-management/resendItemType.enum"; + import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; -import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum"; import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; -import { resolveClaimOwnerFieldsFromBlame } from "src/helpers/blame-damaged-party"; -import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto"; +import { ClaimStatus } from "src/Types&Enums/claim-request-management/claimStatus.enum"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { UserAuthService } from "src/auth/auth-services/user.auth.service"; +import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; +import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service"; +import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references"; +import { ClientService } from "src/client/client.service"; +import { VehicleRegistrationState } from "src/common/dto/inquiry-participants.dto"; +import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; +import { getInquiryErrorMessage } from "src/common/utils/inquiry-error"; import { - RunInquiriesV3Dto, - RunInquiriesVinV3Dto, -} from "./dto/run-inquiries-v3.dto"; -import { SandHubService } from "src/sand-hub/sand-hub.service"; -import { ReqBlameStatus } from "src/Types&Enums/blame-request-management/status.enum"; -import { StepsEnum } from "src/Types&Enums/blame-request-management/steps.enum"; -import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; -import { UserDbService } from "src/users/entities/db-service/user.db.service"; -import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service"; + BusinessErrorCode, + BusinessRuleException, +} from "src/expert-claim/exceptions/business-rule.exception"; import { assertFileMakerCanCreateBlameType, assertFileReviewerCanReviewBlameType, } from "src/fanavaran/fanavaran-file-role-expert-ids"; -import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; -import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; -import { isOtpExpiryActive } from "src/helpers/user-otp-expiry"; -import { parseIranLocalDateTime } from "src/helpers/iran-datetime"; -import { jalaliToGregorianDate } from "src/helpers/date-jalali"; +import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service"; import { - applyListQueryV2, - isInListDateRange, - parseListDateRange, -} from "src/helpers/list-query-v2"; -import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; -import { GetUserBlameListV2ResponseDto } from "src/request-management/dto/blame-list-user-v2.dto"; -import { resolveUnifiedFileStatus } from "src/helpers/unified-file-status"; -import { resolveBlameUserNextAction } from "src/helpers/blame-user-progress"; -import { toPublicListItems } from "src/helpers/public-list-response"; -import { AutoCloseRequestService } from "src/utils/cron/cron.service"; -import { SmsOrchestrationService } from "src/sms-orchestration/sms-orchestration.service"; -import { - DescriptionDto, - DescriptionV4Dto, - LocationDto, - RequestManagementDtoRs, -} from "./dto/create-request-management.dto"; -import { DetailsReplyDtoRs, UserReplyDto } from "./dto/user-reply.dto"; -import { BlameDocumentDbService } from "./entities/db-service/blame-document.db.service"; -import { UserSignDbService } from "./entities/db-service/sign.db.service"; -import { RequestManagementModel } from "./entities/schema/request-management.schema"; -import { BlameDocumentType } from "./entities/schema/blame-document.schema"; -import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service"; -import { ClaimRequestManagementDbService } from "src/claim-request-management/entites/db-service/claim-request-management.db.service"; -import { - CreationMethod, - FilledBy, - FileHistoryEvent, - ExpertLinkInfo, -} from "./entities/schema/request-management.schema"; -import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { PublicIdService } from "src/utils/public-id/public-id.service"; -import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; -import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; -import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; -import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; -import { WorkflowStepDbService } from "src/workflow-step-management/entities/db-service/workflow-step.db.service"; -import { WorkflowStepModel } from "src/workflow-step-management/entities/schema/workflow-step.schema"; -import { BlameStatus } from "src/Types&Enums/blame-request-management/blameStatus.enum"; -import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum"; -import { - BusinessRuleException, - BusinessErrorCode, -} from "src/expert-claim/exceptions/business-rule.exception"; -import { ExpertFileActivityDbService } from "src/users/entities/db-service/expert-file-activity.db.service"; -import { - ExpertFileActivityType, - ExpertFileKind, -} from "src/users/entities/schema/expert-file-activity.schema"; -import { UploadContext } from "./entities/schema/blame-voice.schema"; -import { HashService } from "src/utils/hash/hash.service"; -import { UserAuthService } from "src/auth/auth-services/user.auth.service"; + canUserCreateClaim, + resolveClaimBeneficiary, +} from "src/helpers/blame-claim-eligibility"; +import { resolveClaimOwnerFieldsFromBlame } from "src/helpers/blame-damaged-party"; import { buildMutualAgreementExpertDecision, MUTUAL_AGREEMENT_EXPERT_DECISION_FIELDS, } from "src/helpers/blame-party-agreement-decision"; -import { buildFileLink } from "src/helpers/urlCreator"; +import { resolveBlameUserNextAction } from "src/helpers/blame-user-progress"; +import { jalaliToGregorianDate } from "src/helpers/date-jalali"; +import { parseIranLocalDateTime } from "src/helpers/iran-datetime"; import { buildUserLookupByPhone, iranMobileLookupVariants, normalizeIranMobile, partyPersonMatchesUser, } from "src/helpers/iran-mobile"; +import { + applyListQueryV2, + isInListDateRange, + parseListDateRange, +} from "src/helpers/list-query-v2"; import { buildBlamePartyAccessOrConditions, collectUserIdVariants, } from "src/helpers/party-access-queries"; +import { toPublicListItems } from "src/helpers/public-list-response"; import { blameCaseTouchesClient, requireActorClientKey, } from "src/helpers/tenant-scope"; +import { resolveUnifiedFileStatus } from "src/helpers/unified-file-status"; +import { buildFileLink } from "src/helpers/urlCreator"; import { resolveLinkedUserIdStrings } from "src/helpers/user-access-resolver"; +import { isOtpExpiryActive } from "src/helpers/user-otp-expiry"; +import { selectedDrivingLicenceType } from "src/lookups/driving-licence-types"; +import { LookupsService } from "src/lookups/lookups.service"; +import { AddPlateDto } from "src/profile/dto/user/AddPlateDto"; +import { GetUserBlameListV2ResponseDto } from "src/request-management/dto/blame-list-user-v2.dto"; +import { + CarBodyFormDto, + InitialFormVinDto, +} from "src/request-management/dto/create-request-management.dto"; +import { BlameRequestDbService } from "src/request-management/entities/db-service/blame-request.db.service"; +import { BlameVideoDbService } from "src/request-management/entities/db-service/blame-video.db.service"; +import { BlameVoiceDbService } from "src/request-management/entities/db-service/blame.voice.db.service"; +import { RequestManagementDbService } from "src/request-management/entities/db-service/request-management.db.service"; +import { PartyRole } from "src/request-management/entities/schema/partyRole.enum"; + +import { SandHubService } from "src/sand-hub/sand-hub.service"; +import { SmsOrchestrationService } from "src/sms-orchestration/sms-orchestration.service"; + +import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; +import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; +import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; +import { UserDbService } from "src/users/entities/db-service/user.db.service"; + +import { HashService } from "src/utils/hash/hash.service"; import { normalizePlateText } from "src/utils/plate-normalizer/plate-normalizer.service"; -import { fanavaranClaimReferences } from "src/claim-request-management/fanavaran-claim-references"; +import { PublicIdService } from "src/utils/public-id/public-id.service"; +import { WorkflowStepDbService } from "src/workflow-step-management/entities/db-service/workflow-step.db.service"; +import { WorkflowStepModel } from "src/workflow-step-management/entities/schema/workflow-step.schema"; +import { + DescriptionDto, + DescriptionV4Dto, + LocationDto, +} from "./dto/create-request-management.dto"; +import { ExpertAccidentFieldsDto } from "./dto/expert-accident-fields.dto"; +import { CreateExpertInitiatedFileDto } from "./dto/expert-initiated.dto"; +import { + RunInquiriesV3Dto, + RunInquiriesVinV3Dto, +} from "./dto/run-inquiries-v3.dto"; +import { + UserResendResponseDto, + UserResendUploadResponseDto, +} from "./dto/user-resend.dto"; +import { UserSignatureResponseDto } from "./dto/user-signature.dto"; +import { BlameDocumentDbService } from "./entities/db-service/blame-document.db.service"; +import { UserSignDbService } from "./entities/db-service/sign.db.service"; +import { BlameDocumentType } from "./entities/schema/blame-document.schema"; +import { UploadContext } from "./entities/schema/blame-voice.schema"; +import { + CreationMethod, + FileHistoryEvent, + FilledBy, + RequestManagementModel, +} from "./entities/schema/request-management.schema"; import { - isMappedPolicyCurrent, InquirySubjects, + isMappedPolicyCurrent, NormalizedInquirySubmission, normalizeInquirySubmission, resolveInquirySubjects, runCurrentPlateInquiry, sanitizeStoredInquiryParticipants, } from "./inquiry-participant-resolver"; -import { - getInquiryErrorMessage, -} from "src/common/utils/inquiry-error"; function mappedInquiryErrorMessage(value: any): string | undefined { const message = value?.mapped?.Error?.Message; @@ -669,43 +659,6 @@ export class RequestManagementService { } } - /** Inquiry bundle for the still-routable legacy RequestManagement model. */ - private async collectLegacyParticipantInquiries( - submission: NormalizedInquirySubmission>, - ): Promise | undefined> { - if (submission.participants.legacy) return undefined; - - const personal: Record = {}; - for (const participant of submission.participants.participants) { - personal[participant.participantId] = - await this.sandHubService.getPersonalInquiry( - participant.nationalCode, - participant.birthday, - ); - } - - const plate = submission.vehicle?.currentPlate ?? submission.dto.plate; - const ownership = - submission.vehicleOwner && plate - ? await this.sandHubService.getCarOwnershipInfo( - plate, - submission.vehicleOwner.nationalCode, - ) - : undefined; - const drivingLicence = - submission.driver.hasDrivingLicense === false - ? { - skipped: true, - reason: "Driver declared no driving licence", - } - : await this.sandHubService.getDrivingLicenseInfo( - submission.driver.nationalCode, - submission.driver.licenseNumber!, - ); - - return { personal, ownership, drivingLicence }; - } - private async persistBlameInquiryAudit(req: any): Promise { if (!req?._id || !req.inquiries) return; try { @@ -722,40 +675,6 @@ export class RequestManagementService { } } - private async persistLegacyInquiryAudit( - requestId: string, - partyDetails: "firstPartyDetails" | "secondPartyDetails", - submission: NormalizedInquirySubmission>, - audit: Record, - ): Promise { - if (submission.participants.legacy) return; - const prefix = partyDetails; - try { - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - $set: { - [`${prefix}.participants`]: submission.participants.participants, - [`${prefix}.participantRoles`]: submission.participants.roles, - [`${prefix}.registrationState`]: - submission.vehicle?.registrationState, - [`${prefix}.previousPlateId`]: submission.vehicle?.previousPlate - ? this.plateToPlateIdString(submission.vehicle.previousPlate) - : undefined, - [`${prefix}.previousPolicyholderNationalCode`]: - submission.vehicle?.previousPolicyholderNationalCode, - [`${prefix}.vehicleVin`]: submission.vehicle?.vin, - [`${prefix}.policyInquiry`]: audit, - }, - }, - ); - } catch (error: any) { - this.logger.error( - `Failed to persist legacy inquiry audit for request ${requestId}: ${error?.message || error}`, - ); - } - } - private getPartyIndex(req: any, role: PartyRole): number { return Array.isArray(req.parties) ? req.parties.findIndex((p) => p?.role === role) @@ -1161,14 +1080,13 @@ export class RequestManagementService { private readonly blameVideoDbService: BlameVideoDbService, private readonly userDbService: UserDbService, private readonly sandHubService: SandHubService, - private readonly sandHubDbService: SandHubDbService, + private readonly clientService: ClientService, private readonly blameVoiceDbService: BlameVoiceDbService, private readonly userSign: UserSignDbService, private readonly smsOrchestrationService: SmsOrchestrationService, private readonly expertDbService: ExpertDbService, - private readonly expertFileActivityDbService: ExpertFileActivityDbService, - private readonly autoCloseRequestService: AutoCloseRequestService, + private readonly claimRequestManagementDbService: ClaimRequestManagementDbService, private readonly claimCaseDbService: ClaimCaseDbService, private readonly publicIdService: PublicIdService, @@ -1276,7 +1194,7 @@ export class RequestManagementService { time?: string, ): Date | null { const normalizedDate = - typeof date === "string" ? jalaliToGregorianDate(date) ?? date : date; + typeof date === "string" ? (jalaliToGregorianDate(date) ?? date) : date; return parseIranLocalDateTime(normalizedDate, time); } @@ -1869,10 +1787,7 @@ export class RequestManagementService { : undefined; } - const inquirySubmission = this.normalizeInquiryInput( - req.type, - body, - ); + const inquirySubmission = this.normalizeInquiryInput(req.type, body); await this.validateDrivingLicenceType(inquirySubmission); body = inquirySubmission.dto as unknown as AddPlateDto; this.applyInquiryParticipantsToParty(party, inquirySubmission); @@ -1935,19 +1850,13 @@ export class RequestManagementService { this.logger.log( `[TEJARAT] block inquiry mapped for request=${req._id}: ${JSON.stringify(inquiryMapped)}`, ); - this.recordPartyCaseInquiryStatus( - req, - "thirdParty", - role, - true, - { - source: inquirySource, - plateKind: inquiry.plateKind, - attempts: inquiry.attempts, - raw: inquiryRaw, - mapped: inquiryMapped, - }, - ); + this.recordPartyCaseInquiryStatus(req, "thirdParty", role, true, { + source: inquirySource, + plateKind: inquiry.plateKind, + attempts: inquiry.attempts, + raw: inquiryRaw, + mapped: inquiryMapped, + }); if (inquiry.offline?.fanavaranDriverId != null) { if (!party.person) party.person = {} as any; party.person.fanavaranDriverId = inquiry.offline.fanavaranDriverId; @@ -2317,10 +2226,7 @@ export class RequestManagementService { : undefined; } - const inquirySubmission = this.normalizeInquiryInput( - req.type, - body, - ); + const inquirySubmission = this.normalizeInquiryInput(req.type, body); await this.validateDrivingLicenceType(inquirySubmission); body = inquirySubmission.dto as unknown as InitialFormVinDto; const subjects = resolveInquirySubjects(inquirySubmission); @@ -2377,17 +2283,11 @@ export class RequestManagementService { this.logger.log( `[ESG] carByChassis mapped for request=${req._id}: ${JSON.stringify(inquiryMapped)}`, ); - this.recordPartyCaseInquiryStatus( - req, - "thirdParty", - role, - true, - { - source: "ESG_VIN_INQUIRY", - raw: inquiryRaw, - mapped: inquiryMapped, - }, - ); + this.recordPartyCaseInquiryStatus(req, "thirdParty", role, true, { + source: "ESG_VIN_INQUIRY", + raw: inquiryRaw, + mapped: inquiryMapped, + }); } catch (err: any) { this.logger.error( `[ESG] carByChassis failed for request=${req._id}: ${err?.message || err}`, @@ -3376,2045 +3276,6 @@ export class RequestManagementService { }; } - // async createRequest(user, type) { - // const reqNumber = new ShortUniqueId({ counter: 1 }); - // const publicId = await this.publicIdService.generateRequestPublicId(); - // const createRequest = await this.requestManagementDbService.create({ - // firstPartyDetails: { - // firstPartyId: user.sub, - // firstPartyPhoneNumber: user.username, - // firstPartyCertificate: null, - // }, - // currentStep: StepsEnum.createRequest, - // nextStep: - // type === "THIRD_PARTY" - // ? StepsEnum.F_InitialForm - // : StepsEnum.CarBodyForm, - // requestNumber: reqNumber.rnd(), - // publicId, - // blameStatus: ReqBlameStatus.PendingForFirstParty, - // lockFile: false, - // type, - // }); - // return { requestId: createRequest["_id"] }; - // } - - async initialFormStep( - reqBody: InitialFormDto, - user, - requestId, - ): Promise { - const foundRequest = - await this.requestManagementDbService.findOne(requestId); - - if (!foundRequest) { - throw new NotFoundException("Request not found"); - } - - // For LINK-based expert-initiated files, verify user is the correct party - if ( - foundRequest.expertInitiated && - foundRequest.creationMethod === CreationMethod.LINK - ) { - // User should already be set in firstPartyDetails or secondPartyDetails - const isFirstParty = - foundRequest.firstPartyDetails?.firstPartyId?.toString() === user.sub || - foundRequest.firstPartyDetails?.firstPartyPhoneNumber === user.username; - const isSecondParty = - foundRequest.secondPartyDetails?.secondPartyId?.toString() === - user.sub || - foundRequest.secondPartyDetails?.secondPartyPhoneNumber === - user.username; - - if (!isFirstParty && !isSecondParty) { - throw new ForbiddenException( - "You are not authorized to complete this file. This file was created by an expert for specific parties.", - ); - } - } - - if ( - foundRequest?.secondPartyDetails?.secondPartyPhoneNumber == user.username - ) { - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - "secondPartyDetails.secondPartyId": user.sub, - blameStatus: ReqBlameStatus.PendingForSecondParty, - "secondPartyDetails.secondPartyInitialForm": reqBody, - currentStep: StepsEnum.S_InitialForm, - nextStep: StepsEnum.S_addPlate, - $push: { steps: StepsEnum.S_InitialForm }, - }, - ); - - // Add history for expert-initiated files - if (foundRequest.expertInitiated) { - await this.addHistoryEvent( - requestId, - "SECOND_PARTY_FORM_COMPLETED", - new Types.ObjectId(user.sub), - undefined, - foundRequest.filledBy === FilledBy.EXPERT ? "expert" : "customer", - ); - } - - return new RequestManagementDtoRs( - foundRequest.firstPartyDetails.firstPartyId, - user.sub, - StepsEnum.S_InitialForm, - StepsEnum.S_addPlate, - StepsEnum.S_addPlate, - requestId, - ); - } else if ( - foundRequest?.firstPartyDetails?.firstPartyPhoneNumber == user.username || - (foundRequest.expertInitiated && - foundRequest.creationMethod === CreationMethod.LINK && - foundRequest.firstPartyDetails?.firstPartyId?.toString() === user.sub) - ) { - // Normal flow or link-based - set full firstPartyDetails - const updatePayload: any = { - blameStatus: ReqBlameStatus.PendingForFirstParty, - firstPartyDetails: { - firstPartyId: user.sub, - firstPartyPhoneNumber: user.username, - firstPartyInitialForm: reqBody, - }, - currentStep: StepsEnum.F_InitialForm, - nextStep: StepsEnum.F_videoUpload, - $push: { steps: StepsEnum.F_InitialForm }, - }; - - // For link-based expert-initiated files, ensure filledBy is set - if ( - foundRequest.expertInitiated && - foundRequest.creationMethod === CreationMethod.LINK - ) { - updatePayload.$set = { filledBy: FilledBy.CUSTOMER }; - } - - const createRequestFile = - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - // Add history for expert-initiated link-based files - if ( - foundRequest.expertInitiated && - foundRequest.creationMethod === CreationMethod.LINK - ) { - await this.addHistoryEvent( - requestId, - "FIRST_PARTY_FORM_COMPLETED", - new Types.ObjectId(user.sub), - undefined, - "customer", - ); - } - - return new RequestManagementDtoRs( - createRequestFile.firstPartyDetails.firstPartyId, - null, - StepsEnum.F_InitialForm, - StepsEnum.F_videoUpload, - "Add video", - createRequestFile._id, - ); - } else { - // If none of the conditions match, throw an error - throw new ForbiddenException( - "You are not authorized to complete this form. Please ensure you are the correct party or using a valid link.", - ); - } - } - - async videoUploadStep( - file, - user, - requestId, - ): Promise { - const request = await this.requestManagementDbService.findOne(requestId); - - if (!request) { - throw new NotFoundException("Request not found"); - } - - // Check phone number match for normal flow - if (request?.firstPartyDetails?.firstPartyPhoneNumber !== user.username) { - throw new ForbiddenException("the request doesnt belong you"); - } - - try { - if ( - request.steps.includes(StepsEnum.F_videoUpload) || - request.steps.includes(StepsEnum.CarBodyVideo) - ) - throw new BadRequestException("video steps has exist"); - - const videoDocument = await this.blameVideoDbService.create({ - fileName: file.filename, - path: file.path, - requestId, - }); - - // Determine the step to push and next step based on request type - const stepToPush = - request.type === "THIRD_PARTY" - ? StepsEnum.F_videoUpload - : StepsEnum.CarBodyVideo; - const currentStepValue = - request.type === "THIRD_PARTY" - ? StepsEnum.F_videoUpload - : StepsEnum.CarBodyVideo; - const nextStepValue = StepsEnum.F_addPlate; - - const updated = await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - $push: { steps: stepToPush }, - currentStep: currentStepValue, - "firstPartyDetails.firstPartyFile.firstPartyVideoId": - videoDocument["_doc"]._id, - nextStep: nextStepValue, - }, - ); - - if (updated == undefined) return new BadGatewayException("update failed"); - - return new RequestManagementDtoRs( - user.sub, - null, - currentStepValue, - nextStepValue, - "please add plate", - requestId, - ); - } catch (err) { - return new HttpException(err.message, err.status); - } - } - - async addPlate( - sandHubReport: any, - request: any, - user: any, - body: AddPlateDto, - partyType: "firstParty" | "secondParty", - inquirySubmission?: NormalizedInquirySubmission>, - policyInquiry?: Record, - participantInquiries?: Record, - ) { - if (request.type === "THIRD_PARTY" && partyType === "firstParty") { - this.sandHubService.assertInsuranceMatchesDeployment( - sandHubReport, - "THIRD_PARTY", - ); - } - - const clientName = sandHubReport?.CompanyName; - const companyCode = sandHubReport?.CompanyCode; - - const client = clientName - ? await this.clientService.findOrCreateClientByCompanyCode( - companyCode, - clientName, - ) - : null; - - if (!client) { - throw new HttpException( - "شرکت بیمه موجود در پاسخ استعلام قابل شناسایی نیست.", - HttpStatus.CONFLICT, - ); - } - - const partyDetails = - partyType === "firstParty" ? "firstPartyDetails" : "secondPartyDetails"; - const stepsEnum = - partyType === "firstParty" ? StepsEnum.F_addPlate : StepsEnum.S_addPlate; - const currentStep = - partyType === "firstParty" ? StepsEnum.F_addPlate : StepsEnum.S_addPlate; - - // Determine next step based on request type - let nextStep: StepsEnum; - if (request.type === "CAR_BODY") { - // For CAR_BODY, after plate always go to location - // (Form and video were already completed before plate) - nextStep = StepsEnum.F_addLocation; - } else { - // THIRD_PARTY or default flow - nextStep = - partyType === "firstParty" - ? StepsEnum.F_addLocation - : StepsEnum.S_addLocation; - } - - try { - if (client) { - await this.userDbService.findOneAndUpdate( - { _id: user.sub }, - { clientKey: (client as any)["_doc"]?._id ?? (client as any)._id }, - ); - } - - const sandHubDocData = { - ...sandHubReport, - plate: body.plate, - nationalCode: body.nationalCodeOfInsurer, - }; - const sandHubDoc = await this.sandHubService.sandHubDocumentCreator( - user.sub, - request["_doc"]._id, - sandHubDocData, - ); - - if (partyType === "firstParty" && sandHubDoc) { - await this.requestManagementDbService.findAndUpdate( - { _id: request._id }, - { - sanHubId: sandHubDoc["_doc"]._id, - }, - ); - } - - // Build $set object with all field updates - const setFields: any = { - currentStep: currentStep, - nextStep: nextStep, - [`${partyDetails}.nationalCodeOfInsurer`]: body.nationalCodeOfInsurer, - [`${partyDetails}.${partyType}Plate`]: body.plate, - [`${partyDetails}.${partyType}CarDetail.carName`]: - sandHubReport.MapTypNam, - [`${partyDetails}.${partyType}CarDetail.insurerBirthday`]: - body.insurerBirthday, - [`${partyDetails}.${partyType}CarDetail.driverBirthday`]: - body.driverBirthday, - [`${partyDetails}.${partyType}CarDetail.carType`]: `${sandHubReport.UsageField} / ${sandHubReport.MapUsageName || "-"}`, - [`${partyDetails}.${partyType}CarDetail.isNewCar`]: body.isNewCar, - [`${partyDetails}.${partyType}Certificate`]: body.userNoCertificate, - [`${partyDetails}.${partyType}InsuranceDetail.insuranceId`]: - sandHubReport.LastCompanyDocumentNumber, - [`${partyDetails}.${partyType}InsuranceDetail.insuranceCompany`]: - clientName, - [`${partyDetails}.${partyType}InsuranceDetail.financialCommitmentCeiling`]: - sandHubReport.FinancialCvrCptl, - [`${partyDetails}.${partyType}InsuranceDetail.startDate`]: - sandHubReport.IssueDate, - [`${partyDetails}.${partyType}InsuranceDetail.endDate`]: - sandHubReport.EndDate, - }; - - if (client) { - setFields[`${partyDetails}.${partyType}Client.clientId`] = - (client as any)["_doc"]?._id ?? (client as any)._id; - setFields[`${partyDetails}.${partyType}Client.clientName`] = clientName; - } - if (inquirySubmission && !inquirySubmission.participants.legacy) { - setFields[`${partyDetails}.participants`] = - inquirySubmission.participants.participants; - setFields[`${partyDetails}.participantRoles`] = - inquirySubmission.participants.roles; - setFields[`${partyDetails}.participantInquiries`] = - participantInquiries ?? {}; - setFields[`${partyDetails}.policyInquiry`] = policyInquiry ?? {}; - setFields[`${partyDetails}.registrationState`] = - inquirySubmission.vehicle?.registrationState; - setFields[`${partyDetails}.previousPlateId`] = inquirySubmission.vehicle - ?.previousPlate - ? this.plateToPlateIdString(inquirySubmission.vehicle.previousPlate) - : undefined; - setFields[`${partyDetails}.previousPolicyholderNationalCode`] = - inquirySubmission.vehicle?.previousPolicyholderNationalCode; - setFields[`${partyDetails}.vehicleVin`] = - inquirySubmission.vehicle?.vin; - } - - // For CAR_BODY type, persist the provider response and its mapped fields. - if (request.type === "CAR_BODY" && partyType === "firstParty") { - const carBodyInquiry = - inquirySubmission && !inquirySubmission.participants.legacy - ? await this.getCarBodyPlateInquiry(inquirySubmission) - : await this.sandHubService.getCarBodyInquiry({ - nationalCodeOfInsurer: body.nationalCodeOfInsurer, - plate: body.plate, - } as any); - const carBodyInfo = carBodyInquiry.mapped as any; - - this.logger.log( - `[CAR_BODY] Saving car body insurance data to blame file ${request._id}:`, - JSON.stringify(carBodyInfo, null, 2), - ); - - // Add car body insurance fields to $set - setFields[ - "firstPartyDetails.firstPartyCarBodyInsuranceDetail.policyNumber" - ] = carBodyInfo.policyNumber; - setFields[ - "firstPartyDetails.firstPartyCarBodyInsuranceDetail.startDate" - ] = carBodyInfo.startDate; - setFields[ - "firstPartyDetails.firstPartyCarBodyInsuranceDetail.endDate" - ] = carBodyInfo.endDate; - setFields[ - "firstPartyDetails.firstPartyCarBodyInsuranceDetail.insurerCompany" - ] = carBodyInfo.insurerCompany; - setFields[ - "firstPartyDetails.firstPartyCarBodyInsuranceDetail.coverages" - ] = carBodyInfo.coverages; - setFields["firstPartyDetails.firstPartyCarBodyInsuranceDetail.raw"] = - carBodyInquiry.raw; - setFields["firstPartyDetails.firstPartyCarBodyInsuranceDetail.source"] = - carBodyInquiry.source; - if (inquirySubmission && !inquirySubmission.participants.legacy) { - setFields[`${partyDetails}.policyInquiry`] = { - thirdParty: policyInquiry, - carBody: { - source: carBodyInquiry.source, - plateKind: carBodyInquiry.plateKind, - attempts: carBodyInquiry.attempts, - raw: carBodyInquiry.raw, - mapped: carBodyInquiry.mapped, - }, - }; - } - setFields[`${partyDetails}.${partyType}Client.clientId`] = - await this.resolveCarBodyPolicyClientId(carBodyInfo); - } - - // Build final update payload with proper MongoDB operators - const updatePayload: any = { - $push: { steps: stepsEnum }, - $set: setFields, - }; - - await this.requestManagementDbService.findAndUpdate( - { _id: request._id }, - updatePayload, - ); - } catch (er) { - this.logger.error(er); - if (er instanceof HttpException) throw er; - throw new InternalServerErrorException( - "ذخیره اطلاعات پلاک و بیمه‌نامه انجام نشد.", - ); - } - - const nextStepMessage = `Please add location - clientName is ${clientName}`; - - return new RequestManagementDtoRs( - request?.firstPartyDetails?.firstPartyId, - request?.secondPartyDetails?.secondPartyId || null, - stepsEnum, - nextStep, - nextStepMessage, - request._id, - ); - } - - async addPlateToRequest(user: any, body: AddPlateDto, requestId: string) { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - if ( - (body.nationalCodeOfInsurer === body.nationalCodeOfDriver || - body.insurerLicense === body.driverLicense) && - body.driverIsInsurer === false - ) { - throw new BadRequestException( - "در این حالت، بیمه‌گذار و راننده باید دو شخص متفاوت باشند.", - ); - } - - // Determine if the current user is the first party - // Check if nextStep is firstParty-addPlate OR if user is the first party phone number - const isFirstParty = - (request.nextStep === StepsEnum.F_addPlate || - request.currentStep === StepsEnum.F_addPlate) && - request.firstPartyDetails.firstPartyPhoneNumber === user.username; - const partyRole = isFirstParty ? PartyRole.FIRST : PartyRole.SECOND; - const inquirySubmission = this.normalizeInquiryInput( - request.type as BlameRequestType, - body, - ); - await this.validateDrivingLicenceType(inquirySubmission); - body = inquirySubmission.dto as unknown as AddPlateDto; - - if (!isFirstParty) { - const firstPartyDetails = request.firstPartyDetails as any; - if ( - firstPartyDetails?.firstPartyPlate || - firstPartyDetails?.nationalCodeOfInsurer - ) { - const isSameNationalCode = - firstPartyDetails.nationalCodeOfInsurer === - body.nationalCodeOfInsurer; - - const isSamePlate = - JSON.stringify(firstPartyDetails.firstPartyPlate) === - JSON.stringify(body.plate); - - if (isSameNationalCode || isSamePlate) { - throw new ConflictException( - "پلاک و کد ملی طرف دوم نمی‌تواند با طرف اول یکسان باشد.", - ); - } - } - } - - // TODO: Activate - // --- Proceed with existing logic if the check passes --- - // 1) Main third-party/block inquiry (existing behavior) - const legacyPartyPath = isFirstParty - ? "firstPartyDetails" - : "secondPartyDetails"; - let policyInquiry: any; - try { - policyInquiry = inquirySubmission.participants.legacy - ? await (async () => { - const response = await this.sandHubService.getSandHubResponse({ - plate: body.plate, - nationalCodeOfInsurer: body.nationalCodeOfInsurer, - }); - return { - raw: response, - mapped: response["_doc"] || response, - plateKind: "CURRENT", - attempts: [ - { plateKind: "CURRENT", succeeded: true, usable: true }, - ], - }; - })() - : await this.getThirdPartyPlateInquiry(inquirySubmission); - await this.persistLegacyInquiryAudit( - requestId, - legacyPartyPath, - inquirySubmission, - policyInquiry, - ); - } catch (error: any) { - await this.persistLegacyInquiryAudit( - requestId, - legacyPartyPath, - inquirySubmission, - { - failed: true, - attempts: error?.attempts ?? [], - error: this.normalizeInquiryError(error), - }, - ); - throw error; - } - const sanHubResponse = policyInquiry.mapped; - let participantInquiries: Record | undefined; - try { - participantInquiries = - await this.collectLegacyParticipantInquiries(inquirySubmission); - } catch (error: any) { - await this.persistLegacyInquiryAudit( - requestId, - legacyPartyPath, - inquirySubmission, - { - ...policyInquiry, - participantInquiryFailure: this.normalizeInquiryError(error), - }, - ); - throw error; - } - - // if (sanHubResponse.Error) { - // throw new HttpException( - // sanHubResponse.Error.Message, - // HttpStatus.BAD_REQUEST, - // ); - // } - - // 2) Personal inquiry (new shared SandHub API) - // This is a best-effort call; if it fails we log and continue. - // try { - // const personalInquiry = await this.sandHubService.getPersonalInquiry( - // body.nationalCodeOfInsurer, - // body.insurerBirthday, - // ); - // this.logger.log( - // `[SANDHUB] Personal inquiry succeeded for nationalCode=${body.nationalCodeOfInsurer}: ${JSON.stringify( - // personalInquiry, - // )}`, - // ); - // // NOTE: We are not persisting this data yet; once the exact fields - // // are finalized, we can map and store them on the request document. - // } catch (err) { - // this.logger.error( - // `[SANDHUB] Personal inquiry failed for nationalCode=${body.nationalCodeOfInsurer}: ${err?.message || err}`, - // ); - // } - - return await this.addPlate( - sanHubResponse, - request, - user, - body, - isFirstParty ? "firstParty" : "secondParty", - inquirySubmission, - policyInquiry, - participantInquiries, - ); - } - - async carBodyFormStep( - reqBody: CarBodyFormDto, - user, - requestId, - ): Promise { - const foundRequest = - await this.requestManagementDbService.findOne(requestId); - - if (!foundRequest) { - throw new NotFoundException("Request not found"); - } - - // Validate that this is a CAR_BODY type request - if (foundRequest?.type !== "CAR_BODY") { - throw new BadRequestException( - "This endpoint is only for CAR_BODY type requests", - ); - } - - // Validate that the user is the first party (or expert filling their own file) - if ( - !foundRequest.expertInitiated && - foundRequest?.firstPartyDetails?.firstPartyPhoneNumber !== user.username - ) { - throw new ForbiddenException( - "Only the first party can complete this step", - ); - } - - // For CAR_BODY flow: after form, always go to video upload - // We'll assume guilty by default for car accidents (no second form needed) - const nextStep = StepsEnum.CarBodyVideo; - - const createRequestFile = - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - blameStatus: ReqBlameStatus.PendingForFirstParty, - carBodyForm: { - firstPartyId: user.sub, - firstPartyPhoneNumber: user.username, - carBodyForm: reqBody, - // Assume guilty by default for car accidents - isGuilty: reqBody.car ? true : false, - }, - currentStep: StepsEnum.CarBodyForm, - nextStep: nextStep, - $push: { steps: StepsEnum.CarBodyForm }, - }, - ); - - return new RequestManagementDtoRs( - createRequestFile.firstPartyDetails.firstPartyId, - null, - StepsEnum.CarBodyForm, - nextStep, - "Please upload accident video", - createRequestFile._id, - ); - } - - async carBodySecondForm( - reqBody: CarBodySecondForm, - user, - requestId, - ): Promise { - // This endpoint is deprecated - second form is no longer needed - // We now assume guilty by default in the first form - throw new BadRequestException( - "This endpoint is deprecated. The second form is no longer required. Users are assumed guilty by default for car accidents.", - ); - } - - async addDetailToRequestLocation( - userId: string, - body: LocationDto, - requestId, - user?: any, // Optional user object for expert verification - ) { - const findRequest = - await this.requestManagementDbService.findOne(requestId); - if (!findRequest) throw new NotFoundException("requestId not found"); - - // Allow first party only - if ( - findRequest.firstPartyDetails.firstPartyId == new Types.ObjectId(userId) - ) { - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - firstPartyLocation: body, - currentStep: StepsEnum.F_addLocation, - nextStep: StepsEnum.F_addVoice, - $push: { steps: StepsEnum.F_addLocation }, // Ensure step is saved - }, - ); - - return new RequestManagementDtoRs( - findRequest.firstPartyDetails.firstPartyId, - findRequest?.secondPartyDetails?.secondPartyId || null, - StepsEnum.F_addLocation, - StepsEnum.F_addVoice, - "please add detail", - requestId, - ); - } - if ( - findRequest?.secondPartyDetails?.secondPartyId == - new Types.ObjectId(userId) - ) { - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - secondPartyLocation: body, - currentStep: StepsEnum.S_addLocation, - nextStep: StepsEnum.S_addVoice, - $push: { steps: StepsEnum.S_addLocation }, // Ensure step is saved - }, - ); - return new RequestManagementDtoRs( - findRequest.firstPartyDetails.firstPartyId, - findRequest?.secondPartyDetails?.secondPartyId || null, - StepsEnum.S_addLocation, - StepsEnum.S_addVoice, - "please add detail", - requestId, - ); - } else { - throw new BadGatewayException("parties not allowed"); - } - } - - async voiceUploadStep(userId: any, voice: Express.Multer.File, requestId) { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("request is not found"); - } - - const voiceDoc = await this.blameVoiceDbService.create({ - fileName: voice.filename, - path: voice.path, - requestId, - }); - - // Allow first party - if (request.firstPartyDetails.firstPartyId === userId.sub) { - try { - const updated = await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - currentStep: StepsEnum.F_addVoice, - nextStep: StepsEnum.F_addDescription, - $push: { - "firstPartyDetails.firstPartyFile.voices": voiceDoc["_id"], - steps: StepsEnum.F_addVoice, - }, - }, - ); - if (updated == undefined) { - return new BadGatewayException("update failed"); - } - return new RequestManagementDtoRs( - request.firstPartyDetails.firstPartyId, - request?.secondPartyDetails?.secondPartyId || null, - StepsEnum.F_addVoice, - StepsEnum.F_addDescription, - "please add description", - requestId, - ); - } catch (err) { - console.log(err); - throw new ExternalExceptionFilter(); - } - } - if (request?.secondPartyDetails?.secondPartyId === userId.sub) { - try { - const updated = await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - currentStep: StepsEnum.S_addVoice, - nextStep: StepsEnum.S_addDescription, - $push: { - "secondPartyDetails.secondPartyFiles.voices": voiceDoc["_id"], - steps: StepsEnum.S_addVoice, - }, - }, - ); - if (updated == undefined) { - return new BadGatewayException("update failed"); - } - return new RequestManagementDtoRs( - request.firstPartyDetails.firstPartyId, - request?.secondPartyDetails?.secondPartyId || null, - StepsEnum.S_addVoice, - StepsEnum.S_addDescription, - "add Description for SecondParty", - requestId, - ); - } catch (err) { - console.log(err); - throw new ExternalExceptionFilter(); - } - } - } - - async addDescriptionToRequest( - user: any, - body: DescriptionDto, - requestId: string, - ) { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - this.assertCarBodyDescriptionMinimum(request.type, body.desc); - - // --- First Party Flow --- - if (request.firstPartyDetails.firstPartyId == user.sub) { - // Build base update payload with proper MongoDB operators - const nextStepValue = - request.type === "THIRD_PARTY" - ? StepsEnum.F_addSecondPartyPhoneNumber - : StepsEnum.AddSignatures; - const blameStatusValue = - request.type === "THIRD_PARTY" - ? ReqBlameStatus.PendingForFirstParty - : ReqBlameStatus.WaitingForSignatures; - - // Ensure firstPartyFile exists and initialize descriptions array if needed - const updatePayload: any = { - $set: { - currentStep: StepsEnum.F_addDescription, - nextStep: nextStepValue, - blameStatus: blameStatusValue, - }, - $push: { - steps: StepsEnum.F_addDescription, - }, - }; - - // Initialize firstPartyFile.descriptions if it doesn't exist, then push description - if ( - !request.firstPartyDetails.firstPartyFile || - !request.firstPartyDetails.firstPartyFile.descriptions - ) { - // Initialize the descriptions array if it doesn't exist - if (!request.firstPartyDetails.firstPartyFile) { - updatePayload.$set["firstPartyDetails.firstPartyFile"] = {}; - } - updatePayload.$set["firstPartyDetails.firstPartyFile.descriptions"] = [ - body.desc, - ]; - } else { - // If descriptions array exists, push to it - updatePayload.$push["firstPartyDetails.firstPartyFile.descriptions"] = - body.desc; - } - - // Add CAR_BODY specific fields if type is CAR_BODY - if (request.type === "CAR_BODY") { - this.assertAccidentDateTimeNotInFuture({ - accidentDate: body.accidentDate, - accidentTime: body.accidentTime, - }); - if (body.accidentDate) { - updatePayload.$set["firstPartyDetails.firstPartyFile.accidentDate"] = - body.accidentDate; - } - if (body.accidentTime) { - updatePayload.$set["firstPartyDetails.firstPartyFile.accidentTime"] = - body.accidentTime; - } - if (body.weatherCondition) { - updatePayload.$set[ - "firstPartyDetails.firstPartyFile.weatherCondition" - ] = body.weatherCondition; - } - if (body.roadCondition) { - updatePayload.$set["firstPartyDetails.firstPartyFile.roadCondition"] = - body.roadCondition; - } - if (body.lightCondition) { - updatePayload.$set[ - "firstPartyDetails.firstPartyFile.lightCondition" - ] = body.lightCondition; - } - } - - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - // For expert-initiated files, ensure auto-assignment and add history - if (request.expertInitiated) { - await this.ensureExpertAssignment(requestId); - await this.addHistoryEvent( - requestId, - "FIRST_PARTY_DESCRIPTION_COMPLETED", - new Types.ObjectId(user.sub), - undefined, - request.filledBy === FilledBy.EXPERT ? "expert" : "customer", - ); - } - - const nextStepMessage = - request.type === "CAR_BODY" - ? "Please sign the document to complete your request" - : "add secondParty to request"; - - return new RequestManagementDtoRs( - request.firstPartyDetails.firstPartyId, - request?.secondPartyDetails?.secondPartyId || null, - StepsEnum.F_addDescription, - nextStepValue, - nextStepMessage, - requestId, - ); - } - - // --- Second Party Flow --- - if (request?.secondPartyDetails?.secondPartyId == user.sub) { - const firstPartyForm = request.firstPartyDetails.firstPartyInitialForm; - const secondPartyForm = request.secondPartyDetails.secondPartyInitialForm; - - const shouldAutoResolve = - (firstPartyForm?.imDamaged && secondPartyForm?.imGuilty) || - (secondPartyForm?.imDamaged && firstPartyForm?.imGuilty); - - let updatePayload: any; - - if (shouldAutoResolve) { - // Build the payload for the auto-resolve (agreement) flow - const guiltyPartyId = firstPartyForm.imGuilty - ? request.firstPartyDetails.firstPartyId - : request.secondPartyDetails.secondPartyId; - - updatePayload = { - $set: { - blameStatus: ReqBlameStatus.WaitingForSignatures, - currentStep: StepsEnum.S_addDescription, - nextStep: StepsEnum.AddSignatures, - expertSubmitReply: { - description: "منتظر امضای طرفین برای تایید توافق.", - guiltyUserId: guiltyPartyId, - submitTime: new Date(), - fields: { - /* TODO: The accidentReason field is mocked and is default option for when the shouldAutoResolve is true */ - accidentReason: { - /* it should be removed and replaced with a proper mechanism to identify the accident reason */ - id: 2, - label: "تغيير مسير ناگهانی", - fanavaran: 4, - }, - }, - }, - }, - $push: { - steps: StepsEnum.S_addDescription, - }, - }; - - // Initialize secondPartyFiles.descriptions if it doesn't exist, then push description - if ( - !request.secondPartyDetails?.secondPartyFiles || - !request.secondPartyDetails.secondPartyFiles.descriptions - ) { - // Initialize the descriptions array if it doesn't exist - if (!request.secondPartyDetails.secondPartyFiles) { - updatePayload.$set["secondPartyDetails.secondPartyFiles"] = {}; - } - updatePayload.$set[ - "secondPartyDetails.secondPartyFiles.descriptions" - ] = [body.desc]; - } else { - // If descriptions array exists, push to it - updatePayload.$push[ - "secondPartyDetails.secondPartyFiles.descriptions" - ] = body.desc; - } - - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - return new RequestManagementDtoRs( - request.firstPartyDetails.firstPartyId, - user.sub, - StepsEnum.S_addDescription, - ReqBlameStatus.WaitingForSignatures, - "Agreement detected. Awaiting signatures from both parties.", - requestId, - ); - } else { - // Build the payload for the standard (disagreement) flow - updatePayload = { - $set: { - blameStatus: ReqBlameStatus.UnChecked, - currentStep: StepsEnum.S_addDescription, - nextStep: StepsEnum.S_completed, - }, - $push: { - steps: StepsEnum.S_addDescription, - }, - }; - - // Initialize secondPartyFiles.descriptions if it doesn't exist, then push description - if ( - !request.secondPartyDetails?.secondPartyFiles || - !request.secondPartyDetails.secondPartyFiles.descriptions - ) { - // Initialize the descriptions array if it doesn't exist - if (!request.secondPartyDetails.secondPartyFiles) { - updatePayload.$set["secondPartyDetails.secondPartyFiles"] = {}; - } - updatePayload.$set[ - "secondPartyDetails.secondPartyFiles.descriptions" - ] = [body.desc]; - } else { - // If descriptions array exists, push to it - updatePayload.$push[ - "secondPartyDetails.secondPartyFiles.descriptions" - ] = body.desc; - } - - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - // For expert-initiated files, ensure auto-assignment and add history - if (request.expertInitiated) { - await this.ensureExpertAssignment(requestId); - await this.addHistoryEvent( - requestId, - "SECOND_PARTY_DESCRIPTION_COMPLETED", - new Types.ObjectId(user.sub), - undefined, - request.filledBy === FilledBy.EXPERT ? "expert" : "customer", - ); - await this.addHistoryEvent( - requestId, - "READY_FOR_EXPERT_EVALUATION", - request.initiatedBy, - undefined, - "system", - ); - } - - return new RequestManagementDtoRs( - request.firstPartyDetails.firstPartyId, - user.sub, - StepsEnum.S_addSecondPartyPhoneNumber, - "expertOpinion", - "please wait... for expert reply", - requestId, - ); - } - } - - throw new ForbiddenException("User is not a party to this request."); - } - - async addSecondPartyDetailsToRequest( - phoneNumber, - requestId, - firstPartyUser, - frontendRoutes, - req, - ) { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - if (request?.secondPartyDetails?.secondPartyId) { - throw new BadGatewayException("Second party has already been added"); - } - if (request.firstPartyDetails.firstPartyPhoneNumber === phoneNumber) { - throw new BadRequestException( - "Second party phone number cannot be the same as the first party", - ); - } - - // Only perform the update if the second party details don't exist yet. - if (!request.secondPartyDetails) { - const updatePayload = { - blameStatus: ReqBlameStatus.PendingForSecondParty, - "secondPartyDetails.secondPartyPhoneNumber": phoneNumber, - currentStep: StepsEnum.F_completed, - nextStep: StepsEnum.S_InitialForm, - $push: { - steps: StepsEnum.F_addSecondPartyPhoneNumber, - }, - }; - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - } - - // Send the SMS after the database update is complete. - const URL = this.smsOrchestrationService.buildInviteLink( - frontendRoutes, - requestId, - "v1", - ); - await this.smsOrchestrationService.sendInviteLink( - phoneNumber, - request.publicId, - URL, - ); - - return { url: URL }; - } - - async myRequests(phoneNumber) { - const res = { listOfFirstParty: [], listOfSecondParty: [] }; - const blameStatuses = [ - ReqBlameStatus.CheckedRequest, - ReqBlameStatus.UnChecked, - ReqBlameStatus.PendingForFirstParty, - ReqBlameStatus.PendingForSecondParty, - ReqBlameStatus.ReviewRequest, - ReqBlameStatus.CheckAgain, - ReqBlameStatus.UserPending, - ReqBlameStatus.CloseRequest, - ReqBlameStatus.WaitForUserAccept, - ReqBlameStatus.WaitingForSignatures, - ReqBlameStatus.InPersonVisit, - ]; - - const parties = await this.requestManagementDbService.findAll({ - $or: [ - { - $or: [ - { "firstPartyDetails.firstPartyPhoneNumber": phoneNumber }, - { "secondPartyDetails.secondPartyPhoneNumber": phoneNumber }, - ], - blameStatus: { $in: blameStatuses }, - }, - ], - }); - // TODO create a DTO for Response - parties.forEach((p) => { - if (p?.secondPartyDetails?.secondPartyPhoneNumber == phoneNumber) { - res.listOfSecondParty.push({ - id: p.id, - blameStatus: p.blameStatus, - requestNumber: p.requestNumber, - createdAt: new Date(p.createdAt) - .toLocaleString("fa-IR") - .split("،")[0], - timeCreatedAt: new Date(p.createdAt) - .toLocaleTimeString("fa-IR") - .split(",")[0], - type: p.type || "THIRD_PARTY", // Include type field - }); - } - - if (p.firstPartyDetails.firstPartyPhoneNumber == phoneNumber) { - res.listOfFirstParty.push({ - id: p.id, - blameStatus: p.blameStatus, - requestNumber: p.requestNumber, - createdAt: new Date(p.createdAt) - .toLocaleString("fa-IR") - .split("،")[0], - timeCreatedAt: new Date(p.createdAt) - .toLocaleTimeString("fa-IR") - .split(",")[0], - type: p.type || "THIRD_PARTY", // Include type field - }); - } - }); - return res; - } - - async getCreatableClaims(user: any) { - const userId = user.sub; - - const creatableBlameFiles = await this.requestManagementDbService.findAll({ - blameStatus: ReqBlameStatus.CloseRequest, - - $or: [ - { "firstPartyDetails.firstPartyId": userId }, - { "secondPartyDetails.secondPartyId": userId }, - ], - - "expertSubmitReply.guiltyUserId": { $ne: userId }, - }); - - if (!creatableBlameFiles || creatableBlameFiles.length === 0) { - return []; - } - - // Fetch existing claim files for all blame files in parallel - const claimFilesPromises = creatableBlameFiles.map((blameFile) => - this.claimRequestManagementDbService.findOne(undefined, { - "blameFile._id": new Types.ObjectId(blameFile._id), - }), - ); - const existingClaimFiles = await Promise.all(claimFilesPromises); - - // Create a map of blame file ID to claim file ID for quick lookup - const blameToClaimMap = new Map(); - creatableBlameFiles.forEach((blameFile, index) => { - const claimFile = existingClaimFiles[index]; - if (claimFile) { - blameToClaimMap.set(blameFile._id.toString(), claimFile._id.toString()); - } - }); - - const formattedResponse = creatableBlameFiles.map((p) => { - const claimId = blameToClaimMap.get(p._id.toString()); - return { - id: p.id, - blameStatus: p.blameStatus, - requestNumber: p.requestNumber, - createdAt: new Date(p.createdAt).toLocaleString("fa-IR").split("،")[0], - timeCreatedAt: new Date(p.createdAt) - .toLocaleTimeString("fa-IR") - .split(",")[0], - ...(claimId && { claimId }), - }; - }); - - return formattedResponse; - } - - async requestDetailsWithoutStatus( - request: RequestManagementModel, - user: any, - ) { - const parties = this.determineUserPartyRole(request, user); - - request.actorsChecker = - request.actorsChecker[request.actorsChecker.length - 1]; - - return { theParties: parties, requestDetail: request }; - } - - async requestDetailsCheckedStatus( - request: any, - user: any, - ): Promise { - const finalReply = - request.expertSubmitReplyFinal || request.expertSubmitReply; - - if (!finalReply) { - throw new NotFoundException("Expert reply not found for this request."); - } - - const { guiltyUserId } = finalReply; - const isGuilty = guiltyUserId == user.sub; - - let actorDetail; - for (const a of request.actorsChecker) { - if (Object.keys(a)[0].toString() === ReqBlameStatus.CheckedRequest) { - actorDetail = a; - } - } - - let steps: ReqBlameStatus; - if (!finalReply.firstPartyComment) { - steps = ReqBlameStatus.PendingForSecondParty; - } else if (!finalReply.secondPartyComment) { - steps = ReqBlameStatus.PendingForFirstParty; - } else { - steps = ReqBlameStatus.WaitForUserAccept; - } - - await this.requestManagementDbService.findByIdAndUpdate(request._id, { - currentStep: steps, - $push: { steps: steps }, - }); - - const theParties = this.determineUserPartyRole(request, user); - - return new DetailsReplyDtoRs(request, { - actorDetail, - isGuilty, - steps, - theParties, - }); - } - - async requestDetailCloseStatus(request: RequestManagementModel) { - const finalReply = - request.expertSubmitReplyFinal || request.expertSubmitReply; - - if (!finalReply) { - return { message: "اطلاعات کارشناسی برای این پرونده یافت نشد." }; - } - - const authoritativeReply = finalReply as any; - - const bothPartiesAccepted = - authoritativeReply.firstPartyComment?.isAccept && - authoritativeReply.secondPartyComment?.isAccept; - - const wasAutoClosed = - request.autoCloseTriggerTime && - new Date(request.autoCloseTriggerTime) < new Date(); - - if (bothPartiesAccepted || wasAutoClosed) { - const guiltyUserId = authoritativeReply.guiltyUserId; - if (!guiltyUserId) { - return { message: "اطلاعات طرف مقصر در پرونده یافت نشد." }; - } - - const { firstPartyDetails, secondPartyDetails } = request; - - const isFirstPartyGuilty = - firstPartyDetails.firstPartyId.toString() === guiltyUserId.toString(); - - const guiltyUserDetail = isFirstPartyGuilty - ? [firstPartyDetails] - : [secondPartyDetails]; - const damageUserDetail = isFirstPartyGuilty - ? [secondPartyDetails] - : [firstPartyDetails]; - - return { - requestId: request["_id"], - blameStatus: request.blameStatus, - damageUserDetail, - guiltyUserDetail, - expertResendReply: request.expertResendReply, - expertSubmitReply: request.expertSubmitReply, - expertSubmitReplyFinal: request.expertSubmitReplyFinal, - }; - } else { - return { message: "یکی از طرفین پرونده را تایید نکرده است." }; - } - } - - async requestDetailsUserPendingStatus( - request: RequestManagementModel, - user: any, - ) { - const { expertResendReply } = request; - - const processPartyDetails = (partyKey: "firstParty" | "secondParty") => { - const partyReply = expertResendReply?.[partyKey]; - - if (!partyReply || user.sub !== partyReply[`${partyKey}Id`]) { - return null; - } - - const descriptionString = partyReply[`${partyKey}Description`] || ""; - const allParts = descriptionString - .split(",") - .map((p) => p.trim()) - .filter(Boolean); - - const validDocTypes = Object.values(BlameDocumentType); - const requiredDocuments: BlameDocumentType[] = []; - const descriptionTextParts: string[] = []; - - for (const part of allParts) { - const matchingDocType = validDocTypes.find( - (docType) => - docType.replace(/_/g, "").toUpperCase() === part.toUpperCase(), - ); - - if (matchingDocType) { - requiredDocuments.push(matchingDocType); - } else { - descriptionTextParts.push(part); - } - } - - const description = descriptionTextParts.join(", "); - - const otherPartyKey = - partyKey === "firstParty" ? "secondParty" : "firstParty"; - const otherPartyHasReplied = - !!expertResendReply?.[otherPartyKey]?.userReply; - - const nextStep = otherPartyHasReplied - ? "Wait For Expert Comment" - : partyKey === "firstParty" - ? "Wait For Second Party Reply" - : "Wait For First Party Reply"; - - return { - userId: partyReply[`${partyKey}Id`], - requiredDocuments, - description, - hasReplied: partyReply.userReply != null, - hasVoice: partyReply.voice != null, - nextStep: nextStep, - }; - }; - - const details = - processPartyDetails("firstParty") || processPartyDetails("secondParty"); - - return details; - } - - // TODO fix requestDetailsCheckAginStatus again - async requestDetailsCheckAgainStatus(request, user) { - const { expertResendReply } = request; - const detail = []; - - const addDetail = ( - party, - partyId, - partyDescription, - userReply, - voice, - step1, - step2, - ) => { - if (user.sub === expertResendReply?.[party]?.[`${party}Id`]) { - detail.push(expertResendReply?.[party][`${party}Id`], { - description: expertResendReply?.[party][`${party}Description`], - reply: expertResendReply[party]?.userReply !== null, - voice: !!expertResendReply[party]?.voice, - }); - if ( - expertResendReply?.[party][`${party}Id`] && - !expertResendReply?.[ - party === "firstParty" ? "secondParty" : "firstParty" - ]?.userReply - ) { - detail.push({ step: step1 }); - } else { - detail.push({ step: step2 }); - } - } - }; - - addDetail( - "firstParty", - "firstPartyId", - "firstPartyDescription", - "userReply", - "voice", - "Wait For Second Party Reply", - "Wait For Expert Comment", - ); - addDetail( - "secondParty", - "secondPartyId", - "secondPartyDescription", - "userReply", - "voice", - "Wait For First Party Reply", - "Wait For Expert Comment", - ); - - return detail; - } - - // TODO CREATE DTO FOR RESPONSE ONLY - async requestDetails(user, requestId) { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) throw new NotFoundException("request not found"); - - const formattedRequest = { - ...request, - createdAt: request.createdAt, - updatedAt: request.updatedAt, - }; - - const formattingOptions: Intl.DateTimeFormatOptions = { - timeZone: "Asia/Tehran", - year: "numeric", - month: "2-digit", - day: "2-digit", - hour: "2-digit", - minute: "2-digit", - second: "2-digit", - }; - - // Check if createdAt exists and then format it on our new object. - if (request.createdAt) { - formattedRequest.createdAt = new Date(request.createdAt).toLocaleString( - "fa-IR", - formattingOptions, - ); - } - - // Do the same for updatedAt. - if (request.updatedAt) { - formattedRequest.updatedAt = new Date(request.updatedAt).toLocaleString( - "fa-IR", - formattingOptions, - ) as unknown as Date; - } - - switch (request.blameStatus) { - case ReqBlameStatus.CheckedRequest: - return await this.requestDetailsCheckedStatus(request, user); - case ReqBlameStatus.UserPending: - return await this.requestDetailsUserPendingStatus(request, user); - case ReqBlameStatus.CheckAgain: - return await this.requestDetailsCheckAgainStatus(request, user); - case ReqBlameStatus.CloseRequest: - return await this.requestDetailCloseStatus(request); - default: - // Pass the full user object, not just the username - return await this.requestDetailsWithoutStatus(request, user); - } - } - - private determineUserPartyRole( - request: RequestManagementModel, - user: any, - ): "firstParty" | "secondParty" | null { - const { firstPartyDetails, secondPartyDetails } = request; - const userId = user.sub; // The user's unique ID - const username = user.username; // The user's phone number - - // Check against both ID and phone number for robustness - if ( - userId === firstPartyDetails?.firstPartyId?.toString() || - username === firstPartyDetails?.firstPartyPhoneNumber - ) { - return "firstParty"; - } - if ( - userId === secondPartyDetails?.secondPartyId?.toString() || - username === secondPartyDetails?.secondPartyPhoneNumber - ) { - return "secondParty"; - } - return null; - } - - private async recordBlameExpertActivity(args: { - expertId: string; - tenantId: string; - requestId: string; - eventType: ExpertFileActivityType; - idempotencyKey?: string; - }): Promise { - if ( - !Types.ObjectId.isValid(args.expertId) || - !Types.ObjectId.isValid(args.tenantId) || - !Types.ObjectId.isValid(args.requestId) - ) { - return; - } - await this.expertFileActivityDbService.recordEvent({ - expertId: args.expertId, - tenantId: args.tenantId, - fileId: args.requestId, - fileType: ExpertFileKind.BLAME, - eventType: args.eventType, - idempotencyKey: args.idempotencyKey, - }); - } - - private async handleDisagreement( - request: any, - originalReq: any, - isFirstPartyTheDisagreer: boolean, - ): Promise { - await this.requestManagementDbService.findByIdAndUpdate(request._id, { - blameStatus: ReqBlameStatus.PartiesDisagree, - $unset: { autoCloseTriggerTime: "" }, - }); - - this.logger.log( - `Blame request ${request._id} closed with status 'PartiesDisagree'.`, - ); - - const firstPartyComment = request.expertSubmitReply?.firstPartyComment; - const secondPartyComment = request.expertSubmitReply?.secondPartyComment; - - let phoneNumberToNotify: string | null = null; - if (isFirstPartyTheDisagreer && secondPartyComment?.isAccept === true) { - phoneNumberToNotify = - originalReq.secondPartyDetails?.secondPartyPhoneNumber; - } else if ( - !isFirstPartyTheDisagreer && - firstPartyComment?.isAccept === true - ) { - phoneNumberToNotify = - originalReq.firstPartyDetails?.firstPartyPhoneNumber; - } - - // TODO SMS Sending - if (phoneNumberToNotify) { - await this.smsOrchestrationService.sendTextByKey( - phoneNumberToNotify, - "parties_disagree_notify", - "متاسفانه طرف مقابل با نظر کارشناس مخالفت کرد. فرآیند آنلاین این پرونده بسته شده است و جهت پیگیری حضوری اقدام نمایید.", - ); - } - } - - private async handlePostReplyStateChanges( - updatedReq: any, - originalReq: any, - ): Promise { - const isCarBodyType = updatedReq.type === "CAR_BODY"; - - const finalReply = updatedReq.expertResendReply - ? updatedReq.expertSubmitReplyFinal - : updatedReq.expertSubmitReply; - - const firstAccept = finalReply?.firstPartyComment?.isAccept; - const secondAccept = finalReply?.secondPartyComment?.isAccept; - - // 🟥 Step 1: Handle rejections - if (!isCarBodyType && (firstAccept === false || secondAccept === false)) { - await this.handleDisagreement( - updatedReq, - originalReq, - firstAccept === false, - ); - return; - } - - // 🟦 Step 2: CAR_BODY logic (one side only) - if (isCarBodyType) { - if (firstAccept) { - await this.handleFinalStateChange(updatedReq); - } - return; - } - - // 🟩 Step 3: Two-party logic - if (updatedReq.blameStatus === ReqBlameStatus.WaitingForSignatures) { - if (firstAccept && secondAccept) { - await this.finalizeAutoResolvedRequest(updatedReq); - } else if (firstAccept || secondAccept) { - const message = `طرف مقابل توافق را امضا کرده است. لطفا جهت نهایی کردن پرونده، امضای خود را ثبت نمایید.`; - await this.handleOnePartyReplied( - updatedReq, - originalReq, - firstAccept, - message, - ); - } - return; - } - - if (firstAccept && secondAccept) { - await this.handleFinalStateChange(updatedReq); - } else if (firstAccept || secondAccept) { - const message = `طرف مقابل نظر کارشناس را قبول و امضا کرده است. در طی 24 ساعت آینده فرصت دارید تا پرونده را تکمیل کرده یا پرونده بسته خواهد شد.`; - await this.handleOnePartyReplied( - updatedReq, - originalReq, - firstAccept, - message, - ); - } - } - - private async finalizeAutoResolvedRequest(request: any): Promise { - await this.requestManagementDbService.findByIdAndUpdate(request._id, { - blameStatus: ReqBlameStatus.CloseRequest, - $unset: { autoCloseTriggerTime: "" }, - }); - - this.logger.log( - `Blame request ${request._id} auto-resolved and closed successfully.`, - ); - } - - private buildReplyUpdate( - request: any, - userId: string, - isAccept: boolean, - signDetail: any, - ): any { - const isObjection = !!request.expertResendReply; - const replyField = isObjection - ? "expertSubmitReplyFinal" - : "expertSubmitReply"; - - // Handle cases where firstPartyId might be undefined (e.g., IN_PERSON expert-filled files) - const firstPartyId = request.firstPartyDetails?.firstPartyId; - if (!firstPartyId) { - throw new BadRequestException( - "First party ID is missing. Please ensure the file has been properly initialized.", - ); - } - - const isFirstParty = userId === firstPartyId.toString(); - - const currentPartyKey = isFirstParty - ? "firstPartyComment" - : "secondPartyComment"; - const otherPartyKey = isFirstParty - ? "secondPartyComment" - : "firstPartyComment"; - - const newReplyObject = JSON.parse( - JSON.stringify(request[replyField] ?? {}), - ); - - const currentUserComment = { - isAccept: isAccept, - signDetail: { - fileId: signDetail._id, - fileName: signDetail.fileName, - }, - }; - - newReplyObject[currentPartyKey] = currentUserComment; - - if (!newReplyObject[otherPartyKey]) { - newReplyObject[otherPartyKey] = null; - } - - const update = { - $set: { - [replyField]: newReplyObject, - }, - }; - - return update; - } - - private async handleFinalStateChange(request: any): Promise { - const alreadyClosed = request.blameStatus === ReqBlameStatus.CloseRequest; - const alreadyHandled = request.isHandledStatsUpdated === true; - - if (!alreadyClosed) { - await this.requestManagementDbService.findByIdAndUpdate(request._id, { - blameStatus: ReqBlameStatus.CloseRequest, - $unset: { autoCloseTriggerTime: "" }, - }); - } - - if (!alreadyHandled) { - // Only update expert stats if the request was locked by an expert - // (CAR_BODY requests might not have actorLocked set) - if (request.actorLocked?.actorId) { - // Convert ObjectIds to strings safely - const actorIdStr = request.actorLocked.actorId.toString - ? request.actorLocked.actorId.toString() - : String(request.actorLocked.actorId); - const requestIdStr = request._id.toString - ? request._id.toString() - : String(request._id); - - const tenantIdStr = - request.firstPartyDetails?.firstPartyClient?.clientId?.toString?.() || - request.secondPartyDetails?.secondPartyClient?.clientId?.toString?.() || - ""; - await this.recordBlameExpertActivity({ - expertId: actorIdStr, - tenantId: tenantIdStr, - requestId: requestIdStr, - eventType: ExpertFileActivityType.HANDLED, - idempotencyKey: `blame:${requestIdStr}:handled:${actorIdStr}`, - }); - } - await this.requestManagementDbService.findByIdAndUpdate(request._id, { - $set: { isHandledStatsUpdated: true }, - }); - } - } - - private async handleOnePartyReplied( - updatedReq: any, - originalReq: any, - isFirstPartyAccepted: boolean, - message: string, - ): Promise { - if (updatedReq.autoCloseTriggerTime) { - return; - } - - const phoneNumber = isFirstPartyAccepted - ? originalReq.secondPartyDetails?.secondPartyPhoneNumber - : originalReq.firstPartyDetails?.firstPartyPhoneNumber; - - if (phoneNumber) { - const key = message.includes("24 ساعت") - ? "one_party_accepted_wait_24h" - : "one_party_signed_wait_signature"; - await this.smsOrchestrationService.sendTextByKey( - phoneNumber, - key, - message, - ); - } - - // await this.autoCloseRequestService.scheduleAutoClose({ - // requestId: updatedReq._id.toString(), - // runAt: new Date(Date.now() + 24 * 60 * 60 * 1000), - // }); - } - - async userReply( - props, - isAccept: boolean, - file: Express.Multer.File, - ): Promise { - const { requestId, user } = props; - if (!file) throw new BadRequestException("A signature file is required."); - - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) throw new NotFoundException("Request not found."); - - const signDetail = await this.userSign.create({ - fileName: file.filename, - userId: user.sub, - path: file.path, - requestId, - }); - - const updatePayload = this.buildReplyUpdate( - request, - user.sub, - isAccept, - signDetail, - ); - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - const updatedReq = await this.requestManagementDbService.findOne(requestId); - - await this.handlePostReplyStateChanges(updatedReq, request); - - return new UserReplyDto(requestId); - } - - async userResend( - files: { [key: string]: Express.Multer.File[] }, - user: any, - requestId: string, - description: string, - ) { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - const partyKey = this.determinePartyAndValidate(request, user.sub); - - const { voiceId, uploadedDocumentIds } = await this.processResendUploads( - files, - requestId, - ); - - const updatePayload: any = { - $set: { - [`expertResendReply.${partyKey}.userReply`]: description, - }, - }; - - if (voiceId) { - updatePayload.$set[`expertResendReply.${partyKey}.voice`] = voiceId; - } - - for (const docType in uploadedDocumentIds) { - updatePayload.$set[`expertResendReply.${partyKey}.documents.${docType}`] = - uploadedDocumentIds[docType]; - } - - await this.requestManagementDbService.findByIdAndUpdate( - requestId, - updatePayload, - ); - - await this.updateRequestStatusIfNeeded(requestId); - - return { message: "Update saved successfully." }; - } - - private async processResendUploads( - files: { [key: string]: Express.Multer.File[] }, - requestId: string, - ) { - const uploadedDocumentIds: { [key in BlameDocumentType]?: Types.ObjectId } = - {}; - let voiceId: Types.ObjectId | null = null; - - for (const fieldName in files) { - const fileArray = files[fieldName]; - if (fileArray && fileArray.length > 0) { - const file = fileArray[0]; - - if (fieldName === "voice") { - voiceId = await this.createVoiceDocument( - file, - requestId, - UploadContext.EXPERT_RESEND, - ); - } else { - const documentType = fieldName as BlameDocumentType; - const docId = await this.createBlameDocument( - file, - requestId, - documentType, - ); - uploadedDocumentIds[documentType] = docId; - } - } - } - return { voiceId, uploadedDocumentIds }; - } - - private async createBlameDocument( - file: Express.Multer.File, - requestId: string, - documentType: BlameDocumentType, - ): Promise { - const doc = await this.blameDocumentDbService.create({ - path: file.path, - requestId: new Types.ObjectId(requestId), - fileName: file.filename, - documentType: documentType, - }); - return (doc as any)._id; - } - - private determinePartyAndValidate( - request: any, - userId: string, - ): "firstParty" | "secondParty" { - const firstPartyId = request?.firstPartyDetails?.firstPartyId?.toString(); - const secondPartyId = - request?.secondPartyDetails?.secondPartyId?.toString(); - - if (userId === firstPartyId) { - if (request.expertResendReply?.firstParty?.userReply) { - throw new BadRequestException( - "You have already submitted a reply for this resend request.", - ); - } - return "firstParty"; - } - - if (userId === secondPartyId) { - if (request.expertResendReply?.secondParty?.userReply) { - throw new BadRequestException( - "You have already submitted a reply for this resend request.", - ); - } - return "secondParty"; - } - - throw new ForbiddenException("User is not a party to this request."); - } - - private async createVoiceDocument( - file: Express.Multer.File, - requestId: string, - context: UploadContext, - ): Promise { - const voiceDoc = await this.blameVoiceDbService.create({ - path: file.path, - requestId: new Types.ObjectId(requestId), - fileName: file.filename, - context: context, - }); - return (voiceDoc as any)._id; - } - - private async updateRequestStatusIfNeeded(requestId: string): Promise { - const updatedRequest = - await this.requestManagementDbService.findOne(requestId); - const reply = updatedRequest.expertResendReply; - - if (!reply) { - return; // No resend initiated, nothing to do. - } - - // Helper function to check if a description contains a request for documents. - const doesDescriptionRequireDocuments = ( - description: string | null | undefined, - ): boolean => { - if (!description) return false; - - const validDocTypes = Object.values(BlameDocumentType); - const descriptionParts = description.split(",").map((p) => p.trim()); - - // Return true if any part of the description matches a known document type. - return descriptionParts.some((part) => - validDocTypes.some( - (docType) => - docType.replace(/_/g, "").toUpperCase() === part.toUpperCase(), - ), - ); - }; - - // 1. Determine which parties were actually asked to resubmit DOCUMENTS. - const requiredPartiesToReply: ("firstParty" | "secondParty")[] = []; - - if ( - reply.firstParty && - doesDescriptionRequireDocuments(reply.firstParty.firstPartyDescription) - ) { - requiredPartiesToReply.push("firstParty"); - } - if ( - reply.secondParty && - doesDescriptionRequireDocuments(reply.secondParty.secondPartyDescription) - ) { - requiredPartiesToReply.push("secondParty"); - } - - if (requiredPartiesToReply.length === 0) { - return; - } - - const allRequiredRepliesAreIn = requiredPartiesToReply.every( - (party) => !!reply[party]?.userReply, - ); - - if ( - allRequiredRepliesAreIn && - updatedRequest.blameStatus !== ReqBlameStatus.CheckAgain - ) { - await this.requestManagementDbService.findByIdAndUpdate(requestId, { - blameStatus: ReqBlameStatus.CheckAgain, - }); - this.logger.log( - `Request ${requestId} status updated to CheckAgain as all required parties have resubmitted.`, - ); - } - } - - private async addedClientKey(data: { clientName: any; companyCode: number }) { - if (process.env.ADDED_AUTO_CLIENT_KEY) { - let clientExist = await this.clientService.findOne({ - clientName: data.clientName, - }); - if (!clientExist) { - try { - await this.clientService.addClient({ - clientCode: data.companyCode, - clientName: { - persian: data.clientName, - english: null, - }, - useExpertMode: "genuine", - }); - } catch (err) { - console.log(err); - } - } - } - } - /** * Verify that expert can access this file (only if they initiated it) */ @@ -5665,110 +3526,6 @@ export class RequestManagementService { ); } - /** - * Expert creates an initial blame file (incomplete, waiting for completion) - */ - // async createExpertInitiatedFile( - // expert: any, - // dto: CreateExpertInitiatedFileDto, - // ): Promise<{ requestId: string }> { - // const reqNumber = new ShortUniqueId({ counter: 1 }); - // const expertId = new Types.ObjectId(expert.sub); - // const publicId = await this.publicIdService.generateRequestPublicId(); - - // // For LINK method, validate phone numbers are provided - // if (dto.creationMethod === CreationMethod.LINK) { - // if (!dto.firstPartyPhoneNumber) { - // throw new BadRequestException( - // "First party phone number is required for LINK method", - // ); - // } - // if (dto.type === "THIRD_PARTY" && !dto.secondPartyPhoneNumber) { - // throw new BadRequestException( - // "Second party phone number is required for LINK method with THIRD_PARTY type", - // ); - // } - // if ( - // dto.type === "THIRD_PARTY" && - // dto.firstPartyPhoneNumber === dto.secondPartyPhoneNumber - // ) { - // throw new BadRequestException( - // "First and second party phone numbers must be different", - // ); - // } - // } - - // // For LINK method, create/get users and set their IDs - // let firstPartyUserId: Types.ObjectId | undefined; - // let secondPartyUserId: Types.ObjectId | undefined; - // let firstPartyDetails: any = {}; - // let secondPartyDetails: any = {}; - - // if (dto.creationMethod === CreationMethod.LINK) { - // // Get or create first party user - // firstPartyUserId = await this.getOrCreateUserByPhoneNumber( - // dto.firstPartyPhoneNumber, - // ); - // firstPartyDetails = { - // firstPartyId: firstPartyUserId, - // firstPartyPhoneNumber: dto.firstPartyPhoneNumber, - // }; - - // // Get or create second party user for THIRD_PARTY - // if (dto.type === "THIRD_PARTY" && dto.secondPartyPhoneNumber) { - // secondPartyUserId = await this.getOrCreateUserByPhoneNumber( - // dto.secondPartyPhoneNumber, - // ); - // secondPartyDetails = { - // secondPartyId: secondPartyUserId, - // secondPartyPhoneNumber: dto.secondPartyPhoneNumber, - // }; - // } - // } - - // const createRequest = await this.requestManagementDbService.create({ - // requestNumber: reqNumber.rnd(), - // publicId, - // type: dto.type, - // expertInitiated: true, - // initiatedBy: expertId, - // creationMethod: dto.creationMethod, - // filledBy: dto.creationMethod === CreationMethod.IN_PERSON ? FilledBy.EXPERT : FilledBy.CUSTOMER, - // currentStep: StepsEnum.createRequest, - // nextStep: - // dto.type === "THIRD_PARTY" - // ? StepsEnum.F_InitialForm - // : StepsEnum.CarBodyForm, - // blameStatus: ReqBlameStatus.PendingForFirstParty, - // lockFile: false, - // history: [], - // assignedExpertId: expertId, // Auto-assign to initiating expert - // ...(dto.creationMethod === CreationMethod.LINK && { - // firstPartyDetails, - // ...(dto.type === "THIRD_PARTY" && { secondPartyDetails }), - // }), - // }); - - // const requestId = (createRequest as any)._id.toString(); - - // // Add history event - // await this.addHistoryEvent( - // requestId, - // "FILE_CREATED_BY_EXPERT", - // expertId, - // `${expert.firstName} ${expert.lastName}`, - // "expert", - // { - // creationMethod: dto.creationMethod, - // type: dto.type, - // }, - // ); - - // return { - // requestId, - // }; - // } - /** * V2: Field expert creates an expert-initiated blame file (BlameRequest with workflow). * LINK: creates request with parties identified by phone; expert sends link to user(s) who then fill via normal v2 flow. @@ -5822,7 +3579,9 @@ export class RequestManagementService { const isFileMakerRole = (expert as any)?.role === RoleEnum.FILE_MAKER; let expertBranchId: Types.ObjectId | undefined; if (isFileMakerRole) { - const fileMaker = await this.fileMakerDbService.findById(String(expert.sub)); + const fileMaker = await this.fileMakerDbService.findById( + String(expert.sub), + ); if (!fileMaker) { throw new ForbiddenException("FileMaker account not found."); } @@ -6524,29 +4283,6 @@ export class RequestManagementService { }; } - /** - * List all expert-initiated blame files for the current field expert (their panel). - * Only files where initiatedBy === current user are returned. - */ - async getMyExpertInitiatedFiles(expert: any): Promise { - const expertId = new Types.ObjectId(expert.sub); - const files = await this.requestManagementDbService.findAll({ - expertInitiated: true, - initiatedBy: expertId, - }); - return (files || []).map((f) => ({ - _id: f._id, - requestNumber: f.requestNumber, - type: f.type, - creationMethod: f.creationMethod, - blameStatus: f.blameStatus, - currentStep: f.currentStep, - nextStep: f.nextStep, - createdAt: f.createdAt, - steps: f.steps, - })); - } - /** * V2: List expert-initiated blame files (BlameRequest) for the current field expert. * Only files where initiatedByFieldExpertId === current expert are returned. @@ -6801,6 +4537,7 @@ export class RequestManagementService { hasClaim: boolean; shouldGuideToCreateClaim: boolean; claimRequestId?: string; + canContinueClaim?: boolean; }> { const none = { hasClaim: false, shouldGuideToCreateClaim: false }; if (!user?.sub || !Types.ObjectId.isValid(String(user.sub))) { @@ -6818,60 +4555,17 @@ export class RequestManagementService { hasClaim: true, shouldGuideToCreateClaim: false, claimRequestId: String(existingClaim._id), + ...(String(resolveClaimBeneficiary(blame)?.person?.userId ?? "") !== + currentUserId + ? { canContinueClaim: false } + : {}), }; } - if (blame.status !== CaseStatus.COMPLETED) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - - const parties = blame.parties || []; - - if (blame.type === BlameRequestType.CAR_BODY) { - const first = parties.find( - (p: any) => p?.role === PartyRole.FIRST || p?.role === "FIRST", - ); - const damagedId = first?.person?.userId - ? String(first.person.userId) - : null; - if (!damagedId || damagedId !== currentUserId) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - return { hasClaim: false, shouldGuideToCreateClaim: true }; - } - - if (blame.type === BlameRequestType.THIRD_PARTY) { - const guiltyRaw = blame.expert?.decision?.guiltyPartyId; - if (!guiltyRaw) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - const guiltyId = String(guiltyRaw); - if (currentUserId === guiltyId) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - const userParty = parties.find( - (p: any) => - p?.person?.userId && String(p.person.userId) === currentUserId, - ); - if (!userParty) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - if (parties.length < 2) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - const allSigned = parties.every( - (p: any) => p.confirmation !== undefined && p.confirmation !== null, - ); - const allAccepted = parties.every( - (p: any) => p.confirmation?.accepted === true, - ); - if (!allSigned || !allAccepted) { - return { hasClaim: false, shouldGuideToCreateClaim: false }; - } - return { hasClaim: false, shouldGuideToCreateClaim: true }; - } - - return none; + return { + hasClaim: false, + shouldGuideToCreateClaim: canUserCreateClaim(blame, currentUserId), + }; } /** Party payload for user blame detail: role links are visible, but participant PII and inquiry blobs remain private. */ @@ -7122,37 +4816,6 @@ export class RequestManagementService { }; } - /** - * Single endpoint handler: complete all blame-needed data. - * Routes to THIRD_PARTY or CAR_BODY completion based on request type. - */ - async completeBlameData( - expert: any, - requestId: string, - formData: any, - ): Promise { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - if (!request.expertInitiated) { - throw new BadRequestException( - "This endpoint is only for expert-initiated files", - ); - } - await this.verifyExpertAccess(request, expert); - - if (request.type === "THIRD_PARTY") { - return this.expertCompleteThirdPartyForm(expert, requestId, formData); - } - if (request.type === "CAR_BODY") { - return this.expertCompleteCarBodyForm(expert, requestId, formData); - } - throw new BadRequestException( - "Unknown file type. Must be THIRD_PARTY or CAR_BODY.", - ); - } - /** * V2: Expert completes blame data for IN_PERSON BlameRequest. * Delegates to expertCompleteThirdPartyFormV2 or expertCompleteCarBodyFormV2. @@ -7554,10 +5217,7 @@ export class RequestManagementService { desc: string, role: PartyRole, ) => { - const inquirySubmission = this.normalizeInquiryInput( - req.type, - plateDto, - ); + const inquirySubmission = this.normalizeInquiryInput(req.type, plateDto); await this.validateDrivingLicenceType(inquirySubmission); this.recordInquiryParticipantContext(req, role, inquirySubmission); const existingPartyIndex = this.getPartyIndex(req, role); @@ -7604,19 +5264,13 @@ export class RequestManagementService { "THIRD_PARTY", ); } - this.recordPartyCaseInquiryStatus( - req, - "thirdParty", - role, - true, - { - source: inquiry.offline?.source ?? "TEJARAT_BLOCK_INQUIRY", - plateKind: inquiry.plateKind, - attempts: inquiry.attempts, - raw: inquiry.raw, - mapped: inquiry.mapped, - }, - ); + this.recordPartyCaseInquiryStatus(req, "thirdParty", role, true, { + source: inquiry.offline?.source ?? "TEJARAT_BLOCK_INQUIRY", + plateKind: inquiry.plateKind, + attempts: inquiry.attempts, + raw: inquiry.raw, + mapped: inquiry.mapped, + }); const clientName = sandHubReport?.CompanyName || sandHubReport?.LastCompanyName; const companyCode = sandHubReport?.CompanyCode; @@ -8211,1121 +5865,6 @@ export class RequestManagementService { return { requestId: req._id, workflow: req.workflow, status: req.status }; } - /** - * Expert completes all information for IN_PERSON THIRD_PARTY file at once - * This replaces the step-by-step flow for experts filling files on-site - */ - async expertCompleteThirdPartyForm( - expert: any, - requestId: string, - formData: any, // ExpertCompleteThirdPartyFormDto - ): Promise { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - // Verify this is an expert-initiated IN_PERSON file - if (!request.expertInitiated) { - throw new BadRequestException( - "This endpoint is only for expert-initiated files", - ); - } - - if (request.creationMethod !== CreationMethod.IN_PERSON) { - throw new BadRequestException( - "This endpoint is only for IN_PERSON files. LINK-based files should be completed by users step-by-step.", - ); - } - - // Verify expert access - await this.verifyExpertAccess(request, expert); - - // Validate second party is provided for THIRD_PARTY type - if (request.type === "THIRD_PARTY" && !formData.secondParty) { - throw new BadRequestException( - "Second party information is required for THIRD_PARTY type files", - ); - } - - // Validate guilty party is provided for THIRD_PARTY type - if (request.type === "THIRD_PARTY" && !formData.guiltyPartyPhoneNumber) { - throw new BadRequestException( - "Guilty party phone number is required for THIRD_PARTY type files", - ); - } - - // Validate carBodyForm is provided for CAR_BODY type - if (request.type === "CAR_BODY" && !formData.carBodyForm) { - throw new BadRequestException( - "CAR_BODY form is required for CAR_BODY type files", - ); - } - - // Validate phone numbers are different - if ( - request.type === "THIRD_PARTY" && - formData.firstPartyPhoneNumber === formData.secondParty.phoneNumber - ) { - throw new BadRequestException( - "First and second party phone numbers must be different", - ); - } - - // The first party is the guilty party in every supported THIRD_PARTY flow. - if (request.type === "THIRD_PARTY") { - if (formData.guiltyPartyPhoneNumber !== formData.firstPartyPhoneNumber) { - throw new BadRequestException( - "The first party is the guilty party in this flow.", - ); - } - } - - try { - // Get or create user for first party phone number - const firstPartyUserId = await this.getOrCreateUserByPhoneNumber( - formData.firstPartyPhoneNumber, - ); - - // Collect all steps to be added - const stepsToAdd: StepsEnum[] = [StepsEnum.F_InitialForm]; - - // Initialize firstPartyDetails structure completely - const firstPartyDetails: any = { - firstPartyId: firstPartyUserId, - firstPartyPhoneNumber: formData.firstPartyPhoneNumber, - firstPartyInitialForm: { - expertOpinion: formData.firstPartyInitialForm.expertOpinion, - imDamaged: formData.firstPartyInitialForm.imDamaged, - imGuilty: formData.firstPartyInitialForm.imGuilty, - }, - firstPartyFile: { - descriptions: [formData.firstPartyDescription.desc], - }, - }; - - // Get or create user for second party phone number - const secondPartyUserId = await this.getOrCreateUserByPhoneNumber( - formData.secondParty.phoneNumber, - ); - - const secondPartyDetails: any = { - secondPartyId: secondPartyUserId, - secondPartyPhoneNumber: formData.secondParty.phoneNumber, - secondPartyInitialForm: { - expertOpinion: formData.secondParty.initialForm.expertOpinion, - imDamaged: formData.secondParty.initialForm.imDamaged, - imGuilty: formData.secondParty.initialForm.imGuilty, - }, - secondPartyFiles: { - descriptions: [formData.secondParty.description.desc], - }, - }; - - // Build comprehensive update payload - const updatePayload: any = { - $set: { - filledBy: FilledBy.EXPERT, - firstPartyDetails: firstPartyDetails, - firstPartyLocation: formData.firstPartyLocation, - secondPartyDetails: secondPartyDetails, - secondPartyLocation: formData.secondParty.location, - }, - }; - - // Add steps for location and description - stepsToAdd.push(StepsEnum.F_addLocation); - stepsToAdd.push(StepsEnum.F_addDescription); - stepsToAdd.push(StepsEnum.S_InitialForm); - stepsToAdd.push(StepsEnum.S_addLocation); - stepsToAdd.push(StepsEnum.S_addDescription); - - // Process first party plate with SandHub lookup - const firstInquirySubmission = this.normalizeInquiryInput( - BlameRequestType.THIRD_PARTY, - formData.firstPartyPlate, - ); - await this.validateDrivingLicenceType(firstInquirySubmission); - const firstPartyPlate = firstInquirySubmission.dto; - let firstPolicyInquiry: any; - try { - firstPolicyInquiry = firstInquirySubmission.participants.legacy - ? await (async () => { - const response = await this.sandHubService.getSandHubResponse({ - plate: firstPartyPlate.plate, - nationalCodeOfInsurer: firstPartyPlate.nationalCodeOfInsurer, - }); - return { - raw: response, - mapped: response["_doc"] || response, - plateKind: "CURRENT", - attempts: [ - { plateKind: "CURRENT", succeeded: true, usable: true }, - ], - }; - })() - : await this.getThirdPartyPlateInquiry(firstInquirySubmission); - const sandHubReport = firstPolicyInquiry.mapped; - await this.persistLegacyInquiryAudit( - requestId, - "firstPartyDetails", - firstInquirySubmission, - firstPolicyInquiry, - ); - this.sandHubService.assertInsuranceMatchesDeployment( - sandHubReport, - "THIRD_PARTY", - ); - - const clientName = - sandHubReport?.CompanyName || sandHubReport?.LastCompanyName; - const companyCode = sandHubReport?.CompanyCode; - - // Try to find client by company code first (more reliable) - const client = companyCode - ? await this.clientService.findOrCreateClientByCompanyCode( - companyCode, - clientName, - ) - : await this.clientService.findOne({ clientName: clientName }); - - if (!client) { - const error = new NotFoundException( - "شرکت بیمه موجود در پاسخ استعلام قابل شناسایی نیست.", - ); - await this.persistLegacyInquiryAudit( - requestId, - "firstPartyDetails", - firstInquirySubmission, - { - ...(firstPolicyInquiry ?? {}), - failed: true, - error: this.normalizeInquiryError(error), - }, - ); - throw error; - } - - // Add first party plate and related data to the existing firstPartyDetails object - firstPartyDetails.nationalCodeOfInsurer = - firstPartyPlate.nationalCodeOfInsurer; - firstPartyDetails.firstPartyPlate = firstPartyPlate.plate; - firstPartyDetails.firstPartyCarDetail = { - carName: sandHubReport?.MapTypNam || sandHubReport?.CarName, - insurerBirthday: firstPartyPlate.insurerBirthday, - driverBirthday: firstPartyPlate.driverBirthday, - driverLicenseDate: firstPartyPlate.driverLicenseDate, - carType: `${sandHubReport?.UsageField || ""} / ${sandHubReport?.MapUsageName || "-"}`, - isNewCar: firstPartyPlate.isNewCar, - }; - firstPartyDetails.firstPartyClient = { - clientId: (client as any)["_doc"]?._id || (client as any)._id, - clientName: clientName, - }; - firstPartyDetails.firstPartyCertificate = - firstPartyPlate.userNoCertificate; - firstPartyDetails.firstPartyInsuranceDetail = { - insuranceId: - sandHubReport?.LastCompanyDocumentNumber || - sandHubReport?.DocumentNumber, - insuranceCompany: clientName, - financialCommitmentCeiling: - sandHubReport?.FinancialCvrCptl || - sandHubReport?.FinancialCommitment, - startDate: sandHubReport?.IssueDate || sandHubReport?.StartDate, - endDate: sandHubReport?.EndDate, - }; - if (!firstInquirySubmission.participants.legacy) { - firstPartyDetails.participants = - firstInquirySubmission.participants.participants; - firstPartyDetails.participantRoles = - firstInquirySubmission.participants.roles; - firstPartyDetails.participantInquiries = - await this.collectLegacyParticipantInquiries( - firstInquirySubmission, - ); - firstPartyDetails.policyInquiry = firstPolicyInquiry; - firstPartyDetails.registrationState = - firstInquirySubmission.vehicle?.registrationState; - firstPartyDetails.previousPlateId = firstInquirySubmission.vehicle - ?.previousPlate - ? this.plateToPlateIdString( - firstInquirySubmission.vehicle.previousPlate, - ) - : undefined; - firstPartyDetails.previousPolicyholderNationalCode = - firstInquirySubmission.vehicle?.previousPolicyholderNationalCode; - firstPartyDetails.vehicleVin = firstInquirySubmission.vehicle?.vin; - } - - // Update the firstPartyDetails in the payload with all plate data - updatePayload.$set.firstPartyDetails = firstPartyDetails; - - stepsToAdd.push(StepsEnum.F_addPlate); - } catch (plateError) { - await this.persistLegacyInquiryAudit( - requestId, - "firstPartyDetails", - firstInquirySubmission, - { - ...(firstPolicyInquiry ?? {}), - failed: true, - attempts: (plateError as any)?.attempts ?? [], - error: this.normalizeInquiryError(plateError), - }, - ); - this.logger.error("Error processing first party plate:", plateError); - if (plateError instanceof HttpException) throw plateError; - throw new BadRequestException( - getInquiryErrorMessage(plateError, "thirdPartyPlate"), - ); - } - - // Process second party plate - const secondInquirySubmission = this.normalizeInquiryInput( - BlameRequestType.THIRD_PARTY, - formData.secondParty.plate, - ); - await this.validateDrivingLicenceType(secondInquirySubmission); - let secondPolicyInquiry: any; - try { - const secondPartyPlate = secondInquirySubmission.dto; - secondPolicyInquiry = secondInquirySubmission.participants.legacy - ? await (async () => { - const response = await this.sandHubService.getSandHubResponse({ - plate: secondPartyPlate.plate, - nationalCodeOfInsurer: secondPartyPlate.nationalCodeOfInsurer, - }); - return { - raw: response, - mapped: response["_doc"] || response, - plateKind: "CURRENT", - attempts: [ - { plateKind: "CURRENT", succeeded: true, usable: true }, - ], - }; - })() - : await this.getThirdPartyPlateInquiry(secondInquirySubmission); - const sandHubReport = secondPolicyInquiry.mapped; - await this.persistLegacyInquiryAudit( - requestId, - "secondPartyDetails", - secondInquirySubmission, - secondPolicyInquiry, - ); - - const clientName = - sandHubReport?.CompanyName || sandHubReport?.LastCompanyName; - const companyCode = sandHubReport?.CompanyCode; - - // Try to find client by company code first (more reliable) - const client = clientName - ? companyCode - ? await this.clientService.findOrCreateClientByCompanyCode( - companyCode, - clientName, - ) - : await this.clientService.findOne({ clientName: clientName }) - : null; - - if (!client) { - const error = new NotFoundException( - "شرکت بیمه موجود در پاسخ استعلام قابل شناسایی نیست.", - ); - await this.persistLegacyInquiryAudit( - requestId, - "secondPartyDetails", - secondInquirySubmission, - { - ...(secondPolicyInquiry ?? {}), - failed: true, - error: this.normalizeInquiryError(error), - }, - ); - throw error; - } - - // Add second party plate and related data to the existing secondPartyDetails object - secondPartyDetails.nationalCodeOfInsurer = - secondPartyPlate.nationalCodeOfInsurer; - secondPartyDetails.secondPartyPlate = secondPartyPlate.plate; - secondPartyDetails.secondPartyCarDetail = { - carName: sandHubReport?.MapTypNam || sandHubReport?.CarName, - insurerBirthday: secondPartyPlate.insurerBirthday, - driverBirthday: secondPartyPlate.driverBirthday, - carType: `${sandHubReport?.UsageField || ""} / ${sandHubReport?.MapUsageName || "-"}`, - isNewCar: secondPartyPlate.isNewCar, - }; - if (client) { - secondPartyDetails.secondPartyClient = { - clientId: (client as any)["_doc"]?._id || (client as any)._id, - clientName: clientName, - }; - } - secondPartyDetails.secondPartyCertificate = - secondPartyPlate.userNoCertificate; - secondPartyDetails.secondPartyInsuranceDetail = { - insuranceId: - sandHubReport?.LastCompanyDocumentNumber || - sandHubReport?.DocumentNumber, - insuranceCompany: clientName, - financialCommitmentCeiling: - sandHubReport?.FinancialCvrCptl || - sandHubReport?.FinancialCommitment, - startDate: sandHubReport?.IssueDate || sandHubReport?.StartDate, - endDate: sandHubReport?.EndDate, - }; - if (!secondInquirySubmission.participants.legacy) { - secondPartyDetails.participants = - secondInquirySubmission.participants.participants; - secondPartyDetails.participantRoles = - secondInquirySubmission.participants.roles; - secondPartyDetails.participantInquiries = - await this.collectLegacyParticipantInquiries( - secondInquirySubmission, - ); - secondPartyDetails.policyInquiry = secondPolicyInquiry; - secondPartyDetails.registrationState = - secondInquirySubmission.vehicle?.registrationState; - secondPartyDetails.previousPlateId = secondInquirySubmission.vehicle - ?.previousPlate - ? this.plateToPlateIdString( - secondInquirySubmission.vehicle.previousPlate, - ) - : undefined; - secondPartyDetails.previousPolicyholderNationalCode = - secondInquirySubmission.vehicle?.previousPolicyholderNationalCode; - secondPartyDetails.vehicleVin = secondInquirySubmission.vehicle?.vin; - } - - // Update the secondPartyDetails in the payload - updatePayload.$set.secondPartyDetails = secondPartyDetails; - - stepsToAdd.push(StepsEnum.S_addPlate); - } catch (plateError) { - await this.persistLegacyInquiryAudit( - requestId, - "secondPartyDetails", - secondInquirySubmission, - { - ...(secondPolicyInquiry ?? {}), - failed: true, - attempts: (plateError as any)?.attempts ?? [], - error: this.normalizeInquiryError(plateError), - }, - ); - this.logger.error("Error processing second party plate:", plateError); - if (plateError instanceof HttpException) throw plateError; - throw new BadRequestException( - getInquiryErrorMessage(plateError, "thirdPartyPlate"), - ); - } - - // Determine which party is guilty based on phone number - const guiltyMatchesFirst = - formData.guiltyPartyPhoneNumber === formData.firstPartyPhoneNumber; - const guiltyUserId = guiltyMatchesFirst - ? firstPartyUserId - : secondPartyDetails.secondPartyId; - - // Create initial expertSubmitReply with guiltyUserId - // Accident fields can be added separately via add-accident-fields endpoint - // This allows the file to proceed directly to signatures without expert review - updatePayload.$set.expertSubmitReply = { - description: - "Expert completed all information on-site. Awaiting signatures.", - guiltyUserId: guiltyUserId, - submitTime: new Date(), - fields: { - accidentWay: { - id: "", - label: "To be determined", - }, - accidentReason: { - id: "", - label: "To be determined", - fanavaran: 0, - }, - accidentType: { - id: "", - label: "To be determined", - }, - }, - firstPartyComment: null, - secondPartyComment: null, - }; - - updatePayload.$set.currentStep = StepsEnum.S_addDescription; - updatePayload.$set.nextStep = StepsEnum.AddSignatures; - updatePayload.$set.blameStatus = ReqBlameStatus.WaitingForSignatures; - - // Add all steps at once using $each to push multiple values - if (stepsToAdd.length > 0) { - updatePayload.$push = { - steps: { $each: stepsToAdd }, - }; - } - - // Execute the update - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - // Ensure expert assignment - await this.ensureExpertAssignment(requestId); - - // Add history events - await this.addHistoryEvent( - requestId, - "EXPERT_COMPLETED_ALL_INFORMATION", - new Types.ObjectId(expert.sub), - undefined, - "expert", - { - type: "THIRD_PARTY", - hasSecondParty: true, - }, - ); - - await this.addHistoryEvent( - requestId, - "READY_FOR_SIGNATURES", - new Types.ObjectId(expert.sub), - undefined, - "system", - ); - - // Read updated request - const updatedRequest = - await this.requestManagementDbService.findOne(requestId); - - return new RequestManagementDtoRs( - updatedRequest.firstPartyDetails?.firstPartyId, - updatedRequest?.secondPartyDetails?.secondPartyId || null, - StepsEnum.S_addDescription, - StepsEnum.AddSignatures, - "All information completed. Waiting for user signatures.", - updatedRequest._id.toString(), - ); - } catch (error) { - this.logger.error("Error in expertCompleteForm:", error); - if (error instanceof HttpException) { - throw error; - } - throw new InternalServerErrorException( - "Failed to complete form. Please try again.", - ); - } - } - - /** - * Expert completes all information for IN_PERSON CAR_BODY file at once - * This replaces the step-by-step flow for experts filling files on-site - */ - async expertCompleteCarBodyForm( - expert: any, - requestId: string, - formData: any, // ExpertCompleteCarBodyFormDto - ): Promise { - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - // Verify this is an expert-initiated IN_PERSON CAR_BODY file - if (!request.expertInitiated) { - throw new BadRequestException( - "This endpoint is only for expert-initiated files", - ); - } - - if (request.creationMethod !== CreationMethod.IN_PERSON) { - throw new BadRequestException( - "This endpoint is only for IN_PERSON files. LINK-based files should be completed by users step-by-step.", - ); - } - - if (request.type !== "CAR_BODY") { - throw new BadRequestException( - "This endpoint is only for CAR_BODY type files. Use complete-form-third-party for THIRD_PARTY files.", - ); - } - - // Verify expert access - await this.verifyExpertAccess(request, expert); - - // Validate carBodyForm is provided - if (!formData.carBodyForm) { - throw new BadRequestException( - "CAR_BODY form is required for CAR_BODY type files", - ); - } - - this.assertCarBodyDescriptionMinimum( - request.type, - formData.firstPartyDescription?.desc, - ); - - this.assertAccidentDateTimeNotInFuture({ - accidentDate: formData.firstPartyDescription?.accidentDate, - accidentTime: formData.firstPartyDescription?.accidentTime, - }); - - try { - // Get or create user for first party phone number - const firstPartyUserId = await this.getOrCreateUserByPhoneNumber( - formData.firstPartyPhoneNumber, - ); - - // Collect all steps to be added - const stepsToAdd: StepsEnum[] = [StepsEnum.CarBodyForm]; - - // Initialize firstPartyDetails structure completely - const firstPartyDetails: any = { - firstPartyId: firstPartyUserId, - firstPartyPhoneNumber: formData.firstPartyPhoneNumber, - firstPartyInitialForm: { - expertOpinion: formData.firstPartyInitialForm.expertOpinion, - imDamaged: formData.firstPartyInitialForm.imDamaged, - imGuilty: formData.firstPartyInitialForm.imGuilty, - }, - firstPartyFile: { - descriptions: [formData.firstPartyDescription.desc], - }, - carBodyForm: { - firstPartyId: firstPartyUserId, - firstPartyPhoneNumber: formData.firstPartyPhoneNumber, - carBodyForm: formData.carBodyForm, - // Assume guilty by default if accident was with another car - isGuilty: formData.carBodyForm.car ? true : false, - }, - }; - - // CAR_BODY specific fields - if (formData.firstPartyDescription.accidentDate) { - firstPartyDetails.firstPartyFile.accidentDate = - formData.firstPartyDescription.accidentDate; - } - if (formData.firstPartyDescription.accidentTime) { - firstPartyDetails.firstPartyFile.accidentTime = - formData.firstPartyDescription.accidentTime; - } - if (formData.firstPartyDescription.weatherCondition) { - firstPartyDetails.firstPartyFile.weatherCondition = - formData.firstPartyDescription.weatherCondition; - } - if (formData.firstPartyDescription.roadCondition) { - firstPartyDetails.firstPartyFile.roadCondition = - formData.firstPartyDescription.roadCondition; - } - if (formData.firstPartyDescription.lightCondition) { - firstPartyDetails.firstPartyFile.lightCondition = - formData.firstPartyDescription.lightCondition; - } - - // Build comprehensive update payload - const updatePayload: any = { - $set: { - filledBy: FilledBy.EXPERT, - firstPartyDetails: firstPartyDetails, - firstPartyLocation: formData.firstPartyLocation, - }, - }; - - // Add steps for location and description - stepsToAdd.push(StepsEnum.F_addLocation); - stepsToAdd.push(StepsEnum.F_addDescription); - - // Process first party plate with SandHub lookup - const firstInquirySubmission = this.normalizeInquiryInput( - BlameRequestType.CAR_BODY, - formData.firstPartyPlate, - ); - await this.validateDrivingLicenceType(firstInquirySubmission); - const firstPartyPlate = firstInquirySubmission.dto; - let thirdPartyPolicyInquiry: any; - let carBodyInquiry: any; - try { - thirdPartyPolicyInquiry = firstInquirySubmission.participants.legacy - ? await (async () => { - const response = await this.sandHubService.getSandHubResponse({ - plate: firstPartyPlate.plate, - nationalCodeOfInsurer: firstPartyPlate.nationalCodeOfInsurer, - }); - return { - raw: response, - mapped: response["_doc"] || response, - plateKind: "CURRENT", - attempts: [ - { plateKind: "CURRENT", succeeded: true, usable: true }, - ], - }; - })() - : await this.getThirdPartyPlateInquiry(firstInquirySubmission); - const sandHubReport = thirdPartyPolicyInquiry.mapped; - await this.persistLegacyInquiryAudit( - requestId, - "firstPartyDetails", - firstInquirySubmission, - { thirdParty: thirdPartyPolicyInquiry }, - ); - - const clientName = - sandHubReport?.CompanyName || sandHubReport?.LastCompanyName; - const companyCode = sandHubReport?.CompanyCode; - - // Try to find client by company code first (more reliable) - const client = companyCode - ? await this.clientService.findOrCreateClientByCompanyCode( - companyCode, - clientName, - ) - : await this.clientService.findOne({ clientName: clientName }); - - if (!client) { - const error = new NotFoundException( - "شرکت بیمه موجود در پاسخ استعلام قابل شناسایی نیست.", - ); - await this.persistLegacyInquiryAudit( - requestId, - "firstPartyDetails", - firstInquirySubmission, - { - thirdParty: thirdPartyPolicyInquiry, - failed: true, - error: this.normalizeInquiryError(error), - }, - ); - throw error; - } - - // Add first party plate and related data to the existing firstPartyDetails object - firstPartyDetails.nationalCodeOfInsurer = - firstPartyPlate.nationalCodeOfInsurer; - firstPartyDetails.firstPartyPlate = firstPartyPlate.plate; - firstPartyDetails.firstPartyCarDetail = { - carName: sandHubReport?.MapTypNam || sandHubReport?.CarName, - insurerBirthday: firstPartyPlate.insurerBirthday, - driverBirthday: firstPartyPlate.driverBirthday, - driverLicenseDate: firstPartyPlate.driverLicenseDate, - carType: `${sandHubReport?.UsageField || ""} / ${sandHubReport?.MapUsageName || "-"}`, - isNewCar: firstPartyPlate.isNewCar, - }; - firstPartyDetails.firstPartyClient = { - clientId: (client as any)["_doc"]?._id || (client as any)._id, - clientName: clientName, - }; - firstPartyDetails.firstPartyCertificate = - firstPartyPlate.userNoCertificate; - firstPartyDetails.firstPartyInsuranceDetail = { - insuranceId: - sandHubReport?.LastCompanyDocumentNumber || - sandHubReport?.DocumentNumber, - insuranceCompany: clientName, - financialCommitmentCeiling: - sandHubReport?.FinancialCvrCptl || - sandHubReport?.FinancialCommitment, - startDate: sandHubReport?.IssueDate || sandHubReport?.StartDate, - endDate: sandHubReport?.EndDate, - }; - - // CAR_BODY specific insurance info - carBodyInquiry = firstInquirySubmission.participants.legacy - ? await this.sandHubService.getCarBodyInquiry({ - nationalCodeOfInsurer: firstPartyPlate.nationalCodeOfInsurer, - plate: firstPartyPlate.plate, - } as any) - : await this.getCarBodyPlateInquiry(firstInquirySubmission); - const carBodyInfo = carBodyInquiry.mapped as any; - - firstPartyDetails.firstPartyCarBodyInsuranceDetail = { - policyNumber: carBodyInfo.policyNumber, - startDate: carBodyInfo.startDate, - endDate: carBodyInfo.endDate, - insurerCompany: carBodyInfo.insurerCompany, - coverages: carBodyInfo.coverages, - raw: carBodyInquiry.raw, - source: carBodyInquiry.source, - }; - if (!firstInquirySubmission.participants.legacy) { - firstPartyDetails.participants = - firstInquirySubmission.participants.participants; - firstPartyDetails.participantRoles = - firstInquirySubmission.participants.roles; - firstPartyDetails.participantInquiries = - await this.collectLegacyParticipantInquiries( - firstInquirySubmission, - ); - firstPartyDetails.policyInquiry = { - thirdParty: thirdPartyPolicyInquiry, - carBody: { - source: carBodyInquiry.source, - plateKind: carBodyInquiry.plateKind, - attempts: carBodyInquiry.attempts, - raw: carBodyInquiry.raw, - mapped: carBodyInquiry.mapped, - }, - }; - firstPartyDetails.registrationState = - firstInquirySubmission.vehicle?.registrationState; - firstPartyDetails.previousPlateId = firstInquirySubmission.vehicle - ?.previousPlate - ? this.plateToPlateIdString( - firstInquirySubmission.vehicle.previousPlate, - ) - : undefined; - firstPartyDetails.previousPolicyholderNationalCode = - firstInquirySubmission.vehicle?.previousPolicyholderNationalCode; - firstPartyDetails.vehicleVin = firstInquirySubmission.vehicle?.vin; - } - firstPartyDetails.firstPartyClient.clientId = - await this.resolveCarBodyPolicyClientId(carBodyInfo); - - // Update the firstPartyDetails in the payload with all plate data - updatePayload.$set.firstPartyDetails = firstPartyDetails; - - stepsToAdd.push(StepsEnum.F_addPlate); - } catch (plateError) { - await this.persistLegacyInquiryAudit( - requestId, - "firstPartyDetails", - firstInquirySubmission, - { - ...(thirdPartyPolicyInquiry - ? { thirdParty: thirdPartyPolicyInquiry } - : {}), - ...(carBodyInquiry - ? { - carBody: { - source: carBodyInquiry.source, - plateKind: carBodyInquiry.plateKind, - attempts: carBodyInquiry.attempts, - raw: carBodyInquiry.raw, - mapped: carBodyInquiry.mapped, - }, - } - : {}), - failed: true, - attempts: (plateError as any)?.attempts ?? [], - error: this.normalizeInquiryError(plateError), - }, - ); - this.logger.error("Error processing first party plate:", plateError); - if (plateError instanceof HttpException) throw plateError; - throw new BadRequestException(getInquiryErrorMessage(plateError)); - } - - // For CAR_BODY: Create expertSubmitReply - // First party is guilty by default if accident was with another car - const guiltyUserId = firstPartyUserId; - - // Accident fields can be added separately via add-accident-fields endpoint - updatePayload.$set.expertSubmitReply = { - description: - "Expert completed all information on-site. Awaiting signature.", - guiltyUserId: guiltyUserId, - submitTime: new Date(), - fields: { - accidentWay: { - id: "", - label: "To be determined", - }, - accidentReason: { - id: "", - label: "To be determined", - fanavaran: 0, - }, - accidentType: { - id: "", - label: "To be determined", - }, - }, - firstPartyComment: null, - secondPartyComment: null, - }; - - updatePayload.$set.currentStep = StepsEnum.F_addDescription; - updatePayload.$set.nextStep = StepsEnum.AddSignatures; - updatePayload.$set.blameStatus = ReqBlameStatus.WaitingForSignatures; - - // Add all steps at once using $each to push multiple values - if (stepsToAdd.length > 0) { - updatePayload.$push = { - steps: { $each: stepsToAdd }, - }; - } - - // Execute the update - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - updatePayload, - ); - - // Ensure expert assignment - await this.ensureExpertAssignment(requestId); - - // Add history events - await this.addHistoryEvent( - requestId, - "EXPERT_COMPLETED_ALL_INFORMATION", - new Types.ObjectId(expert.sub), - undefined, - "expert", - { - type: "CAR_BODY", - hasSecondParty: false, - }, - ); - - await this.addHistoryEvent( - requestId, - "READY_FOR_SIGNATURES", - new Types.ObjectId(expert.sub), - undefined, - "system", - ); - - // Read updated request - const updatedRequest = - await this.requestManagementDbService.findOne(requestId); - - return new RequestManagementDtoRs( - updatedRequest.firstPartyDetails?.firstPartyId, - null, - StepsEnum.F_addDescription, - StepsEnum.AddSignatures, - "All information completed. Waiting for user signature.", - updatedRequest._id.toString(), - ); - } catch (error) { - this.logger.error("Error in expertCompleteCarBodyForm:", error); - if (error instanceof HttpException) { - throw error; - } - throw new InternalServerErrorException( - "Failed to complete form. Please try again.", - ); - } - } - - /** - * Expert uploads video for expert-initiated file - * Only one video is needed per file (not per party) - */ - async expertUploadVideo( - expert: any, - requestId: string, - file: Express.Multer.File, - ): Promise { - if (!file) { - throw new BadRequestException("Video file is required"); - } - - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - // Verify this is an expert-initiated file - if (!request.expertInitiated) { - throw new BadRequestException( - "This endpoint is only for expert-initiated files", - ); - } - - // Verify expert access - await this.verifyExpertAccess(request, expert); - - // Check if video already exists - const stepToCheck = - request.type === "THIRD_PARTY" - ? StepsEnum.F_videoUpload - : StepsEnum.CarBodyVideo; - if (request.steps?.includes(stepToCheck)) { - throw new BadRequestException( - "Video has already been uploaded for this file", - ); - } - - try { - // Create video document - const videoDocument = await this.blameVideoDbService.create({ - fileName: file.filename, - path: file.path, - requestId: new Types.ObjectId(requestId), - }); - - // Determine the step based on request type - const stepToPush = - request.type === "THIRD_PARTY" - ? StepsEnum.F_videoUpload - : StepsEnum.CarBodyVideo; - const currentStepValue = stepToPush; - const nextStepValue = StepsEnum.F_addPlate; - - // Update request with video - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - $push: { steps: stepToPush }, - $set: { - currentStep: currentStepValue, - "firstPartyDetails.firstPartyFile.firstPartyVideoId": - videoDocument["_doc"]._id, - nextStep: nextStepValue, - }, - }, - ); - - // Add history event - await this.addHistoryEvent( - requestId, - "EXPERT_UPLOADED_VIDEO", - new Types.ObjectId(expert.sub), - undefined, - "expert", - { - videoId: videoDocument["_doc"]._id.toString(), - fileName: file.filename, - }, - ); - - return new RequestManagementDtoRs( - request.firstPartyDetails?.firstPartyId || - new Types.ObjectId(expert.sub), - request?.secondPartyDetails?.secondPartyId || null, - currentStepValue, - nextStepValue, - "Video uploaded successfully", - request._id, - ); - } catch (error) { - this.logger.error("Error uploading expert video:", error); - if (error instanceof HttpException) { - throw error; - } - throw new InternalServerErrorException("Failed to upload video"); - } - } - - /** - * Expert uploads voice for expert-initiated file - * Only one voice is needed per file (not per party) - */ - async expertUploadVoice( - expert: any, - requestId: string, - voice: Express.Multer.File, - ): Promise { - if (!voice) { - throw new BadRequestException("Voice file is required"); - } - - const request = await this.requestManagementDbService.findOne(requestId); - if (!request) { - throw new NotFoundException("Request not found"); - } - - // Verify this is an expert-initiated file - if (!request.expertInitiated) { - throw new BadRequestException( - "This endpoint is only for expert-initiated files", - ); - } - - // Verify expert access - await this.verifyExpertAccess(request, expert); - - // Check if voice already exists (check both first and second party steps) - if ( - request.steps?.includes(StepsEnum.F_addVoice) || - request.steps?.includes(StepsEnum.S_addVoice) - ) { - throw new BadRequestException( - "Voice has already been uploaded for this file", - ); - } - - try { - // Create voice document - const voiceDoc = await this.blameVoiceDbService.create({ - fileName: voice.filename, - path: voice.path, - requestId: new Types.ObjectId(requestId), - context: UploadContext.INITIAL, // Use INITIAL context for expert uploads - }); - - // Determine current step and next step based on request state - // If description is already added, next step is different - const hasDescription = - request.steps?.includes(StepsEnum.F_addDescription) || - request.steps?.includes(StepsEnum.S_addDescription); - - const currentStep = - request.type === "THIRD_PARTY" - ? StepsEnum.F_addVoice - : StepsEnum.F_addVoice; - - const nextStep = hasDescription - ? request.type === "THIRD_PARTY" - ? StepsEnum.AddSignatures - : StepsEnum.AddSignatures - : request.type === "THIRD_PARTY" - ? StepsEnum.F_addDescription - : StepsEnum.F_addDescription; - - // Update request with voice - // For expert uploads, we store it in firstPartyFile but it represents the entire file - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - $push: { - "firstPartyDetails.firstPartyFile.voices": voiceDoc["_id"], - steps: StepsEnum.F_addVoice, - }, - $set: { - currentStep: currentStep, - nextStep: nextStep, - }, - }, - ); - - // Add history event - await this.addHistoryEvent( - requestId, - "EXPERT_UPLOADED_VOICE", - new Types.ObjectId(expert.sub), - undefined, - "expert", - { - voiceId: voiceDoc["_id"].toString(), - fileName: voice.filename, - }, - ); - - const message = hasDescription - ? "Voice uploaded successfully. File is ready for signatures." - : "Voice uploaded successfully. Please add description."; - - return new RequestManagementDtoRs( - request.firstPartyDetails?.firstPartyId || - new Types.ObjectId(expert.sub), - request?.secondPartyDetails?.secondPartyId || null, - currentStep, - nextStep, - message, - request._id, - ); - } catch (error) { - this.logger.error("Error uploading expert voice:", error); - if (error instanceof HttpException) { - throw error; - } - throw new InternalServerErrorException("Failed to upload voice"); - } - } - /** * Expert adds accident fields to expert-initiated file * Can be used for both IN_PERSON and LINK-based files @@ -9435,42 +5974,6 @@ export class RequestManagementService { }; } - /** - * Check if request is expert-initiated and should be auto-assigned - */ - async ensureExpertAssignment(requestId: string): Promise { - const request = await this.requestManagementDbService.findOne(requestId); - - if (request?.expertInitiated && request.initiatedBy) { - // Ensure the file is assigned to the initiating expert - if ( - !request.assignedExpertId || - String(request.assignedExpertId) !== String(request.initiatedBy) - ) { - await this.requestManagementDbService.findAndUpdate( - { _id: requestId }, - { - $set: { - assignedExpertId: request.initiatedBy, - }, - }, - ); - - // Add history event - await this.addHistoryEvent( - requestId, - "AUTO_ASSIGNED_TO_EXPERT", - request.initiatedBy, - undefined, - "system", - { - expertId: request.initiatedBy.toString(), - }, - ); - } - } - } - /** * Get or create a user by phone number * Used for IN_PERSON expert-initiated files where expert provides phone numbers @@ -10091,10 +6594,7 @@ export class RequestManagementService { partyRole: PartyRole, party: any, ): Promise<{ clientId?: string; subjects: InquirySubjects }> { - const inquirySubmission = this.normalizeInquiryInput( - req.type, - partyData, - ); + const inquirySubmission = this.normalizeInquiryInput(req.type, partyData); await this.validateDrivingLicenceType(inquirySubmission); partyData = inquirySubmission.dto as RunInquiriesV3Dto; const subjects = resolveInquirySubjects(inquirySubmission); @@ -10121,19 +6621,13 @@ export class RequestManagementService { if (inquiry.offline?.source) { inquirySource = inquiry.offline.source; } - this.recordPartyCaseInquiryStatus( - req, - "thirdParty", - partyRole, - true, - { - source: inquirySource, - plateKind: inquiry.plateKind, - attempts: inquiry.attempts, - raw: inquiryRaw, - mapped: inquiryMapped, - }, - ); + this.recordPartyCaseInquiryStatus(req, "thirdParty", partyRole, true, { + source: inquirySource, + plateKind: inquiry.plateKind, + attempts: inquiry.attempts, + raw: inquiryRaw, + mapped: inquiryMapped, + }); if (inquiry.offline?.fanavaranDriverId != null) { if (!party.person) party.person = {} as any; party.person.fanavaranDriverId = inquiry.offline.fanavaranDriverId; @@ -10249,7 +6743,9 @@ export class RequestManagementService { party.person.driverLicenseDate = (partyData as any).driverLicenseDate; if ((partyData as any).licenseType) (party.person as any).licenseType = (partyData as any).licenseType; - (party.person as any).licenseTypeLabel = (partyData as any).licenseTypeLabel; + (party.person as any).licenseTypeLabel = ( + partyData as any + ).licenseTypeLabel; if (!party.vehicle) party.vehicle = {} as any; party.vehicle.plateId = this.plateToPlateIdString(partyData.plate); @@ -10447,9 +6943,7 @@ export class RequestManagementService { clientId?: string, ): Promise { if (!String(sheba ?? "").trim()) { - throw new BadRequestException( - "شماره شبا برای طرف زیان‌دیده الزامی است.", - ); + throw new BadRequestException("شماره شبا برای طرف زیان‌دیده الزامی است."); } await this.sandHubService.getShebaValidation( vehicleOwnerNationalCode, @@ -11023,10 +7517,7 @@ export class RequestManagementService { partyRole: PartyRole, party: any, ): Promise<{ clientId?: string; subjects: InquirySubjects }> { - const inquirySubmission = this.normalizeInquiryInput( - req.type, - partyData, - ); + const inquirySubmission = this.normalizeInquiryInput(req.type, partyData); await this.validateDrivingLicenceType(inquirySubmission); partyData = inquirySubmission.dto as RunInquiriesVinV3Dto; const subjects = resolveInquirySubjects(inquirySubmission); @@ -11045,17 +7536,11 @@ export class RequestManagementService { ); inquiryRaw = inquiry.raw; inquiryMapped = inquiry.mapped; - this.recordPartyCaseInquiryStatus( - req, - "thirdParty", - partyRole, - true, - { - source: "ESG_VIN_INQUIRY", - raw: inquiryRaw, - mapped: inquiryMapped, - }, - ); + this.recordPartyCaseInquiryStatus(req, "thirdParty", partyRole, true, { + source: "ESG_VIN_INQUIRY", + raw: inquiryRaw, + mapped: inquiryMapped, + }); } catch (err: any) { this.logger.error( `[V3-VIN] vin inquiry failed for ${roleLabel} party (request=${req._id}): ${err?.message || err}`, @@ -11161,7 +7646,9 @@ export class RequestManagementService { party.person.driverLicenseDate = (partyData as any).driverLicenseDate; if ((partyData as any).licenseType) (party.person as any).licenseType = (partyData as any).licenseType; - (party.person as any).licenseTypeLabel = (partyData as any).licenseTypeLabel; + (party.person as any).licenseTypeLabel = ( + partyData as any + ).licenseTypeLabel; if (!party.vehicle) party.vehicle = {} as any; // Derive plateId from the plate parts returned by the VIN inquiry. @@ -11766,13 +8253,6 @@ export class RequestManagementService { }; } - /** - * @deprecated V3 blame completes via expertUploadBlameVideoV3 (WAITING_FOR_EXPERT). - */ - async tryAutoCompleteBlameV3ForField(_req: any): Promise { - return; - } - private partyHasInquiryData(req: any, role: PartyRole): boolean { const roleKey = role === PartyRole.FIRST ? "FIRST" : "SECOND"; if (req.inquiries?.thirdParty?.data?.[roleKey]) return true; @@ -13224,8 +9704,7 @@ export class RequestManagementService { } } const files = (ownFiles || []).filter( - (file: any) => - !file.branchId || String(file.branchId) === makerBranchId, + (file: any) => !file.branchId || String(file.branchId) === makerBranchId, ); const blameIds = (files || []).map((f: any) => f._id).filter(Boolean); const claims = @@ -13462,9 +9941,7 @@ export class RequestManagementService { ) ).filter((file): file is any => file != null); - const visibleBlameIds = visibleFiles - .map((f: any) => f._id) - .filter(Boolean); + const visibleBlameIds = visibleFiles.map((f: any) => f._id).filter(Boolean); const claims = visibleBlameIds.length > 0 ? await this.claimCaseDbService.find( diff --git a/src/request-management/request-management.user-progress.spec.ts b/src/request-management/request-management.user-progress.spec.ts index 9380731..ea37cb6 100644 --- a/src/request-management/request-management.user-progress.spec.ts +++ b/src/request-management/request-management.user-progress.spec.ts @@ -141,6 +141,30 @@ describe("user blame next action and claim eligibility", () => { expect(service.claimCaseDbService.findOne).not.toHaveBeenCalled(); }); + it("shows an existing claim as actionable only to its beneficiary", async () => { + const service = subject(); + for (const [viewer, nextAction] of [ + [guiltyId, "VIEW_RESULT"], + [damagedId, "CONTINUE_CLAIM"], + ]) { + const hint = await service.computeClaimCreationHintForViewer( + blame(), + { sub: viewer }, + { _id: blameId }, + ); + expect(resolveBlameUserNextAction("COMPLETED", {}, hint)).toBe( + nextAction, + ); + } + const unknown = blame({ expert: { decision: { guiltyPartyId: blameId } } }); + const hint = await service.computeClaimCreationHintForViewer( + unknown, + { sub: damagedId }, + null, + ); + expect(hint.shouldGuideToCreateClaim).toBe(false); + }); + it("permits a completed body-insurance claim only for its own party", async () => { const service = subject(); const body = blame({ @@ -172,15 +196,13 @@ describe("user blame next action and claim eligibility", () => { it("keeps identity filters working but omits private/search-only fields in list responses", async () => { const service = subject(); service.blameRequestDbService = { - find: jest - .fn() - .mockResolvedValue([ - blame({ - __v: 42, - inquiries: { raw: "private" }, - initiatedByFieldExpertId: guiltyId, - }), - ]), + find: jest.fn().mockResolvedValue([ + blame({ + __v: 42, + inquiries: { raw: "private" }, + initiatedByFieldExpertId: guiltyId, + }), + ]), }; const response = await service.getAllBlameRequestsV2( { sub: damagedId, role: RoleEnum.USER }, diff --git a/src/sand-hub/entity/db-service/sand-hub.db.service.ts b/src/sand-hub/entity/db-service/sand-hub.db.service.ts deleted file mode 100644 index 1e11aae..0000000 --- a/src/sand-hub/entity/db-service/sand-hub.db.service.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { InjectModel } from "@nestjs/mongoose"; -import { Model, Types, UpdateQuery } from "mongoose"; -import { SandHubInterface, SandHubModel } from "../schema/sand-hub.schema"; - -export class SandHubDbService { - constructor( - @InjectModel(SandHubModel.name) - private readonly sandHubModel: Model, - ) {} - - async create(sandHubData: any): Promise { - return await this.sandHubModel.create(sandHubData); - } - - async findOneByRequestId(requestId: string, userId): Promise { - return await this.sandHubModel.findOne({ requestId, userId }); - } - - async findOneBySandHubId(requestId: string): Promise { - return await this.sandHubModel.findOne({ - _id: new Types.ObjectId(requestId), - }); - } - - async findOneByRequestIdAndUpdate( - requestId: string, - userId: string, - update: UpdateQuery, - ): Promise { - return await this.sandHubModel.findOneAndUpdate( - { requestId, userId }, - update, - ); - } -} diff --git a/src/sand-hub/sand-hub.module.ts b/src/sand-hub/sand-hub.module.ts index f02c30b..705c30c 100644 --- a/src/sand-hub/sand-hub.module.ts +++ b/src/sand-hub/sand-hub.module.ts @@ -8,7 +8,6 @@ import { SystemSettingsModule } from "src/system-settings/system-settings.module import { PlateNormalizerModule } from "src/utils/plate-normalizer/plate-normalizer.module"; import { OfflineInquiryModule } from "src/offline-inquiry/offline-inquiry.module"; import { LookupsModule } from "src/lookups/lookups.module"; -import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service"; import { SandHubModel, SandHubSchema } from "./entity/schema/sand-hub.schema"; import { SandHubService } from "./sand-hub.service"; @@ -28,8 +27,8 @@ import { SandHubService } from "./sand-hub.service"; { name: SandHubModel.name, schema: SandHubSchema }, ]), ], - providers: [SandHubService, SandHubDbService], - exports: [SandHubService, SandHubDbService], + providers: [SandHubService], + exports: [SandHubService], controllers: [], }) export class SandHubModule {} diff --git a/src/sand-hub/sand-hub.service.spec.ts b/src/sand-hub/sand-hub.service.spec.ts index ccaf633..626c059 100644 --- a/src/sand-hub/sand-hub.service.spec.ts +++ b/src/sand-hub/sand-hub.service.spec.ts @@ -10,7 +10,6 @@ import { isMappedPolicyCurrent } from "src/request-management/inquiry-participan describe("SandHubService inquiry mocks", () => { const httpService = { post: jest.fn() }; - const sandHubDbService = { findOneBySandHubId: jest.fn() }; const externalInquirySettings = { isInquiryLive: jest.fn(), getMockCompanyContext: jest.fn(), @@ -44,7 +43,6 @@ describe("SandHubService inquiry mocks", () => { delete process.env.FANAVARAN_CLIENT; service = new SandHubService( httpService as any, - sandHubDbService as any, externalInquirySettings as unknown as ExternalInquirySettingsService, plateNormalizer as any, offlineInquiryService as any, diff --git a/src/sand-hub/sand-hub.service.ts b/src/sand-hub/sand-hub.service.ts index 1891fcb..4906bd7 100644 --- a/src/sand-hub/sand-hub.service.ts +++ b/src/sand-hub/sand-hub.service.ts @@ -10,20 +10,13 @@ import { ServiceUnavailableException, UnauthorizedException, } from "@nestjs/common"; -import { SandHubDbService } from "src/sand-hub/entity/db-service/sand-hub.db.service"; -import { SandHubModel } from "src/sand-hub/entity/schema/sand-hub.schema"; -import { ExternalInquirySettingsService } from "src/client/external-inquiry-settings.service"; -import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service"; -import type { ExternalInquiryType } from "src/common/types/external-inquiry.types"; -import type { MockInquiryCompanyContext } from "src/common/types/external-inquiry.types"; -import { OfflineInquiryService } from "src/offline-inquiry/offline-inquiry.service"; -import { LookupsService } from "src/lookups/lookups.service"; -import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; -import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto"; -import { jalaliToGregorianDate } from "src/helpers/date-jalali"; import { firstValueFrom } from "rxjs"; -import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper"; import type { Plates } from "src/Types&Enums/plate.interface"; +import { ExternalInquirySettingsService } from "src/client/external-inquiry-settings.service"; +import type { + ExternalInquiryType, + MockInquiryCompanyContext, +} from "src/common/types/external-inquiry.types"; import { getInquiryErrorMessage, inquiryErrorStatus, @@ -31,6 +24,14 @@ import { isInquiryTimeout, type InquiryErrorContext, } from "src/common/utils/inquiry-error"; +import { resolveFanavaranClientKey } from "src/core/config/fanavaran-client.config"; +import { jalaliToGregorianDate } from "src/helpers/date-jalali"; +import { LookupsService } from "src/lookups/lookups.service"; +import { OfflineInquiryService } from "src/offline-inquiry/offline-inquiry.service"; + +import { PlateNormalizerService } from "src/utils/plate-normalizer/plate-normalizer.service"; +import { SandHubDetailDto, SandHubInquiryOptions } from "./dto/sand-hub.dto"; +import { mapEsgCarBodyPolicyToInquiry } from "./esg-car-body-inquiry.mapper"; type CarBodyInquiryDetail = Omit & { plate: Plates | string; @@ -52,7 +53,7 @@ export class SandHubService { constructor( private readonly httpService: HttpService, - private readonly sandHubDbService: SandHubDbService, + private readonly externalInquirySettings: ExternalInquirySettingsService, private readonly plateNormalizer: PlateNormalizerService, private readonly offlineInquiryService: OfflineInquiryService, @@ -977,10 +978,6 @@ export class SandHubService { return { raw, mapped }; } - async getSandHubDataFromId(sandHubId) { - return await this.sandHubDbService.findOneBySandHubId(sandHubId); - } - /** * CAR_BODY is the only ESG product that uses the processed Fanavaran lookup. * THIRD_PARTY remains on its established provider-specific inquiry path. @@ -1781,25 +1778,4 @@ export class SandHubService { ); } } - - async sandHubDocumentCreator( - userId: string, - requestId: string, - doc: Partial, - ) { - const existingDoc = await this.sandHubDbService.findOneByRequestId( - requestId, - userId, - ); - if (!existingDoc) { - return await this.sandHubDbService.create({ ...doc, userId, requestId }); - } else { - const updatePayload = { ...existingDoc, ...doc }; - return await this.sandHubDbService.findOneByRequestIdAndUpdate( - requestId, - userId, - updatePayload, - ); - } - } } diff --git a/src/super-admin/super-admin.controller.ts b/src/super-admin/super-admin.controller.ts index 8c39f0e..e94f958 100644 --- a/src/super-admin/super-admin.controller.ts +++ b/src/super-admin/super-admin.controller.ts @@ -1,6 +1,3 @@ -import { AiService } from "src/ai/ai.service"; -import { currentAiCaptures } from "src/ai/ai-captures"; -import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; import { BadRequestException, Body, @@ -23,40 +20,38 @@ import { ApiTags, } from "@nestjs/swagger"; import { Types } from "mongoose"; -import { SuperAdminGuard } from "./guards/super-admin.guard"; -import { SuperAdminService } from "./super-admin.service"; -import { - CreateSuperAdminDto, - CreateFieldExpertAdminDto, - CreateRegistrarAdminDto, - CreateCallCenterAgentDto, -} from "./dto/super-admin.dto"; +import { currentAiCaptures } from "src/ai/ai-captures"; +import { AiService } from "src/ai/ai.service"; +import { InsurerRegisterDto } from "src/auth/dto/actor/register.actor.dto"; +import { ClaimCaseDbService } from "src/claim-request-management/entites/db-service/claim-case.db.service"; +import { CreateBranchDto } from "src/client/dto/create-branch.dto"; import { ClientDto } from "src/client/dto/create-client.dto"; -import { - InsurerRegisterDto, - GenuineRegisterDto, - LegalRegisterDto, -} from "src/auth/dto/actor/register.actor.dto"; -import { SystemSettingsService } from "src/system-settings/system-settings.service"; -import { - SystemSettingsResponseDto, - UpdateSystemSettingsDto, -} from "src/system-settings/dto/system-settings.dto"; import { SetExternalInquiriesLiveDto } from "src/client/dto/external-inquiries-live.dto"; -import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service"; import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; import { UnifiedFileStatusReportDto, UnifiedFileStatusReportQueryDto, } from "src/common/dto/unified-file-status-report.dto"; -import { CreateBranchDto } from "src/client/dto/create-branch.dto"; -import { FileRating } from "src/request-management/entities/schema/request-management.schema"; import { CreateBlameExpertByInsurerDto, CreateClaimExpertByInsurerDto, CreateFileMakerByInsurerDto, CreateFileReviewerByInsurerDto, } from "src/expert-insurer/dto/create-insurer-expert.dto"; +import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service"; +import { + SystemSettingsResponseDto, + UpdateSystemSettingsDto, +} from "src/system-settings/dto/system-settings.dto"; +import { SystemSettingsService } from "src/system-settings/system-settings.service"; +import { + CreateCallCenterAgentDto, + CreateFieldExpertAdminDto, + CreateRegistrarAdminDto, + CreateSuperAdminDto, +} from "./dto/super-admin.dto"; +import { SuperAdminGuard } from "./guards/super-admin.guard"; +import { SuperAdminService } from "./super-admin.service"; @ApiTags("super-admin") @ApiBearerAuth() @@ -119,30 +114,6 @@ export class SuperAdminController { return this.superAdminService.registerInsurer(body); } - @Post("register/genuine") - @ApiOperation({ - deprecated: true, - summary: "[DEPRECATED] Register a genuine actor", - description: - "Kept for legacy clients. Use the unified onboarding flow instead.", - }) - @ApiBody({ type: GenuineRegisterDto }) - registerGenuine(@Body() body: GenuineRegisterDto) { - return this.superAdminService.registerGenuine(body); - } - - @Post("register/legal") - @ApiOperation({ - deprecated: true, - summary: "[DEPRECATED] Register a legal actor", - description: - "Kept for legacy clients. Use the unified onboarding flow instead.", - }) - @ApiBody({ type: LegalRegisterDto }) - registerLegal(@Body() body: LegalRegisterDto) { - return this.superAdminService.registerLegal(body); - } - @Post("create-field-expert") @ApiOperation({ summary: "Create a field expert" }) @ApiBody({ type: CreateFieldExpertAdminDto }) @@ -201,9 +172,21 @@ export class SuperAdminController { @ApiOperation({ summary: "List branches for a given client" }) @ApiQuery({ name: "clientId", required: true, type: String }) @ApiQuery({ name: "search", required: false, type: String }) - @ApiQuery({ name: "from", required: false, description: "Optional start datetime (ISO string)" }) - @ApiQuery({ name: "to", required: false, description: "Optional end datetime (ISO string)" }) - @ApiQuery({ name: "isActive", required: false, description: "Filter active state (true/false)" }) + @ApiQuery({ + name: "from", + required: false, + description: "Optional start datetime (ISO string)", + }) + @ApiQuery({ + name: "to", + required: false, + description: "Optional end datetime (ISO string)", + }) + @ApiQuery({ + name: "isActive", + required: false, + description: "Filter active state (true/false)", + }) getInsuranceBranches( @Query("clientId") clientId: string, @Query("search") search?: string, @@ -211,10 +194,12 @@ export class SuperAdminController { @Query("to") to?: string, @Query("isActive") isActive?: string, ) { - return this.expertInsurerService.retrieveInsuranceBranches( - clientId, - { search, from, to, isActive }, - ); + return this.expertInsurerService.retrieveInsuranceBranches(clientId, { + search, + from, + to, + isActive, + }); } @Post("insurer/branches") @@ -226,7 +211,9 @@ export class SuperAdminController { { type: "object", required: ["clientId"], - properties: { clientId: { type: "string", description: "Client ObjectId" } }, + properties: { + clientId: { type: "string", description: "Client ObjectId" }, + }, }, ], }, @@ -260,13 +247,19 @@ export class SuperAdminController { if (typeof isActive === "boolean") { active = isActive; } else { - const normalized = String(isActive ?? "").trim().toLowerCase(); + const normalized = String(isActive ?? "") + .trim() + .toLowerCase(); if (!["true", "false", "1", "0", "yes", "no"].includes(normalized)) { throw new BadRequestException("isActive must be a boolean"); } active = ["true", "1", "yes"].includes(normalized); } - return this.expertInsurerService.setBranchActive(clientId, branchId, active); + return this.expertInsurerService.setBranchActive( + clientId, + branchId, + active, + ); } @Post("insurer/experts/blame") @@ -278,7 +271,9 @@ export class SuperAdminController { { type: "object", required: ["clientId"], - properties: { clientId: { type: "string", description: "Client ObjectId" } }, + properties: { + clientId: { type: "string", description: "Client ObjectId" }, + }, }, ], }, @@ -299,7 +294,9 @@ export class SuperAdminController { { type: "object", required: ["clientId"], - properties: { clientId: { type: "string", description: "Client ObjectId" } }, + properties: { + clientId: { type: "string", description: "Client ObjectId" }, + }, }, ], }, @@ -320,7 +317,9 @@ export class SuperAdminController { { type: "object", required: ["clientId"], - properties: { clientId: { type: "string", description: "Client ObjectId" } }, + properties: { + clientId: { type: "string", description: "Client ObjectId" }, + }, }, ], }, @@ -333,7 +332,9 @@ export class SuperAdminController { } @Post("insurer/experts/file-reviewer") - @ApiOperation({ summary: "Create a FileReviewer account under a given client" }) + @ApiOperation({ + summary: "Create a FileReviewer account under a given client", + }) @ApiBody({ schema: { allOf: [ @@ -341,7 +342,9 @@ export class SuperAdminController { { type: "object", required: ["clientId"], - properties: { clientId: { type: "string", description: "Client ObjectId" } }, + properties: { + clientId: { type: "string", description: "Client ObjectId" }, + }, }, ], }, @@ -374,11 +377,15 @@ export class SuperAdminController { @ApiOperation({ summary: "Top blame vs claim experts for a given client" }) @ApiQuery({ name: "clientId", required: true, type: String }) getTopExperts(@Query("clientId") clientId: string) { - return this.expertInsurerService.getTopExpertsForClient({ clientKey: clientId }); + return this.expertInsurerService.getTopExpertsForClient({ + clientKey: clientId, + }); } @Get("insurer/files") - @ApiOperation({ summary: "List files (blame + claim merged) for a given client" }) + @ApiOperation({ + summary: "List files (blame + claim merged) for a given client", + }) @ApiQuery({ name: "clientId", required: true, type: String }) getAllFiles( @Query("clientId") clientId: string, @@ -388,7 +395,9 @@ export class SuperAdminController { } @Get("insurer/report/unified-file-statuses") - @ApiOperation({ summary: "Unified file status catalog + counts for a given client" }) + @ApiOperation({ + summary: "Unified file status catalog + counts for a given client", + }) @ApiQuery({ name: "clientId", required: true, type: String }) @ApiResponse({ status: 200, type: UnifiedFileStatusReportDto }) getUnifiedFileStatusReport( @@ -408,8 +417,16 @@ export class SuperAdminController { description: "Prefer GET insurer/report/unified-file-statuses.", }) @ApiQuery({ name: "clientId", required: true, type: String }) - @ApiQuery({ name: "from", required: false, description: "Optional start datetime (ISO string)" }) - @ApiQuery({ name: "to", required: false, description: "Optional end datetime (ISO string)" }) + @ApiQuery({ + name: "from", + required: false, + description: "Optional start datetime (ISO string)", + }) + @ApiQuery({ + name: "to", + required: false, + description: "Optional end datetime (ISO string)", + }) getInsurerStatusReport( @Query("clientId") clientId: string, @Query("from") from?: string, @@ -436,20 +453,42 @@ export class SuperAdminController { @Get("insurer/files/:publicId/ai-analysis") @ApiOperation({ summary: "AI analysis for a file of the selected client" }) @ApiQuery({ name: "clientId", required: true, type: String }) - async getAiAnalysis(@Query("clientId") clientId: string, @Param("publicId") publicId: string) { - const detail = await this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId); - const id = typeof detail.claim?.claimRequestId === "string" ? detail.claim.claimRequestId : undefined; + async getAiAnalysis( + @Query("clientId") clientId: string, + @Param("publicId") publicId: string, + ) { + const detail = + await this.expertInsurerService.retrieveFileDetailsByPublicId( + clientId, + publicId, + ); + const id = + typeof detail.claim?.claimRequestId === "string" + ? detail.claim.claimRequestId + : undefined; if (!id) return { enabled: this.aiService.enabled, images: [] }; const claim = await this.claimCaseDbService.findById(id); return this.aiService.list(id, currentAiCaptures(claim)); } @Post("insurer/files/:publicId/ai-analysis/retry") - @ApiOperation({ summary: "Retry failed AI analyses for the selected client's file" }) + @ApiOperation({ + summary: "Retry failed AI analyses for the selected client's file", + }) @ApiQuery({ name: "clientId", required: true, type: String }) - async retryAiAnalysis(@Query("clientId") clientId: string, @Param("publicId") publicId: string) { - const detail = await this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId); - const id = typeof detail.claim?.claimRequestId === "string" ? detail.claim.claimRequestId : undefined; + async retryAiAnalysis( + @Query("clientId") clientId: string, + @Param("publicId") publicId: string, + ) { + const detail = + await this.expertInsurerService.retrieveFileDetailsByPublicId( + clientId, + publicId, + ); + const id = + typeof detail.claim?.claimRequestId === "string" + ? detail.claim.claimRequestId + : undefined; if (!id) return { enabled: this.aiService.enabled, images: [] }; const claim = await this.claimCaseDbService.findById(id); return this.aiService.retry(id, currentAiCaptures(claim)); @@ -463,7 +502,10 @@ export class SuperAdminController { @Query("clientId") clientId: string, @Param("publicId") publicId: string, ) { - return this.expertInsurerService.retrieveFileDetailsByPublicId(clientId, publicId); + return this.expertInsurerService.retrieveFileDetailsByPublicId( + clientId, + publicId, + ); } // @Put("insurer/files/:publicId/rating") @@ -509,11 +551,15 @@ export class SuperAdminController { @ApiOperation({ summary: "Expert statistics report for a given client" }) @ApiQuery({ name: "clientId", required: true, type: String }) getExpertStatistics(@Query("clientId") clientId: string) { - return this.expertInsurerService.getExpertStatisticsReport({ clientKey: clientId }); + return this.expertInsurerService.getExpertStatisticsReport({ + clientKey: clientId, + }); } @Get("insurer/:expertId") - @ApiOperation({ summary: "Files handled by one roster expert for a given client" }) + @ApiOperation({ + summary: "Files handled by one roster expert for a given client", + }) @ApiParam({ name: "expertId" }) @ApiQuery({ name: "clientId", required: true, type: String }) getExpertFiles( @@ -523,6 +569,9 @@ export class SuperAdminController { if (!Types.ObjectId.isValid(expertId)) { throw new BadRequestException("Invalid expert ID"); } - return this.expertInsurerService.getAllFilesForInsurerExpert(expertId, clientId); + return this.expertInsurerService.getAllFilesForInsurerExpert( + expertId, + clientId, + ); } } diff --git a/src/super-admin/super-admin.service.ts b/src/super-admin/super-admin.service.ts index a7b7a0d..285c74e 100644 --- a/src/super-admin/super-admin.service.ts +++ b/src/super-admin/super-admin.service.ts @@ -1,30 +1,20 @@ -import { - BadRequestException, - ConflictException, - Injectable, - NotFoundException, -} from "@nestjs/common"; +import { ConflictException, Injectable } from "@nestjs/common"; import { Types } from "mongoose"; -import { HashService } from "src/utils/hash/hash.service"; +import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; +import { InsurerRegisterDto } from "src/auth/dto/actor/register.actor.dto"; import { ClientService } from "src/client/client.service"; import { ClientDto } from "src/client/dto/create-client.dto"; -import { ActorAuthService } from "src/auth/auth-services/actor.auth.service"; +import { RoleEnum } from "src/Types&Enums/role.enum"; +import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service"; + +import { HashService } from "src/utils/hash/hash.service"; import { - InsurerRegisterDto, - GenuineRegisterDto, - LegalRegisterDto, -} from "src/auth/dto/actor/register.actor.dto"; -import { SuperAdminDbService } from "./entities/db-service/super-admin.db.service"; -import { - CreateSuperAdminDto, + CreateCallCenterAgentDto, CreateFieldExpertAdminDto, CreateRegistrarAdminDto, - CreateCallCenterAgentDto, + CreateSuperAdminDto, } from "./dto/super-admin.dto"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; -import { RegistrarDbService } from "src/users/entities/db-service/registrar.db.service"; -import { CallCenterAgentDbService } from "src/users/entities/db-service/call-center-agent.db.service"; +import { SuperAdminDbService } from "./entities/db-service/super-admin.db.service"; @Injectable() export class SuperAdminService { @@ -33,8 +23,7 @@ export class SuperAdminService { private readonly hashService: HashService, private readonly clientService: ClientService, private readonly actorAuthService: ActorAuthService, - private readonly fieldExpertDbService: FieldExpertDbService, - private readonly registrarDbService: RegistrarDbService, + private readonly callCenterAgentDbService: CallCenterAgentDbService, ) {} @@ -87,14 +76,6 @@ export class SuperAdminService { return this.actorAuthService.insurerRegister(body); } - async registerGenuine(body: GenuineRegisterDto) { - return this.actorAuthService.genuineRegister(body); - } - - async registerLegal(body: LegalRegisterDto) { - return this.actorAuthService.legalRegister(body); - } - async createFieldExpert(body: CreateFieldExpertAdminDto) { return this.actorAuthService.createFieldExpertMock(body); } diff --git a/src/users/entities/db-service/call-center-agent.db.service.ts b/src/users/entities/db-service/call-center-agent.db.service.ts index 20cdaec..6f8d856 100644 --- a/src/users/entities/db-service/call-center-agent.db.service.ts +++ b/src/users/entities/db-service/call-center-agent.db.service.ts @@ -39,12 +39,4 @@ export class CallCenterAgentDbService { } return this.model.findOne({ $or: or }); } - - async findAll( - filter: FilterQuery, - ): Promise<(CallCenterAgentModel & { _id: Types.ObjectId })[]> { - return this.model.find(filter).lean() as Promise< - (CallCenterAgentModel & { _id: Types.ObjectId })[] - >; - } } diff --git a/src/users/entities/db-service/damage-expert.db.service.ts b/src/users/entities/db-service/damage-expert.db.service.ts index 13ce8b1..cad909e 100644 --- a/src/users/entities/db-service/damage-expert.db.service.ts +++ b/src/users/entities/db-service/damage-expert.db.service.ts @@ -40,12 +40,6 @@ export class DamageExpertDbService { return await this.damageExpertModel.find(filter).lean(); } - async findAndUpdate(filter: any, update: any): Promise { - return this.damageExpertModel - .findOneAndUpdate(filter, update, { new: true }) - .exec(); - } - async updateOne(filter: any, update: any) { return this.damageExpertModel.updateOne(filter, update); } diff --git a/src/users/entities/db-service/expert-file-activity.db.service.ts b/src/users/entities/db-service/expert-file-activity.db.service.ts index 9057691..2778e6e 100644 --- a/src/users/entities/db-service/expert-file-activity.db.service.ts +++ b/src/users/entities/db-service/expert-file-activity.db.service.ts @@ -46,31 +46,6 @@ export class ExpertFileActivityDbService { await this.activityModel.create(payload); } - async findByTenantAndExperts( - tenantId: string | Types.ObjectId, - expertIds: Array, - ): Promise< - Array<{ - expertId: Types.ObjectId; - fileId: Types.ObjectId; - eventType: ExpertFileActivityType; - occurredAt: Date; - }> - > { - if (expertIds.length === 0) return []; - const ids = expertIds.map((id) => new Types.ObjectId(String(id))); - return this.activityModel - .find( - { - tenantId: new Types.ObjectId(String(tenantId)), - expertId: { $in: ids }, - }, - { expertId: 1, fileId: 1, eventType: 1, occurredAt: 1 }, - ) - .sort({ occurredAt: 1, _id: 1 }) - .lean(); - } - /** Activity rows for one expert and file kind (claim or blame panel). */ async findByExpert( expertId: string | Types.ObjectId, diff --git a/src/users/entities/db-service/file-maker.db.service.ts b/src/users/entities/db-service/file-maker.db.service.ts index 988b030..39c1dc6 100644 --- a/src/users/entities/db-service/file-maker.db.service.ts +++ b/src/users/entities/db-service/file-maker.db.service.ts @@ -26,10 +26,7 @@ export class FileMakerDbService { identifier: string, ): Promise { const id = identifier.trim(); - const or: FilterQuery[] = [ - { email: id }, - { username: id }, - ]; + const or: FilterQuery[] = [{ email: id }, { username: id }]; if (/^\d{10}$/.test(id)) { or.push({ nationalCode: id }); } @@ -50,14 +47,4 @@ export class FileMakerDbService { new: true, }); } - - async findAll( - filter: FilterQuery, - ): Promise<(FileMakerModel & { _id: Types.ObjectId })[]> { - return await this.fileMakerModel.find(filter).lean(); - } - - async updateOne(filter: FilterQuery, update: any) { - return this.fileMakerModel.updateOne(filter, update); - } } diff --git a/src/users/entities/db-service/file-reviewer.db.service.ts b/src/users/entities/db-service/file-reviewer.db.service.ts index c6556f4..b51debc 100644 --- a/src/users/entities/db-service/file-reviewer.db.service.ts +++ b/src/users/entities/db-service/file-reviewer.db.service.ts @@ -50,14 +50,4 @@ export class FileReviewerDbService { new: true, }); } - - async findAll( - filter: FilterQuery, - ): Promise<(FileReviewerModel & { _id: Types.ObjectId })[]> { - return await this.fileReviewerModel.find(filter).lean(); - } - - async updateOne(filter: FilterQuery, update: any) { - return this.fileReviewerModel.updateOne(filter, update); - } } diff --git a/src/users/entities/db-service/registrar.db.service.ts b/src/users/entities/db-service/registrar.db.service.ts index 18f176e..cc89621 100644 --- a/src/users/entities/db-service/registrar.db.service.ts +++ b/src/users/entities/db-service/registrar.db.service.ts @@ -29,12 +29,7 @@ export class RegistrarDbService { return this.registrarModel.findOneAndUpdate(filter, update, { new: true }); } - async updateOne(filter: FilterQuery, update: any) { - return this.registrarModel.updateOne(filter, update); - } - async findById(userId: string): Promise { return this.registrarModel.findOne({ _id: new Types.ObjectId(userId) }); } } - diff --git a/src/users/entities/db-service/user.db.service.ts b/src/users/entities/db-service/user.db.service.ts index 6a430eb..602c2ed 100644 --- a/src/users/entities/db-service/user.db.service.ts +++ b/src/users/entities/db-service/user.db.service.ts @@ -24,10 +24,6 @@ export class UserDbService { .lean()) as UserModel[]; } - async findPlate(plate: number) { - return await this.userModel.find({ "plates.leftDigits": { $in: plate } }); - } - async findOneAndUpdate( user: FilterQuery, update: UpdateQuery, diff --git a/src/utils/pipes/parse-json.pipe.ts b/src/utils/pipes/parse-json.pipe.ts deleted file mode 100644 index 8c71a52..0000000 --- a/src/utils/pipes/parse-json.pipe.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { - PipeTransform, - Injectable, - BadRequestException, - ArgumentMetadata, -} from "@nestjs/common"; - -@Injectable() -export class ParseJsonPipe implements PipeTransform { - transform(value: string | undefined, metadata: ArgumentMetadata): any { - if (value === undefined) { - return undefined; - } - - if (typeof value !== "string") { - throw new BadRequestException( - `Validation failed: Expected a stringified JSON for query parameter '${metadata.data}'.`, - ); - } - - try { - return JSON.parse(value); - } catch (e) { - throw new BadRequestException( - `Invalid JSON format in query parameter '${metadata.data}'.`, - ); - } - } -} diff --git a/src/workflow-step-management/dto/claim-workflow-step.examples.ts b/src/workflow-step-management/dto/claim-workflow-step.examples.ts deleted file mode 100644 index 4ba76be..0000000 --- a/src/workflow-step-management/dto/claim-workflow-step.examples.ts +++ /dev/null @@ -1,510 +0,0 @@ -/** - * Swagger example bodies for CLAIM workflow step management - */ - -export const createClaimWorkflowStepExamples = { - claimCreated: { - summary: 'Claim Created Step', - value: { - stepKey: 'CLAIM_CREATED', - type: 'CLAIM', - stepNumber: 1, - isActive: true, - stepName_fa: 'ایجاد درخواست خسارت', - stepName_en: 'Create Claim Request', - description_fa: 'ایجاد درخواست خسارت از پرونده تعیین تقصیر تکمیل شده - فقط طرف آسیب‌دیده می‌تواند درخواست دهد', - description_en: 'Create claim request from completed blame case - only damaged party can proceed', - category: 'CLAIM', - requiredPreviousSteps: [], - nextPossibleSteps: ['SELECT_OUTER_PARTS'], - allowedRoles: ['user'], - estimatedDuration: 1, - fields: [], - metadata: { - icon: 'file-plus', - color: '#8B5CF6', - requiresBlameCase: true, - blameStatusRequired: 'COMPLETED', - bothPartiesMustAccept: true, - userMustBeDamagedParty: true - } - } - }, - - selectOuterParts: { - summary: 'Select Outer Parts Step', - value: { - stepKey: 'SELECT_OUTER_PARTS', - type: 'CLAIM', - stepNumber: 2, - isActive: true, - stepName_fa: 'انتخاب قطعات خارجی آسیب‌دیده', - stepName_en: 'Select Damaged Outer Parts', - description_fa: 'انتخاب قطعات خارجی خودرو که در حادثه آسیب دیده‌اند (کاپوت، درب‌ها، سپر و...)', - description_en: 'Select vehicle outer parts damaged in the accident (hood, doors, bumpers, etc.)', - category: 'CLAIM', - requiredPreviousSteps: ['CLAIM_CREATED'], - nextPossibleSteps: ['SELECT_OTHER_PARTS'], - allowedRoles: ['user'], - estimatedDuration: 3, - fields: [ - { - id: '67fa10c259e15f231a2d1001', - name_fa: 'قطعات خارجی', - name_en: 'outerParts', - label_fa: 'قطعات خارجی آسیب‌دیده', - label_en: 'Damaged Outer Parts', - placeholder_fa: 'قطعات خارجی آسیب‌دیده را انتخاب کنید', - placeholder_en: 'Select damaged outer parts', - value: [ - { label_fa: 'کاپوت', label_en: 'Hood', value: 'hood' }, - { label_fa: 'درب جلو راست', label_en: 'Front Right Door', value: 'front_right_door' }, - { label_fa: 'درب جلو چپ', label_en: 'Front Left Door', value: 'front_left_door' }, - { label_fa: 'درب عقب راست', label_en: 'Rear Right Door', value: 'rear_right_door' }, - { label_fa: 'درب عقب چپ', label_en: 'Rear Left Door', value: 'rear_left_door' }, - { label_fa: 'سپر جلو', label_en: 'Front Bumper', value: 'front_bumper' }, - { label_fa: 'سپر عقب', label_en: 'Rear Bumper', value: 'rear_bumper' }, - { label_fa: 'گلگیر جلو راست', label_en: 'Front Right Fender', value: 'front_right_fender' }, - { label_fa: 'گلگیر جلو چپ', label_en: 'Front Left Fender', value: 'front_left_fender' }, - { label_fa: 'گلگیر عقب راست', label_en: 'Rear Right Fender', value: 'rear_right_fender' }, - { label_fa: 'گلگیر عقب چپ', label_en: 'Rear Left Fender', value: 'rear_left_fender' }, - { label_fa: 'صندوق عقب', label_en: 'Trunk', value: 'trunk' }, - { label_fa: 'سقف', label_en: 'Roof', value: 'roof' } - ], - dataType: 'multiselect', - required: true, - order: 1, - isActive: true, - validation: { - minItems: 1, - maxItems: 13 - } - } - ], - metadata: { - icon: 'car', - color: '#3B82F6', - requiresMultipleSelection: true - } - } - }, - - selectOtherParts: { - summary: 'Select Other Parts & Bank Info Step', - value: { - stepKey: 'SELECT_OTHER_PARTS', - type: 'CLAIM', - stepNumber: 3, - isActive: true, - stepName_fa: 'انتخاب سایر قطعات و اطلاعات بانکی', - stepName_en: 'Select Other Parts & Bank Information', - description_fa: 'انتخاب سایر قطعات آسیب‌دیده (غیر از بدنه)، شماره شبا و کد ملی بیمه‌گذار', - description_en: 'Select other damaged parts (non-body), Sheba number and insurer national code', - category: 'CLAIM', - requiredPreviousSteps: ['SELECT_OUTER_PARTS'], - nextPossibleSteps: ['CAPTURE_PART_DAMAGES'], - allowedRoles: ['user'], - estimatedDuration: 4, - fields: [ - { - id: '67fa10c259e15f231a2d1002', - name_fa: 'سایر قطعات', - name_en: 'otherParts', - label_fa: 'سایر قطعات آسیب‌دیده', - label_en: 'Other Damaged Parts', - placeholder_fa: 'سایر قطعات آسیب‌دیده را انتخاب کنید', - placeholder_en: 'Select other damaged parts', - value: [ - { label_fa: 'موتور', label_en: 'Engine', value: 'engine' }, - { label_fa: 'سیستم تعلیق', label_en: 'Suspension', value: 'suspension' }, - { label_fa: 'سیستم ترمز', label_en: 'Brake System', value: 'brake_system' }, - { label_fa: 'سیستم برق', label_en: 'Electrical System', value: 'electrical' }, - { label_fa: 'رادیاتور', label_en: 'Radiator', value: 'radiator' }, - { label_fa: 'گیربکس', label_en: 'Transmission', value: 'transmission' }, - { label_fa: 'اگزوز', label_en: 'Exhaust', value: 'exhaust' }, - { label_fa: 'چراغ جلو', label_en: 'Headlight', value: 'headlight' }, - { label_fa: 'چراغ عقب', label_en: 'Taillight', value: 'taillight' }, - { label_fa: 'آینه', label_en: 'Mirror', value: 'mirror' }, - { label_fa: 'شیشه', label_en: 'Glass', value: 'glass' } - ], - dataType: 'multiselect', - required: false, - order: 1, - isActive: true, - validation: { - minItems: 0, - maxItems: 11 - } - }, - { - id: '67fa10c259e15f231a2d1003', - name_fa: 'شماره شبا', - name_en: 'shebaNumber', - label_fa: 'شماره شبا', - label_en: 'Sheba Number', - placeholder_fa: 'شماره شبا (24 رقم بدون IR)', - placeholder_en: 'Sheba number (24 digits without IR)', - value: null, - dataType: 'string', - required: true, - order: 2, - isActive: true, - validation: { - pattern: '^[0-9]{24}$', - minLength: 24, - maxLength: 24 - } - }, - { - id: '67fa10c259e15f231a2d1004', - name_fa: 'کد ملی مالک', - name_en: 'nationalCodeOfOwner', - label_fa: 'کد ملی مالک', - label_en: 'National Code of Owner', - placeholder_fa: 'کد ملی 10 رقمی مالک', - placeholder_en: '10-digit national code of owner', - value: null, - dataType: 'string', - required: true, - order: 3, - isActive: true, - validation: { - pattern: '^[0-9]{10}$', - minLength: 10, - maxLength: 10 - } - } - ], - metadata: { - icon: 'list', - color: '#10B981', - requiresBankInfo: true - } - } - }, - - uploadRequiredDocuments: { - summary: 'Upload Required Documents Step', - value: { - stepKey: 'UPLOAD_REQUIRED_DOCUMENTS', - type: 'CLAIM', - stepNumber: 5, - isActive: true, - stepName_fa: 'آپلود مدارک مورد نیاز', - stepName_en: 'Upload Required Documents', - description_fa: 'آپلود مدارک مورد نیاز برای بررسی خسارت (لیست داینامیک بر اساس قطعات انتخاب شده)', - description_en: 'Upload required documents for claim review (dynamic list based on selected parts)', - category: 'CLAIM', - requiredPreviousSteps: ['CAPTURE_PART_DAMAGES'], - nextPossibleSteps: ['USER_SUBMISSION_COMPLETE'], - allowedRoles: ['user'], - estimatedDuration: 5, - fields: [], - metadata: { - icon: 'upload', - color: '#F59E0B', - dynamicFields: true, - requiresAPI: '/claim-request-management/car-part-image-required/:claimRequestID', - note: 'لیست مدارک به صورت داینامیک از API دریافت می‌شود' - } - } - }, - - capturePartDamages: { - summary: 'Capture Part Damages Step', - value: { - stepKey: 'CAPTURE_PART_DAMAGES', - type: 'CLAIM', - stepNumber: 4, - isActive: true, - stepName_fa: 'ثبت تصاویر آسیب‌های قطعات', - stepName_en: 'Capture Part Damages', - description_fa: 'ثبت تصاویر آسیب برای هر قطعه (یک درخواست به ازای هر قطعه)', - description_en: 'Capture damage images for each part (one request per part)', - category: 'CLAIM', - requiredPreviousSteps: ['SELECT_OTHER_PARTS'], - nextPossibleSteps: ['UPLOAD_REQUIRED_DOCUMENTS'], - allowedRoles: ['user'], - estimatedDuration: 10, - fields: [], - metadata: { - icon: 'camera', - color: '#EF4444', - dynamicFields: true, - requiresAPI: '/claim-request-management/capture-car-part-damage/:claimRequestID/:partId', - requiresCamera: true, - multipleRequests: true, - note: 'برای هر قطعه یک درخواست جداگانه ارسال می‌شود' - } - } - }, - - userSubmissionComplete: { - summary: 'User Submission Complete', - value: { - stepKey: 'USER_SUBMISSION_COMPLETE', - type: 'CLAIM', - stepNumber: 6, - isActive: true, - stepName_fa: 'تکمیل ثبت اطلاعات کاربر', - stepName_en: 'User Submission Complete', - description_fa: 'اطلاعات کاربر به طور کامل ثبت شد و در انتظار بررسی کارشناس خسارت', - description_en: 'User information completed, waiting for damage expert review', - category: 'CLAIM', - requiredPreviousSteps: ['UPLOAD_REQUIRED_DOCUMENTS'], - nextPossibleSteps: ['EXPERT_DAMAGE_ASSESSMENT'], - allowedRoles: ['user', 'damage_expert', 'admin'], - estimatedDuration: 0, - fields: [], - metadata: { - icon: 'check-circle', - color: '#10B981', - readOnly: true, - isSystemStep: true - } - } - }, - - expertDamageAssessment: { - summary: 'Expert Damage Assessment', - value: { - stepKey: 'EXPERT_DAMAGE_ASSESSMENT', - type: 'CLAIM', - stepNumber: 7, - isActive: true, - stepName_fa: 'ارزیابی خسارت توسط کارشناس', - stepName_en: 'Expert Damage Assessment', - description_fa: 'بررسی و ارزیابی خسارت توسط کارشناس خسارت', - description_en: 'Damage review and assessment by damage expert', - category: 'EXPERT', - requiredPreviousSteps: ['USER_SUBMISSION_COMPLETE'], - nextPossibleSteps: ['EXPERT_COST_EVALUATION'], - allowedRoles: ['damage_expert', 'admin'], - estimatedDuration: 30, - fields: [ - { - id: '67fa10c259e15f231a2d1005', - name_fa: 'وضعیت ارزیابی', - name_en: 'assessmentStatus', - label_fa: 'وضعیت ارزیابی', - label_en: 'Assessment Status', - placeholder_fa: 'وضعیت ارزیابی را انتخاب کنید', - placeholder_en: 'Select assessment status', - value: [ - { label_fa: 'تایید شده', label_en: 'Approved', value: 'approved' }, - { label_fa: 'نیاز به بازنگری', label_en: 'Needs Revision', value: 'needs_revision' }, - { label_fa: 'رد شده', label_en: 'Rejected', value: 'rejected' } - ], - dataType: 'select', - required: true, - order: 1, - isActive: true, - validation: { - enum: ['approved', 'needs_revision', 'rejected'] - } - }, - { - id: '67fa10c259e15f231a2d1006', - name_fa: 'توضیحات کارشناس', - name_en: 'expertComments', - label_fa: 'توضیحات کارشناس', - label_en: 'Expert Comments', - placeholder_fa: 'توضیحات خود را وارد کنید', - placeholder_en: 'Enter your comments', - value: null, - dataType: 'textarea', - required: true, - order: 2, - isActive: true, - validation: { - minLength: 10, - maxLength: 2000 - } - } - ], - metadata: { - icon: 'clipboard-check', - color: '#8B5CF6', - requiresExpertRole: true - } - } - }, - - expertCostEvaluation: { - summary: 'Expert Cost Evaluation', - value: { - stepKey: 'EXPERT_COST_EVALUATION', - type: 'CLAIM', - stepNumber: 8, - isActive: true, - stepName_fa: 'برآورد هزینه توسط کارشناس', - stepName_en: 'Expert Cost Evaluation', - description_fa: 'محاسبه و برآورد هزینه تعمیرات توسط کارشناس', - description_en: 'Repair cost calculation and estimation by expert', - category: 'EXPERT', - requiredPreviousSteps: ['EXPERT_DAMAGE_ASSESSMENT'], - nextPossibleSteps: ['INSURER_REVIEW'], - allowedRoles: ['damage_expert', 'admin'], - estimatedDuration: 20, - fields: [ - { - id: '67fa10c259e15f231a2d1007', - name_fa: 'هزینه کل برآورد شده', - name_en: 'estimatedTotalCost', - label_fa: 'هزینه کل برآورد شده (ریال)', - label_en: 'Estimated Total Cost (Rials)', - placeholder_fa: 'مبلغ را وارد کنید', - placeholder_en: 'Enter amount', - value: null, - dataType: 'number', - required: true, - order: 1, - isActive: true, - validation: { - min: 0, - max: 999999999999 - } - }, - { - id: '67fa10c259e15f231a2d1008', - name_fa: 'جزئیات هزینه', - name_en: 'costBreakdown', - label_fa: 'جزئیات هزینه', - label_en: 'Cost Breakdown', - placeholder_fa: 'جزئیات هزینه را وارد کنید', - placeholder_en: 'Enter cost breakdown', - value: null, - dataType: 'textarea', - required: true, - order: 2, - isActive: true, - validation: { - minLength: 20, - maxLength: 5000 - } - } - ], - metadata: { - icon: 'dollar-sign', - color: '#F59E0B', - requiresExpertRole: true, - requiresCostCalculation: true - } - } - }, - - insurerReview: { - summary: 'Insurer Review', - value: { - stepKey: 'INSURER_REVIEW', - type: 'CLAIM', - stepNumber: 9, - isActive: true, - stepName_fa: 'بررسی بیمه‌گر', - stepName_en: 'Insurer Review', - description_fa: 'بررسی نهایی و تایید یا رد خسارت توسط بیمه‌گر', - description_en: 'Final review and approval/rejection by insurer', - category: 'INSURER', - requiredPreviousSteps: ['EXPERT_COST_EVALUATION'], - nextPossibleSteps: ['CLAIM_COMPLETED'], - allowedRoles: ['insurer', 'admin'], - estimatedDuration: 60, - fields: [ - { - id: '67fa10c259e15f231a2d1009', - name_fa: 'تصمیم بیمه‌گر', - name_en: 'insurerDecision', - label_fa: 'تصمیم بیمه‌گر', - label_en: 'Insurer Decision', - placeholder_fa: 'تصمیم خود را انتخاب کنید', - placeholder_en: 'Select your decision', - value: [ - { label_fa: 'تایید', label_en: 'Approved', value: 'approved' }, - { label_fa: 'رد', label_en: 'Rejected', value: 'rejected' } - ], - dataType: 'select', - required: true, - order: 1, - isActive: true, - validation: { - enum: ['approved', 'rejected'] - } - }, - { - id: '67fa10c259e15f231a2d100a', - name_fa: 'توضیحات بیمه‌گر', - name_en: 'insurerNotes', - label_fa: 'توضیحات بیمه‌گر', - label_en: 'Insurer Notes', - placeholder_fa: 'توضیحات خود را وارد کنید', - placeholder_en: 'Enter your notes', - value: null, - dataType: 'textarea', - required: true, - order: 2, - isActive: true, - validation: { - minLength: 10, - maxLength: 2000 - } - } - ], - metadata: { - icon: 'shield-check', - color: '#6366F1', - requiresInsurerRole: true, - isFinalStep: false - } - } - }, - - claimCompleted: { - summary: 'Claim Completed', - value: { - stepKey: 'CLAIM_COMPLETED', - type: 'CLAIM', - stepNumber: 10, - isActive: true, - stepName_fa: 'تکمیل خسارت', - stepName_en: 'Claim Completed', - description_fa: 'خسارت به طور کامل بررسی و نتیجه‌گیری شده است', - description_en: 'Claim has been fully reviewed and concluded', - category: 'FINAL', - requiredPreviousSteps: ['INSURER_REVIEW'], - nextPossibleSteps: [], - allowedRoles: ['user', 'damage_expert', 'insurer', 'admin'], - estimatedDuration: 0, - fields: [], - metadata: { - icon: 'check-circle', - color: '#10B981', - readOnly: true, - isSystemStep: true, - isFinalStep: true - } - } - } -}; - -export const updateClaimWorkflowStepExamples = { - example1: { - summary: 'Update claim step name', - value: { - stepName_fa: 'انتخاب قطعات خارجی - بروزرسانی شده', - stepName_en: 'Select Outer Parts - Updated', - category: 'CLAIM', - isActive: true - } - }, - example2: { - summary: 'Update claim step metadata', - value: { - metadata: { - icon: 'car', - color: '#10B981', - requiresMultipleSelection: true, - priority: 'high' - } - } - } -}; diff --git a/src/workflow-step-management/dto/create-claim-workflow-step.dto.ts b/src/workflow-step-management/dto/create-claim-workflow-step.dto.ts deleted file mode 100644 index d5fd877..0000000 --- a/src/workflow-step-management/dto/create-claim-workflow-step.dto.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { IsNotEmpty, IsString, IsNumber, IsBoolean, IsOptional, IsArray, IsEnum, ValidateNested, IsObject } from 'class-validator'; -import { Type } from 'class-transformer'; -import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'; -import { ClaimWorkflowStep } from 'src/Types&Enums/claim-request-management/claim-workflow-steps.enum'; -import { WorkflowStep } from 'src/Types&Enums/blame-request-management/blameWorkflow-steps.enum'; -import { Types } from 'mongoose'; - -// Combined enum for validation -const AllWorkflowSteps = { ...WorkflowStep, ...ClaimWorkflowStep }; - -export class ClaimStepFieldDto { - @ApiProperty({ - description: 'Unique identifier for the field', - example: '67fa10c259e15f231a2d1001' - }) - @IsNotEmpty() - id: Types.ObjectId; - - @ApiProperty({ - description: 'Field name in Farsi', - example: 'قطعات خارجی' - }) - @IsNotEmpty() - @IsString() - name_fa: string; - - @ApiProperty({ - description: 'Field name in English', - example: 'outerParts' - }) - @IsNotEmpty() - @IsString() - name_en: string; - - @ApiPropertyOptional({ - description: 'Field label in Farsi', - example: 'قطعات خارجی آسیب‌دیده' - }) - @IsOptional() - @IsString() - label_fa?: string; - - @ApiPropertyOptional({ - description: 'Field label in English', - example: 'Damaged Outer Parts' - }) - @IsOptional() - @IsString() - label_en?: string; - - @ApiPropertyOptional({ - description: 'Placeholder text in Farsi', - example: 'قطعات خارجی آسیب‌دیده را انتخاب کنید' - }) - @IsOptional() - @IsString() - placeholder_fa?: string; - - @ApiPropertyOptional({ - description: 'Placeholder text in English', - example: 'Select damaged outer parts' - }) - @IsOptional() - @IsString() - placeholder_en?: string; - - @ApiPropertyOptional({ - description: 'Possible values for select/multiselect fields (null for non-select fields)', - example: null, - nullable: true, - default: null - }) - @IsOptional() - value?: Object[] | null; - - @ApiProperty({ - description: 'Data type of the field', - example: 'multiselect', - enum: ['string', 'number', 'boolean', 'date', 'select', 'multiselect', 'file', 'textarea', 'email', 'phone', 'object'] - }) - @IsNotEmpty() - @IsString() - dataType: string; - - @ApiPropertyOptional({ - description: 'Whether the field is required', - example: true, - default: false - }) - @IsOptional() - @IsBoolean() - required?: boolean; - - @ApiPropertyOptional({ - description: 'Validation rules for the field', - example: { minItems: 1, maxItems: 13 } - }) - @IsOptional() - @IsObject() - validation?: Object; - - @ApiPropertyOptional({ - description: 'Display order of the field in the form', - example: 1 - }) - @IsOptional() - @IsNumber() - order?: number; - - @ApiPropertyOptional({ - description: 'Whether the field is active', - example: true, - default: true - }) - @IsOptional() - @IsBoolean() - isActive?: boolean; -} - -export class CreateClaimWorkflowStepDto { - @ApiProperty({ - description: 'Unique key identifying the claim workflow step', - example: 'CLAIM_CREATED', - enum: AllWorkflowSteps - }) - @IsNotEmpty() - @IsEnum(AllWorkflowSteps) - stepKey: ClaimWorkflowStep | WorkflowStep; - - @ApiProperty({ - description: 'Workflow type: CLAIM for claim workflow', - example: 'CLAIM', - default: 'CLAIM' - }) - @IsNotEmpty() - @IsString() - type: string; - - @ApiProperty({ - description: 'Order number of the step in the claim workflow', - example: 1 - }) - @IsNotEmpty() - @IsNumber() - stepNumber: number; - - @ApiPropertyOptional({ - description: 'Whether the step is active', - example: true, - default: true - }) - @IsOptional() - @IsBoolean() - isActive?: boolean; - - @ApiProperty({ - description: 'Step name in Farsi', - example: 'ایجاد درخواست خسارت' - }) - @IsNotEmpty() - @IsString() - stepName_fa: string; - - @ApiProperty({ - description: 'Step name in English', - example: 'Create Claim Request' - }) - @IsNotEmpty() - @IsString() - stepName_en: string; - - @ApiPropertyOptional({ - description: 'Step description in Farsi', - example: 'ایجاد درخواست خسارت از پرونده تعیین تقصیر تکمیل شده' - }) - @IsOptional() - @IsString() - description_fa?: string; - - @ApiPropertyOptional({ - description: 'Step description in English', - example: 'Create claim request from completed blame case' - }) - @IsOptional() - @IsString() - description_en?: string; - - @ApiPropertyOptional({ - description: 'Category of the step', - example: 'CLAIM', - enum: ['CLAIM', 'EXPERT', 'INSURER', 'FINAL'] - }) - @IsOptional() - @IsString() - category?: string; - - @ApiPropertyOptional({ - description: 'Dynamic fields for this step', - type: [ClaimStepFieldDto], - example: [] - }) - @IsOptional() - @IsArray() - @ValidateNested({ each: true }) - @Type(() => ClaimStepFieldDto) - fields?: ClaimStepFieldDto[]; - - @ApiPropertyOptional({ - description: 'Steps that must be completed before this step', - example: [], - enum: AllWorkflowSteps, - isArray: true - }) - @IsOptional() - @IsArray() - @IsEnum(AllWorkflowSteps, { each: true }) - requiredPreviousSteps?: (ClaimWorkflowStep | WorkflowStep)[]; - - @ApiPropertyOptional({ - description: 'Possible next steps after completing this step', - example: ['SELECT_OUTER_PARTS'], - enum: AllWorkflowSteps, - isArray: true - }) - @IsOptional() - @IsArray() - @IsEnum(AllWorkflowSteps, { each: true }) - nextPossibleSteps?: (ClaimWorkflowStep | WorkflowStep)[]; - - @ApiPropertyOptional({ - description: 'Additional metadata for the step', - example: { icon: 'file-plus', color: '#8B5CF6' } - }) - @IsOptional() - @IsObject() - metadata?: Record; - - @ApiPropertyOptional({ - description: 'Estimated duration in minutes', - example: 1 - }) - @IsOptional() - @IsNumber() - estimatedDuration?: number; - - @ApiPropertyOptional({ - description: 'Roles allowed to access this step', - example: ['user', 'damage_expert', 'admin'] - }) - @IsOptional() - @IsArray() - @IsString({ each: true }) - allowedRoles?: string[]; -} diff --git a/src/workflow-step-management/entities/db-service/workflow-step.db.service.ts b/src/workflow-step-management/entities/db-service/workflow-step.db.service.ts index 0a9710a..2bb76e9 100644 --- a/src/workflow-step-management/entities/db-service/workflow-step.db.service.ts +++ b/src/workflow-step-management/entities/db-service/workflow-step.db.service.ts @@ -1,11 +1,14 @@ -import { Injectable } from '@nestjs/common'; -import { InjectModel } from '@nestjs/mongoose'; -import { Model } from 'mongoose'; -import { WorkflowStepModel, WorkflowStepsDB } from '../schema/workflow-step.schema'; -import { CreateWorkflowStepDto } from '../../dto/create-workflow-step.dto'; -import { UpdateWorkflowStepDto } from '../../dto/update-workflow-step.dto'; -import { WorkflowStep } from 'src/Types&Enums/blame-request-management/blameWorkflow-steps.enum'; -import { ClaimWorkflowStep } from 'src/Types&Enums/claim-request-management/claim-workflow-steps.enum'; +import { Injectable } from "@nestjs/common"; +import { InjectModel } from "@nestjs/mongoose"; +import { Model } from "mongoose"; +import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; +import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; +import { CreateWorkflowStepDto } from "../../dto/create-workflow-step.dto"; +import { UpdateWorkflowStepDto } from "../../dto/update-workflow-step.dto"; +import { + WorkflowStepModel, + WorkflowStepsDB, +} from "../schema/workflow-step.schema"; // Type alias for combined workflow steps type AnyWorkflowStep = WorkflowStep | ClaimWorkflowStep; @@ -39,10 +42,7 @@ export class WorkflowStepDbService { * Find all workflow steps including inactive ones */ async findAllIncludingInactive(): Promise { - return await this.workflowStepModel - .find() - .sort({ stepNumber: 1 }) - .exec(); + return await this.workflowStepModel.find().sort({ stepNumber: 1 }).exec(); } /** @@ -55,31 +55,28 @@ export class WorkflowStepDbService { /** * Find a workflow step by step key (supports both blame and claim) */ - async findByStepKey(stepKey: AnyWorkflowStep): Promise { + async findByStepKey( + stepKey: AnyWorkflowStep, + ): Promise { return await this.workflowStepModel.findOne({ stepKey }).exec(); } /** * Find a workflow step by step number */ - async findByStepNumber(stepNumber: number): Promise { + async findByStepNumber( + stepNumber: number, + ): Promise { return await this.workflowStepModel.findOne({ stepNumber }).exec(); } - /** - * Find steps by category - */ - async findByCategory(category: string): Promise { - return await this.workflowStepModel - .find({ category, isActive: true }) - .sort({ stepNumber: 1 }) - .exec(); - } - /** * Update a workflow step by ID */ - async update(id: string, updateDto: UpdateWorkflowStepDto): Promise { + async update( + id: string, + updateDto: UpdateWorkflowStepDto, + ): Promise { return await this.workflowStepModel .findByIdAndUpdate(id, updateDto, { new: true }) .exec(); @@ -133,24 +130,13 @@ export class WorkflowStepDbService { return await this.workflowStepModel.bulkWrite(bulkOps as any); } - /** - * Get the next step number - */ - async getNextStepNumber(): Promise { - const maxStep = await this.workflowStepModel - .findOne() - .sort({ stepNumber: -1 }) - .select('stepNumber') - .exec(); - - return maxStep ? maxStep.stepNumber + 1 : 1; - } - /** * Check if a step exists (supports both blame and claim) */ async exists(stepKey: AnyWorkflowStep): Promise { - const count = await this.workflowStepModel.countDocuments({ stepKey }).exec(); + const count = await this.workflowStepModel + .countDocuments({ stepKey }) + .exec(); return count > 0; } } diff --git a/src/workflow-step-management/index.ts b/src/workflow-step-management/index.ts deleted file mode 100644 index b85e1f7..0000000 --- a/src/workflow-step-management/index.ts +++ /dev/null @@ -1,8 +0,0 @@ -export * from './workflow-step-management.module'; -export * from './workflow-step-management.service'; -export * from './workflow-step-management.controller'; -export * from './dto/create-workflow-step.dto'; -export * from './dto/update-workflow-step.dto'; -export * from './dto/workflow-step.examples'; -export * from './entities/schema/workflow-step.schema'; -export * from './entities/db-service/workflow-step.db.service'; diff --git a/src/workflow-step-management/workflow-step-management.controller.ts b/src/workflow-step-management/workflow-step-management.controller.ts index e23cf63..9520fcd 100644 --- a/src/workflow-step-management/workflow-step-management.controller.ts +++ b/src/workflow-step-management/workflow-step-management.controller.ts @@ -1,39 +1,36 @@ import { - Controller, - Get, - Post, Body, - Patch, - Param, + Controller, Delete, - Query, + Get, HttpCode, HttpStatus, -} from '@nestjs/common'; -import { - ApiTags, - ApiOperation, - ApiResponse, - ApiBody, - ApiParam, - ApiQuery, - ApiBearerAuth -} from '@nestjs/swagger'; -import { WorkflowStepManagementService } from './workflow-step-management.service'; -import { CreateWorkflowStepDto } from './dto/create-workflow-step.dto'; -import { UpdateWorkflowStepDto } from './dto/update-workflow-step.dto'; -import { WorkflowStep } from 'src/Types&Enums/blame-request-management/blameWorkflow-steps.enum'; -import { ClaimWorkflowStep } from 'src/Types&Enums/claim-request-management/claim-workflow-steps.enum'; + Param, + Patch, + Post, + Query, +} from "@nestjs/common"; import { + ApiBody, + ApiOperation, + ApiParam, + ApiQuery, + ApiResponse, + ApiTags, +} from "@nestjs/swagger"; +import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; +import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; +import { CreateWorkflowStepDto } from "./dto/create-workflow-step.dto"; +import { UpdateWorkflowStepDto } from "./dto/update-workflow-step.dto"; +import { + claimWorkflowStepExamples, createWorkflowStepExamples, updateWorkflowStepExamples, - bulkUpsertWorkflowStepExamples, - validateAccessExamples, - claimWorkflowStepExamples, -} from './dto/workflow-step.examples'; +} from "./dto/workflow-step.examples"; +import { WorkflowStepManagementService } from "./workflow-step-management.service"; -@ApiTags('Workflow Step Management') -@Controller('workflow-step-management') +@ApiTags("Workflow Step Management") +@Controller("workflow-step-management") export class WorkflowStepManagementController { constructor( private readonly workflowStepManagementService: WorkflowStepManagementService, @@ -44,20 +41,24 @@ export class WorkflowStepManagementController { */ @Post() @HttpCode(HttpStatus.CREATED) - @ApiOperation({ - summary: 'Create a new workflow step', - description: 'Creates a new workflow step configuration with fields and validation rules' + @ApiOperation({ + summary: "Create a new workflow step", + description: + "Creates a new workflow step configuration with fields and validation rules", }) @ApiBody({ type: CreateWorkflowStepDto, examples: { ...createWorkflowStepExamples, - ...claimWorkflowStepExamples - } + ...claimWorkflowStepExamples, + }, }) - @ApiResponse({ status: 201, description: 'Workflow step created successfully' }) - @ApiResponse({ status: 400, description: 'Bad request - Invalid input data' }) - @ApiResponse({ status: 409, description: 'Conflict - Step already exists' }) + @ApiResponse({ + status: 201, + description: "Workflow step created successfully", + }) + @ApiResponse({ status: 400, description: "Bad request - Invalid input data" }) + @ApiResponse({ status: 409, description: "Conflict - Step already exists" }) async create(@Body() createDto: CreateWorkflowStepDto) { return await this.workflowStepManagementService.create(createDto); } @@ -66,20 +67,24 @@ export class WorkflowStepManagementController { * Get all active workflow steps */ @Get() - @ApiOperation({ - summary: 'Get all workflow steps', - description: 'Retrieves all workflow steps, optionally including inactive ones' + @ApiOperation({ + summary: "Get all workflow steps", + description: + "Retrieves all workflow steps, optionally including inactive ones", }) - @ApiQuery({ - name: 'includeInactive', - required: false, + @ApiQuery({ + name: "includeInactive", + required: false, type: String, description: 'Set to "true" to include inactive steps', - example: 'false' + example: "false", }) - @ApiResponse({ status: 200, description: 'List of workflow steps retrieved successfully' }) - async findAll(@Query('includeInactive') includeInactive?: string) { - if (includeInactive === 'true') { + @ApiResponse({ + status: 200, + description: "List of workflow steps retrieved successfully", + }) + async findAll(@Query("includeInactive") includeInactive?: string) { + if (includeInactive === "true") { return await this.workflowStepManagementService.findAllIncludingInactive(); } return await this.workflowStepManagementService.findAll(); @@ -88,58 +93,77 @@ export class WorkflowStepManagementController { /** * Update a workflow step by ID */ - @Patch(':id') - @ApiOperation({ - summary: 'Update workflow step by ID', - description: 'Updates a workflow step using its database ID' + @Patch(":id") + @ApiOperation({ + summary: "Update workflow step by ID", + description: "Updates a workflow step using its database ID", + }) + @ApiParam({ + name: "id", + description: "Workflow step ID", + example: "507f1f77bcf86cd799439011", }) - @ApiParam({ name: 'id', description: 'Workflow step ID', example: '507f1f77bcf86cd799439011' }) @ApiBody({ type: UpdateWorkflowStepDto, - examples: updateWorkflowStepExamples + examples: updateWorkflowStepExamples, }) - @ApiResponse({ status: 200, description: 'Workflow step updated successfully' }) - @ApiResponse({ status: 404, description: 'Workflow step not found' }) - async update(@Param('id') id: string, @Body() updateDto: UpdateWorkflowStepDto) { + @ApiResponse({ + status: 200, + description: "Workflow step updated successfully", + }) + @ApiResponse({ status: 404, description: "Workflow step not found" }) + async update( + @Param("id") id: string, + @Body() updateDto: UpdateWorkflowStepDto, + ) { return await this.workflowStepManagementService.update(id, updateDto); } /** * Update a workflow step by key */ - @Patch('step/:stepKey') - @ApiOperation({ - summary: 'Update workflow step by key', - description: 'Updates a workflow step using its step key from the enum' + @Patch("step/:stepKey") + @ApiOperation({ + summary: "Update workflow step by key", + description: "Updates a workflow step using its step key from the enum", }) - @ApiParam({ - name: 'stepKey', - description: 'Workflow step key (blame or claim)', - example: 'FIRST_VIDEO' + @ApiParam({ + name: "stepKey", + description: "Workflow step key (blame or claim)", + example: "FIRST_VIDEO", }) @ApiBody({ type: UpdateWorkflowStepDto, - examples: updateWorkflowStepExamples + examples: updateWorkflowStepExamples, }) - @ApiResponse({ status: 200, description: 'Workflow step updated successfully' }) - @ApiResponse({ status: 404, description: 'Workflow step not found' }) + @ApiResponse({ + status: 200, + description: "Workflow step updated successfully", + }) + @ApiResponse({ status: 404, description: "Workflow step not found" }) async updateByStepKey( - @Param('stepKey') stepKey: WorkflowStep | ClaimWorkflowStep, + @Param("stepKey") stepKey: WorkflowStep | ClaimWorkflowStep, @Body() updateDto: UpdateWorkflowStepDto, ) { - return await this.workflowStepManagementService.updateByStepKey(stepKey as any, updateDto); + return await this.workflowStepManagementService.updateByStepKey( + stepKey as any, + updateDto, + ); } /** * Initialize default workflow steps */ - @Post('initialize') + @Post("initialize") @HttpCode(HttpStatus.OK) - @ApiOperation({ - summary: 'Initialize default workflow steps', - description: 'Creates default workflow step configurations for the system' + @ApiOperation({ + summary: "Initialize default workflow steps", + description: "Creates default workflow step configurations for the system", + }) + @ApiResponse({ + status: 200, + description: "Default steps initialized successfully", }) - @ApiResponse({ status: 200, description: 'Default steps initialized successfully' }) async initialize() { return await this.workflowStepManagementService.initializeDefaultSteps(); } @@ -147,207 +171,80 @@ export class WorkflowStepManagementController { /** * Get a specific step by stepKey or stepNumber (intelligent lookup) */ - @Get('find/:identifier') - @ApiOperation({ - summary: 'Get workflow step by stepKey or stepNumber', - description: 'Retrieves a workflow step by either its stepKey (enum) or stepNumber. Automatically detects which one is provided.' + @Get("find/:identifier") + @ApiOperation({ + summary: "Get workflow step by stepKey or stepNumber", + description: + "Retrieves a workflow step by either its stepKey (enum) or stepNumber. Automatically detects which one is provided.", }) - @ApiParam({ - name: 'identifier', + @ApiParam({ + name: "identifier", description: 'Step key (e.g., "FIRST_VIDEO") or step number (e.g., 3)', - example: 'FIRST_VIDEO', + example: "FIRST_VIDEO", examples: { byStepKey: { - summary: 'By Step Key', - value: 'FIRST_VIDEO' + summary: "By Step Key", + value: "FIRST_VIDEO", }, byStepNumber: { - summary: 'By Step Number', - value: 3 - } - } + summary: "By Step Number", + value: 3, + }, + }, }) - @ApiResponse({ status: 200, description: 'Workflow step retrieved successfully' }) - @ApiResponse({ status: 404, description: 'Workflow step not found' }) - async findByStepKeyOrNumber(@Param('identifier') identifier: string) { - return await this.workflowStepManagementService.findByStepKeyOrNumber(identifier); + @ApiResponse({ + status: 200, + description: "Workflow step retrieved successfully", + }) + @ApiResponse({ status: 404, description: "Workflow step not found" }) + async findByStepKeyOrNumber(@Param("identifier") identifier: string) { + return await this.workflowStepManagementService.findByStepKeyOrNumber( + identifier, + ); } /** * Get a specific step by ID */ - @Get(':id') - @ApiOperation({ - summary: 'Get workflow step by ID', - description: 'Retrieves a specific workflow step by its database ID' + @Get(":id") + @ApiOperation({ + summary: "Get workflow step by ID", + description: "Retrieves a specific workflow step by its database ID", }) - @ApiParam({ name: 'id', description: 'Workflow step ID', example: '507f1f77bcf86cd799439011' }) - @ApiResponse({ status: 200, description: 'Workflow step retrieved successfully' }) - @ApiResponse({ status: 404, description: 'Workflow step not found' }) - async findById(@Param('id') id: string) { + @ApiParam({ + name: "id", + description: "Workflow step ID", + example: "507f1f77bcf86cd799439011", + }) + @ApiResponse({ + status: 200, + description: "Workflow step retrieved successfully", + }) + @ApiResponse({ status: 404, description: "Workflow step not found" }) + async findById(@Param("id") id: string) { return await this.workflowStepManagementService.findById(id); } /** * Soft delete a step */ - @Delete(':id') + @Delete(":id") @HttpCode(HttpStatus.OK) - @ApiOperation({ - summary: 'Delete workflow step', - description: 'Soft deletes a workflow step by setting isActive to false' + @ApiOperation({ + summary: "Delete workflow step", + description: "Soft deletes a workflow step by setting isActive to false", }) - @ApiParam({ name: 'id', description: 'Workflow step ID', example: '507f1f77bcf86cd799439011' }) - @ApiResponse({ status: 200, description: 'Workflow step deleted successfully' }) - @ApiResponse({ status: 404, description: 'Workflow step not found' }) - async remove(@Param('id') id: string) { + @ApiParam({ + name: "id", + description: "Workflow step ID", + example: "507f1f77bcf86cd799439011", + }) + @ApiResponse({ + status: 200, + description: "Workflow step deleted successfully", + }) + @ApiResponse({ status: 404, description: "Workflow step not found" }) + async remove(@Param("id") id: string) { return await this.workflowStepManagementService.remove(id); } - - // ============================================================ - // DEPRECATED ENDPOINTS - Will be removed in future versions - // ============================================================ - - /** - * @deprecated Use individual create endpoint instead - * Bulk upsert steps (for initial setup or migrations) - */ - @Post('bulk-upsert') - @HttpCode(HttpStatus.OK) - @ApiOperation({ - summary: '[DEPRECATED] Bulk upsert workflow steps', - description: 'This endpoint is deprecated and will be removed in a future version. Use the individual create endpoint instead.', - deprecated: true - }) - @ApiBody({ - type: [CreateWorkflowStepDto], - examples: bulkUpsertWorkflowStepExamples - }) - @ApiResponse({ status: 200, description: 'Steps upserted successfully' }) - async bulkUpsert(@Body() steps: CreateWorkflowStepDto[]) { - return await this.workflowStepManagementService.bulkUpsert(steps); - } - - /** - * @deprecated This endpoint is no longer needed - * Validate step access - */ - @Post('validate-access') - @HttpCode(HttpStatus.OK) - @ApiOperation({ - summary: '[DEPRECATED] Validate step access', - description: 'This endpoint is deprecated and will be removed in a future version.', - deprecated: true - }) - @ApiBody({ - schema: { - type: 'object', - properties: { - stepKey: { - type: 'string', - description: 'Workflow step key (blame or claim)', - example: 'FIRST_VIDEO' - }, - completedSteps: { - type: 'array', - items: { - type: 'string' - }, - example: ['CREATED'] - } - } - }, - examples: validateAccessExamples - }) - @ApiResponse({ status: 200, description: 'Validation result returned' }) - async validateAccess( - @Body() body: { stepKey: WorkflowStep | ClaimWorkflowStep; completedSteps: (WorkflowStep | ClaimWorkflowStep)[] }, - ) { - return await this.workflowStepManagementService.validateStepAccess( - body.stepKey as any, - body.completedSteps as any, - ); - } - - /** - * @deprecated This endpoint is no longer needed - * Get steps by category - */ - @Get('category/:category') - @ApiOperation({ - summary: '[DEPRECATED] Get steps by category', - description: 'This endpoint is deprecated and will be removed in a future version.', - deprecated: true - }) - @ApiParam({ - name: 'category', - description: 'Step category', - example: 'FIRST_PARTY', - enum: ['INITIAL', 'FIRST_PARTY', 'SECOND_PARTY', 'RESOLUTION'] - }) - @ApiResponse({ status: 200, description: 'Steps retrieved successfully' }) - async findByCategory(@Param('category') category: string) { - return await this.workflowStepManagementService.findByCategory(category); - } - - /** - * @deprecated This endpoint is no longer needed - * Get next possible steps from current step - */ - @Get('next-steps/:stepKey') - @ApiOperation({ - summary: '[DEPRECATED] Get next possible steps', - description: 'This endpoint is deprecated and will be removed in a future version.', - deprecated: true - }) - @ApiParam({ - name: 'stepKey', - description: 'Current workflow step key (blame or claim)', - example: 'FIRST_VIDEO' - }) - @ApiResponse({ status: 200, description: 'Next steps retrieved successfully' }) - async getNextSteps(@Param('stepKey') stepKey: WorkflowStep | ClaimWorkflowStep) { - return await this.workflowStepManagementService.getNextSteps(stepKey as any); - } - - /** - * @deprecated This endpoint is no longer needed - * Get step fields (for form generation) - */ - @Get('fields/:stepKey') - @ApiOperation({ - summary: '[DEPRECATED] Get step fields', - description: 'This endpoint is deprecated and will be removed in a future version.', - deprecated: true - }) - @ApiParam({ - name: 'stepKey', - description: 'Workflow step key (blame or claim)', - example: 'FIRST_VIDEO' - }) - @ApiResponse({ status: 200, description: 'Step fields retrieved successfully' }) - async getStepFields(@Param('stepKey') stepKey: WorkflowStep | ClaimWorkflowStep) { - return await this.workflowStepManagementService.getStepFields(stepKey as any); - } - - /** - * @deprecated Use findById instead - * Get a specific step by key - */ - @Get('step/:stepKey') - @ApiOperation({ - summary: '[DEPRECATED] Get workflow step by key', - description: 'This endpoint is deprecated and will be removed in a future version. Use GET /:id instead.', - deprecated: true - }) - @ApiParam({ - name: 'stepKey', - description: 'Workflow step key (blame or claim)', - example: 'FIRST_VIDEO' - }) - @ApiResponse({ status: 200, description: 'Workflow step retrieved successfully' }) - @ApiResponse({ status: 404, description: 'Workflow step not found' }) - async findByStepKey(@Param('stepKey') stepKey: WorkflowStep | ClaimWorkflowStep) { - return await this.workflowStepManagementService.findByStepKey(stepKey as any); - } } diff --git a/src/workflow-step-management/workflow-step-management.service.ts b/src/workflow-step-management/workflow-step-management.service.ts index 77e5251..b9d980c 100644 --- a/src/workflow-step-management/workflow-step-management.service.ts +++ b/src/workflow-step-management/workflow-step-management.service.ts @@ -1,15 +1,14 @@ import { - Injectable, - NotFoundException, - BadRequestException, ConflictException, + Injectable, Logger, + NotFoundException, } from "@nestjs/common"; -import { WorkflowStepDbService } from "./entities/db-service/workflow-step.db.service"; -import { CreateWorkflowStepDto } from "./dto/create-workflow-step.dto"; -import { UpdateWorkflowStepDto } from "./dto/update-workflow-step.dto"; import { WorkflowStep } from "src/Types&Enums/blame-request-management/blameWorkflow-steps.enum"; import { ClaimWorkflowStep } from "src/Types&Enums/claim-request-management/claim-workflow-steps.enum"; +import { CreateWorkflowStepDto } from "./dto/create-workflow-step.dto"; +import { UpdateWorkflowStepDto } from "./dto/update-workflow-step.dto"; +import { WorkflowStepDbService } from "./entities/db-service/workflow-step.db.service"; import { WorkflowStepModel } from "./entities/schema/workflow-step.schema"; // Type alias for combined workflow steps @@ -76,19 +75,6 @@ export class WorkflowStepManagementService { return step; } - /** - * Find a workflow step by step key (supports both blame and claim workflows) - */ - async findByStepKey(stepKey: AnyWorkflowStep): Promise { - const step = await this.workflowStepDbService.findByStepKey(stepKey as any); - if (!step) { - throw new NotFoundException( - `Workflow step with key ${stepKey} not found`, - ); - } - return step; - } - /** * Find a workflow step by stepKey or stepNumber (intelligent lookup) */ @@ -121,13 +107,6 @@ export class WorkflowStepManagementService { return step; } - /** - * Find steps by category - */ - async findByCategory(category: string): Promise { - return await this.workflowStepDbService.findByCategory(category); - } - /** * Update a workflow step by ID */ @@ -172,74 +151,6 @@ export class WorkflowStepManagementService { return removed; } - /** - * Get the next possible steps from a given step (supports both blame and claim) - */ - async getNextSteps(stepKey: AnyWorkflowStep): Promise { - const currentStep = await this.findByStepKey(stepKey); - - if ( - !currentStep.nextPossibleSteps || - currentStep.nextPossibleSteps.length === 0 - ) { - return []; - } - - const nextSteps: WorkflowStepModel[] = []; - for (const nextStepKey of currentStep.nextPossibleSteps) { - const step = await this.workflowStepDbService.findByStepKey( - nextStepKey as any, - ); - if (step && step.isActive) { - nextSteps.push(step); - } - } - - return nextSteps; - } - - /** - * Validate if a step can be accessed based on completed steps (supports both blame and claim) - */ - async validateStepAccess( - stepKey: AnyWorkflowStep, - completedSteps: AnyWorkflowStep[], - ): Promise<{ canAccess: boolean; missingSteps: AnyWorkflowStep[] }> { - const step = await this.findByStepKey(stepKey); - - if ( - !step.requiredPreviousSteps || - step.requiredPreviousSteps.length === 0 - ) { - return { canAccess: true, missingSteps: [] }; - } - - const missingSteps = step.requiredPreviousSteps.filter( - (requiredStep) => !completedSteps.includes(requiredStep as any), - ); - - return { - canAccess: missingSteps.length === 0, - missingSteps, - }; - } - - /** - * Get the fields for a specific step (for dynamic form generation) - */ - async getStepFields(stepKey: AnyWorkflowStep): Promise { - const step = await this.findByStepKey(stepKey); - - return { - stepKey: step.stepKey, - stepName_fa: step.stepName_fa, - stepName_en: step.stepName_en, - description_fa: step.description_fa, - description_en: step.description_en, - fields: step.fields || [], - }; - } - /** * Bulk upsert workflow steps */ diff --git a/test/contracts/api-routes.json b/test/contracts/api-routes.json new file mode 100644 index 0000000..1b18762 --- /dev/null +++ b/test/contracts/api-routes.json @@ -0,0 +1,4372 @@ +[ + { + "controller": "ProfileController", + "method": "DELETE", + "path": "/user/profile/plate/:id", + "guards": [ + "GlobalGuard" + ], + "roles": [] + }, + { + "controller": "WorkflowStepManagementController", + "method": "DELETE", + "path": "/workflow-step-management/:id", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "GET", + "path": "/actor/captcha", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "GET", + "path": "/actor/captcha/:captchaId/image", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "GET", + "path": "/actor/profile", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "GET", + "path": "/actor/register/form/cities/list/:stateId", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "GET", + "path": "/actor/register/form/states/list", + "guards": [], + "roles": [] + }, + { + "controller": "ClaimRequestManagementController", + "method": "GET", + "path": "/claim-request-management/car-other-part", + "guards": [ + "ClaimAccessGuard", + "RolesGuard" + ], + "roles": [ + "user", + "expert", + "damage_expert" + ] + }, + { + "controller": "ClientController", + "method": "GET", + "path": "/client", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ClientPanelController", + "method": "GET", + "path": "/client-panel/settings", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ClientExternalInquiriesController", + "method": "GET", + "path": "/client/:clientId/external-inquiries", + "guards": [], + "roles": [] + }, + { + "controller": "ClientExternalInquiriesController", + "method": "GET", + "path": "/client/external-inquiries", + "guards": [], + "roles": [] + }, + { + "controller": "ClientExternalInquiriesController", + "method": "GET", + "path": "/client/external-inquiries/catalog", + "guards": [], + "roles": [] + }, + { + "controller": "ClientController", + "method": "GET", + "path": "/client/list", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ExpertBlameController", + "method": "GET", + "path": "/expert-blame", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "GET", + "path": "/expert-blame/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "GET", + "path": "/expert-blame/request/accident-fields", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "GET", + "path": "/expert-blame/stream/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "GET", + "path": "/expert-blame/voice/:requestId/:voiceId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "damage_expert" + ] + }, + { + "controller": "ExpertClaimController", + "method": "GET", + "path": "/expert-claim/imageRequired/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert" + ] + }, + { + "controller": "ExpertClaimController", + "method": "GET", + "path": "/expert-claim/stream/:id/voice", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/:expertId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/branches", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/expert-work-log", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/experts/list", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/experts/top", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/files/:publicId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/files/:publicId/ai-analysis", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "CaseExpertReportInsurerController", + "method": "GET", + "path": "/expert-insurer/files/:publicId/report", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/files/:publicId/timeline", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/report/charts", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/report/status-counts", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/report/unified-file-statuses", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/statistics", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/top-experts", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "GET", + "path": "/expert-insurer/top-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-causes", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-culprit-type", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-fields", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-level", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-reason", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-report-type", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-type", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/accident-way", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/ans", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/body-policy/:policyId", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/car-components", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/cii-validation-status", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/cities", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/countries", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/detection-accident-culprits", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/dmg-business-line", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/dmg-case-type", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/dmg-history-status", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/dmg-pay-method", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/driving-licence-types", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/drop-amount-status", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/expert-status", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/fanavaran", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/fanavaran/:lookupName", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/file-types", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/gender", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/inquiry-by-unique-identifier", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/inquiry-by-vin", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/inspection-place", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/marital-status", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/my-policies", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/other-people/:personId", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/person-kind", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/person-role", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/processed-body-policy", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/processed-third-party-policy", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/provinces", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/third-party-policy/:policyId", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/used-place", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-hull-accident-culprit-type", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-hull-accident-types", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-hull-dmg-accessories/:policyId", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-hull-dmg-cost-kinds", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-hull-dmg-kind", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-kinds", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-list", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle-use-types", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "LookupsController", + "method": "GET", + "path": "/lookups/vehicle/:vehicleId", + "guards": [ + "AuthGuard" + ], + "roles": [] + }, + { + "controller": "ReportsController", + "method": "GET", + "path": "/reports/report/insurer/checked-requests", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ReportsController", + "method": "GET", + "path": "/reports/report/insurer/expert-work-log", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ReportsController", + "method": "GET", + "path": "/reports/report/insurer/expert-work-log/per-month", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ReportsController", + "method": "GET", + "path": "/reports/report/insurer/per-month-requests", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ReportsController", + "method": "GET", + "path": "/reports/report/insurer/requests", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/accounts", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/clients", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/clients/names", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/:expertId", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/branches", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/experts/list", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/experts/top", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/files", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/files/:publicId", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/files/:publicId/ai-analysis", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/files/:publicId/timeline", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/report/status-counts", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/report/unified-file-statuses", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/statistics", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/insurer/top-files", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "GET", + "path": "/super-admin/system-settings", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SystemSettingsController", + "method": "GET", + "path": "/system-settings", + "guards": [ + "SettingsJwtGuard", + "RolesGuard" + ], + "roles": [ + "admin", + "company", + "super_admin" + ] + }, + { + "controller": "SystemSettingsController", + "method": "GET", + "path": "/system-settings/offline-inquiry", + "guards": [ + "SettingsJwtGuard", + "RolesGuard" + ], + "roles": [ + "admin", + "super_admin", + "expert", + "damage_expert", + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ProfileController", + "method": "GET", + "path": "/user/profile", + "guards": [ + "GlobalGuard" + ], + "roles": [] + }, + { + "controller": "RequestManagementV2Controller", + "method": "GET", + "path": "/v2/blame-request-management", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "GET", + "path": "/v2/blame-request-management/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "GET", + "path": "/v2/blame-request-management/resend-requirements/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "GET", + "path": "/v2/claim-request-management/branches/:insuranceId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "GET", + "path": "/v2/claim-request-management/capture-requirements/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "GET", + "path": "/v2/claim-request-management/car-other-part", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "GET", + "path": "/v2/claim-request-management/outer-parts-catalog", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "GET", + "path": "/v2/claim-request-management/request/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "GET", + "path": "/v2/claim-request-management/requests", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "GET", + "path": "/v2/expert-blame", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "GET", + "path": "/v2/expert-blame/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "GET", + "path": "/v2/expert-blame/report/status-counts", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "GET", + "path": "/v2/expert-blame/report/unified-file-statuses", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/branches", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/inner-parts-catalog", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/outer-parts-catalog", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/report/status-counts", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/report/unified-file-statuses", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/request/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/request/:claimRequestId/ai-analysis", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/request/:claimRequestId/fanavaran-stage-fields", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/request/:claimRequestId/fanavaran-vehicle-options", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/request/:claimRequestId/price-drop", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/requests", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "GET", + "path": "/v2/expert-claim/stream/:id/video", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "GET", + "path": "/v2/expert-initiated-blame/blame/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "GET", + "path": "/v2/expert-initiated-blame/my-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "GET", + "path": "/v2/expert-initiated/claim-request-management/branches/:insuranceId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "GET", + "path": "/v2/expert-initiated/claim-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "GET", + "path": "/v2/expert-initiated/claim-request-management/car-other-part", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "GET", + "path": "/v2/expert-initiated/claim-request-management/outer-parts-catalog", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "FanavaranController", + "method": "GET", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/attachments/preview", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "GET", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/base-claim/preview", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "GET", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/damage-case/preview", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "GET", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/expertise/preview", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "GET", + "path": "/v2/fanavaran/clients", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "GET", + "path": "/v2/registrar/claim-request-management/branches/:insuranceId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "GET", + "path": "/v2/registrar/claim-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "GET", + "path": "/v2/registrar/claim-request-management/car-other-part", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "GET", + "path": "/v2/registrar/claim-request-management/outer-parts-catalog", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "GET", + "path": "/v3/expert-initiated/blame-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "GET", + "path": "/v3/expert-initiated/blame-request-management/claim-id/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "GET", + "path": "/v4/file-maker/blame-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "GET", + "path": "/v4/file-maker/blame-request-management/claim-id/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "GET", + "path": "/v4/file-maker/blame-request-management/my-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "GET", + "path": "/v4/file-maker/blame-request-management/my-files/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "GET", + "path": "/v4/file-reviewer/blame-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "GET", + "path": "/v4/file-reviewer/blame-request-management/claim-id/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "GET", + "path": "/v4/file-reviewer/blame-request-management/my-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "GET", + "path": "/v4/file-reviewer/blame-request-management/my-files/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "GET", + "path": "/v5/file-maker/blame-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "GET", + "path": "/v5/file-maker/blame-request-management/claim-id/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "GET", + "path": "/v5/file-maker/blame-request-management/my-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "GET", + "path": "/v5/file-maker/blame-request-management/my-files/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "GET", + "path": "/v5/file-reviewer/blame-request-management/capture-requirements/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "GET", + "path": "/v5/file-reviewer/blame-request-management/claim-id/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "GET", + "path": "/v5/file-reviewer/blame-request-management/my-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "GET", + "path": "/v5/file-reviewer/blame-request-management/my-files/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "CallCenterBlameV6Controller", + "method": "GET", + "path": "/v6/call-center-blame/blame/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "call_center" + ] + }, + { + "controller": "CallCenterBlameV6Controller", + "method": "GET", + "path": "/v6/call-center-blame/my-files", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "call_center" + ] + }, + { + "controller": "WorkflowStepManagementController", + "method": "GET", + "path": "/workflow-step-management", + "guards": [], + "roles": [] + }, + { + "controller": "WorkflowStepManagementController", + "method": "GET", + "path": "/workflow-step-management/:id", + "guards": [], + "roles": [] + }, + { + "controller": "WorkflowStepManagementController", + "method": "GET", + "path": "/workflow-step-management/find/:identifier", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "PATCH", + "path": "/actor/profile", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "ClientPanelController", + "method": "PATCH", + "path": "/client-panel/settings", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ClientExternalInquiriesController", + "method": "PATCH", + "path": "/client/:clientId/external-inquiries", + "guards": [], + "roles": [] + }, + { + "controller": "ClientController", + "method": "PATCH", + "path": "/client/external-inquiries-live", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ExpertBlameController", + "method": "PATCH", + "path": "/expert-blame/:id/visit", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "SuperAdminController", + "method": "PATCH", + "path": "/super-admin/external-inquiries-live", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "PATCH", + "path": "/super-admin/system-settings", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SystemSettingsController", + "method": "PATCH", + "path": "/system-settings", + "guards": [ + "SettingsJwtGuard", + "RolesGuard" + ], + "roles": [ + "admin", + "super_admin" + ] + }, + { + "controller": "SystemSettingsController", + "method": "PATCH", + "path": "/system-settings/offline-inquiry", + "guards": [ + "SettingsJwtGuard", + "RolesGuard" + ], + "roles": [ + "admin", + "super_admin", + "expert", + "damage_expert", + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ProfileController", + "method": "PATCH", + "path": "/user/profile", + "guards": [ + "GlobalGuard" + ], + "roles": [] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PATCH", + "path": "/v2/claim-request-management/car-capture/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PATCH", + "path": "/v2/claim-request-management/request/reply/:claimRequestId/:partId/upload-factor", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PATCH", + "path": "/v2/claim-request-management/select-other-parts/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PATCH", + "path": "/v2/claim-request-management/select-outer-parts/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PATCH", + "path": "/v2/expert-claim/:claimRequestId/visit", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PATCH", + "path": "/v2/expert-claim/request/:claimRequestId/damaged-parts", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PATCH", + "path": "/v2/expert-claim/request/:claimRequestId/fanavaran-stage-fields", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PATCH", + "path": "/v2/expert-claim/validate-factors/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "PATCH", + "path": "/v2/expert-initiated/claim-request-management/car-capture/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "PATCH", + "path": "/v2/expert-initiated/claim-request-management/select-other-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "PATCH", + "path": "/v2/expert-initiated/claim-request-management/select-outer-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "PATCH", + "path": "/v2/registrar/claim-request-management/car-capture/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "PATCH", + "path": "/v2/registrar/claim-request-management/select-other-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "PATCH", + "path": "/v2/registrar/claim-request-management/select-outer-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "PATCH", + "path": "/v3/expert-initiated/blame-request-management/car-capture/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "PATCH", + "path": "/v3/expert-initiated/blame-request-management/select-other-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "PATCH", + "path": "/v3/expert-initiated/blame-request-management/select-outer-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "PATCH", + "path": "/v4/file-reviewer/blame-request-management/car-capture/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "PATCH", + "path": "/v4/file-reviewer/blame-request-management/select-other-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "PATCH", + "path": "/v4/file-reviewer/blame-request-management/select-outer-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "PATCH", + "path": "/v5/file-reviewer/blame-request-management/car-capture/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "PATCH", + "path": "/v5/file-reviewer/blame-request-management/select-other-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "PATCH", + "path": "/v5/file-reviewer/blame-request-management/select-outer-parts/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "WorkflowStepManagementController", + "method": "PATCH", + "path": "/workflow-step-management/:id", + "guards": [], + "roles": [] + }, + { + "controller": "WorkflowStepManagementController", + "method": "PATCH", + "path": "/workflow-step-management/step/:stepKey", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "POST", + "path": "/actor/create-field-expert", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "POST", + "path": "/actor/create-registrar", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "POST", + "path": "/actor/forget-password", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "POST", + "path": "/actor/forget-password-verify", + "guards": [], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "POST", + "path": "/actor/login", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "ActorAuthController", + "method": "POST", + "path": "/actor/register/insurer", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ClientController", + "method": "POST", + "path": "/client", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "ExpertInitiatedController", + "method": "POST", + "path": "/expert-initiated-blame/add-accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "POST", + "path": "/expert-insurer/branches", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "POST", + "path": "/expert-insurer/experts/blame", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "POST", + "path": "/expert-insurer/experts/claim", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "POST", + "path": "/expert-insurer/experts/file-maker", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "POST", + "path": "/expert-insurer/experts/file-reviewer", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "POST", + "path": "/expert-insurer/files/:publicId/ai-analysis/retry", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/accounts", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/clients", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/create-call-center-agent", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/create-field-expert", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/create-registrar", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/insurer/branches", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/insurer/experts/blame", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/insurer/experts/claim", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/insurer/experts/file-maker", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/insurer/experts/file-reviewer", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/insurer/files/:publicId/ai-analysis/retry", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SuperAdminController", + "method": "POST", + "path": "/super-admin/register/insurer", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "SystemSettingsController", + "method": "POST", + "path": "/system-settings/fanavaran-config/reload", + "guards": [ + "SettingsJwtGuard", + "RolesGuard" + ], + "roles": [ + "admin", + "super_admin", + "expert", + "damage_expert", + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "UserAuthController", + "method": "POST", + "path": "/user/login", + "guards": [ + "LocalUserAuthGuard" + ], + "roles": [] + }, + { + "controller": "ProfileController", + "method": "POST", + "path": "/user/profile/plate", + "guards": [ + "GlobalGuard" + ], + "roles": [] + }, + { + "controller": "UserAuthController", + "method": "POST", + "path": "/user/send-otp", + "guards": [], + "roles": [] + }, + { + "controller": "InquiryRefreshController", + "method": "POST", + "path": "/v2/blame-inquiries/reinquiry", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "admin", + "field_expert" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/add-detail-description/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/add-detail-location/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/add-second-party/:phoneNumber/:requestId/:frontendRoute", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/blame-confession/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/car-body-form/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/initial-form-vin/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/initial-form/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/upload-video/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "POST", + "path": "/v2/blame-request-management/upload-voice/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard", + "GlobalGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "POST", + "path": "/v2/claim-request-management/capture-part/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "POST", + "path": "/v2/claim-request-management/create-from-blame/:blameRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "POST", + "path": "/v2/claim-request-management/request/:claimRequestId/expert-resend/acknowledge", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "POST", + "path": "/v2/claim-request-management/upload-document/:claimRequestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "POST", + "path": "/v2/expert-blame/:id/assign", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "POST", + "path": "/v2/expert-claim/assign/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "POST", + "path": "/v2/expert-claim/request/:claimRequestId/ai-analysis/retry", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/add-accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/add-locations/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/complete-blame-data/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/complete-claim-data/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/create", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/create-claim-from-blame/:blameRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/send-link/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/send-party-otps/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/upload-party-signature/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/upload-video/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/upload-voice/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedV2Controller", + "method": "POST", + "path": "/v2/expert-initiated-blame/verify-party-otps/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/add-detail-description/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/add-detail-location/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/add-second-party/:phoneNumber/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/car-body-form/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/run-inquiries-vin/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/run-inquiries/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/send-link/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/send-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/upload-video/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/upload-voice/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/blame-request-management/verify-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/claim-request-management/capture-part/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/claim-request-management/create-from-blame/:blameRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "POST", + "path": "/v2/expert-initiated/claim-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "FanavaranController", + "method": "POST", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/attachments/submit", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "POST", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/base-claim/submit", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "POST", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/damage-case/submit", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "FanavaranController", + "method": "POST", + "path": "/v2/fanavaran/:client/claim-cases/:claimCaseId/expertise/submit", + "guards": [ + "LocalActorAuthGuard" + ], + "roles": [] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/add-accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/add-detail-description/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/add-detail-location/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/add-second-party/:phoneNumber/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/car-body-form/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/initial-form-vin/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/initial-form/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/send-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/upload-video/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/upload-voice/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "POST", + "path": "/v2/registrar/blame-request-management/verify-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "POST", + "path": "/v2/registrar/claim-request-management/capture-part/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "POST", + "path": "/v2/registrar/claim-request-management/create-from-blame/:blameRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "RegistrarClaimMirrorController", + "method": "POST", + "path": "/v2/registrar/claim-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/add-detail-description/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/add-detail-location/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/capture-part/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/car-body-form/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/run-inquiries-vin/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/run-inquiries/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/send-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/upload-video/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/upload-voice/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "POST", + "path": "/v3/expert-initiated/blame-request-management/verify-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/add-detail-description/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/add-detail-location/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/car-body-form/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/run-inquiries-vin/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/run-inquiries/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/send-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/upload-voice/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "POST", + "path": "/v4/file-maker/blame-request-management/verify-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "POST", + "path": "/v4/file-reviewer/blame-request-management/accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "POST", + "path": "/v4/file-reviewer/blame-request-management/capture-part/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "POST", + "path": "/v4/file-reviewer/blame-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "POST", + "path": "/v4/file-reviewer/blame-request-management/upload-video/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/add-detail-description/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/add-detail-location/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/car-body-form/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/run-inquiries-vin/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/run-inquiries/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/send-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/upload-voice/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "POST", + "path": "/v5/file-maker/blame-request-management/verify-party-otp/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerClaimApprovalV5Controller", + "method": "POST", + "path": "/v5/file-maker/claim-approval/approve/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileMakerClaimApprovalV5Controller", + "method": "POST", + "path": "/v5/file-maker/claim-approval/reject/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "POST", + "path": "/v5/file-reviewer/blame-request-management/accident-fields/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "POST", + "path": "/v5/file-reviewer/blame-request-management/capture-part/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "POST", + "path": "/v5/file-reviewer/blame-request-management/upload-document/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "POST", + "path": "/v5/file-reviewer/blame-request-management/upload-video/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "CallCenterBlameV6Controller", + "method": "POST", + "path": "/v6/call-center-blame/create", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "call_center" + ] + }, + { + "controller": "CallCenterBlameV6Controller", + "method": "POST", + "path": "/v6/call-center-blame/run-inquiry-vin/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "call_center" + ] + }, + { + "controller": "CallCenterBlameV6Controller", + "method": "POST", + "path": "/v6/call-center-blame/run-inquiry/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "call_center" + ] + }, + { + "controller": "CallCenterBlameV6Controller", + "method": "POST", + "path": "/v6/call-center-blame/send-link/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "call_center" + ] + }, + { + "controller": "WorkflowStepManagementController", + "method": "POST", + "path": "/workflow-step-management", + "guards": [], + "roles": [] + }, + { + "controller": "WorkflowStepManagementController", + "method": "POST", + "path": "/workflow-step-management/initialize", + "guards": [], + "roles": [] + }, + { + "controller": "ClientExternalInquiriesController", + "method": "PUT", + "path": "/client/:clientId/external-inquiries", + "guards": [], + "roles": [] + }, + { + "controller": "ExpertBlameController", + "method": "PUT", + "path": "/expert-blame/lock/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "PUT", + "path": "/expert-blame/reply/resend/first/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "PUT", + "path": "/expert-blame/reply/resend/second/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertBlameController", + "method": "PUT", + "path": "/expert-blame/reply/submit/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "PUT", + "path": "/expert-insurer/branches/:branchId/status", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "ExpertInsurerController", + "method": "PUT", + "path": "/expert-insurer/files/:publicId/rating", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "company" + ] + }, + { + "controller": "SuperAdminController", + "method": "PUT", + "path": "/super-admin/insurer/branches/:branchId/status", + "guards": [ + "SuperAdminGuard" + ], + "roles": [] + }, + { + "controller": "RequestManagementV2Controller", + "method": "PUT", + "path": "/v2/blame-request-management/resend/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "RequestManagementV2Controller", + "method": "PUT", + "path": "/v2/blame-request-management/sign/:requestId", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PUT", + "path": "/v2/claim-request-management/request/:claimRequestId/objection", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PUT", + "path": "/v2/claim-request-management/request/:claimRequestId/owner-insurer-approval/sign", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ClaimRequestManagementV2Controller", + "method": "PUT", + "path": "/v2/claim-request-management/request/:claimRequestId/user-rating", + "guards": [ + "GlobalGuard", + "RolesGuard" + ], + "roles": [ + "user", + "field_expert", + "registrar", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "PUT", + "path": "/v2/expert-blame/lock/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "PUT", + "path": "/v2/expert-blame/reply/inPerson/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "PUT", + "path": "/v2/expert-blame/reply/resend/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertBlameV2Controller", + "method": "PUT", + "path": "/v2/expert-blame/reply/submit/:id", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "expert", + "field_expert" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PUT", + "path": "/v2/expert-claim/lock/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PUT", + "path": "/v2/expert-claim/reply/resend/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PUT", + "path": "/v2/expert-claim/reply/submit/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PUT", + "path": "/v2/expert-claim/request/:claimRequestId/fanavaran-vehicle-review", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertClaimV2Controller", + "method": "PUT", + "path": "/v2/expert-claim/request/:claimRequestId/price-drop", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "damage_expert", + "field_expert", + "file_reviewer", + "file_maker" + ] + }, + { + "controller": "ExpertInitiatedBlameMirrorController", + "method": "PUT", + "path": "/v2/expert-initiated/blame-request-management/sign/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "ExpertInitiatedClaimMirrorController", + "method": "PUT", + "path": "/v2/expert-initiated/claim-request-management/claim-sign/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert", + "file_maker", + "file_reviewer" + ] + }, + { + "controller": "RegistrarBlameMirrorController", + "method": "PUT", + "path": "/v2/registrar/blame-request-management/sign/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "registrar" + ] + }, + { + "controller": "ExpertInitiatedBlameV3MirrorController", + "method": "PUT", + "path": "/v3/expert-initiated/blame-request-management/sign/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "field_expert" + ] + }, + { + "controller": "FileMakerBlameV4Controller", + "method": "PUT", + "path": "/v4/file-maker/blame-request-management/sign/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileReviewerBlameV4Controller", + "method": "PUT", + "path": "/v4/file-reviewer/blame-request-management/claim-sign/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + }, + { + "controller": "FileMakerBlameV5Controller", + "method": "PUT", + "path": "/v5/file-maker/blame-request-management/sign/:requestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_maker" + ] + }, + { + "controller": "FileReviewerBlameV5Controller", + "method": "PUT", + "path": "/v5/file-reviewer/blame-request-management/claim-sign/:claimRequestId", + "guards": [ + "LocalActorAuthGuard", + "RolesGuard" + ], + "roles": [ + "file_reviewer" + ] + } +]
MethodRouteWhat it does
POSTregistrar-initiated-blame/createCreate IN_PERSON blame file.