From 84b92eb55a15ae452034d16e39556fa45714189c Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Wed, 11 Nov 2026 17:59:48 +0330 Subject: [PATCH] update the 2 new apis for getting expertise and files of the request --- docs/fanavaran/attachment-upload-status.md | 70 ++++ docs/fanavaran/hull-retrieval.md | 62 +++ .../claim-request-management.service.ts | 352 +++++++++--------- .../dto/claim-details-v2.dto.ts | 18 +- .../entites/schema/claim-cases.schema.ts | 4 + .../fanavaran-attachment-status.spec.ts | 219 +++++++++++ .../fanavaran-attachment-status.ts | 75 ++++ .../fanavaran-claim-references.ts | 26 +- .../fanavaran-hull-read.controller.ts | 104 ++++++ .../fanavaran-hull-read.service.spec.ts | 221 +++++++++++ src/fanavaran/fanavaran-hull-read.service.ts | 131 +++++++ src/fanavaran/fanavaran.controller.ts | 4 +- src/fanavaran/fanavaran.module.ts | 20 +- 13 files changed, 1111 insertions(+), 195 deletions(-) create mode 100644 docs/fanavaran/attachment-upload-status.md create mode 100644 docs/fanavaran/hull-retrieval.md create mode 100644 src/claim-request-management/fanavaran-attachment-status.spec.ts create mode 100644 src/claim-request-management/fanavaran-attachment-status.ts create mode 100644 src/fanavaran/fanavaran-hull-read.controller.ts create mode 100644 src/fanavaran/fanavaran-hull-read.service.spec.ts create mode 100644 src/fanavaran/fanavaran-hull-read.service.ts diff --git a/docs/fanavaran/attachment-upload-status.md b/docs/fanavaran/attachment-upload-status.md new file mode 100644 index 0000000..f643360 --- /dev/null +++ b/docs/fanavaran/attachment-upload-status.md @@ -0,0 +1,70 @@ +# Fanavaran image receipts and upload failures + +The image ID is the external `Id` returned by Fanavaran's attachment upload, not +the MongoDB ID of the local image. Both batch and single-image uploads persist it +in `claimCases.fanavaranSync.attachments.files[].fileId`, together with `fileName`, +`source`, `submittedAt`, and the response. Per-image success, failure, and skip +events are saved in `fanavaranSync.attachments.attempts`. Failures include an error +and, when an audited HTTP upload started, a tracking code. + +## Read the IDs beside the claim references + +Claim detail responses that expose `fanavaran` now include: + +```json +{ + "fanavaran": { + "claimId": 5190845, + "fileIds": [700001], + "attachments": { + "status": "success", + "uploadedCount": 1, + "lastError": null, + "files": [ + { + "fileId": 700001, + "fileName": "image.jpg", + "source": "capture:angle:front" + } + ], + "attempts": [] + } + } +} +``` + +Existing claim-reference codes remain gated on COMPLETED. Image receipts and +status can appear earlier. The expertise preview also returns `fileIds` and +`attachments` beside `claimId`, `dmgCaseId`, and `expertiseId`. + +## Check every planned image and why it is pending + +`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/attachments/preview` + +This returns `totalLocalImages`, `alreadySubmitted`, `pendingSubmit`, `fileIds`, +`uploadStatus`, and one `attachments` row per local upload candidate. Each row +includes `fileId`, `alreadySubmitted`, `localFileExists`, `status`, and `lastError`. +Use `pendingSubmit` to check whether all current local candidates have saved +receipts. Summary status describes recorded outcomes, not unattempted images. + +- `success`: confirmed external file IDs are recorded. +- `partial`: receipts exist, but another recorded image failed or was skipped. +- `failed` / `skipped`: inspect the per-image error and `nextRetryAt` if present. +- `not_recorded`: no upload outcome is stored; this is not proof of remote absence. +- `unconfirmed`: legacy upload records have no valid external file ID. + +`POST /v2/fanavaran/parsian/claim-cases/{claimCaseId}/attachments/submit` submits +pending candidates and returns each upload's `fileId` or failure/skip reason. +Already-recorded successful uploads are skipped. Missing local files are reported +instead of silently excluded. A response with no external file ID is unconfirmed +and is not automatically retried, to avoid duplicating a possibly accepted upload. + +Older batch uploads did not persist their returned IDs. This change cannot +reconstruct those historical receipts from the local database; verify them with +Fanavaran before deciding to re-upload. New uploads use the shared persistence +path and record their outcomes. + +To verify remote receipts directly, use +`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/hull/files`. +Retrieve one image and its Base64 content using `/hull/files/{fileId}`. +See [hull retrieval](hull-retrieval.md) for all supported read routes. diff --git a/docs/fanavaran/hull-retrieval.md b/docs/fanavaran/hull-retrieval.md new file mode 100644 index 0000000..af074c9 --- /dev/null +++ b/docs/fanavaran/hull-retrieval.md @@ -0,0 +1,62 @@ +# Retrieve submitted hull files and expertise sections + +Implemented from the supplied Fanavaran V2.0 customer documents: + +- `CAR.VHUD.APIH.GEN.05 - سرویس فایل های پیوست خسارت بدنه.docx` +- `CAR.VHUD.APIH.GEN.12 - سرویس بازیابی نقاط آسیب دیده کارشناسی خسارت بدنه.docx` + +All routes require the existing actor Bearer token and access to the local claim. +The path's `claimCaseId` is a local MongoDB ObjectId. The backend resolves the +saved external `claimId` (never `claimNo`), hull ContractId, and the claim staff's +Location using the submission header resolver. Non-hull claims are rejected. + +## Routes + +Base: `/v2/fanavaran/{client}/claim-cases/{claimCaseId}/hull` + +| Local GET route | Fanavaran GET resource | Result | +|---|---|---| +| `/files` | `/car/vehicle-hull-claims/{claimId}/files` | Live file metadata: `Id`, `ClaimId`, `FileName`, `FileTypeId`, `Status` | +| `/files/{fileId}` | `/car/vehicle-hull-claims/{claimId}/files/{fileId}` | One file with the same metadata plus Base64 `Data` | +| `/expertise/dmg-sections` | `/car/vehicle-hull-claims/{claimId}/expertise/{expertiseId}/dmg-sections` | Damage sections, nested costs, section/cost IDs, and provider tracking codes | + +The sections route defaults to the saved `expertiseId`. To read a historical +expertise on this same claim, supply `?expertiseId=44237`. A missing saved +expertise ID without an explicit override returns 400. File and expertise IDs +must be positive safe integers. + +Every response wraps the unmodified vendor body in `data`, with `clientKey`, +`claimCaseId`, `claimId`, and the selected `fileId` or `expertiseId` when relevant: + +```json +{ + "clientKey": "parsian", + "claimCaseId": "6af4594a32d485128a55742d", + "claimId": 5190845, + "data": [ + { + "Id": 2008737, + "ClaimId": 5190845, + "FileName": "1.jpg", + "FileTypeId": 70, + "Status": 2003 + } + ] +} +``` + +The list response does **not** contain image bytes. Retrieve the desired file ID +with the single-file route to obtain `data.Data` as Base64. Preserve the numeric +`Status` value; its meaning belongs to Fanavaran's +`/common/code-list/file-status` lookup and is not inferred by these routes. + +GEN.12 responses preserve `Id`, `ExpertiseId`, `AccessoryKindId`, +`VehicleHullAccessoryId`, `DmgKindId`, `Count`, `WasteValue`, `DmgAmount`, `Desc`, +`CINumber`, `CITrackingCode`, and `DmgSectionCosts` when returned. Each nested cost +can include its own `Id`, `DmgSectionId`, `DmgCostKindId`, `Caption`, and `Amount`. + +These reads call Fanavaran directly without resubmitting claims/files/expertise, +using local upload receipt caches, or changing local claim records. In particular, +the remote file list can reveal historical uploads whose file IDs were not saved +by the old batch uploader. Vendor errors retain their original `Message` and +`RuleName`; transient errors participate in the shared tenant backoff. diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 4d368c0..398a1a4 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -4,6 +4,7 @@ import { } from 'src/fanavaran/tejarat-notifier'; import { BadRequestException, + BadGatewayException, ConflictException, ForbiddenException, HttpException, @@ -101,7 +102,10 @@ import { collectUserIdVariants, } from 'src/helpers/party-access-queries'; import { toPublicListItems } from 'src/helpers/public-list-response'; -import { claimCaseInitiatedByFieldExpert } from 'src/helpers/tenant-scope'; +import { + claimCaseInitiatedByFieldExpert, + assertClaimCaseForTenant, +} from 'src/helpers/tenant-scope'; import { resolveUnifiedFileStatus } from 'src/helpers/unified-file-status'; import { buildFileLink, resolveStoredFileUrl } from 'src/helpers/urlCreator'; import { @@ -184,6 +188,7 @@ import { type FanavaranClaimProduct, } from './fanavaran-claim-product'; import { fanavaranClaimReferences } from './fanavaran-claim-references'; +import { fanavaranAttachmentStatus } from './fanavaran-attachment-status'; import { actualPremiumFromHullPolicyRecord, authorityCulpritIdFromDetectionRows, @@ -3370,6 +3375,47 @@ export class ClaimRequestManagementService { ); } + /** Read-only context for retrieving a submitted hull claim from Fanavaran. */ + async getFanavaranHullReadContext( + claimCaseId: string, + clientKey: FanavaranClientKey, + actor: { sub: string; role?: string; clientKey?: string; username?: string }, + ) { + if (!Types.ObjectId.isValid(claimCaseId)) { + throw new BadRequestException('Invalid claim case ID'); + } + const claim = await this.claimCaseDbService.findById(claimCaseId); + if (!claim) throw new NotFoundException('Claim case not found'); + if (!actor?.sub) { + throw new ForbiddenException('Claim access requires an authenticated actor'); + } + const initiatingRoles = [ + RoleEnum.FIELD_EXPERT, RoleEnum.FILE_MAKER, + RoleEnum.FILE_REVIEWER, RoleEnum.REGISTRAR, + ]; + if (initiatingRoles.includes(actor.role as RoleEnum)) { + await this.assertActorCanViewClaimV2(claim, actor.sub, actor); + } else if (actor.role !== RoleEnum.SUPER_ADMIN) { + assertClaimCaseForTenant(claim, actor); + } + if ((await this.resolveFanavaranClaimProduct(claimCaseId)) !== 'car-body') { + throw new BadRequestException('This endpoint only retrieves vehicle-hull claims'); + } + const claimId = parseFanavaranId( + claim.claimId ?? claim.fanavaranSync?.baseClaim?.claimId, + ); + if (claimId == null) { + throw new BadRequestException('No submitted Fanavaran claimId is stored for this claim'); + } + return { + claimId, + expertiseId: parseFanavaranId( + claim.expertiseId ?? claim.fanavaranSync?.expertise?.expertiseId, + ), + headers: await this.getFanavaranAuthHeaders(clientKey, undefined, claimCaseId), + }; + } + private async getFanavaranAuthHeaders( clientKey: FanavaranClientKey, auditSession?: FanavaranAuditSession, @@ -5065,8 +5111,9 @@ export class ClaimRequestManagementService { for (const file of files) { const fileName = (file as { fileName?: unknown })?.fileName; - if (typeof fileName === 'string' && fileName.trim()) { - submitted.set(fileName, (file as { fileId?: unknown })?.fileId); + const fileId = pickFanavaranRecordId((file as { fileId?: unknown })?.fileId); + if (typeof fileName === 'string' && fileName.trim() && fileId != null) { + submitted.set(fileName, fileId); } } @@ -5192,6 +5239,9 @@ export class ClaimRequestManagementService { const { claimCase, candidates } = await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey); const claimsUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId); + const uploadStatus = fanavaranAttachmentStatus(claimCase.fanavaranSync?.attachments) ?? { + status: 'not_recorded', uploadedCount: 0, files: [], attempts: [], lastError: null, + }; return { clientKey, @@ -5199,6 +5249,8 @@ export class ClaimRequestManagementService { claimId: claimCase.claimId ?? null, claimNo: claimCase.claimNo ?? null, dmgCaseId: claimCase.dmgCaseId ?? null, + fileIds: [...new Set(uploadStatus?.files.map(file => file.fileId) ?? [])], + uploadStatus, submitUrl: claimCase.claimId ? `${claimsUrl}/${claimCase.claimId}/files` : null, @@ -5212,7 +5264,15 @@ export class ClaimRequestManagementService { pendingSubmit: candidates.filter( (candidate) => !candidate.alreadySubmitted, ).length, - attachments: candidates, + attachments: candidates.map(candidate => { + const latestAttempt = uploadStatus?.attempts.filter(attempt => attempt.fileName === candidate.fileName).at(-1); + const localFileExists = existsSync(candidate.path); + return { + ...candidate, fileId: candidate.submittedFileId ?? null, localFileExists, + status: candidate.alreadySubmitted ? 'success' : !localFileExists ? 'skipped' : latestAttempt?.status ?? 'pending', + lastError: candidate.alreadySubmitted ? null : !localFileExists ? 'Local attachment file does not exist.' : latestAttempt?.error ?? null, + }; + }), }; } @@ -5220,183 +5280,60 @@ export class ClaimRequestManagementService { claimCaseId: string, clientKey: FanavaranClientKey, ): Promise { - const { candidates } = await this.collectFanavaranAttachmentCandidates( - claimCaseId, - clientKey, - ); - const pending = candidates.filter( - (candidate) => !candidate.alreadySubmitted && existsSync(candidate.path), - ); - - if (pending.length === 0) { + const { claimCase: initialClaim, candidates } = + await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey); + const pending = candidates.filter(candidate => !candidate.alreadySubmitted); + const skippedAlreadySubmitted = candidates.length - pending.length; + if (!pending.length) { return { - clientKey, - claimCaseId, - totalLocalImages: candidates.length, - skippedAlreadySubmitted: candidates.length, - attempted: 0, - submitted: 0, - failed: 0, - skipped: candidates.length, - results: [], + clientKey, claimCaseId, totalLocalImages: candidates.length, + skippedAlreadySubmitted, attempted: 0, submitted: 0, failed: 0, + skipped: candidates.length, results: [], }; } - - const profile = getFanavaranClientProfile(clientKey); - let claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (claimCase) this.assertFanavaranVehicleReviewApproved(claimCase); - if (!claimCase?.claimId) { - try { - await this.ensureFanavaranBaseClaim( - claimCaseId, - clientKey, - FanavaranAuditSource.SUBMIT, - ); + const skipPending = async (warning: string) => { + await Promise.all(pending.map(candidate => this.recordSkippedFanavaranAttachment( + claimCaseId, candidate.fileName, candidate.source, warning, + ))); + return { + clientKey, claimCaseId, totalLocalImages: candidates.length, + skippedAlreadySubmitted, attempted: 0, submitted: 0, failed: 0, + skipped: pending.length, warning, + results: pending.map(candidate => ({ + attempted: false, submitted: false, skipped: true, + skipReason: warning, fileName: candidate.fileName, + })), + }; + }; + let nestedClaimId: number | null; + try { + let claimCase = initialClaim; + this.assertFanavaranVehicleReviewApproved(claimCase); + if (!claimCase?.claimId) { + await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, FanavaranAuditSource.SUBMIT); claimCase = await this.claimCaseDbService.findById(claimCaseId); - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - return { - clientKey, - claimCaseId, - totalLocalImages: candidates.length, - skippedAlreadySubmitted: candidates.length - pending.length, - attempted: 0, - submitted: 0, - failed: 0, - skipped: pending.length, - warning, - results: pending.map((c) => ({ - attempted: false, - submitted: false, - skipped: true, - skipReason: warning, - fileName: c.fileName, - })), - }; } - } - if (!claimCase?.claimId) { - return { - clientKey, - claimCaseId, - totalLocalImages: candidates.length, - skippedAlreadySubmitted: candidates.length - pending.length, - attempted: 0, - submitted: 0, - failed: 0, - skipped: pending.length, - warning: 'Fanavaran base claimId is missing', - results: pending.map((c) => ({ - attempted: false, - submitted: false, - skipped: true, - skipReason: 'Fanavaran base claimId is missing', - fileName: c.fileName, - })), - }; - } - - await this.syncFanavaranHullBaseClaim(claimCaseId, clientKey); - claimCase = await this.claimCaseDbService.findById(claimCaseId); - const nestedClaimId = fanavaranHullNestedClaimId({ - claimId: claimCase?.claimId, - claimNo: claimCase?.claimNo, - }); - if (nestedClaimId == null) { - return { - clientKey, - claimCaseId, - totalLocalImages: candidates.length, - skippedAlreadySubmitted: candidates.length - pending.length, - attempted: 0, - submitted: 0, - failed: 0, - skipped: pending.length, - warning: 'Fanavaran base claimId is missing', - results: pending.map((c) => ({ - attempted: false, - submitted: false, - skipped: true, - skipReason: 'Fanavaran base claimId is missing', - fileName: c.fileName, - })), - }; + if (!claimCase?.claimId) return skipPending('Fanavaran base claimId is missing'); + await this.syncFanavaranHullBaseClaim(claimCaseId, clientKey); + claimCase = await this.claimCaseDbService.findById(claimCaseId); + nestedClaimId = fanavaranHullNestedClaimId({ claimId: claimCase?.claimId, claimNo: claimCase?.claimNo }); + if (nestedClaimId == null) return skipPending('Fanavaran base claimId is missing'); + } catch (error) { + return skipPending(this.extractFanavaranErrorMessage(error)); } const url = `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${nestedClaimId}/files`; - const fileTypeId = profile.defaults.ClaimFileTypeId; - const product = await this.resolveFanavaranClaimProduct(claimCaseId); - - const logPrefix = `[Fanavaran ${clientKey} V2 Attachment Batch] claimCaseId=${claimCaseId}`; const results: any[] = []; for (let i = 0; i < pending.length; i++) { const candidate = pending[i]; - const content = { - FileName: candidate.fileName, - FileTypeId: fileTypeId, - ...(product === 'car-body' ? { ClaimId: nestedClaimId } : {}), - }; - - this.logger.log( - `${logPrefix} [${i + 1}/${pending.length}] UPLOADING: ${candidate.fileName}`, + const result = await this.autoSubmitFanavaranAttachment( + claimCaseId, + { path: candidate.path, fileName: candidate.fileName, source: candidate.source }, + { clientKey, auditSource: FanavaranAuditSource.SUBMIT }, ); - - try { - const response = await this.postFanavaranMultipart( - url, - content, - [{ path: candidate.path, fileName: candidate.fileName }], - clientKey, - undefined, - claimCaseId, - ); - this.logger.log( - `${logPrefix} [${i + 1}/${pending.length}] SUCCESS: status=${response.status} body=${JSON.stringify(response.data)}`, - ); - results.push({ - attempted: true, - submitted: true, - claimId: nestedClaimId, - fileName: candidate.fileName, - submitUrl: url, - fanavaranResponse: response.data, - }); - } catch (error) { - const warning = this.extractFanavaranErrorMessage(error); - this.logger.warn( - `${logPrefix} [${i + 1}/${pending.length}] FAILED: ${warning}`, - ); - results.push({ - attempted: true, - submitted: false, - warning, - fileName: candidate.fileName, - claimId: nestedClaimId, - submitUrl: url, - }); - - // Schedule a retry for this individual file via autoSubmitFanavaranAttachment, - // which handles idempotency (won't re-upload if already recorded as submitted) - // and has its own inner retry/back-off via scheduleFanavaranRetry. - await this.scheduleFanavaranRetry( - claimCaseId, - 'attachments', - () => - this.autoSubmitFanavaranAttachment( - claimCaseId, - { - path: candidate.path, - fileName: candidate.fileName, - source: candidate.source, - }, - { clientKey, auditSource: FanavaranAuditSource.AUTO_SUBMIT }, - ), - `${logPrefix} [${i + 1}/${pending.length}] retry`, - { error, clientKey }, - ); - } + results.push({ ...result, claimId: nestedClaimId, submitUrl: url }); if (i < pending.length - 1) { await new Promise((resolve) => setTimeout(resolve, 1_000)); @@ -5406,6 +5343,24 @@ export class ClaimRequestManagementService { return results; } + private async recordSkippedFanavaranAttachment( + claimCaseId: string, + fileName: string, + source: string | undefined, + reason: string, + ): Promise { + await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { + $set: { + 'fanavaranSync.attachments.status': 'skipped', + 'fanavaranSync.attachments.lastTriedAt': new Date(), + 'fanavaranSync.attachments.lastError': reason, + }, + $push: { 'fanavaranSync.attachments.attempts': { + fileName, source, status: 'skipped', error: reason, attemptedAt: new Date(), + } }, + }); + } + async autoSubmitFanavaranAttachment( claimCaseId: string, file: { path?: string | null; fileName?: string | null; source?: string }, @@ -5428,9 +5383,11 @@ export class ClaimRequestManagementService { const profile = getFanavaranClientProfile(clientKey); let url = ''; let content: Record = {}; + let auditSession: FanavaranAuditSession | undefined; try { if (!filePath || !fileName) { + await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, 'Attachment file path or filename is missing'); return { attempted: false, submitted: false, @@ -5439,6 +5396,7 @@ export class ClaimRequestManagementService { }; } if (!existsSync(filePath)) { + await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, `Attachment file does not exist: ${filePath}`); return { attempted: false, submitted: false, @@ -5458,6 +5416,15 @@ export class ClaimRequestManagementService { }; } + const existingFileId = this.getSubmittedFanavaranAttachmentFileNames(claimCase).get(fileName); + if (existingFileId != null) { + return { + attempted: false, submitted: true, skipped: true, + skipReason: 'Attachment already uploaded to Fanavaran.', + claimId: claimCase.claimId, fileName, fileId: Number(existingFileId), + }; + } + if (!claimCase.claimId) { if (options?.clientKey) { await this.executeFanavaranV2Submit(claimCaseId, clientKey); @@ -5470,13 +5437,7 @@ export class ClaimRequestManagementService { if (!claimCase?.claimId) { const warning = 'Fanavaran base claim is missing, so attachment was not submitted.'; - await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { - $set: { - 'fanavaranSync.attachments.status': 'skipped', - 'fanavaranSync.attachments.lastTriedAt': new Date(), - 'fanavaranSync.attachments.lastError': warning, - }, - }); + await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, warning); return { attempted: false, submitted: false, @@ -5500,7 +5461,7 @@ export class ClaimRequestManagementService { : {}), }; - const auditSession: FanavaranAuditSession = { + auditSession = { trackingCode: this.fanavaranAuditService.generateTrackingCode(), clientKey, source: auditSource, @@ -5536,7 +5497,13 @@ export class ClaimRequestManagementService { `${logPrefix} Fanavaran response: ${JSON.stringify(response.data)}`, ); - const fileId = response.data?.Id; + const fileId = pickFanavaranRecordId(response.data); + if (fileId == null) { + throw new BadGatewayException({ + code: 'FANAVARAN_ATTACHMENT_ID_MISSING', + message: 'Fanavaran returned no attachment Id; upload receipt could not be confirmed.', + }); + } const exchange = this.fanavaranAuditService.captureAxiosExchange(response); @@ -5560,8 +5527,13 @@ export class ClaimRequestManagementService { 'fanavaranSync.attachments.lastTriedAt': new Date(), 'fanavaranSync.attachments.claimId': claimCase.claimId, 'fanavaranSync.attachments.response': response.data, + 'fanavaranSync.attachments.lastError': null, }, $push: { + 'fanavaranSync.attachments.attempts': { + fileId, fileName, source: file.source, status: 'success', + attemptedAt: new Date(), trackingCode: auditSession.trackingCode, + }, 'fanavaranSync.attachments.files': { fileId, fileName, @@ -5596,6 +5568,22 @@ export class ClaimRequestManagementService { const warning = this.extractFanavaranErrorMessage(error); this.logger.warn(`${logPrefix} Fanavaran error: ${warning}`); + if (auditSession) { + try { + const exchange = this.fanavaranAuditService.captureAxiosExchange(error); + await this.fanavaranAuditService.recordStep({ + session: auditSession, + step: FanavaranAuditStep.SUBMIT_ATTACHMENT, + status: FanavaranAuditStatus.FAILURE, + requestUrl: url, requestMethod: 'POST', requestBody: content, + httpStatus: exchange.httpStatus, responseBody: exchange.responseBody, + requestMeta: { fileName, source: file.source }, errorMessage: warning, + }); + } catch (auditError) { + this.logger.warn(`${logPrefix} Failed to record upload audit failure`, auditError); + } + } + try { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { @@ -5604,6 +5592,10 @@ export class ClaimRequestManagementService { 'fanavaranSync.attachments.lastError': warning, }, $push: { + 'fanavaranSync.attachments.attempts': { + fileName, source: file.source, status: 'failed', + error: warning, attemptedAt: new Date(), trackingCode: auditSession?.trackingCode, + }, history: { type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED', actor: { actorType: 'system' }, @@ -5627,7 +5619,10 @@ export class ClaimRequestManagementService { // Schedule retry for attachments — never let retry bookkeeping fail the // caller: local media/docs are already persisted before this submit. try { - await this.scheduleFanavaranRetry( + const missingId = error instanceof BadGatewayException && + typeof error.getResponse() === 'object' && + (error.getResponse() as { code?: string }).code === 'FANAVARAN_ATTACHMENT_ID_MISSING'; + if (!missingId) await this.scheduleFanavaranRetry( claimCaseId, 'attachments', () => this.autoSubmitFanavaranAttachment(claimCaseId, file, options), @@ -6093,12 +6088,15 @@ export class ClaimRequestManagementService { }, }); + const attachments = fanavaranAttachmentStatus(claimCase.fanavaranSync?.attachments); return { clientKey, claimCaseId, claimId: claimCase.claimId ?? null, dmgCaseId: claimCase.dmgCaseId ?? null, expertiseId: claimCase.expertiseId ?? null, + fileIds: [...new Set(attachments?.files.map(file => file.fileId) ?? [])], + attachments, replyKey, submitUrl: claimCase.claimId ? `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/expertise` diff --git a/src/claim-request-management/dto/claim-details-v2.dto.ts b/src/claim-request-management/dto/claim-details-v2.dto.ts index 40ad3d7..4a7505b 100644 --- a/src/claim-request-management/dto/claim-details-v2.dto.ts +++ b/src/claim-request-management/dto/claim-details-v2.dto.ts @@ -1,5 +1,6 @@ import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; import { DamageSelectedPartV2BodyDto } from "./damage-selected-part-v2.dto"; +import type { FanavaranClaimReferences } from "../fanavaran-claim-references"; /** Suggested HTTP call for the owner UI (`pathTemplate`: replace placeholders). */ export class ClaimDetailsOwnerNextActionV2Dto { @@ -255,20 +256,23 @@ export class ClaimDetailsV2ResponseDto { @ApiPropertyOptional({ description: - "Fanavaran claim reference. Returned only after the local claim reaches COMPLETED. Each of claimId, claimNo, dmgCaseId, and expertiseId is included when Fanavaran has supplied it.", + "Fanavaran codes and image upload receipts. Claim codes appear on COMPLETED; fileIds and attachments upload status/errors are available earlier when recorded.", example: { claimId: 987654, claimNo: 123456, dmgCaseId: 11, expertiseId: 22, + fileIds: [700001], + attachments: { + status: "success", + uploadedCount: 1, + lastError: null, + files: [{ fileId: 700001, fileName: "image.jpg" }], + attempts: [], + }, }, }) - fanavaran?: { - claimId?: number; - claimNo?: number; - dmgCaseId?: number; - expertiseId?: number; - }; + fanavaran?: FanavaranClaimReferences; @ApiPropertyOptional({ description: diff --git a/src/claim-request-management/entites/schema/claim-cases.schema.ts b/src/claim-request-management/entites/schema/claim-cases.schema.ts index 86c9e03..65e584a 100644 --- a/src/claim-request-management/entites/schema/claim-cases.schema.ts +++ b/src/claim-request-management/entites/schema/claim-cases.schema.ts @@ -150,6 +150,10 @@ export class FanavaranSyncStage { @Prop({ type: [MongooseSchema.Types.Mixed], default: [] }) files?: unknown[]; + /** Per-image Fanavaran upload outcomes, including failures and skipped files. */ + @Prop({ type: [MongooseSchema.Types.Mixed], default: [] }) + attempts?: unknown[]; + @Prop({ type: MongooseSchema.Types.Mixed }) response?: unknown; diff --git a/src/claim-request-management/fanavaran-attachment-status.spec.ts b/src/claim-request-management/fanavaran-attachment-status.spec.ts new file mode 100644 index 0000000..f26575f --- /dev/null +++ b/src/claim-request-management/fanavaran-attachment-status.spec.ts @@ -0,0 +1,219 @@ +import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { ClaimRequestManagementService } from "./claim-request-management.service"; +import { fanavaranClaimReferences } from "./fanavaran-claim-references"; + +describe("Fanavaran image upload persistence and visibility", () => { + let directory: string; + beforeEach(() => { + directory = mkdtempSync(join(tmpdir(), "y724-attachment-")); + }); + afterEach(() => { + rmSync(directory, { recursive: true, force: true }); + }); + + function setup(missing = false) { + const path = join(directory, "image.jpg"); + if (!missing) writeFileSync(path, "test image"); + const claim: any = { + claimId: 5190845, + status: "COMPLETED", + fanavaranSync: { attachments: { files: [], attempts: [] } }, + }; + const service = Object.create( + ClaimRequestManagementService.prototype, + ) as any; + service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() }; + service.assertFanavaranVehicleReviewApproved = jest.fn(); + service.syncFanavaranHullBaseClaim = jest.fn().mockResolvedValue(undefined); + service.resolveFanavaranClaimProduct = jest + .fn() + .mockResolvedValue("car-body"); + service.fanavaranClaimsUrlForClaim = jest + .fn() + .mockResolvedValue("https://example.test/car/vehicle-hull-claims"); + service.postFanavaranMultipart = jest + .fn() + .mockResolvedValue({ status: 200, data: { Id: 700001 } }); + service.fanavaranAuditService = { + generateTrackingCode: () => "test-tracking", + recordStep: jest.fn(), + captureAxiosExchange: () => ({}), + }; + service.scheduleFanavaranRetry = jest.fn(); + service.claimCaseDbService = { + findById: jest.fn().mockResolvedValue(claim), + findByIdAndUpdate: jest + .fn() + .mockImplementation(async (_id: string, update: any) => { + const stage = claim.fanavaranSync.attachments; + for (const [key, value] of Object.entries(update.$set ?? {})) { + if (key.startsWith("fanavaranSync.attachments.")) + stage[key.split(".").at(-1)!] = value; + } + for (const key of ["files", "attempts"]) { + const value = update.$push?.[`fanavaranSync.attachments.${key}`]; + if (value) stage[key].push(value); + } + return claim; + }), + }; + service.collectFanavaranAttachmentCandidates = jest + .fn() + .mockImplementation(async () => { + const files = service.getSubmittedFanavaranAttachmentFileNames(claim); + return { + claimCase: claim, + candidates: [ + { + path, + fileName: "image.jpg", + source: "capture:angle:front", + alreadySubmitted: files.has("image.jpg"), + submittedFileId: files.get("image.jpg"), + }, + ], + }; + }); + return { service, claim }; + } + + it("persists batch image IDs, exposes them beside claimId, and skips subsequent uploads", async () => { + const { service, claim } = setup(); + const result = await service.submitFanavaranAttachmentsV2( + "claim-1", + "parsian", + ); + expect(result[0]).toMatchObject({ submitted: true, fileId: 700001 }); + expect(fanavaranClaimReferences(claim)).toMatchObject({ + claimId: 5190845, + fileIds: [700001], + attachments: { + files: [ + expect.objectContaining({ fileId: 700001, fileName: "image.jpg" }), + ], + }, + }); + await service.submitFanavaranAttachmentsV2("claim-1", "parsian"); + expect(service.postFanavaranMultipart).toHaveBeenCalledTimes(1); + }); + + it("persists per-image upload failures and returns their reason", async () => { + const { service, claim } = setup(); + service.postFanavaranMultipart.mockRejectedValue( + new Error("Fanavaran rejected FileTypeId"), + ); + await service.submitFanavaranAttachmentsV2("claim-1", "parsian"); + expect(fanavaranClaimReferences(claim)).toMatchObject({ + fileIds: [], + attachments: { + attempts: [ + expect.objectContaining({ + fileName: "image.jpg", + status: "failed", + error: "Fanavaran rejected FileTypeId", + }), + ], + }, + }); + }); + + it("reports missing local files rather than silently filtering them out", async () => { + const { service, claim } = setup(true); + const result = await service.submitFanavaranAttachmentsV2( + "claim-1", + "parsian", + ); + expect(result[0]).toMatchObject({ + skipped: true, + skipReason: expect.stringContaining("does not exist"), + }); + expect(service.postFanavaranMultipart).not.toHaveBeenCalled(); + expect(fanavaranClaimReferences(claim)).toMatchObject({ + attachments: { + attempts: [expect.objectContaining({ status: "skipped" })], + }, + }); + }); + + it("records why hull preparation prevented image submission", async () => { + const { service, claim } = setup(); + service.syncFanavaranHullBaseClaim.mockRejectedValue( + new Error("Policy lookup unavailable"), + ); + await service.submitFanavaranAttachmentsV2("claim-1", "parsian"); + expect(service.postFanavaranMultipart).not.toHaveBeenCalled(); + expect(fanavaranClaimReferences(claim)).toMatchObject({ + attachments: { + attempts: [ + expect.objectContaining({ + status: "skipped", + error: "Policy lookup unavailable", + }), + ], + }, + }); + }); + + it("does not claim a confirmed upload when Fanavaran returns no file ID", async () => { + const { service, claim } = setup(); + service.postFanavaranMultipart.mockResolvedValue({ status: 200, data: {} }); + const result = await service.submitFanavaranAttachmentsV2( + "claim-1", + "parsian", + ); + expect(result[0]).toMatchObject({ + submitted: false, + warning: expect.stringContaining("no attachment Id"), + }); + expect(fanavaranClaimReferences(claim)).toMatchObject({ fileIds: [] }); + expect(service.scheduleFanavaranRetry).not.toHaveBeenCalled(); + }); + + it("exposes upload status before completion and reports mixed outcomes as partial", async () => { + const { service, claim } = setup(); + claim.status = "EXPERT_REVIEWING"; + await service.submitFanavaranAttachmentsV2("claim-1", "parsian"); + claim.fanavaranSync.attachments.attempts.push({ + fileName: "other.jpg", + status: "failed", + error: "Rejected", + }); + expect(fanavaranClaimReferences(claim)).toMatchObject({ + fileIds: [700001], + attachments: { status: "partial", lastError: "Rejected" }, + }); + expect(fanavaranClaimReferences(claim)).not.toHaveProperty("claimId"); + const preview = await service.previewFanavaranAttachmentsV2( + "claim-1", + "parsian", + ); + expect(preview).toMatchObject({ + claimId: 5190845, + fileIds: [700001], + alreadySubmitted: 1, + attachments: [ + expect.objectContaining({ fileId: 700001, status: "success" }), + ], + }); + }); + + it("distinguishes legacy records without a Fanavaran image ID from confirmed receipts", () => { + expect( + fanavaranClaimReferences({ + status: "COMPLETED", + claimId: 5190845, + fanavaranSync: { + attachments: { + status: "success", + files: [{ fileName: "legacy.jpg" }], + }, + }, + }), + ).toMatchObject({ + fileIds: [], + attachments: { status: "unconfirmed", uploadedCount: 0 }, + }); + }); +}); diff --git a/src/claim-request-management/fanavaran-attachment-status.ts b/src/claim-request-management/fanavaran-attachment-status.ts new file mode 100644 index 0000000..eacee47 --- /dev/null +++ b/src/claim-request-management/fanavaran-attachment-status.ts @@ -0,0 +1,75 @@ +import { pickFanavaranRecordId } from "./fanavaran-other-people"; + +export type FanavaranAttachmentStage = { + status?: string; + lastError?: string | null; + lastTriedAt?: Date | string; + nextRetryAt?: Date | string; + files?: unknown[]; + attempts?: unknown[]; +}; + +export function fanavaranAttachmentStatus( + stage?: FanavaranAttachmentStage | null, +) { + if (!stage) return undefined; + const records = (rows: unknown) => + (Array.isArray(rows) ? rows : []).filter( + (row): row is Record => !!row && typeof row === "object", + ); + const files = records(stage.files).flatMap((row) => { + const fileId = pickFanavaranRecordId(row.fileId); + if (fileId == null) return []; + return [ + { + fileId, + fileName: String(row.fileName ?? ""), + source: row.source as string | undefined, + submittedAt: row.submittedAt as Date | string | undefined, + }, + ]; + }); + const attempts = records(stage.attempts).map((row) => ({ + fileName: String(row.fileName ?? ""), + source: row.source as string | undefined, + status: String(row.status ?? "unknown"), + fileId: pickFanavaranRecordId(row.fileId) ?? undefined, + error: row.error as string | undefined, + attemptedAt: row.attemptedAt as Date | string | undefined, + trackingCode: row.trackingCode as string | undefined, + })); + const uploadedNames = new Set(files.map((file) => file.fileName)); + const latest = new Map( + attempts.map((attempt) => [attempt.fileName, attempt]), + ); + const outstanding = [...latest.values()].filter( + (attempt) => + !uploadedNames.has(attempt.fileName) && attempt.status !== "success", + ); + const lastProblem = outstanding.at(-1); + const status = lastProblem + ? files.length + ? "partial" + : lastProblem.status + : files.length + ? "success" + : records(stage.files).length + ? "unconfirmed" + : (stage.status ?? "not_recorded"); + return { + status, + uploadedCount: files.length, + lastError: + lastProblem?.error ?? + (files.length + ? null + : (stage.lastError ?? + (status === "unconfirmed" + ? "No valid Fanavaran image ID was recorded; remote receipt is unconfirmed." + : null))), + lastTriedAt: stage.lastTriedAt, + nextRetryAt: stage.nextRetryAt, + files, + attempts, + }; +} diff --git a/src/claim-request-management/fanavaran-claim-references.ts b/src/claim-request-management/fanavaran-claim-references.ts index d1bce8f..8528886 100644 --- a/src/claim-request-management/fanavaran-claim-references.ts +++ b/src/claim-request-management/fanavaran-claim-references.ts @@ -1,4 +1,8 @@ import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum"; +import { + fanavaranAttachmentStatus, + type FanavaranAttachmentStage, +} from "./fanavaran-attachment-status"; export type FanavaranClaimReferences = { claimId?: number; @@ -12,10 +16,12 @@ export type FanavaranClaimReferences = { plaqueSampleId?: number; accidentVehicleUsedId?: number; insuranceCorpId?: number; + fileIds?: number[]; + attachments?: ReturnType; }; /** - * Fanavaran ids for v2 claim GET. Only on COMPLETED; each field is omitted when missing. + * Claim reference codes appear on COMPLETED. Upload receipts/status are visible earlier. */ export function fanavaranClaimReferences(claim: { status?: string; @@ -26,13 +32,20 @@ export function fanavaranClaimReferences(claim: { fanavaranSync?: { baseClaim?: FanavaranReferenceStage | null; damageCase?: FanavaranReferenceStage | null; + attachments?: FanavaranAttachmentStage | null; } | null; }): FanavaranClaimReferences | undefined { - if (claim.status !== ClaimCaseStatus.COMPLETED) { - return undefined; - } - const refs: FanavaranClaimReferences = {}; + const attachments = fanavaranAttachmentStatus( + claim.fanavaranSync?.attachments, + ); + if (attachments) { + refs.fileIds = [...new Set(attachments.files.map((file) => file.fileId))]; + refs.attachments = attachments; + } + if (claim.status !== ClaimCaseStatus.COMPLETED) { + return attachments ? refs : undefined; + } if (claim.claimId != null) refs.claimId = claim.claimId; if (claim.claimNo != null) refs.claimNo = claim.claimNo; if (claim.dmgCaseId != null) refs.dmgCaseId = claim.dmgCaseId; @@ -45,8 +58,7 @@ export function fanavaranClaimReferences(claim: { refs.driverId = damageCase?.driverId ?? baseClaim?.driverId; } if ((damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId) != null) { - refs.vehicleKindId = - damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId; + refs.vehicleKindId = damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId; } if (damageCase?.plaqueKindId != null) { refs.plaqueKindId = damageCase.plaqueKindId; diff --git a/src/fanavaran/fanavaran-hull-read.controller.ts b/src/fanavaran/fanavaran-hull-read.controller.ts new file mode 100644 index 0000000..4b1c516 --- /dev/null +++ b/src/fanavaran/fanavaran-hull-read.controller.ts @@ -0,0 +1,104 @@ +import { + BadRequestException, + Controller, + Get, + Param, + Query, + UseGuards, +} from "@nestjs/common"; +import { + ApiBearerAuth, + ApiOperation, + ApiParam, + ApiQuery, + ApiTags, +} from "@nestjs/swagger"; +import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard"; +import { CurrentUser } from "src/decorators/user.decorator"; +import { + FANAVARAN_CLIENT_SWAGGER_ENUM, + isFanavaranClientKey, + normalizeFanavaranClientKey, +} from "src/core/config/fanavaran-client.config"; +import { FanavaranHullReadService } from "./fanavaran-hull-read.service"; + +@ApiTags("fanavaran") +@ApiBearerAuth() +@UseGuards(LocalActorAuthGuard) +@ApiParam({ name: "client", enum: FANAVARAN_CLIENT_SWAGGER_ENUM }) +@ApiParam({ + name: "claimCaseId", + description: + "Local claim case MongoDB ObjectId; the saved Fanavaran claimId is used upstream", +}) +@Controller("v2/fanavaran/:client/claim-cases/:claimCaseId/hull") +export class FanavaranHullReadController { + constructor(private readonly hull: FanavaranHullReadService) {} + + @Get("files") + @ApiOperation({ + summary: + "Retrieve submitted hull attachment metadata from Fanavaran (GEN.05)", + description: + "Live file list, including Id, ClaimId, FileName, FileTypeId and Status. The list does not include Base64 Data. Does not depend on locally recorded file IDs.", + }) + files( + @Param("client") client: string, + @Param("claimCaseId") claimCaseId: string, + @CurrentUser() actor: any, + ) { + return this.hull.files(this.clientKey(client), claimCaseId, actor); + } + + @Get("files/:fileId") + @ApiParam({ + name: "fileId", + type: Number, + description: "Fanavaran file Id returned by the remote file list", + }) + @ApiOperation({ + summary: "Retrieve a submitted hull file including Base64 Data (GEN.05)", + }) + file( + @Param("client") client: string, + @Param("claimCaseId") claimCaseId: string, + @Param("fileId") fileId: string, + @CurrentUser() actor: any, + ) { + return this.hull.file(this.clientKey(client), claimCaseId, fileId, actor); + } + + @Get("expertise/dmg-sections") + @ApiQuery({ + name: "expertiseId", + required: false, + type: Number, + description: + "Optional historical Fanavaran expertise Id; defaults to the saved expertiseId", + }) + @ApiOperation({ + summary: + "Retrieve submitted hull expertise damage sections and costs (GEN.12)", + description: + "Reads live damage section IDs, costs, amounts, CINumber and CITrackingCode when supplied by Fanavaran. Does not resubmit expertise.", + }) + damageSections( + @Param("client") client: string, + @Param("claimCaseId") claimCaseId: string, + @CurrentUser() actor: any, + @Query("expertiseId") expertiseId?: string, + ) { + return this.hull.damageSections( + this.clientKey(client), + claimCaseId, + actor, + expertiseId, + ); + } + + private clientKey(client: string) { + if (!isFanavaranClientKey(client)) + throw new BadRequestException("Invalid Fanavaran client"); + return normalizeFanavaranClientKey(client); + } +} diff --git a/src/fanavaran/fanavaran-hull-read.service.spec.ts b/src/fanavaran/fanavaran-hull-read.service.spec.ts new file mode 100644 index 0000000..6efe125 --- /dev/null +++ b/src/fanavaran/fanavaran-hull-read.service.spec.ts @@ -0,0 +1,221 @@ +import { ForbiddenException } from "@nestjs/common"; +import { of, throwError } from "rxjs"; +import { FanavaranHullReadService } from "./fanavaran-hull-read.service"; +import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; + +const actor = { sub: "staff-1", role: "damage_expert", clientKey: "tenant-1" }; +const localId = "6af4594a32d485128a55742d"; +const headers = { + authenticationToken: "test-token", + CorpId: "543", + ContractId: "hull-contract", + Location: "110011", +}; +const base = + "https://apimanager.iraneit.com/BimeApiManager/api/BimeApi/v2.0/car/vehicle-hull-claims/5190845"; + +function setup(data: unknown = []) { + const management = { + getFanavaranHullReadContext: jest + .fn() + .mockResolvedValue({ claimId: 5190845, expertiseId: 44237, headers }), + }; + const http = { get: jest.fn().mockReturnValue(of({ data })) }; + const auth = { + assertNotInBackoff: jest.fn(), + registerFailure: jest.fn(), + clearBackoff: jest.fn(), + }; + return { + service: new FanavaranHullReadService( + management as any, + http as any, + auth as any, + ), + management, + http, + auth, + }; +} + +describe("Fanavaran hull retrieval", () => { + it("reads the remote file list even without any locally saved file IDs", async () => { + const data = [ + { + Id: 2008737, + ClaimId: 5190845, + FileName: "1.jpg", + FileTypeId: 70, + Status: 2003, + }, + ]; + const { service, management, http } = setup(data); + expect(await service.files("parsian", localId, actor)).toEqual({ + clientKey: "parsian", + claimCaseId: localId, + claimId: 5190845, + data, + }); + expect(management.getFanavaranHullReadContext).toHaveBeenCalledWith( + localId, + "parsian", + actor, + ); + expect(http.get).toHaveBeenCalledWith(`${base}/files`, { + headers: { ...headers, Accept: "application/json" }, + timeout: 20000, + }); + }); + + it("preserves the single-file Base64 Data and provider Status", async () => { + const data = { Id: 2008737, Data: "aW1hZ2U=", Status: 2003 }; + const { service, http } = setup(data); + expect( + await service.file("parsian", localId, "2008737", actor), + ).toMatchObject({ fileId: 2008737, data }); + expect(http.get.mock.calls[0][0]).toBe(`${base}/files/2008737`); + }); + + it("retrieves damage sections using stored expertiseId and retains cost IDs/tracking codes", async () => { + const data = [ + { + Id: 9, + ExpertiseId: 44237, + CINumber: "86", + CITrackingCode: "tracking", + DmgSectionCosts: [{ Id: 10, DmgSectionId: 9, Amount: 120000000 }], + }, + ]; + const { service, http } = setup(data); + expect( + await service.damageSections("parsian", localId, actor), + ).toMatchObject({ expertiseId: 44237, data }); + expect(http.get.mock.calls[0][0]).toBe( + `${base}/expertise/44237/dmg-sections`, + ); + await service.damageSections("parsian", localId, actor, "44238"); + expect(http.get.mock.calls[1][0]).toBe( + `${base}/expertise/44238/dmg-sections`, + ); + }); + + it("requires a saved or explicitly selected expertise before calling Fanavaran", async () => { + const { service, management, http } = setup(); + management.getFanavaranHullReadContext.mockResolvedValue({ + claimId: 5190845, + expertiseId: null, + headers, + }); + await expect( + service.damageSections("parsian", localId, actor), + ).rejects.toThrow("expertiseId"); + expect(http.get).not.toHaveBeenCalled(); + }); + + it.each(["0", "-1", "1.2", "../files", "9007199254740992"])( + "rejects invalid remote IDs: %s", + async (id) => { + const { service, http } = setup(); + await expect( + service.file("parsian", localId, id, actor), + ).rejects.toThrow(); + await expect( + service.damageSections("parsian", localId, actor, id), + ).rejects.toThrow(); + expect(http.get).not.toHaveBeenCalled(); + }, + ); + + it("does not make a remote request when claim access is denied", async () => { + const { service, management, http } = setup(); + management.getFanavaranHullReadContext.mockRejectedValue( + new ForbiddenException(), + ); + await expect(service.files("parsian", localId, actor)).rejects.toThrow( + ForbiddenException, + ); + expect(http.get).not.toHaveBeenCalled(); + }); + + it("preserves vendor errors and registers them with shared backoff", async () => { + const { service, http, auth } = setup(); + const error = { + isAxiosError: true, + response: { + status: 404, + data: { Message: "پرونده یافت نشد", RuleName: "HullClaimRule" }, + }, + }; + http.get.mockReturnValue(throwError(() => error)); + await expect( + service.files("parsian", localId, actor), + ).rejects.toMatchObject({ + response: { + statusCode: 404, + Message: "پرونده یافت نشد", + RuleName: "HullClaimRule", + }, + }); + expect(auth.registerFailure).toHaveBeenCalledWith("parsian", error); + }); +}); + +describe("hull read context", () => { + function context(claim: any = {}) { + const service = Object.create( + ClaimRequestManagementService.prototype, + ) as any; + service.claimCaseDbService = { + findById: jest + .fn() + .mockResolvedValue({ + claimId: 5190845, + claimNo: 123, + expertiseId: 44237, + owner: { clientId: "tenant-1" }, + ...claim, + }), + }; + service.resolveFanavaranClaimProduct = jest + .fn() + .mockResolvedValue("car-body"); + service.getFanavaranAuthHeaders = jest.fn().mockResolvedValue(headers); + return service; + } + + it("uses the saved claimId rather than claimNo and shares submission headers", async () => { + const service = context(); + expect( + await service.getFanavaranHullReadContext(localId, "parsian", actor), + ).toEqual({ claimId: 5190845, expertiseId: 44237, headers }); + expect(service.getFanavaranAuthHeaders).toHaveBeenCalledWith( + "parsian", + undefined, + localId, + ); + }); + + it("rejects another organization's claim before retrieving credentials", async () => { + const service = context({ owner: { clientId: "other-tenant" } }); + await expect( + service.getFanavaranHullReadContext(localId, "parsian", actor), + ).rejects.toThrow(ForbiddenException); + expect(service.getFanavaranAuthHeaders).not.toHaveBeenCalled(); + }); + + it("rejects third-party claims and claims that only have a claimNo", async () => { + const service = context(); + service.resolveFanavaranClaimProduct.mockResolvedValue("third-party"); + await expect( + service.getFanavaranHullReadContext(localId, "parsian", actor), + ).rejects.toThrow("vehicle-hull"); + service.resolveFanavaranClaimProduct.mockResolvedValue("car-body"); + service.claimCaseDbService.findById.mockResolvedValue({ + claimNo: 123, + owner: { clientId: "tenant-1" }, + }); + await expect( + service.getFanavaranHullReadContext(localId, "parsian", actor), + ).rejects.toThrow("claimId"); + }); +}); diff --git a/src/fanavaran/fanavaran-hull-read.service.ts b/src/fanavaran/fanavaran-hull-read.service.ts new file mode 100644 index 0000000..3e10334 --- /dev/null +++ b/src/fanavaran/fanavaran-hull-read.service.ts @@ -0,0 +1,131 @@ +import { HttpService } from "@nestjs/axios"; +import { BadRequestException, Injectable } from "@nestjs/common"; +import { firstValueFrom } from "rxjs"; +import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service"; +import { + getFanavaranLookupBaseUrl, + type FanavaranClientKey, +} from "src/core/config/fanavaran-client.config"; +import { FanavaranAuthService } from "./fanavaran-auth.service"; +import { toFanavaranHttpException } from "./fanavaran-http-exception"; + +type ReadActor = { + sub: string; + role?: string; + clientKey?: string; + username?: string; +}; + +@Injectable() +export class FanavaranHullReadService { + constructor( + private readonly management: ClaimRequestManagementService, + private readonly http: HttpService, + private readonly auth: FanavaranAuthService, + ) {} + + /** GEN.05 list contains file metadata/Status, not Base64 Data. */ + async files( + clientKey: FanavaranClientKey, + claimCaseId: string, + actor: ReadActor, + ) { + const context = await this.management.getFanavaranHullReadContext( + claimCaseId, + clientKey, + actor, + ); + const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/files`; + return { + clientKey, + claimCaseId, + claimId: context.claimId, + data: await this.get(clientKey, url, context.headers), + }; + } + + /** GEN.05 single-file response includes Data as Base64. */ + async file( + clientKey: FanavaranClientKey, + claimCaseId: string, + fileId: string, + actor: ReadActor, + ) { + const id = this.positiveId(fileId, "fileId"); + const context = await this.management.getFanavaranHullReadContext( + claimCaseId, + clientKey, + actor, + ); + const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/files/${id}`; + return { + clientKey, + claimCaseId, + claimId: context.claimId, + fileId: id, + data: await this.get(clientKey, url, context.headers), + }; + } + + /** GEN.12: read the stored expertise, or an explicitly selected historical one. */ + async damageSections( + clientKey: FanavaranClientKey, + claimCaseId: string, + actor: ReadActor, + expertiseId?: string, + ) { + const selectedId = + expertiseId === undefined + ? undefined + : this.positiveId(expertiseId, "expertiseId"); + const context = await this.management.getFanavaranHullReadContext( + claimCaseId, + clientKey, + actor, + ); + const id = selectedId ?? context.expertiseId; + if (id == null) + throw new BadRequestException( + "No submitted expertiseId is stored; provide expertiseId for a previously submitted expertise", + ); + const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/expertise/${id}/dmg-sections`; + return { + clientKey, + claimCaseId, + claimId: context.claimId, + expertiseId: id, + data: await this.get(clientKey, url, context.headers), + }; + } + + private positiveId(value: string, field: string): number { + const id = Number(value); + if (!/^\d+$/.test(value) || !Number.isSafeInteger(id) || id <= 0) { + throw new BadRequestException(`${field} must be a positive integer`); + } + return id; + } + + private async get( + clientKey: FanavaranClientKey, + url: string, + headers: Record, + ): Promise { + this.auth.assertNotInBackoff(clientKey); + try { + const response = await firstValueFrom( + this.http.get(url, { + headers: { ...headers, Accept: "application/json" }, + timeout: 20000, + }), + ); + this.auth.clearBackoff(clientKey); + return response.data; + } catch (error) { + this.auth.registerFailure(clientKey, error); + throw toFanavaranHttpException(error, { + fallback: "Failed to retrieve submitted hull data from Fanavaran", + }); + } + } +} diff --git a/src/fanavaran/fanavaran.controller.ts b/src/fanavaran/fanavaran.controller.ts index 9b9b853..f0996a4 100644 --- a/src/fanavaran/fanavaran.controller.ts +++ b/src/fanavaran/fanavaran.controller.ts @@ -205,7 +205,7 @@ export class FanavaranController { @ApiOperation({ summary: "Preview Fanavaran attachment upload plan", description: - "Lists local required-document and captured damage images that would be sent to GEN.07. Shows which images are already recorded as uploaded to Fanavaran.", + "Lists local documents and captured images for third-party GEN.07 or hull GEN.05. Returns external file IDs, saved upload status/errors, local file availability, and pending image counts.", }) @ApiParam({ name: "client", @@ -231,7 +231,7 @@ export class FanavaranController { @ApiOperation({ summary: "Submit missing Fanavaran attachments", description: - "Uploads every local image that does not already have a recorded successful GEN.07 Fanavaran file upload. Uses one multipart request per image.", + "Uploads pending local images to third-party GEN.07 or hull GEN.05 and persists each returned fileId. Reports failures and skipped/missing local files. Uses one multipart request per image.", }) @ApiParam({ name: "client", diff --git a/src/fanavaran/fanavaran.module.ts b/src/fanavaran/fanavaran.module.ts index b2b4e9f..7b99955 100644 --- a/src/fanavaran/fanavaran.module.ts +++ b/src/fanavaran/fanavaran.module.ts @@ -1,10 +1,26 @@ import { Module } from "@nestjs/common"; +import { HttpModule } from "@nestjs/axios"; +import { ConfigModule, ConfigService } from "@nestjs/config"; +import { createHttpModuleOptions } from "src/core/config/http-proxy.factory"; import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module"; import { FanavaranAuditModule } from "./fanavaran-audit.module"; import { FanavaranController } from "./fanavaran.controller"; +import { FanavaranLookupModule } from "./fanavaran-lookup.module"; +import { FanavaranHullReadService } from "./fanavaran-hull-read.service"; +import { FanavaranHullReadController } from "./fanavaran-hull-read.controller"; @Module({ - imports: [ClaimRequestManagementModule, FanavaranAuditModule], - controllers: [FanavaranController], + imports: [ + ClaimRequestManagementModule, + FanavaranAuditModule, + FanavaranLookupModule, + HttpModule.registerAsync({ + imports: [ConfigModule], + inject: [ConfigService], + useFactory: createHttpModuleOptions, + }), + ], + controllers: [FanavaranController, FanavaranHullReadController], + providers: [FanavaranHullReadService], }) export class FanavaranModule {}