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
@@ -0,0 +1,70 @@
# Fanavaran image receipts and upload failures
The image ID is the external `Id` returned by Fanavaran's attachment upload, not
the MongoDB ID of the local image. Both batch and single-image uploads persist it
in `claimCases.fanavaranSync.attachments.files[].fileId`, together with `fileName`,
`source`, `submittedAt`, and the response. Per-image success, failure, and skip
events are saved in `fanavaranSync.attachments.attempts`. Failures include an error
and, when an audited HTTP upload started, a tracking code.
## Read the IDs beside the claim references
Claim detail responses that expose `fanavaran` now include:
```json
{
"fanavaran": {
"claimId": 5190845,
"fileIds": [700001],
"attachments": {
"status": "success",
"uploadedCount": 1,
"lastError": null,
"files": [
{
"fileId": 700001,
"fileName": "image.jpg",
"source": "capture:angle:front"
}
],
"attempts": []
}
}
}
```
Existing claim-reference codes remain gated on COMPLETED. Image receipts and
status can appear earlier. The expertise preview also returns `fileIds` and
`attachments` beside `claimId`, `dmgCaseId`, and `expertiseId`.
## Check every planned image and why it is pending
`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/attachments/preview`
This returns `totalLocalImages`, `alreadySubmitted`, `pendingSubmit`, `fileIds`,
`uploadStatus`, and one `attachments` row per local upload candidate. Each row
includes `fileId`, `alreadySubmitted`, `localFileExists`, `status`, and `lastError`.
Use `pendingSubmit` to check whether all current local candidates have saved
receipts. Summary status describes recorded outcomes, not unattempted images.
- `success`: confirmed external file IDs are recorded.
- `partial`: receipts exist, but another recorded image failed or was skipped.
- `failed` / `skipped`: inspect the per-image error and `nextRetryAt` if present.
- `not_recorded`: no upload outcome is stored; this is not proof of remote absence.
- `unconfirmed`: legacy upload records have no valid external file ID.
`POST /v2/fanavaran/parsian/claim-cases/{claimCaseId}/attachments/submit` submits
pending candidates and returns each upload's `fileId` or failure/skip reason.
Already-recorded successful uploads are skipped. Missing local files are reported
instead of silently excluded. A response with no external file ID is unconfirmed
and is not automatically retried, to avoid duplicating a possibly accepted upload.
Older batch uploads did not persist their returned IDs. This change cannot
reconstruct those historical receipts from the local database; verify them with
Fanavaran before deciding to re-upload. New uploads use the shared persistence
path and record their outcomes.
To verify remote receipts directly, use
`GET /v2/fanavaran/parsian/claim-cases/{claimCaseId}/hull/files`.
Retrieve one image and its Base64 content using `/hull/files/{fileId}`.
See [hull retrieval](hull-retrieval.md) for all supported read routes.
+62
View File
@@ -0,0 +1,62 @@
# Retrieve submitted hull files and expertise sections
Implemented from the supplied Fanavaran V2.0 customer documents:
- `CAR.VHUD.APIH.GEN.05 - سرویس فایل های پیوست خسارت بدنه.docx`
- `CAR.VHUD.APIH.GEN.12 - سرویس بازیابی نقاط آسیب دیده کارشناسی خسارت بدنه.docx`
All routes require the existing actor Bearer token and access to the local claim.
The path's `claimCaseId` is a local MongoDB ObjectId. The backend resolves the
saved external `claimId` (never `claimNo`), hull ContractId, and the claim staff's
Location using the submission header resolver. Non-hull claims are rejected.
## Routes
Base: `/v2/fanavaran/{client}/claim-cases/{claimCaseId}/hull`
| Local GET route | Fanavaran GET resource | Result |
|---|---|---|
| `/files` | `/car/vehicle-hull-claims/{claimId}/files` | Live file metadata: `Id`, `ClaimId`, `FileName`, `FileTypeId`, `Status` |
| `/files/{fileId}` | `/car/vehicle-hull-claims/{claimId}/files/{fileId}` | One file with the same metadata plus Base64 `Data` |
| `/expertise/dmg-sections` | `/car/vehicle-hull-claims/{claimId}/expertise/{expertiseId}/dmg-sections` | Damage sections, nested costs, section/cost IDs, and provider tracking codes |
The sections route defaults to the saved `expertiseId`. To read a historical
expertise on this same claim, supply `?expertiseId=44237`. A missing saved
expertise ID without an explicit override returns 400. File and expertise IDs
must be positive safe integers.
Every response wraps the unmodified vendor body in `data`, with `clientKey`,
`claimCaseId`, `claimId`, and the selected `fileId` or `expertiseId` when relevant:
```json
{
"clientKey": "parsian",
"claimCaseId": "6af4594a32d485128a55742d",
"claimId": 5190845,
"data": [
{
"Id": 2008737,
"ClaimId": 5190845,
"FileName": "1.jpg",
"FileTypeId": 70,
"Status": 2003
}
]
}
```
The list response does **not** contain image bytes. Retrieve the desired file ID
with the single-file route to obtain `data.Data` as Base64. Preserve the numeric
`Status` value; its meaning belongs to Fanavaran's
`/common/code-list/file-status` lookup and is not inferred by these routes.
GEN.12 responses preserve `Id`, `ExpertiseId`, `AccessoryKindId`,
`VehicleHullAccessoryId`, `DmgKindId`, `Count`, `WasteValue`, `DmgAmount`, `Desc`,
`CINumber`, `CITrackingCode`, and `DmgSectionCosts` when returned. Each nested cost
can include its own `Id`, `DmgSectionId`, `DmgCostKindId`, `Caption`, and `Amount`.
These reads call Fanavaran directly without resubmitting claims/files/expertise,
using local upload receipt caches, or changing local claim records. In particular,
the remote file list can reveal historical uploads whose file IDs were not saved
by the old batch uploader. Vendor errors retain their original `Message` and
`RuleName`; transient errors participate in the shared tenant backoff.
@@ -4,6 +4,7 @@ import {
} from 'src/fanavaran/tejarat-notifier'; } from 'src/fanavaran/tejarat-notifier';
import { import {
BadRequestException, BadRequestException,
BadGatewayException,
ConflictException, ConflictException,
ForbiddenException, ForbiddenException,
HttpException, HttpException,
@@ -101,7 +102,10 @@ import {
collectUserIdVariants, collectUserIdVariants,
} from 'src/helpers/party-access-queries'; } from 'src/helpers/party-access-queries';
import { toPublicListItems } from 'src/helpers/public-list-response'; 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 { resolveUnifiedFileStatus } from 'src/helpers/unified-file-status';
import { buildFileLink, resolveStoredFileUrl } from 'src/helpers/urlCreator'; import { buildFileLink, resolveStoredFileUrl } from 'src/helpers/urlCreator';
import { import {
@@ -184,6 +188,7 @@ import {
type FanavaranClaimProduct, type FanavaranClaimProduct,
} from './fanavaran-claim-product'; } from './fanavaran-claim-product';
import { fanavaranClaimReferences } from './fanavaran-claim-references'; import { fanavaranClaimReferences } from './fanavaran-claim-references';
import { fanavaranAttachmentStatus } from './fanavaran-attachment-status';
import { import {
actualPremiumFromHullPolicyRecord, actualPremiumFromHullPolicyRecord,
authorityCulpritIdFromDetectionRows, 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( private async getFanavaranAuthHeaders(
clientKey: FanavaranClientKey, clientKey: FanavaranClientKey,
auditSession?: FanavaranAuditSession, auditSession?: FanavaranAuditSession,
@@ -5065,8 +5111,9 @@ export class ClaimRequestManagementService {
for (const file of files) { for (const file of files) {
const fileName = (file as { fileName?: unknown })?.fileName; const fileName = (file as { fileName?: unknown })?.fileName;
if (typeof fileName === 'string' && fileName.trim()) { const fileId = pickFanavaranRecordId((file as { fileId?: unknown })?.fileId);
submitted.set(fileName, (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 } = const { claimCase, candidates } =
await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey); await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey);
const claimsUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId); const claimsUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId);
const uploadStatus = fanavaranAttachmentStatus(claimCase.fanavaranSync?.attachments) ?? {
status: 'not_recorded', uploadedCount: 0, files: [], attempts: [], lastError: null,
};
return { return {
clientKey, clientKey,
@@ -5199,6 +5249,8 @@ export class ClaimRequestManagementService {
claimId: claimCase.claimId ?? null, claimId: claimCase.claimId ?? null,
claimNo: claimCase.claimNo ?? null, claimNo: claimCase.claimNo ?? null,
dmgCaseId: claimCase.dmgCaseId ?? null, dmgCaseId: claimCase.dmgCaseId ?? null,
fileIds: [...new Set(uploadStatus?.files.map(file => file.fileId) ?? [])],
uploadStatus,
submitUrl: claimCase.claimId submitUrl: claimCase.claimId
? `${claimsUrl}/${claimCase.claimId}/files` ? `${claimsUrl}/${claimCase.claimId}/files`
: null, : null,
@@ -5212,7 +5264,15 @@ export class ClaimRequestManagementService {
pendingSubmit: candidates.filter( pendingSubmit: candidates.filter(
(candidate) => !candidate.alreadySubmitted, (candidate) => !candidate.alreadySubmitted,
).length, ).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, claimCaseId: string,
clientKey: FanavaranClientKey, clientKey: FanavaranClientKey,
): Promise<any> { ): Promise<any> {
const { candidates } = await this.collectFanavaranAttachmentCandidates( const { claimCase: initialClaim, candidates } =
claimCaseId, await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey);
clientKey, const pending = candidates.filter(candidate => !candidate.alreadySubmitted);
); const skippedAlreadySubmitted = candidates.length - pending.length;
const pending = candidates.filter( if (!pending.length) {
(candidate) => !candidate.alreadySubmitted && existsSync(candidate.path),
);
if (pending.length === 0) {
return { return {
clientKey, clientKey, claimCaseId, totalLocalImages: candidates.length,
claimCaseId, skippedAlreadySubmitted, attempted: 0, submitted: 0, failed: 0,
totalLocalImages: candidates.length, skipped: candidates.length, results: [],
skippedAlreadySubmitted: candidates.length,
attempted: 0,
submitted: 0,
failed: 0,
skipped: candidates.length,
results: [],
}; };
} }
const skipPending = async (warning: string) => {
const profile = getFanavaranClientProfile(clientKey); await Promise.all(pending.map(candidate => this.recordSkippedFanavaranAttachment(
let claimCase = await this.claimCaseDbService.findById(claimCaseId); claimCaseId, candidate.fileName, candidate.source, warning,
if (claimCase) this.assertFanavaranVehicleReviewApproved(claimCase); )));
if (!claimCase?.claimId) { 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 { try {
await this.ensureFanavaranBaseClaim( let claimCase = initialClaim;
claimCaseId, this.assertFanavaranVehicleReviewApproved(claimCase);
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) { if (!claimCase?.claimId) {
return { await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, FanavaranAuditSource.SUBMIT);
clientKey, claimCase = await this.claimCaseDbService.findById(claimCaseId);
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); await this.syncFanavaranHullBaseClaim(claimCaseId, clientKey);
claimCase = await this.claimCaseDbService.findById(claimCaseId); claimCase = await this.claimCaseDbService.findById(claimCaseId);
const nestedClaimId = fanavaranHullNestedClaimId({ nestedClaimId = fanavaranHullNestedClaimId({ claimId: claimCase?.claimId, claimNo: claimCase?.claimNo });
claimId: claimCase?.claimId, if (nestedClaimId == null) return skipPending('Fanavaran base claimId is missing');
claimNo: claimCase?.claimNo, } catch (error) {
}); return skipPending(this.extractFanavaranErrorMessage(error));
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,
})),
};
} }
const url = `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${nestedClaimId}/files`; 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[] = []; const results: any[] = [];
for (let i = 0; i < pending.length; i++) { for (let i = 0; i < pending.length; i++) {
const candidate = pending[i]; const candidate = pending[i];
const content = { const result = await this.autoSubmitFanavaranAttachment(
FileName: candidate.fileName,
FileTypeId: fileTypeId,
...(product === 'car-body' ? { ClaimId: nestedClaimId } : {}),
};
this.logger.log(
`${logPrefix} [${i + 1}/${pending.length}] UPLOADING: ${candidate.fileName}`,
);
try {
const response = await this.postFanavaranMultipart(
url,
content,
[{ path: candidate.path, fileName: candidate.fileName }],
clientKey,
undefined,
claimCaseId, claimCaseId,
{ path: candidate.path, fileName: candidate.fileName, source: candidate.source },
{ clientKey, auditSource: FanavaranAuditSource.SUBMIT },
); );
this.logger.log( results.push({ ...result, claimId: nestedClaimId, submitUrl: url });
`${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 },
);
}
if (i < pending.length - 1) { if (i < pending.length - 1) {
await new Promise((resolve) => setTimeout(resolve, 1_000)); await new Promise((resolve) => setTimeout(resolve, 1_000));
@@ -5406,6 +5343,24 @@ export class ClaimRequestManagementService {
return results; 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( async autoSubmitFanavaranAttachment(
claimCaseId: string, claimCaseId: string,
file: { path?: string | null; fileName?: string | null; source?: string }, file: { path?: string | null; fileName?: string | null; source?: string },
@@ -5428,9 +5383,11 @@ export class ClaimRequestManagementService {
const profile = getFanavaranClientProfile(clientKey); const profile = getFanavaranClientProfile(clientKey);
let url = ''; let url = '';
let content: Record<string, unknown> = {}; let content: Record<string, unknown> = {};
let auditSession: FanavaranAuditSession | undefined;
try { try {
if (!filePath || !fileName) { if (!filePath || !fileName) {
await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, 'Attachment file path or filename is missing');
return { return {
attempted: false, attempted: false,
submitted: false, submitted: false,
@@ -5439,6 +5396,7 @@ export class ClaimRequestManagementService {
}; };
} }
if (!existsSync(filePath)) { if (!existsSync(filePath)) {
await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, `Attachment file does not exist: ${filePath}`);
return { return {
attempted: false, attempted: false,
submitted: 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 (!claimCase.claimId) {
if (options?.clientKey) { if (options?.clientKey) {
await this.executeFanavaranV2Submit(claimCaseId, clientKey); await this.executeFanavaranV2Submit(claimCaseId, clientKey);
@@ -5470,13 +5437,7 @@ export class ClaimRequestManagementService {
if (!claimCase?.claimId) { if (!claimCase?.claimId) {
const warning = const warning =
'Fanavaran base claim is missing, so attachment was not submitted.'; 'Fanavaran base claim is missing, so attachment was not submitted.';
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, warning);
$set: {
'fanavaranSync.attachments.status': 'skipped',
'fanavaranSync.attachments.lastTriedAt': new Date(),
'fanavaranSync.attachments.lastError': warning,
},
});
return { return {
attempted: false, attempted: false,
submitted: false, submitted: false,
@@ -5500,7 +5461,7 @@ export class ClaimRequestManagementService {
: {}), : {}),
}; };
const auditSession: FanavaranAuditSession = { auditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(), trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey, clientKey,
source: auditSource, source: auditSource,
@@ -5536,7 +5497,13 @@ export class ClaimRequestManagementService {
`${logPrefix} Fanavaran response: ${JSON.stringify(response.data)}`, `${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 = const exchange =
this.fanavaranAuditService.captureAxiosExchange(response); this.fanavaranAuditService.captureAxiosExchange(response);
@@ -5560,8 +5527,13 @@ export class ClaimRequestManagementService {
'fanavaranSync.attachments.lastTriedAt': new Date(), 'fanavaranSync.attachments.lastTriedAt': new Date(),
'fanavaranSync.attachments.claimId': claimCase.claimId, 'fanavaranSync.attachments.claimId': claimCase.claimId,
'fanavaranSync.attachments.response': response.data, 'fanavaranSync.attachments.response': response.data,
'fanavaranSync.attachments.lastError': null,
}, },
$push: { $push: {
'fanavaranSync.attachments.attempts': {
fileId, fileName, source: file.source, status: 'success',
attemptedAt: new Date(), trackingCode: auditSession.trackingCode,
},
'fanavaranSync.attachments.files': { 'fanavaranSync.attachments.files': {
fileId, fileId,
fileName, fileName,
@@ -5596,6 +5568,22 @@ export class ClaimRequestManagementService {
const warning = this.extractFanavaranErrorMessage(error); const warning = this.extractFanavaranErrorMessage(error);
this.logger.warn(`${logPrefix} Fanavaran error: ${warning}`); 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 { try {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: { $set: {
@@ -5604,6 +5592,10 @@ export class ClaimRequestManagementService {
'fanavaranSync.attachments.lastError': warning, 'fanavaranSync.attachments.lastError': warning,
}, },
$push: { $push: {
'fanavaranSync.attachments.attempts': {
fileName, source: file.source, status: 'failed',
error: warning, attemptedAt: new Date(), trackingCode: auditSession?.trackingCode,
},
history: { history: {
type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED', type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED',
actor: { actorType: 'system' }, actor: { actorType: 'system' },
@@ -5627,7 +5619,10 @@ export class ClaimRequestManagementService {
// Schedule retry for attachments — never let retry bookkeeping fail the // Schedule retry for attachments — never let retry bookkeeping fail the
// caller: local media/docs are already persisted before this submit. // caller: local media/docs are already persisted before this submit.
try { 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, claimCaseId,
'attachments', 'attachments',
() => this.autoSubmitFanavaranAttachment(claimCaseId, file, options), () => this.autoSubmitFanavaranAttachment(claimCaseId, file, options),
@@ -6093,12 +6088,15 @@ export class ClaimRequestManagementService {
}, },
}); });
const attachments = fanavaranAttachmentStatus(claimCase.fanavaranSync?.attachments);
return { return {
clientKey, clientKey,
claimCaseId, claimCaseId,
claimId: claimCase.claimId ?? null, claimId: claimCase.claimId ?? null,
dmgCaseId: claimCase.dmgCaseId ?? null, dmgCaseId: claimCase.dmgCaseId ?? null,
expertiseId: claimCase.expertiseId ?? null, expertiseId: claimCase.expertiseId ?? null,
fileIds: [...new Set(attachments?.files.map(file => file.fileId) ?? [])],
attachments,
replyKey, replyKey,
submitUrl: claimCase.claimId submitUrl: claimCase.claimId
? `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/expertise` ? `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/expertise`
@@ -1,5 +1,6 @@
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger"; import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { DamageSelectedPartV2BodyDto } from "./damage-selected-part-v2.dto"; 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). */ /** Suggested HTTP call for the owner UI (`pathTemplate`: replace placeholders). */
export class ClaimDetailsOwnerNextActionV2Dto { export class ClaimDetailsOwnerNextActionV2Dto {
@@ -255,20 +256,23 @@ export class ClaimDetailsV2ResponseDto {
@ApiPropertyOptional({ @ApiPropertyOptional({
description: 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: { example: {
claimId: 987654, claimId: 987654,
claimNo: 123456, claimNo: 123456,
dmgCaseId: 11, dmgCaseId: 11,
expertiseId: 22, expertiseId: 22,
fileIds: [700001],
attachments: {
status: "success",
uploadedCount: 1,
lastError: null,
files: [{ fileId: 700001, fileName: "image.jpg" }],
attempts: [],
},
}, },
}) })
fanavaran?: { fanavaran?: FanavaranClaimReferences;
claimId?: number;
claimNo?: number;
dmgCaseId?: number;
expertiseId?: number;
};
@ApiPropertyOptional({ @ApiPropertyOptional({
description: description:
@@ -150,6 +150,10 @@ export class FanavaranSyncStage {
@Prop({ type: [MongooseSchema.Types.Mixed], default: [] }) @Prop({ type: [MongooseSchema.Types.Mixed], default: [] })
files?: unknown[]; 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 }) @Prop({ type: MongooseSchema.Types.Mixed })
response?: unknown; 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 { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import {
fanavaranAttachmentStatus,
type FanavaranAttachmentStage,
} from "./fanavaran-attachment-status";
export type FanavaranClaimReferences = { export type FanavaranClaimReferences = {
claimId?: number; claimId?: number;
@@ -12,10 +16,12 @@ export type FanavaranClaimReferences = {
plaqueSampleId?: number; plaqueSampleId?: number;
accidentVehicleUsedId?: number; accidentVehicleUsedId?: number;
insuranceCorpId?: 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: { export function fanavaranClaimReferences(claim: {
status?: string; status?: string;
@@ -26,13 +32,20 @@ export function fanavaranClaimReferences(claim: {
fanavaranSync?: { fanavaranSync?: {
baseClaim?: FanavaranReferenceStage | null; baseClaim?: FanavaranReferenceStage | null;
damageCase?: FanavaranReferenceStage | null; damageCase?: FanavaranReferenceStage | null;
attachments?: FanavaranAttachmentStage | null;
} | null; } | null;
}): FanavaranClaimReferences | undefined { }): FanavaranClaimReferences | undefined {
if (claim.status !== ClaimCaseStatus.COMPLETED) {
return undefined;
}
const refs: FanavaranClaimReferences = {}; 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.claimId != null) refs.claimId = claim.claimId;
if (claim.claimNo != null) refs.claimNo = claim.claimNo; if (claim.claimNo != null) refs.claimNo = claim.claimNo;
if (claim.dmgCaseId != null) refs.dmgCaseId = claim.dmgCaseId; if (claim.dmgCaseId != null) refs.dmgCaseId = claim.dmgCaseId;
@@ -45,8 +58,7 @@ export function fanavaranClaimReferences(claim: {
refs.driverId = damageCase?.driverId ?? baseClaim?.driverId; refs.driverId = damageCase?.driverId ?? baseClaim?.driverId;
} }
if ((damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId) != null) { if ((damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId) != null) {
refs.vehicleKindId = refs.vehicleKindId = damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId;
damageCase?.vehicleKindId ?? baseClaim?.vehicleKindId;
} }
if (damageCase?.plaqueKindId != null) { if (damageCase?.plaqueKindId != null) {
refs.plaqueKindId = damageCase.plaqueKindId; refs.plaqueKindId = damageCase.plaqueKindId;
@@ -0,0 +1,104 @@
import {
BadRequestException,
Controller,
Get,
Param,
Query,
UseGuards,
} from "@nestjs/common";
import {
ApiBearerAuth,
ApiOperation,
ApiParam,
ApiQuery,
ApiTags,
} from "@nestjs/swagger";
import { LocalActorAuthGuard } from "src/auth/guards/actor-local.guard";
import { CurrentUser } from "src/decorators/user.decorator";
import {
FANAVARAN_CLIENT_SWAGGER_ENUM,
isFanavaranClientKey,
normalizeFanavaranClientKey,
} from "src/core/config/fanavaran-client.config";
import { FanavaranHullReadService } from "./fanavaran-hull-read.service";
@ApiTags("fanavaran")
@ApiBearerAuth()
@UseGuards(LocalActorAuthGuard)
@ApiParam({ name: "client", enum: FANAVARAN_CLIENT_SWAGGER_ENUM })
@ApiParam({
name: "claimCaseId",
description:
"Local claim case MongoDB ObjectId; the saved Fanavaran claimId is used upstream",
})
@Controller("v2/fanavaran/:client/claim-cases/:claimCaseId/hull")
export class FanavaranHullReadController {
constructor(private readonly hull: FanavaranHullReadService) {}
@Get("files")
@ApiOperation({
summary:
"Retrieve submitted hull attachment metadata from Fanavaran (GEN.05)",
description:
"Live file list, including Id, ClaimId, FileName, FileTypeId and Status. The list does not include Base64 Data. Does not depend on locally recorded file IDs.",
})
files(
@Param("client") client: string,
@Param("claimCaseId") claimCaseId: string,
@CurrentUser() actor: any,
) {
return this.hull.files(this.clientKey(client), claimCaseId, actor);
}
@Get("files/:fileId")
@ApiParam({
name: "fileId",
type: Number,
description: "Fanavaran file Id returned by the remote file list",
})
@ApiOperation({
summary: "Retrieve a submitted hull file including Base64 Data (GEN.05)",
})
file(
@Param("client") client: string,
@Param("claimCaseId") claimCaseId: string,
@Param("fileId") fileId: string,
@CurrentUser() actor: any,
) {
return this.hull.file(this.clientKey(client), claimCaseId, fileId, actor);
}
@Get("expertise/dmg-sections")
@ApiQuery({
name: "expertiseId",
required: false,
type: Number,
description:
"Optional historical Fanavaran expertise Id; defaults to the saved expertiseId",
})
@ApiOperation({
summary:
"Retrieve submitted hull expertise damage sections and costs (GEN.12)",
description:
"Reads live damage section IDs, costs, amounts, CINumber and CITrackingCode when supplied by Fanavaran. Does not resubmit expertise.",
})
damageSections(
@Param("client") client: string,
@Param("claimCaseId") claimCaseId: string,
@CurrentUser() actor: any,
@Query("expertiseId") expertiseId?: string,
) {
return this.hull.damageSections(
this.clientKey(client),
claimCaseId,
actor,
expertiseId,
);
}
private clientKey(client: string) {
if (!isFanavaranClientKey(client))
throw new BadRequestException("Invalid Fanavaran client");
return normalizeFanavaranClientKey(client);
}
}
@@ -0,0 +1,221 @@
import { ForbiddenException } from "@nestjs/common";
import { of, throwError } from "rxjs";
import { FanavaranHullReadService } from "./fanavaran-hull-read.service";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
const actor = { sub: "staff-1", role: "damage_expert", clientKey: "tenant-1" };
const localId = "6af4594a32d485128a55742d";
const headers = {
authenticationToken: "test-token",
CorpId: "543",
ContractId: "hull-contract",
Location: "110011",
};
const base =
"https://apimanager.iraneit.com/BimeApiManager/api/BimeApi/v2.0/car/vehicle-hull-claims/5190845";
function setup(data: unknown = []) {
const management = {
getFanavaranHullReadContext: jest
.fn()
.mockResolvedValue({ claimId: 5190845, expertiseId: 44237, headers }),
};
const http = { get: jest.fn().mockReturnValue(of({ data })) };
const auth = {
assertNotInBackoff: jest.fn(),
registerFailure: jest.fn(),
clearBackoff: jest.fn(),
};
return {
service: new FanavaranHullReadService(
management as any,
http as any,
auth as any,
),
management,
http,
auth,
};
}
describe("Fanavaran hull retrieval", () => {
it("reads the remote file list even without any locally saved file IDs", async () => {
const data = [
{
Id: 2008737,
ClaimId: 5190845,
FileName: "1.jpg",
FileTypeId: 70,
Status: 2003,
},
];
const { service, management, http } = setup(data);
expect(await service.files("parsian", localId, actor)).toEqual({
clientKey: "parsian",
claimCaseId: localId,
claimId: 5190845,
data,
});
expect(management.getFanavaranHullReadContext).toHaveBeenCalledWith(
localId,
"parsian",
actor,
);
expect(http.get).toHaveBeenCalledWith(`${base}/files`, {
headers: { ...headers, Accept: "application/json" },
timeout: 20000,
});
});
it("preserves the single-file Base64 Data and provider Status", async () => {
const data = { Id: 2008737, Data: "aW1hZ2U=", Status: 2003 };
const { service, http } = setup(data);
expect(
await service.file("parsian", localId, "2008737", actor),
).toMatchObject({ fileId: 2008737, data });
expect(http.get.mock.calls[0][0]).toBe(`${base}/files/2008737`);
});
it("retrieves damage sections using stored expertiseId and retains cost IDs/tracking codes", async () => {
const data = [
{
Id: 9,
ExpertiseId: 44237,
CINumber: "86",
CITrackingCode: "tracking",
DmgSectionCosts: [{ Id: 10, DmgSectionId: 9, Amount: 120000000 }],
},
];
const { service, http } = setup(data);
expect(
await service.damageSections("parsian", localId, actor),
).toMatchObject({ expertiseId: 44237, data });
expect(http.get.mock.calls[0][0]).toBe(
`${base}/expertise/44237/dmg-sections`,
);
await service.damageSections("parsian", localId, actor, "44238");
expect(http.get.mock.calls[1][0]).toBe(
`${base}/expertise/44238/dmg-sections`,
);
});
it("requires a saved or explicitly selected expertise before calling Fanavaran", async () => {
const { service, management, http } = setup();
management.getFanavaranHullReadContext.mockResolvedValue({
claimId: 5190845,
expertiseId: null,
headers,
});
await expect(
service.damageSections("parsian", localId, actor),
).rejects.toThrow("expertiseId");
expect(http.get).not.toHaveBeenCalled();
});
it.each(["0", "-1", "1.2", "../files", "9007199254740992"])(
"rejects invalid remote IDs: %s",
async (id) => {
const { service, http } = setup();
await expect(
service.file("parsian", localId, id, actor),
).rejects.toThrow();
await expect(
service.damageSections("parsian", localId, actor, id),
).rejects.toThrow();
expect(http.get).not.toHaveBeenCalled();
},
);
it("does not make a remote request when claim access is denied", async () => {
const { service, management, http } = setup();
management.getFanavaranHullReadContext.mockRejectedValue(
new ForbiddenException(),
);
await expect(service.files("parsian", localId, actor)).rejects.toThrow(
ForbiddenException,
);
expect(http.get).not.toHaveBeenCalled();
});
it("preserves vendor errors and registers them with shared backoff", async () => {
const { service, http, auth } = setup();
const error = {
isAxiosError: true,
response: {
status: 404,
data: { Message: "پرونده یافت نشد", RuleName: "HullClaimRule" },
},
};
http.get.mockReturnValue(throwError(() => error));
await expect(
service.files("parsian", localId, actor),
).rejects.toMatchObject({
response: {
statusCode: 404,
Message: "پرونده یافت نشد",
RuleName: "HullClaimRule",
},
});
expect(auth.registerFailure).toHaveBeenCalledWith("parsian", error);
});
});
describe("hull read context", () => {
function context(claim: any = {}) {
const service = Object.create(
ClaimRequestManagementService.prototype,
) as any;
service.claimCaseDbService = {
findById: jest
.fn()
.mockResolvedValue({
claimId: 5190845,
claimNo: 123,
expertiseId: 44237,
owner: { clientId: "tenant-1" },
...claim,
}),
};
service.resolveFanavaranClaimProduct = jest
.fn()
.mockResolvedValue("car-body");
service.getFanavaranAuthHeaders = jest.fn().mockResolvedValue(headers);
return service;
}
it("uses the saved claimId rather than claimNo and shares submission headers", async () => {
const service = context();
expect(
await service.getFanavaranHullReadContext(localId, "parsian", actor),
).toEqual({ claimId: 5190845, expertiseId: 44237, headers });
expect(service.getFanavaranAuthHeaders).toHaveBeenCalledWith(
"parsian",
undefined,
localId,
);
});
it("rejects another organization's claim before retrieving credentials", async () => {
const service = context({ owner: { clientId: "other-tenant" } });
await expect(
service.getFanavaranHullReadContext(localId, "parsian", actor),
).rejects.toThrow(ForbiddenException);
expect(service.getFanavaranAuthHeaders).not.toHaveBeenCalled();
});
it("rejects third-party claims and claims that only have a claimNo", async () => {
const service = context();
service.resolveFanavaranClaimProduct.mockResolvedValue("third-party");
await expect(
service.getFanavaranHullReadContext(localId, "parsian", actor),
).rejects.toThrow("vehicle-hull");
service.resolveFanavaranClaimProduct.mockResolvedValue("car-body");
service.claimCaseDbService.findById.mockResolvedValue({
claimNo: 123,
owner: { clientId: "tenant-1" },
});
await expect(
service.getFanavaranHullReadContext(localId, "parsian", actor),
).rejects.toThrow("claimId");
});
});
@@ -0,0 +1,131 @@
import { HttpService } from "@nestjs/axios";
import { BadRequestException, Injectable } from "@nestjs/common";
import { firstValueFrom } from "rxjs";
import { ClaimRequestManagementService } from "src/claim-request-management/claim-request-management.service";
import {
getFanavaranLookupBaseUrl,
type FanavaranClientKey,
} from "src/core/config/fanavaran-client.config";
import { FanavaranAuthService } from "./fanavaran-auth.service";
import { toFanavaranHttpException } from "./fanavaran-http-exception";
type ReadActor = {
sub: string;
role?: string;
clientKey?: string;
username?: string;
};
@Injectable()
export class FanavaranHullReadService {
constructor(
private readonly management: ClaimRequestManagementService,
private readonly http: HttpService,
private readonly auth: FanavaranAuthService,
) {}
/** GEN.05 list contains file metadata/Status, not Base64 Data. */
async files(
clientKey: FanavaranClientKey,
claimCaseId: string,
actor: ReadActor,
) {
const context = await this.management.getFanavaranHullReadContext(
claimCaseId,
clientKey,
actor,
);
const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/files`;
return {
clientKey,
claimCaseId,
claimId: context.claimId,
data: await this.get(clientKey, url, context.headers),
};
}
/** GEN.05 single-file response includes Data as Base64. */
async file(
clientKey: FanavaranClientKey,
claimCaseId: string,
fileId: string,
actor: ReadActor,
) {
const id = this.positiveId(fileId, "fileId");
const context = await this.management.getFanavaranHullReadContext(
claimCaseId,
clientKey,
actor,
);
const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/files/${id}`;
return {
clientKey,
claimCaseId,
claimId: context.claimId,
fileId: id,
data: await this.get(clientKey, url, context.headers),
};
}
/** GEN.12: read the stored expertise, or an explicitly selected historical one. */
async damageSections(
clientKey: FanavaranClientKey,
claimCaseId: string,
actor: ReadActor,
expertiseId?: string,
) {
const selectedId =
expertiseId === undefined
? undefined
: this.positiveId(expertiseId, "expertiseId");
const context = await this.management.getFanavaranHullReadContext(
claimCaseId,
clientKey,
actor,
);
const id = selectedId ?? context.expertiseId;
if (id == null)
throw new BadRequestException(
"No submitted expertiseId is stored; provide expertiseId for a previously submitted expertise",
);
const url = `${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims/${context.claimId}/expertise/${id}/dmg-sections`;
return {
clientKey,
claimCaseId,
claimId: context.claimId,
expertiseId: id,
data: await this.get(clientKey, url, context.headers),
};
}
private positiveId(value: string, field: string): number {
const id = Number(value);
if (!/^\d+$/.test(value) || !Number.isSafeInteger(id) || id <= 0) {
throw new BadRequestException(`${field} must be a positive integer`);
}
return id;
}
private async get(
clientKey: FanavaranClientKey,
url: string,
headers: Record<string, string>,
): Promise<unknown> {
this.auth.assertNotInBackoff(clientKey);
try {
const response = await firstValueFrom(
this.http.get(url, {
headers: { ...headers, Accept: "application/json" },
timeout: 20000,
}),
);
this.auth.clearBackoff(clientKey);
return response.data;
} catch (error) {
this.auth.registerFailure(clientKey, error);
throw toFanavaranHttpException(error, {
fallback: "Failed to retrieve submitted hull data from Fanavaran",
});
}
}
}
+2 -2
View File
@@ -205,7 +205,7 @@ export class FanavaranController {
@ApiOperation({ @ApiOperation({
summary: "Preview Fanavaran attachment upload plan", summary: "Preview Fanavaran attachment upload plan",
description: description:
"Lists local required-document and captured damage images that would be sent to GEN.07. Shows which images are already recorded as uploaded to Fanavaran.", "Lists local documents and captured images for third-party GEN.07 or hull GEN.05. Returns external file IDs, saved upload status/errors, local file availability, and pending image counts.",
}) })
@ApiParam({ @ApiParam({
name: "client", name: "client",
@@ -231,7 +231,7 @@ export class FanavaranController {
@ApiOperation({ @ApiOperation({
summary: "Submit missing Fanavaran attachments", summary: "Submit missing Fanavaran attachments",
description: description:
"Uploads every local image that does not already have a recorded successful GEN.07 Fanavaran file upload. Uses one multipart request per image.", "Uploads pending local images to third-party GEN.07 or hull GEN.05 and persists each returned fileId. Reports failures and skipped/missing local files. Uses one multipart request per image.",
}) })
@ApiParam({ @ApiParam({
name: "client", name: "client",
+18 -2
View File
@@ -1,10 +1,26 @@
import { Module } from "@nestjs/common"; import { Module } from "@nestjs/common";
import { HttpModule } from "@nestjs/axios";
import { ConfigModule, ConfigService } from "@nestjs/config";
import { createHttpModuleOptions } from "src/core/config/http-proxy.factory";
import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module"; import { ClaimRequestManagementModule } from "src/claim-request-management/claim-request-management.module";
import { FanavaranAuditModule } from "./fanavaran-audit.module"; import { FanavaranAuditModule } from "./fanavaran-audit.module";
import { FanavaranController } from "./fanavaran.controller"; import { FanavaranController } from "./fanavaran.controller";
import { FanavaranLookupModule } from "./fanavaran-lookup.module";
import { FanavaranHullReadService } from "./fanavaran-hull-read.service";
import { FanavaranHullReadController } from "./fanavaran-hull-read.controller";
@Module({ @Module({
imports: [ClaimRequestManagementModule, FanavaranAuditModule], imports: [
controllers: [FanavaranController], ClaimRequestManagementModule,
FanavaranAuditModule,
FanavaranLookupModule,
HttpModule.registerAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: createHttpModuleOptions,
}),
],
controllers: [FanavaranController, FanavaranHullReadController],
providers: [FanavaranHullReadService],
}) })
export class FanavaranModule {} export class FanavaranModule {}