update the 2 new apis for getting expertise and files of the request

This commit is contained in:
2026-11-11 17:59:48 +03:30
parent 90bdc51715
commit 84b92eb55a
13 changed files with 1111 additions and 195 deletions
@@ -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<any> {
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<void> {
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<string, unknown> = {};
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`
@@ -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:
@@ -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;
@@ -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 },
});
});
});
@@ -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<string, unknown> => !!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,
};
}
@@ -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<typeof fanavaranAttachmentStatus>;
};
/**
* 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;