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`,