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`