forked from Yara724/api
Merge pull request 'Enforce claim beneficiary access and retire unused legacy APIs' (#354) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#354
This commit is contained in:
@@ -290,7 +290,7 @@
|
||||
<div class="max-wrap">
|
||||
<h1>Blame & Claim Flow Architecture</h1>
|
||||
<p class="subtitle">
|
||||
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.
|
||||
</p>
|
||||
|
||||
@@ -394,9 +394,9 @@
|
||||
<th>Claim / Review prefix</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>V1 (legacy)</td>
|
||||
<td><code>blame-request-management/</code></td>
|
||||
<td><code>claim-request-management/</code></td>
|
||||
<td>V1 user screens</td>
|
||||
<td><code>v2/blame-request-management/</code></td>
|
||||
<td><code>v2/claim-request-management/</code></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>V2 user</td>
|
||||
@@ -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, <code>@ApiExcludeController</code>) ·
|
||||
V2 = same logic, <code>v2/</code> prefix, GlobalGuard + RolesGuard (USER).
|
||||
Both current V1 and V2 user screens use the <code>v2/</code> APIs with GlobalGuard + RolesGuard (USER).
|
||||
Retired unversioned V1 mutations are removed; active V1 business rules and the blame-expert APIs remain.
|
||||
See <a href="legacy-api-cleanup.md">the route retirement audit</a> for retained compatibility routes.
|
||||
</p>
|
||||
<div class="grid grid-2">
|
||||
<div class="card">
|
||||
|
||||
@@ -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.
|
||||
@@ -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` |
|
||||
@@ -536,8 +536,9 @@
|
||||
</p>
|
||||
|
||||
<div class="card card-gray">
|
||||
<h3>ثبت تقصیر — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">توجه: <code>@ApiExcludeController</code> — مسیرها وجود دارند اما در مستندات Swagger نمایش داده نمیشوند.</p>
|
||||
<h3>مرجع تاریخی ثبت تقصیر — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">مسیرهای بدون نسخه زیر حذف شدهاند. مسیر فعال ثبت تقصیر <code>v2/registrar/blame-request-management/</code> است. <a href="legacy-api-cleanup.md">گزارش حذف مسیرهای قدیمی</a></p>
|
||||
<p class="note">این جدول فقط مرجع تاریخی است؛ هندلرهای زیر دیگر ثبت نشدهاند.</p>
|
||||
<table>
|
||||
<tr><th style="width:70px">متد</th><th>مسیر</th><th>توضیح</th></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>registrar-initiated-blame/create</code></td><td>ایجاد فایل تقصیر IN_PERSON.</td></tr>
|
||||
|
||||
@@ -528,8 +528,9 @@
|
||||
</p>
|
||||
|
||||
<div class="card card-gray">
|
||||
<h3>Blame filing — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">Note: <code>@ApiExcludeController</code> — routes exist but not surfaced in Swagger docs.</p>
|
||||
<h3>Historical blame filing — <code>registrar-initiated-blame/</code></h3>
|
||||
<p class="note">The unversioned routes below have been retired. Current filing uses <code>v2/registrar/blame-request-management/</code>. See <a href="legacy-api-cleanup.md">the retirement audit</a>.</p>
|
||||
<p class="note">Historical reference only — these handlers are no longer registered.</p>
|
||||
<table>
|
||||
<tr><th style="width:70px">Method</th><th>Route</th><th>What it does</th></tr>
|
||||
<tr><td><span class="method post">POST</span></td><td><code>registrar-initiated-blame/create</code></td><td>Create IN_PERSON blame file.</td></tr>
|
||||
|
||||
@@ -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",
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
export class PriceDropIF {
|
||||
total: number;
|
||||
carPrice: number;
|
||||
carModel: number;
|
||||
carValue: number[];
|
||||
sumOfSeverity: number;
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export enum InPersonDocumentsEnum {
|
||||
NationalCertificate = "nationalCertificate",
|
||||
CarCertificate = "carCertificate",
|
||||
DrivingLicense = "drivingLicense",
|
||||
CarGreenCard = "carGreenCard",
|
||||
Plate = "plate",
|
||||
CarPlate = "carPlate",
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export enum UploaderModeEnum {
|
||||
Sign = "uploadService",
|
||||
Certificate = "certService",
|
||||
}
|
||||
@@ -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 })
|
||||
|
||||
@@ -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<string, any>, keys: string[]) {
|
||||
const out: Record<string, any> = {};
|
||||
@@ -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<string, unknown>);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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<string, { uploaded: boolean; fileUrl?: string }>;
|
||||
|
||||
@ApiPropertyOptional({ description: 'Car angles captured' })
|
||||
@ApiPropertyOptional({ description: "Car angles captured" })
|
||||
carAngles?: Record<string, { captured: boolean; url?: string }>;
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
export class CreateClaimRequestDtoRs {
|
||||
message: string;
|
||||
requestId: string;
|
||||
constructor(requestId: string, message: string) {
|
||||
this.requestId = requestId;
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
export class UserReplyDtoRs {
|
||||
requestId: string;
|
||||
isAccept: string;
|
||||
}
|
||||
@@ -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<CarGreenCardModel>,
|
||||
) {}
|
||||
async create(greenCard): Promise<CarGreenCardModel> {
|
||||
return await this.model.create(greenCard);
|
||||
}
|
||||
|
||||
async findOne(
|
||||
filter: FilterQuery<CarGreenCardModel>,
|
||||
): Promise<CarGreenCardModel> {
|
||||
return await this.model.findOne({ filter });
|
||||
}
|
||||
}
|
||||
@@ -14,11 +14,15 @@ export class ClaimCaseDbService {
|
||||
return this.claimCaseModel.create(payload);
|
||||
}
|
||||
|
||||
async findById(id: string | Types.ObjectId): Promise<ClaimCaseDocument | null> {
|
||||
async findById(
|
||||
id: string | Types.ObjectId,
|
||||
): Promise<ClaimCaseDocument | null> {
|
||||
return this.claimCaseModel.findById(id);
|
||||
}
|
||||
|
||||
async findOne(filter: FilterQuery<ClaimCase>): Promise<ClaimCaseDocument | null> {
|
||||
async findOne(
|
||||
filter: FilterQuery<ClaimCase>,
|
||||
): Promise<ClaimCaseDocument | null> {
|
||||
return this.claimCaseModel.findOne(filter);
|
||||
}
|
||||
|
||||
@@ -54,8 +58,4 @@ export class ClaimCaseDbService {
|
||||
: this.claimCaseModel.find(filter);
|
||||
return query.exec() as Promise<ClaimCaseDocument[]>;
|
||||
}
|
||||
|
||||
async countByFilter(filter: FilterQuery<ClaimCase>): Promise<number> {
|
||||
return this.claimCaseModel.countDocuments(filter);
|
||||
}
|
||||
}
|
||||
|
||||
-72
@@ -11,16 +11,6 @@ export class ClaimRequestManagementDbService {
|
||||
private readonly model: Model<ClaimRequestManagementModel>,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
claimRequest: ClaimRequestManagementModel,
|
||||
): Promise<ClaimRequestManagementModel> {
|
||||
const uniqueRequestNumber = await this.generateUniqueNumbers();
|
||||
return this.model.create({
|
||||
...claimRequest,
|
||||
requestNumber: uniqueRequestNumber,
|
||||
});
|
||||
}
|
||||
|
||||
async findOne(
|
||||
id?: string,
|
||||
filter?: FilterQuery<ClaimRequestManagementModel>,
|
||||
@@ -45,31 +35,6 @@ export class ClaimRequestManagementDbService {
|
||||
return await this.model.findOneAndUpdate(filter, update, option);
|
||||
}
|
||||
|
||||
async findAllByStatus(filter: FilterQuery<ClaimRequestManagementModel>) {
|
||||
return await this.model.find(filter);
|
||||
}
|
||||
|
||||
async findAndDelete(
|
||||
filter: FilterQuery<ClaimRequestManagementModel>,
|
||||
option,
|
||||
) {
|
||||
return await this.model.deleteMany(filter, option);
|
||||
}
|
||||
|
||||
async findAllAndPagination(
|
||||
filter: FilterQuery<ClaimRequestManagementModel>,
|
||||
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<ClaimRequestManagementModel>,
|
||||
@@ -81,41 +46,4 @@ export class ClaimRequestManagementDbService {
|
||||
option,
|
||||
);
|
||||
}
|
||||
|
||||
async findAllByAnyFilter(
|
||||
filter: FilterQuery<ClaimRequestManagementModel>,
|
||||
): Promise<ClaimRequestManagementModel[]> {
|
||||
return await this.model.find(filter);
|
||||
}
|
||||
|
||||
async countByFilter(
|
||||
filter: FilterQuery<ClaimRequestManagementModel>,
|
||||
): Promise<number> {
|
||||
return await this.model.countDocuments(filter);
|
||||
}
|
||||
async findAll(): Promise<ClaimRequestManagementModel[]> {
|
||||
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<ClaimRequestManagementModel>) {
|
||||
return await this.model.find(filter);
|
||||
}
|
||||
|
||||
async findByIdAndUpdate(
|
||||
id: string,
|
||||
updateDto: UpdateQuery<ClaimRequestManagementModel>,
|
||||
): Promise<ClaimRequestManagementModel | null> {
|
||||
return this.model.findByIdAndUpdate(id, updateDto, { new: true }).lean();
|
||||
}
|
||||
}
|
||||
|
||||
+4
-23
@@ -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<ClaimRequiredDocument>,
|
||||
) {}
|
||||
|
||||
async create(document: Partial<ClaimRequiredDocument>): Promise<ClaimRequiredDocument> {
|
||||
async create(
|
||||
document: Partial<ClaimRequiredDocument>,
|
||||
): Promise<ClaimRequiredDocument> {
|
||||
return await this.model.create(document);
|
||||
}
|
||||
|
||||
async findOne(
|
||||
filter: FilterQuery<ClaimRequiredDocument>,
|
||||
): Promise<ClaimRequiredDocument | null> {
|
||||
return await this.model.findOne(filter);
|
||||
}
|
||||
|
||||
async findAll(
|
||||
filter: FilterQuery<ClaimRequiredDocument>,
|
||||
): Promise<ClaimRequiredDocument[]> {
|
||||
return await this.model.find(filter);
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<ClaimRequiredDocument | null> {
|
||||
return this.model.findById(id).lean();
|
||||
}
|
||||
|
||||
async findByClaimId(claimId: string): Promise<ClaimRequiredDocument[]> {
|
||||
return this.model.find({ claimId: new Types.ObjectId(claimId) });
|
||||
}
|
||||
|
||||
async delete(id: string): Promise<void> {
|
||||
await this.model.findByIdAndDelete(id);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<DamagePartImageModel>,
|
||||
) {}
|
||||
|
||||
async create(image): Promise<DamagePartImageModel> {
|
||||
return await this.model.create(image);
|
||||
}
|
||||
|
||||
async findOne(id: string): Promise<DamagePartImageModel> {
|
||||
return await this.model.findById(new Types.ObjectId(id));
|
||||
}
|
||||
}
|
||||
@@ -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<ClaimFactorsImage>,
|
||||
): Promise<ClaimFactorsImage> {
|
||||
return await this.model.findOne({ filter });
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<ClaimFactorsImage | null> {
|
||||
return this.model.findById(id).lean();
|
||||
}
|
||||
|
||||
@@ -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<VideoCaptureModel>,
|
||||
): Promise<VideoCaptureModel> {
|
||||
return await this.videoCapture.findOne(filter);
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<VideoCaptureModel | null> {
|
||||
return this.videoCapture.findById(id);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<ClientExternalInquiriesViewDto> {
|
||||
const client = await this.loadClientOrThrow(clientKey);
|
||||
const flags = mergeExternalInquiryFlags(body as Partial<Record<string, boolean>>);
|
||||
const flags = mergeExternalInquiryFlags(
|
||||
body as Partial<Record<string, boolean>>,
|
||||
);
|
||||
const $set: Record<string, unknown> = {};
|
||||
for (const key of EXTERNAL_INQUIRY_TYPES) {
|
||||
$set[`settings.externalInquiries.${key}`] = flags[key];
|
||||
|
||||
@@ -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<BranchModel | null> {
|
||||
async findByIdAndUpdate(
|
||||
id: string,
|
||||
update: any,
|
||||
): Promise<BranchModel | null> {
|
||||
return this.branchModel.findByIdAndUpdate(id, update, { new: true }).lean();
|
||||
}
|
||||
|
||||
|
||||
@@ -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<string, { doc: any; at: number }>();
|
||||
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<ExternalInquiryFlags> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -1,8 +0,0 @@
|
||||
export {
|
||||
CURRENT_ALGORITHM,
|
||||
CURRENT_VERSION,
|
||||
KEY_LENGTH,
|
||||
KEY_LENGTH_FOR_OTP,
|
||||
SCRYPT_PARAMS,
|
||||
SCRYPT_PARAMS_FOR_OTP,
|
||||
} from "./hash.constants";
|
||||
@@ -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<string, any>;
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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[];
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<Record<string, { totalHandled: number; totalChecked: number }>> {
|
||||
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<string, unknown> | 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<string, unknown>) };
|
||||
@@ -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<Array<{
|
||||
publicId: string;
|
||||
createdAt: string;
|
||||
combinedScore: number;
|
||||
userRating: { comment: string | null; overallEvaluation: number | null };
|
||||
}>> {
|
||||
): 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<any[]>)
|
||||
? (this.blameRequestDbService.find({}, { lean: true }) as Promise<
|
||||
any[]
|
||||
>)
|
||||
: Promise.resolve([] as any[]),
|
||||
(this.claimCaseDbService.find({}, { lean: true }) as Promise<any[]>),
|
||||
this.claimCaseDbService.find({}, { lean: true }) as Promise<any[]>,
|
||||
]);
|
||||
|
||||
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<string, string> = {
|
||||
user: "کاربر",
|
||||
field_expert: "کارشناس میدانی",
|
||||
damage_expert: "کارشناس خسارت",
|
||||
file_maker: "پروندهساز",
|
||||
file_reviewer: "بازبین پرونده",
|
||||
registrar: "ثبتکننده",
|
||||
call_center: "اپراتور کالسنتر",
|
||||
system: "سیستم",
|
||||
expert: "کارشناس",
|
||||
};
|
||||
private static readonly TIMELINE_PERFORMER_FA_LABELS: Record<string, string> =
|
||||
{
|
||||
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),
|
||||
|
||||
@@ -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]";
|
||||
|
||||
@@ -174,7 +174,6 @@ describe("FanavaranAuthService", () => {
|
||||
"parsian",
|
||||
"کد پیگیری خطا: 1\r\n.لطفا پس از چند لحظه مجدد تلاش فرمایید.",
|
||||
);
|
||||
expect(service.isInBackoff("parsian")).toBe(true);
|
||||
expect(() => service.assertNotInBackoff("parsian")).toThrow(/backoff/i);
|
||||
});
|
||||
|
||||
|
||||
@@ -58,7 +58,10 @@ export class FanavaranAuthService {
|
||||
*/
|
||||
static readonly TOKEN_TIME_ZONE = "Asia/Tehran";
|
||||
|
||||
private readonly tokenCache = new Map<FanavaranClientKey, CachedFanavaranAuth>();
|
||||
private readonly tokenCache = new Map<
|
||||
FanavaranClientKey,
|
||||
CachedFanavaranAuth
|
||||
>();
|
||||
private readonly inflightLogin = new Map<
|
||||
FanavaranClientKey,
|
||||
Promise<string>
|
||||
@@ -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<string | null> {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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.");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -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";
|
||||
|
||||
@@ -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<typeof PDFDocument> & {
|
||||
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<typeof PDFDocument>,
|
||||
neededPts: number,
|
||||
): void {
|
||||
if (doc.y + neededPts > doc.page.maxY()) {
|
||||
doc.addPage();
|
||||
}
|
||||
}
|
||||
|
||||
function drawRtlLine(
|
||||
doc: InstanceType<typeof PDFDocument>,
|
||||
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<typeof PDFDocument>,
|
||||
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<typeof PDFDocument>,
|
||||
): Promise<Buffer> {
|
||||
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();
|
||||
});
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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, "\\)")})`;
|
||||
}
|
||||
@@ -10,13 +10,7 @@ export class LookupDbService {
|
||||
private readonly lookupModel: Model<LookupModel>,
|
||||
) {}
|
||||
|
||||
async create(lookupData: Partial<LookupModel>): Promise<LookupModel> {
|
||||
return await this.lookupModel.create(lookupData);
|
||||
}
|
||||
|
||||
async findOne(
|
||||
filter: FilterQuery<LookupModel>,
|
||||
): Promise<LookupModel | null> {
|
||||
async findOne(filter: FilterQuery<LookupModel>): Promise<LookupModel | null> {
|
||||
return await this.lookupModel.findOne(filter).lean();
|
||||
}
|
||||
|
||||
@@ -29,9 +23,4 @@ export class LookupDbService {
|
||||
upsert: true,
|
||||
});
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<LookupModel | null> {
|
||||
return await this.lookupModel.findById(id).lean();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<TKeys extends string>(
|
||||
files: Partial<Record<TKeys, UploadedFileLike[] | undefined>>,
|
||||
claimRequestId: string,
|
||||
fieldKindMap: Record<TKeys, MediaKind | undefined>,
|
||||
): Promise<void> {
|
||||
const provided = this.flattenProvidedFiles<TKeys>(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<TKeys extends string>(
|
||||
files: Partial<Record<TKeys, UploadedFileLike[] | undefined>>,
|
||||
): Array<{ field: TKeys; file: NonNullable<UploadedFileLike> }> {
|
||||
const out: Array<{ field: TKeys; file: NonNullable<UploadedFileLike> }> = [];
|
||||
const out: Array<{ field: TKeys; file: NonNullable<UploadedFileLike> }> =
|
||||
[];
|
||||
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) {
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
export interface PlateType {
|
||||
nationalCodeOfInsurer: string;
|
||||
userId: string;
|
||||
leftDigits: number;
|
||||
centerAlphabet: string;
|
||||
centerDigits: number;
|
||||
ir: number;
|
||||
}
|
||||
@@ -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<boolean> {
|
||||
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");
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<BlameDocumentModel>,
|
||||
) {}
|
||||
|
||||
async create(createDto: Partial<BlameDocumentModel>): Promise<BlameDocumentModel> {
|
||||
async create(
|
||||
createDto: Partial<BlameDocumentModel>,
|
||||
): Promise<BlameDocumentModel> {
|
||||
const newDocument = new this.blameDocumentModel(createDto);
|
||||
return newDocument.save();
|
||||
}
|
||||
|
||||
async findOne(filter: FilterQuery<BlameDocumentModel>): Promise<BlameDocumentModel | null> {
|
||||
return this.blameDocumentModel.findOne(filter).lean();
|
||||
}
|
||||
|
||||
async findAll(filter: FilterQuery<BlameDocumentModel>): Promise<BlameDocumentModel[]> {
|
||||
return this.blameDocumentModel.find(filter).lean();
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<BlameDocumentModel | null> {
|
||||
return this.blameDocumentModel.findById(id).lean();
|
||||
}
|
||||
|
||||
async findByIdAndUpdate(
|
||||
id: string,
|
||||
updateDto: UpdateQuery<BlameDocumentModel>,
|
||||
): Promise<BlameDocumentModel | null> {
|
||||
return this.blameDocumentModel.findByIdAndUpdate(id, updateDto, { new: true }).lean();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,12 +17,6 @@ export class BlameRequestDbService {
|
||||
return this.blameRequestModel.create(payload);
|
||||
}
|
||||
|
||||
async findOne(
|
||||
filter: FilterQuery<BlameRequest>,
|
||||
): Promise<BlameRequestDocument | null> {
|
||||
return this.blameRequestModel.findOne(filter);
|
||||
}
|
||||
|
||||
async findById(
|
||||
id: string | Types.ObjectId,
|
||||
): Promise<BlameRequestDocument | null> {
|
||||
|
||||
@@ -16,10 +16,6 @@ export class BlameVideoDbService {
|
||||
return await this.blameVideoModel.findOne(new Types.ObjectId(id));
|
||||
}
|
||||
|
||||
async findOneByRequestId(id: string): Promise<BlameVideosModel> {
|
||||
return await this.blameVideoModel.findById(id);
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<BlameVideosModel | null> {
|
||||
return this.blameVideoModel.findById(id).lean();
|
||||
}
|
||||
|
||||
@@ -8,12 +8,6 @@ export class RequestManagementDbService {
|
||||
private readonly requestModel: Model<RequestManagementModel>,
|
||||
) {}
|
||||
|
||||
async create(
|
||||
request: RequestManagementModel,
|
||||
): Promise<RequestManagementModel> {
|
||||
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<RequestManagementModel>,
|
||||
): Promise<number> {
|
||||
return await this.requestModel.countDocuments(filter);
|
||||
}
|
||||
|
||||
async findAndUpdate(
|
||||
filter: FilterQuery<RequestManagementModel>,
|
||||
update: UpdateQuery<RequestManagementModel>,
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<UserSignModel> {
|
||||
return await this.blameVoiceModel.findOne(new Types.ObjectId(id));
|
||||
}
|
||||
|
||||
async findById(id: string): Promise<UserSignModel | null> {
|
||||
// Use your correct Model type
|
||||
return this.blameVoiceModel.findById(id).lean();
|
||||
|
||||
@@ -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 {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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!,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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 },
|
||||
|
||||
@@ -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<SandHubModel>,
|
||||
) {}
|
||||
|
||||
async create(sandHubData: any): Promise<SandHubModel> {
|
||||
return await this.sandHubModel.create(sandHubData);
|
||||
}
|
||||
|
||||
async findOneByRequestId(requestId: string, userId): Promise<SandHubModel> {
|
||||
return await this.sandHubModel.findOne({ requestId, userId });
|
||||
}
|
||||
|
||||
async findOneBySandHubId(requestId: string): Promise<SandHubModel> {
|
||||
return await this.sandHubModel.findOne({
|
||||
_id: new Types.ObjectId(requestId),
|
||||
});
|
||||
}
|
||||
|
||||
async findOneByRequestIdAndUpdate(
|
||||
requestId: string,
|
||||
userId: string,
|
||||
update: UpdateQuery<SandHubInterface>,
|
||||
): Promise<any> {
|
||||
return await this.sandHubModel.findOneAndUpdate(
|
||||
{ requestId, userId },
|
||||
update,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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 {}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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<SandHubDetailDto, "plate"> & {
|
||||
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<SandHubModel>,
|
||||
) {
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -39,12 +39,4 @@ export class CallCenterAgentDbService {
|
||||
}
|
||||
return this.model.findOne({ $or: or });
|
||||
}
|
||||
|
||||
async findAll(
|
||||
filter: FilterQuery<CallCenterAgentModel>,
|
||||
): Promise<(CallCenterAgentModel & { _id: Types.ObjectId })[]> {
|
||||
return this.model.find(filter).lean() as Promise<
|
||||
(CallCenterAgentModel & { _id: Types.ObjectId })[]
|
||||
>;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -40,12 +40,6 @@ export class DamageExpertDbService {
|
||||
return await this.damageExpertModel.find(filter).lean();
|
||||
}
|
||||
|
||||
async findAndUpdate(filter: any, update: any): Promise<DamageExpertModel> {
|
||||
return this.damageExpertModel
|
||||
.findOneAndUpdate(filter, update, { new: true })
|
||||
.exec();
|
||||
}
|
||||
|
||||
async updateOne(filter: any, update: any) {
|
||||
return this.damageExpertModel.updateOne(filter, update);
|
||||
}
|
||||
|
||||
@@ -46,31 +46,6 @@ export class ExpertFileActivityDbService {
|
||||
await this.activityModel.create(payload);
|
||||
}
|
||||
|
||||
async findByTenantAndExperts(
|
||||
tenantId: string | Types.ObjectId,
|
||||
expertIds: Array<string | Types.ObjectId>,
|
||||
): 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,
|
||||
|
||||
@@ -26,10 +26,7 @@ export class FileMakerDbService {
|
||||
identifier: string,
|
||||
): Promise<FileMakerModel | null> {
|
||||
const id = identifier.trim();
|
||||
const or: FilterQuery<FileMakerModel>[] = [
|
||||
{ email: id },
|
||||
{ username: id },
|
||||
];
|
||||
const or: FilterQuery<FileMakerModel>[] = [{ 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<FileMakerModel>,
|
||||
): Promise<(FileMakerModel & { _id: Types.ObjectId })[]> {
|
||||
return await this.fileMakerModel.find(filter).lean();
|
||||
}
|
||||
|
||||
async updateOne(filter: FilterQuery<FileMakerModel>, update: any) {
|
||||
return this.fileMakerModel.updateOne(filter, update);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,14 +50,4 @@ export class FileReviewerDbService {
|
||||
new: true,
|
||||
});
|
||||
}
|
||||
|
||||
async findAll(
|
||||
filter: FilterQuery<FileReviewerModel>,
|
||||
): Promise<(FileReviewerModel & { _id: Types.ObjectId })[]> {
|
||||
return await this.fileReviewerModel.find(filter).lean();
|
||||
}
|
||||
|
||||
async updateOne(filter: FilterQuery<FileReviewerModel>, update: any) {
|
||||
return this.fileReviewerModel.updateOne(filter, update);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,12 +29,7 @@ export class RegistrarDbService {
|
||||
return this.registrarModel.findOneAndUpdate(filter, update, { new: true });
|
||||
}
|
||||
|
||||
async updateOne(filter: FilterQuery<RegistrarModel>, update: any) {
|
||||
return this.registrarModel.updateOne(filter, update);
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<RegistrarModel | null> {
|
||||
return this.registrarModel.findOne({ _id: new Types.ObjectId(userId) });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<UserModel>,
|
||||
update: UpdateQuery<UserModel>,
|
||||
|
||||
@@ -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}'.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -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<string, any>;
|
||||
|
||||
@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[];
|
||||
}
|
||||
@@ -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<WorkflowStepModel[]> {
|
||||
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<WorkflowStepModel | null> {
|
||||
async findByStepKey(
|
||||
stepKey: AnyWorkflowStep,
|
||||
): Promise<WorkflowStepModel | null> {
|
||||
return await this.workflowStepModel.findOne({ stepKey }).exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a workflow step by step number
|
||||
*/
|
||||
async findByStepNumber(stepNumber: number): Promise<WorkflowStepModel | null> {
|
||||
async findByStepNumber(
|
||||
stepNumber: number,
|
||||
): Promise<WorkflowStepModel | null> {
|
||||
return await this.workflowStepModel.findOne({ stepNumber }).exec();
|
||||
}
|
||||
|
||||
/**
|
||||
* Find steps by category
|
||||
*/
|
||||
async findByCategory(category: string): Promise<WorkflowStepModel[]> {
|
||||
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<WorkflowStepModel | null> {
|
||||
async update(
|
||||
id: string,
|
||||
updateDto: UpdateWorkflowStepDto,
|
||||
): Promise<WorkflowStepModel | null> {
|
||||
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<number> {
|
||||
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<boolean> {
|
||||
const count = await this.workflowStepModel.countDocuments({ stepKey }).exec();
|
||||
const count = await this.workflowStepModel
|
||||
.countDocuments({ stepKey })
|
||||
.exec();
|
||||
return count > 0;
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user