invalid image formats after two retries skips

This commit is contained in:
2026-11-12 13:38:08 +03:30
parent af9bed3b0d
commit cbdf4fd2bc
6 changed files with 326 additions and 24 deletions
@@ -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<string, unknown>;
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<string, string> {
const waived = new Map<string, string>();
const attempts = claimCase?.fanavaranSync?.attachments?.attempts;
if (!Array.isArray(attempts)) return waived;
const latest = new Map<string, { status?: string; error?: string }>();
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<string>,
submittedFiles: Map<string, unknown>,
waivedFiles: Map<string, string>,
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<string>();
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<FanavaranAttachmentSubmitResult> {
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<string, unknown>,
@@ -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<string, unknown>).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`,
@@ -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";
@@ -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
@@ -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(