From cbdf4fd2bcc37e35cb0b6ce7b88bd368a8fa1fcd Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Thu, 12 Nov 2026 13:38:08 +0330 Subject: [PATCH] invalid image formats after two retries skips --- docs/fanavaran/09-error-handling.md | 1 + docs/fanavaran/attachment-upload-status.md | 11 +- .../claim-request-management.service.ts | 232 +++++++++++++++++- .../fanavaran-attachment-status.spec.ts | 48 +++- .../fanavaran-attachment-status.ts | 5 +- .../fanavaran-expertise-sequence.spec.ts | 53 +++- 6 files changed, 326 insertions(+), 24 deletions(-) diff --git a/docs/fanavaran/09-error-handling.md b/docs/fanavaran/09-error-handling.md index 252618e..bb1f11b 100644 --- a/docs/fanavaran/09-error-handling.md +++ b/docs/fanavaran/09-error-handling.md @@ -24,6 +24,7 @@ source: fanavaran-module-docs | Missing PolicyId | No/expired policies messages | Block submit; preview may leave null | Manual after data fix | Stage fail history | Admin | | Duplicate create | Local `claimId`/`claimNo` exists | Skip create; use follow-ups | N/A | skipReason | — | | Invalid FileTypeId | `نوع فايل با منبع لوکاپ مطابقت ندارد` | Set `ClaimFileTypeId` from tenant `file-types` (Parsian **63**) | After config fix | Attachment stage | Ops | +| Invalid file bytes | `فرمت فایل معتبر نیست` | File is not a real JPEG/PNG/PDF (wrong magic bytes / empty / WEBP-as-jpg). YARA now sniffs magic + sets multipart `contentType` before upload | After replacing the file | Attachment stage | Ops / user re-upload | | Expertise not ready | `Fanavaran expertise payload is not ready` + warnings | Wait for priced parts / factor | Auto when ready | — | Expert UI | | Network / 5xx | Axios / gateway errors | Stage failed + schedule retry | Up to `maxRetries` (2) | Audit | Ops | | Max retries exhausted | Logged warn | Manual submit only | Stop auto | Stage status | Ops | diff --git a/docs/fanavaran/attachment-upload-status.md b/docs/fanavaran/attachment-upload-status.md index fb6e257..8cceb0a 100644 --- a/docs/fanavaran/attachment-upload-status.md +++ b/docs/fanavaran/attachment-upload-status.md @@ -82,8 +82,15 @@ Existing claim/damage IDs and successful image receipts are reused. A previously skipped attachment stage is retried. Completion is checked against a fresh read of the saved receipts for all current local image candidates, not just the attachment stage's status or an upload response saying success. Missing local -files, rejected uploads, and unconfirmed receipts stop expertise submission. -If there are no local attachment candidates, there is nothing to upload. +files, non-format rejected uploads, and unconfirmed receipts stop expertise +submission. If there are no local attachment candidates, there is nothing to +upload. + +Invalid file format (`فرمت فایل معتبر نیست` / local magic-byte rejection) is +retried once in the same submit. If the second attempt still fails, the file is +permanently waived (`FANAVARAN_ATTACHMENT_FORMAT_WAIVED` on the skipped attempt). +Waived files count as handled: they are not re-uploaded and do not block +expertise or later stages. Errors identify `stage` (`baseClaim`, `damageCase`, or `attachments`) and preserve vendor details. An attachment failure includes: diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 0b36ffa..8003338 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -16,7 +16,7 @@ import { } from '@nestjs/common'; import { isAxiosError } from 'axios'; import { Types } from 'mongoose'; -import { createReadStream, existsSync } from 'node:fs'; +import { createReadStream, existsSync, openSync, readSync, closeSync, statSync } from 'node:fs'; import { basename, resolve } from 'node:path'; import { BlameRequestType } from 'src/Types&Enums/blame-request-management/blameRequestType.enum'; import { CaseStatus as BlameCaseStatus } from 'src/Types&Enums/blame-request-management/caseStatus.enum'; @@ -363,9 +363,16 @@ interface FanavaranAttachmentCandidate { source: string; content: Record; alreadySubmitted: boolean; + /** Format rejected twice (or local invalid magic); treated as done for later stages. */ + alreadyWaived?: boolean; + waivedReason?: string; submittedFileId?: unknown; } +/** Persisted on skipped attempts so collect/ensure treat the file as handled. */ +const FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX = + 'FANAVARAN_ATTACHMENT_FORMAT_WAIVED:'; + interface FanavaranClaimExpertContext { initiatedByFieldExpertId?: unknown; evaluation?: object; @@ -5175,10 +5182,65 @@ export class ClaimRequestManagementService { return submitted; } + /** + * Files whose latest attempt is a permanent format waive after 2 failed uploads. + * Expertise and batch submit treat these as handled (no further upload / no block). + */ + private getWaivedFanavaranAttachmentFileNames( + claimCase: any, + ): Map { + const waived = new Map(); + const attempts = claimCase?.fanavaranSync?.attachments?.attempts; + if (!Array.isArray(attempts)) return waived; + + const latest = new Map(); + for (const row of attempts) { + const fileName = (row as { fileName?: unknown })?.fileName; + if (typeof fileName !== 'string' || !fileName.trim()) continue; + latest.set(fileName, { + status: String((row as { status?: unknown })?.status ?? ''), + error: + typeof (row as { error?: unknown })?.error === 'string' + ? ((row as { error: string }).error) + : undefined, + }); + } + for (const [fileName, attempt] of latest) { + if ( + attempt.status === 'skipped' && + typeof attempt.error === 'string' && + attempt.error.startsWith(FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX) + ) { + waived.set(fileName, attempt.error); + } + } + return waived; + } + + private isFanavaranAttachmentFormatError( + error: unknown, + warning: string, + ): boolean { + if (warning.includes('فرمت فایل معتبر نیست')) return true; + if (warning.includes('FANAVARAN_ATTACHMENT_INVALID_FORMAT')) return true; + if (error instanceof BadRequestException) { + const body = error.getResponse(); + if ( + body && + typeof body === 'object' && + (body as { code?: string }).code === 'FANAVARAN_ATTACHMENT_INVALID_FORMAT' + ) { + return true; + } + } + return false; + } + private appendFanavaranAttachmentCandidate( candidates: FanavaranAttachmentCandidate[], seen: Set, submittedFiles: Map, + waivedFiles: Map, input: { path?: unknown; fileName?: unknown; source: string }, fileTypeId: number, ): void { @@ -5192,6 +5254,8 @@ export class ClaimRequestManagementService { if (!path || !fileName || seen.has(fileName)) return; seen.add(fileName); + const waivedReason = waivedFiles.get(fileName); + const alreadyWaived = waivedReason != null; candidates.push({ path, fileName, @@ -5201,7 +5265,9 @@ export class ClaimRequestManagementService { FileTypeId: fileTypeId, Files: [{ FileName: fileName, FileTypeId: fileTypeId }], }, - alreadySubmitted: submittedFiles.has(fileName), + alreadySubmitted: submittedFiles.has(fileName) || alreadyWaived, + alreadyWaived, + waivedReason, submittedFileId: submittedFiles.get(fileName), }); } @@ -5223,6 +5289,7 @@ export class ClaimRequestManagementService { const seen = new Set(); const submittedFiles = this.getSubmittedFanavaranAttachmentFileNames(claimCase); + const waivedFiles = this.getWaivedFanavaranAttachmentFileNames(claimCase); const fileTypeId = profile.defaults.ClaimFileTypeId; const documents = @@ -5232,6 +5299,7 @@ export class ClaimRequestManagementService { candidates, seen, submittedFiles, + waivedFiles, { path: (document as { path?: unknown }).path, fileName: (document as { fileName?: unknown }).fileName, @@ -5254,6 +5322,7 @@ export class ClaimRequestManagementService { candidates, seen, submittedFiles, + waivedFiles, { path: capture?.path, fileName: capture?.fileName, @@ -5275,6 +5344,7 @@ export class ClaimRequestManagementService { candidates, seen, submittedFiles, + waivedFiles, { path: capture?.path, fileName: capture?.fileName, @@ -5322,10 +5392,23 @@ export class ClaimRequestManagementService { attachments: candidates.map(candidate => { const latestAttempt = uploadStatus?.attempts.filter(attempt => attempt.fileName === candidate.fileName).at(-1); const localFileExists = existsSync(candidate.path); + const status = candidate.alreadyWaived + ? 'skipped' + : candidate.alreadySubmitted + ? 'success' + : !localFileExists + ? 'skipped' + : latestAttempt?.status ?? 'pending'; 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, + status, + lastError: candidate.alreadyWaived + ? candidate.waivedReason ?? latestAttempt?.error ?? null + : candidate.alreadySubmitted + ? null + : !localFileExists + ? 'Local attachment file does not exist.' + : latestAttempt?.error ?? null, }; }), }; @@ -5422,6 +5505,8 @@ export class ClaimRequestManagementService { options?: { clientKey?: FanavaranClientKey; auditSource?: FanavaranAuditSource; + /** True on the immediate second try after a format rejection. */ + formatRetryAttempted?: boolean; }, ): Promise { const clientKey = options?.clientKey ?? resolveFanavaranClientKey(); @@ -5480,6 +5565,19 @@ export class ClaimRequestManagementService { }; } + const waivedReason = + this.getWaivedFanavaranAttachmentFileNames(claimCase).get(fileName); + if (waivedReason) { + return { + attempted: false, + submitted: false, + skipped: true, + skipReason: waivedReason, + warning: waivedReason, + fileName, + }; + } + if (!claimCase.claimId) { if (options?.clientKey) { await this.executeFanavaranV2Submit(claimCaseId, clientKey); @@ -5671,6 +5769,36 @@ export class ClaimRequestManagementService { ); } + // Invalid format: try once more immediately; if it still fails, waive permanently + // so expertise and later stages can continue without this file. + const formatError = this.isFanavaranAttachmentFormatError(error, warning); + if (formatError && !options?.formatRetryAttempted) { + this.logger.warn( + `${logPrefix} format rejected; retrying once fileName=${fileName}`, + ); + return this.autoSubmitFanavaranAttachment(claimCaseId, file, { + ...options, + formatRetryAttempted: true, + }); + } + if (formatError && options?.formatRetryAttempted) { + const reason = `${FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX} ${warning} (after 2 attempts); continuing without this file.`; + await this.recordSkippedFanavaranAttachment( + claimCaseId, + fileName, + file.source, + reason, + ); + return { + attempted: true, + submitted: false, + skipped: true, + skipReason: reason, + warning: reason, + fileName, + }; + } + // Schedule retry for attachments — never let retry bookkeeping fail the // caller: local media/docs are already persisted before this submit. try { @@ -6838,6 +6966,67 @@ export class ClaimRequestManagementService { } } + /** + * Fanavaran GEN.05/07 rejects unknown binaries with «فرمت فایل معتبر نیست». + * Detect real JPEG/PNG/PDF from magic bytes (extension alone is not enough). + */ + private inspectFanavaranUploadFile(filePath: string): { + contentType: string; + extension: string; + } { + const absolute = resolve(filePath); + const size = existsSync(absolute) ? statSync(absolute).size : 0; + if (size <= 0) { + throw new BadRequestException({ + code: 'FANAVARAN_ATTACHMENT_EMPTY', + message: `Attachment file is empty: ${filePath}`, + }); + } + const fd = openSync(absolute, 'r'); + const header = Buffer.alloc(16); + try { + readSync(fd, header, 0, 16, 0); + } finally { + closeSync(fd); + } + if (header[0] === 0xff && header[1] === 0xd8 && header[2] === 0xff) { + return { contentType: 'image/jpeg', extension: '.jpg' }; + } + if ( + header[0] === 0x89 && + header[1] === 0x50 && + header[2] === 0x4e && + header[3] === 0x47 + ) { + return { contentType: 'image/png', extension: '.png' }; + } + if ( + header.slice(0, 4).toString('ascii') === '%PDF' + ) { + return { contentType: 'application/pdf', extension: '.pdf' }; + } + throw new BadRequestException({ + code: 'FANAVARAN_ATTACHMENT_INVALID_FORMAT', + message: `Attachment is not a valid JPEG/PNG/PDF (Fanavaran «فرمت فایل معتبر نیست»). path=${filePath} magic=${header + .slice(0, 8) + .toString('hex')}`, + }); + } + + private fanavaranUploadFileName( + preferredName: string, + extension: string, + ): string { + const base = basename(preferredName || 'upload'); + const withoutExt = base.replace(/\.[^.]+$/, '') || 'upload'; + const safe = withoutExt + .replace(/[^\w.-]+/g, '_') + .replace(/_+/g, '_') + .replace(/^_|_$/g, '') + .slice(0, 80); + return `${safe || 'upload'}${extension}`; + } + private async postFanavaranMultipart( url: string, content: Record, @@ -6855,12 +7044,36 @@ export class ClaimRequestManagementService { ); const form = new FormData(); + const prepared = files.map((file) => { + const inspected = this.inspectFanavaranUploadFile(file.path); + const fileName = this.fanavaranUploadFileName( + file.fileName || basename(file.path), + inspected.extension, + ); + return { + path: resolve(file.path), + fileName, + contentType: inspected.contentType, + }; + }); + + // Keep Param.FileName / Files[].FileName aligned with the multipart filename. + if (prepared.length === 1) { + content.FileName = prepared[0].fileName; + if (Array.isArray(content.Files) && content.Files[0]) { + (content.Files[0] as Record).FileName = + prepared[0].fileName; + } + } + form.append('Param', JSON.stringify(content), { contentType: 'application/json', }); - for (const file of files) { - form.append('Param1', createReadStream(resolve(file.path)), { + for (const file of prepared) { + form.append('Param1', createReadStream(file.path), { filename: file.fileName, + contentType: file.contentType, + knownLength: statSync(file.path).size, }); } @@ -6870,8 +7083,11 @@ export class ClaimRequestManagementService { `-H 'CorpId: ${headers.CorpId}'`, `-H 'ContractId: ${headers.ContractId}'`, `-H 'Location: ${headers.Location}'`, - `-F 'Param=${JSON.stringify(content)}'`, - ...files.map((f) => `-F 'Param1=@${f.path};filename=${f.fileName}'`), + `-F 'Param=${JSON.stringify(content)};type=application/json'`, + ...prepared.map( + (f) => + `-F 'Param1=@${f.path};filename=${f.fileName};type=${f.contentType}'`, + ), ]; this.logger.log( `\n====== COPY THIS CURL ======\n${curlParts.join(' \\\n ')}\n====== END CURL ======\n`, diff --git a/src/claim-request-management/fanavaran-attachment-status.spec.ts b/src/claim-request-management/fanavaran-attachment-status.spec.ts index f26575f..22ca263 100644 --- a/src/claim-request-management/fanavaran-attachment-status.spec.ts +++ b/src/claim-request-management/fanavaran-attachment-status.spec.ts @@ -63,6 +63,7 @@ describe("Fanavaran image upload persistence and visibility", () => { .fn() .mockImplementation(async () => { const files = service.getSubmittedFanavaranAttachmentFileNames(claim); + const waived = service.getWaivedFanavaranAttachmentFileNames(claim); return { claimCase: claim, candidates: [ @@ -70,7 +71,9 @@ describe("Fanavaran image upload persistence and visibility", () => { path, fileName: "image.jpg", source: "capture:angle:front", - alreadySubmitted: files.has("image.jpg"), + alreadySubmitted: files.has("image.jpg") || waived.has("image.jpg"), + alreadyWaived: waived.has("image.jpg"), + waivedReason: waived.get("image.jpg"), submittedFileId: files.get("image.jpg"), }, ], @@ -171,6 +174,49 @@ describe("Fanavaran image upload persistence and visibility", () => { expect(service.scheduleFanavaranRetry).not.toHaveBeenCalled(); }); + it("retries invalid-format uploads once then waives so later stages can continue", async () => { + const { service, claim } = setup(); + service.postFanavaranMultipart.mockRejectedValue( + new Error("فرمت فایل معتبر نیست"), + ); + const result = await service.submitFanavaranAttachmentsV2( + "claim-1", + "parsian", + ); + expect(service.postFanavaranMultipart).toHaveBeenCalledTimes(2); + expect(service.scheduleFanavaranRetry).not.toHaveBeenCalled(); + expect(result[0]).toMatchObject({ + submitted: false, + skipped: true, + skipReason: expect.stringContaining("FANAVARAN_ATTACHMENT_FORMAT_WAIVED"), + }); + expect(claim.fanavaranSync.attachments.attempts).toEqual( + expect.arrayContaining([ + expect.objectContaining({ status: "failed", error: "فرمت فایل معتبر نیست" }), + expect.objectContaining({ + status: "skipped", + error: expect.stringContaining("FANAVARAN_ATTACHMENT_FORMAT_WAIVED"), + }), + ]), + ); + expect( + claim.fanavaranSync.attachments.attempts.filter( + (row: { status?: string }) => row.status === "failed", + ), + ).toHaveLength(2); + + const second = await service.submitFanavaranAttachmentsV2( + "claim-1", + "parsian", + ); + expect(service.postFanavaranMultipart).toHaveBeenCalledTimes(2); + expect(second).toMatchObject({ + attempted: 0, + skipped: 1, + results: [], + }); + }); + it("exposes upload status before completion and reports mixed outcomes as partial", async () => { const { service, claim } = setup(); claim.status = "EXPERT_REVIEWING"; diff --git a/src/claim-request-management/fanavaran-attachment-status.ts b/src/claim-request-management/fanavaran-attachment-status.ts index eacee47..f69dd95 100644 --- a/src/claim-request-management/fanavaran-attachment-status.ts +++ b/src/claim-request-management/fanavaran-attachment-status.ts @@ -42,9 +42,12 @@ export function fanavaranAttachmentStatus( const latest = new Map( attempts.map((attempt) => [attempt.fileName, attempt]), ); + // Skipped (including format-waived) files are intentional omissions, not blockers. const outstanding = [...latest.values()].filter( (attempt) => - !uploadedNames.has(attempt.fileName) && attempt.status !== "success", + !uploadedNames.has(attempt.fileName) && + attempt.status !== "success" && + attempt.status !== "skipped", ); const lastProblem = outstanding.at(-1); const status = lastProblem diff --git a/src/claim-request-management/fanavaran-expertise-sequence.spec.ts b/src/claim-request-management/fanavaran-expertise-sequence.spec.ts index 5d60376..a988c33 100644 --- a/src/claim-request-management/fanavaran-expertise-sequence.spec.ts +++ b/src/claim-request-management/fanavaran-expertise-sequence.spec.ts @@ -4,7 +4,7 @@ function setup(product = "third-party") { const service = Object.create(ClaimRequestManagementService.prototype) as any; const claim: any = { _id: "claim-1", - fanavaranSync: { attachments: { files: [] } }, + fanavaranSync: { attachments: { files: [], attempts: [] } }, }; const events: string[] = []; service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() }; @@ -24,17 +24,23 @@ function setup(product = "third-party") { }); service.collectFanavaranAttachmentCandidates = jest .fn() - .mockImplementation(async () => ({ - claimCase: claim, - candidates: [ - { - fileName: "image.jpg", - source: "capture:angle:front", - path: "/tmp/image.jpg", - alreadySubmitted: claim.fanavaranSync.attachments.files.length > 0, - }, - ], - })); + .mockImplementation(async () => { + const waived = service.getWaivedFanavaranAttachmentFileNames(claim); + const uploaded = claim.fanavaranSync.attachments.files.length > 0; + return { + claimCase: claim, + candidates: [ + { + fileName: "image.jpg", + source: "capture:angle:front", + path: "/tmp/image.jpg", + alreadySubmitted: uploaded || waived.has("image.jpg"), + alreadyWaived: waived.has("image.jpg"), + waivedReason: waived.get("image.jpg"), + }, + ], + }; + }); service.submitFanavaranAttachmentsV2 = jest .fn() .mockImplementation(async () => { @@ -113,6 +119,29 @@ describe("expertise submit completes earlier Fanavaran stages", () => { }, ); + it("continues to expertise when an invalid-format image was waived after 2 tries", async () => { + const { service, claim, events } = setup(); + Object.assign(claim, { claimId: 100, dmgCaseId: 200 }); + claim.fanavaranSync.attachments.attempts.push({ + fileName: "image.jpg", + status: "skipped", + error: + "FANAVARAN_ATTACHMENT_FORMAT_WAIVED: فرمت فایل معتبر نیست (after 2 attempts); continuing without this file.", + }); + service.submitFanavaranAttachmentsV2.mockImplementation(async () => { + events.push("attachments"); + return { + attempted: 0, + submitted: 0, + skipped: 1, + results: [], + }; + }); + await service.submitFanavaranExpertiseV2("claim-1", "parsian"); + expect(events).toEqual(["expertise"]); + expect(service.submitFanavaranAttachmentsV2).not.toHaveBeenCalled(); + }); + it("stops immediately if the base stage fails", async () => { const { service } = setup(); service.executeFanavaranV2Submit.mockRejectedValue(