forked from Yara724/api
Compare commits
2
Commits
90bdc51715
...
8b9dabc9f2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8b9dabc9f2 | ||
|
|
84b92eb55a |
@@ -0,0 +1,104 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## Expertise submit completes missing prerequisites
|
||||||
|
|
||||||
|
The frontend can call
|
||||||
|
`POST /v2/fanavaran/{client}/claim-cases/{claimCaseId}/expertise/submit`
|
||||||
|
without separately retrying earlier stages. The backend completes them in order:
|
||||||
|
|
||||||
|
- Third-party: base claim → damage case → pending attachments → expertise.
|
||||||
|
- Hull: base claim → pending attachments → expertise. Hull has no damage-case stage.
|
||||||
|
|
||||||
|
Existing claim/damage IDs and successful image receipts are reused. A previously
|
||||||
|
skipped attachment stage is retried. Completion is checked against a fresh read
|
||||||
|
of the saved receipts for all current local image candidates, not just the
|
||||||
|
attachment stage's status or an upload response saying success. Missing local
|
||||||
|
files, rejected uploads, and unconfirmed receipts stop expertise submission.
|
||||||
|
If there are no local attachment candidates, there is nothing to upload.
|
||||||
|
|
||||||
|
Errors identify `stage` (`baseClaim`, `damageCase`, or `attachments`) and preserve
|
||||||
|
vendor details. An attachment failure includes:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statusCode": 400,
|
||||||
|
"code": "FANAVARAN_ATTACHMENTS_INCOMPLETE",
|
||||||
|
"stage": "attachments",
|
||||||
|
"pendingFiles": [
|
||||||
|
{ "fileName": "image.jpg", "error": "Upload failure reason", "skipped": false }
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Retrying resumes pending work. Even when expertise already exists, this API first
|
||||||
|
repairs missing prerequisites, then returns the existing expertise response/Id
|
||||||
|
without posting another expertise. Automatic final writes also check attachments.
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
Local validation errors return a stable `code`, a specific Persian message, and
|
||||||
|
the relevant field/product metadata. They do not collapse to the generic form
|
||||||
|
validation message:
|
||||||
|
|
||||||
|
| Code | Meaning |
|
||||||
|
|---|---|
|
||||||
|
| `FANAVARAN_LOCAL_CLAIM_ID_INVALID` | `claimCaseId` must be a local MongoDB ObjectId, not the numeric external claim ID |
|
||||||
|
| `FANAVARAN_HULL_CLAIM_REQUIRED` | The linked claim resolves to third-party; `actualProduct` and `expectedProduct` identify the mismatch |
|
||||||
|
| `FANAVARAN_HULL_CLAIM_NOT_SUBMITTED` | No external `claimId` is saved for the local claim |
|
||||||
|
| `FANAVARAN_HULL_EXPERTISE_ID_MISSING` | No expertise ID is saved and no override was supplied |
|
||||||
|
| `FANAVARAN_HULL_FILE_ID_INVALID` / `FANAVARAN_HULL_EXPERTISE_ID_INVALID` | The selected external ID is not a positive safe integer |
|
||||||
|
| `FANAVARAN_CLIENT_INVALID` | The requested tenant is unsupported |
|
||||||
|
|
||||||
|
Selecting `parsian` chooses the insurer; it does not change a third-party claim
|
||||||
|
into a hull claim. These VHUD routes intentionally reject third-party claims.
|
||||||
|
|
||||||
|
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,61 @@ 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({
|
||||||
|
statusCode: 400,
|
||||||
|
code: 'FANAVARAN_LOCAL_CLAIM_ID_INVALID',
|
||||||
|
field: 'claimCaseId',
|
||||||
|
message: 'شناسه پرونده باید شناسه داخلی ۲۴ کاراکتری باشد؛ کد عددی پرونده فناوران را در این بخش وارد نکنید.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
|
||||||
|
if (product !== 'car-body') {
|
||||||
|
throw new BadRequestException({
|
||||||
|
statusCode: 400, code: 'FANAVARAN_HULL_CLAIM_REQUIRED',
|
||||||
|
actualProduct: product, expectedProduct: 'car-body', claimCaseId,
|
||||||
|
message: 'این پرونده بهعنوان بیمه شخص ثالث شناسایی شده است؛ مسیر بازیابی انتخابشده فقط برای پروندههای بیمه بدنه است.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const claimId = parseFanavaranId(
|
||||||
|
claim.claimId ?? claim.fanavaranSync?.baseClaim?.claimId,
|
||||||
|
);
|
||||||
|
if (claimId == null) {
|
||||||
|
throw new BadRequestException({
|
||||||
|
statusCode: 400, code: 'FANAVARAN_HULL_CLAIM_NOT_SUBMITTED',
|
||||||
|
field: 'claimId',
|
||||||
|
message: 'کد پرونده فناوران در این پرونده ثبت نشده است؛ ابتدا ارسال اولیه پرونده را تکمیل کنید.',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
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 +5125,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 +5253,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 +5263,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 +5278,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 +5294,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 +5357,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 +5397,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 +5410,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 +5430,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 +5451,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 +5475,7 @@ export class ClaimRequestManagementService {
|
|||||||
: {}),
|
: {}),
|
||||||
};
|
};
|
||||||
|
|
||||||
const auditSession: FanavaranAuditSession = {
|
auditSession = {
|
||||||
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
|
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
|
||||||
clientKey,
|
clientKey,
|
||||||
source: auditSource,
|
source: auditSource,
|
||||||
@@ -5536,7 +5511,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 +5541,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 +5582,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 +5606,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 +5633,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 +6102,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`
|
||||||
@@ -6109,19 +6121,103 @@ export class ClaimRequestManagementService {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Complete applicable stages in order; do not treat skipped images as done. */
|
||||||
|
private async completeFanavaranExpertisePrerequisites(
|
||||||
|
claimCaseId: string,
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
auditSource: FanavaranAuditSource,
|
||||||
|
): Promise<void> {
|
||||||
|
let stage: 'baseClaim' | 'damageCase' | 'attachments' = 'baseClaim';
|
||||||
|
try {
|
||||||
|
await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource);
|
||||||
|
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
|
||||||
|
if (fanavaranHasDamageCaseStage(product)) {
|
||||||
|
stage = 'damageCase';
|
||||||
|
await this.ensureFanavaranDamageCase(claimCaseId, clientKey, auditSource);
|
||||||
|
}
|
||||||
|
stage = 'attachments';
|
||||||
|
await this.ensureFanavaranAttachmentsComplete(claimCaseId, clientKey);
|
||||||
|
} catch (error) {
|
||||||
|
const exception = toFanavaranHttpException(error);
|
||||||
|
const body = exception.getResponse();
|
||||||
|
const details = typeof body === 'object'
|
||||||
|
? body as Record<string, unknown>
|
||||||
|
: {};
|
||||||
|
const messages = {
|
||||||
|
baseClaim: 'ارسال پرونده اولیه به فناوران تکمیل نشد؛ ارسال کارشناسی متوقف شد.',
|
||||||
|
damageCase: 'ارسال مرحله خسارت به فناوران تکمیل نشد؛ ارسال کارشناسی متوقف شد.',
|
||||||
|
attachments: 'ارسال همه تصاویر به فناوران تکمیل نشده است؛ پس از رفع خطای تصاویر، ارسال کارشناسی را دوباره انجام دهید.',
|
||||||
|
};
|
||||||
|
throw new HttpException(
|
||||||
|
{
|
||||||
|
...details,
|
||||||
|
statusCode: exception.getStatus(),
|
||||||
|
code: details.code ?? 'FANAVARAN_PREVIOUS_STAGE_FAILED',
|
||||||
|
stage,
|
||||||
|
message: messages[stage],
|
||||||
|
upstreamMessage: this.extractFanavaranErrorMessage(error),
|
||||||
|
},
|
||||||
|
exception.getStatus(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async ensureFanavaranAttachmentsComplete(
|
||||||
|
claimCaseId: string,
|
||||||
|
clientKey: FanavaranClientKey,
|
||||||
|
): Promise<void> {
|
||||||
|
const initial = await this.collectFanavaranAttachmentCandidates(
|
||||||
|
claimCaseId, clientKey,
|
||||||
|
);
|
||||||
|
if (initial.candidates.every(candidate => candidate.alreadySubmitted)) return;
|
||||||
|
|
||||||
|
const upload = await this.submitFanavaranAttachmentsV2(
|
||||||
|
claimCaseId, clientKey,
|
||||||
|
);
|
||||||
|
// Re-read saved receipts: a success response or a stage-level status alone is insufficient.
|
||||||
|
const refreshed = await this.collectFanavaranAttachmentCandidates(
|
||||||
|
claimCaseId, clientKey,
|
||||||
|
);
|
||||||
|
const pending = refreshed.candidates.filter(candidate => !candidate.alreadySubmitted);
|
||||||
|
if (!pending.length) return;
|
||||||
|
|
||||||
|
const results = Array.isArray(upload) ? upload : upload?.results ?? [];
|
||||||
|
const attempts = fanavaranAttachmentStatus(
|
||||||
|
refreshed.claimCase.fanavaranSync?.attachments,
|
||||||
|
)?.attempts ?? [];
|
||||||
|
throw new BadRequestException({
|
||||||
|
statusCode: 400,
|
||||||
|
code: 'FANAVARAN_ATTACHMENTS_INCOMPLETE',
|
||||||
|
stage: 'attachments',
|
||||||
|
message: 'ارسال تصاویر به فناوران کامل نشده است.',
|
||||||
|
pendingFiles: pending.map(candidate => {
|
||||||
|
const result = results.find((item: { fileName?: string }) => item.fileName === candidate.fileName);
|
||||||
|
const attempt = attempts.filter(item => item.fileName === candidate.fileName).at(-1);
|
||||||
|
return {
|
||||||
|
fileName: candidate.fileName, source: candidate.source,
|
||||||
|
error: result?.warning ?? result?.skipReason ?? attempt?.error ?? upload?.warning ?? 'No confirmed Fanavaran file ID is stored.',
|
||||||
|
skipped: result?.skipped ?? (attempt?.status === 'skipped'),
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
async submitFanavaranExpertiseV2(
|
async submitFanavaranExpertiseV2(
|
||||||
claimCaseId: string,
|
claimCaseId: string,
|
||||||
clientKey: FanavaranClientKey,
|
clientKey: FanavaranClientKey,
|
||||||
bodyOverride?: Record<string, unknown>,
|
bodyOverride?: Record<string, unknown>,
|
||||||
): Promise<any> {
|
): Promise<any> {
|
||||||
try {
|
try {
|
||||||
await this.ensureFanavaranDamageCase(
|
await this.completeFanavaranExpertisePrerequisites(
|
||||||
claimCaseId,
|
claimCaseId,
|
||||||
clientKey,
|
clientKey,
|
||||||
FanavaranAuditSource.SUBMIT,
|
FanavaranAuditSource.SUBMIT,
|
||||||
);
|
);
|
||||||
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
|
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
|
||||||
if (!claimCase) throw new NotFoundException('Claim case not found');
|
if (!claimCase) throw new NotFoundException('Claim case not found');
|
||||||
|
if (claimCase.expertiseId != null) {
|
||||||
|
return claimCase.fanavaranSync?.expertise?.response ?? { Id: claimCase.expertiseId };
|
||||||
|
}
|
||||||
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
|
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
|
||||||
const built = await this.buildFanavaranExpertisePayload({
|
const built = await this.buildFanavaranExpertisePayload({
|
||||||
claimCase,
|
claimCase,
|
||||||
@@ -6175,6 +6271,8 @@ export class ClaimRequestManagementService {
|
|||||||
'Fanavaran claimId is required before submitting expertise',
|
'Fanavaran claimId is required before submitting expertise',
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
// The automatic path also uses this method; keep the same attachment prerequisite.
|
||||||
|
await this.ensureFanavaranAttachmentsComplete(claimCaseId, clientKey);
|
||||||
if (claimCase.expertiseId != null) {
|
if (claimCase.expertiseId != null) {
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`[executeFanavaranExpertiseSubmit] Already have expertiseId=${claimCase.expertiseId}; skipping Fanavaran POST`,
|
`[executeFanavaranExpertiseSubmit] Already have expertiseId=${claimCase.expertiseId}; skipping Fanavaran POST`,
|
||||||
|
|||||||
@@ -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,197 @@
|
|||||||
|
import { ClaimRequestManagementService } from "./claim-request-management.service";
|
||||||
|
|
||||||
|
function setup(product = "third-party") {
|
||||||
|
const service = Object.create(ClaimRequestManagementService.prototype) as any;
|
||||||
|
const claim: any = {
|
||||||
|
_id: "claim-1",
|
||||||
|
fanavaranSync: { attachments: { files: [] } },
|
||||||
|
};
|
||||||
|
const events: string[] = [];
|
||||||
|
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
|
||||||
|
service.resolveFanavaranClaimProduct = jest.fn().mockResolvedValue(product);
|
||||||
|
service.claimCaseDbService = {
|
||||||
|
findById: jest.fn().mockImplementation(async () => claim),
|
||||||
|
};
|
||||||
|
service.executeFanavaranV2Submit = jest.fn().mockImplementation(async () => {
|
||||||
|
events.push("baseClaim");
|
||||||
|
claim.claimId = 100;
|
||||||
|
});
|
||||||
|
service.executeFanavaranDamageCaseSubmit = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => {
|
||||||
|
events.push("damageCase");
|
||||||
|
claim.dmgCaseId = 200;
|
||||||
|
});
|
||||||
|
service.collectFanavaranAttachmentCandidates = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => ({
|
||||||
|
claimCase: claim,
|
||||||
|
candidates: [
|
||||||
|
{
|
||||||
|
fileName: "image.jpg",
|
||||||
|
source: "capture:angle:front",
|
||||||
|
path: "/tmp/image.jpg",
|
||||||
|
alreadySubmitted: claim.fanavaranSync.attachments.files.length > 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}));
|
||||||
|
service.submitFanavaranAttachmentsV2 = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => {
|
||||||
|
events.push("attachments");
|
||||||
|
claim.fanavaranSync.attachments.files.push({
|
||||||
|
fileName: "image.jpg",
|
||||||
|
fileId: 71,
|
||||||
|
});
|
||||||
|
return [{ submitted: true, fileId: 71, fileName: "image.jpg" }];
|
||||||
|
});
|
||||||
|
service.buildFanavaranExpertisePayload = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => ({
|
||||||
|
payload: { DmgCaseId: claim.dmgCaseId },
|
||||||
|
warnings: [],
|
||||||
|
}));
|
||||||
|
service.assertFanavaranExpertisePayloadReady = jest.fn();
|
||||||
|
service.executeFanavaranExpertiseSubmit = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => {
|
||||||
|
events.push("expertise");
|
||||||
|
claim.expertiseId = 300;
|
||||||
|
return { Id: 300 };
|
||||||
|
});
|
||||||
|
return { service, claim, events };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("expertise submit completes earlier Fanavaran stages", () => {
|
||||||
|
it("runs base, damage, attachments, expertise in order for third-party", async () => {
|
||||||
|
const { service, events } = setup();
|
||||||
|
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
|
||||||
|
expect(events).toEqual([
|
||||||
|
"baseClaim",
|
||||||
|
"damageCase",
|
||||||
|
"attachments",
|
||||||
|
"expertise",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("runs base, attachments, expertise for hull without creating a damage case", async () => {
|
||||||
|
const { service, events } = setup("car-body");
|
||||||
|
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
|
||||||
|
expect(events).toEqual(["baseClaim", "attachments", "expertise"]);
|
||||||
|
expect(service.executeFanavaranDamageCaseSubmit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("retries previously skipped images while reusing existing base/damage IDs", async () => {
|
||||||
|
const { service, claim, events } = setup();
|
||||||
|
Object.assign(claim, { claimId: 100, dmgCaseId: 200 });
|
||||||
|
claim.fanavaranSync.attachments.status = "skipped";
|
||||||
|
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
|
||||||
|
expect(events).toEqual(["attachments", "expertise"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each(["failed", "skipped"])(
|
||||||
|
"does not submit expertise if an image remains %s",
|
||||||
|
async (status) => {
|
||||||
|
const { service } = setup();
|
||||||
|
service.submitFanavaranAttachmentsV2.mockResolvedValue([
|
||||||
|
{
|
||||||
|
fileName: "image.jpg",
|
||||||
|
submitted: false,
|
||||||
|
skipped: status === "skipped",
|
||||||
|
warning: "Image unavailable",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
await expect(
|
||||||
|
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({
|
||||||
|
stage: "attachments",
|
||||||
|
pendingFiles: [expect.objectContaining({ fileName: "image.jpg" })],
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("stops immediately if the base stage fails", async () => {
|
||||||
|
const { service } = setup();
|
||||||
|
service.executeFanavaranV2Submit.mockRejectedValue(
|
||||||
|
new Error("Base unavailable"),
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({ stage: "baseClaim" }),
|
||||||
|
});
|
||||||
|
expect(service.executeFanavaranDamageCaseSubmit).not.toHaveBeenCalled();
|
||||||
|
expect(service.submitFanavaranAttachmentsV2).not.toHaveBeenCalled();
|
||||||
|
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("stops before images and expertise if the damage stage fails", async () => {
|
||||||
|
const { service } = setup();
|
||||||
|
service.executeFanavaranDamageCaseSubmit.mockRejectedValue(
|
||||||
|
new Error("Damage unavailable"),
|
||||||
|
);
|
||||||
|
await expect(
|
||||||
|
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({ stage: "damageCase" }),
|
||||||
|
});
|
||||||
|
expect(service.submitFanavaranAttachmentsV2).not.toHaveBeenCalled();
|
||||||
|
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires saved image receipts even if the upload call reports success", async () => {
|
||||||
|
const { service } = setup();
|
||||||
|
service.submitFanavaranAttachmentsV2.mockResolvedValue([
|
||||||
|
{ submitted: true, fileId: 71 },
|
||||||
|
]);
|
||||||
|
await expect(
|
||||||
|
service.submitFanavaranExpertiseV2("claim-1", "parsian"),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({ stage: "attachments" }),
|
||||||
|
});
|
||||||
|
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("also enforces attachments on the shared final write used by automatic submission", async () => {
|
||||||
|
const { service, claim } = setup("car-body");
|
||||||
|
claim.claimId = 100;
|
||||||
|
service.assertFanavaranVehicleReviewApproved = jest.fn();
|
||||||
|
service.postFanavaranJson = jest.fn();
|
||||||
|
service.submitFanavaranAttachmentsV2.mockResolvedValue([
|
||||||
|
{ submitted: false, warning: "Image unavailable" },
|
||||||
|
]);
|
||||||
|
const execute = (ClaimRequestManagementService.prototype as any)
|
||||||
|
.executeFanavaranExpertiseSubmit;
|
||||||
|
await expect(
|
||||||
|
execute.call(service, "claim-1", "parsian", {}, "AUTO_SUBMIT"),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({ stage: "attachments" }),
|
||||||
|
});
|
||||||
|
expect(service.postFanavaranJson).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("repairs missing attachments even if expertise already exists, without resubmitting expertise", async () => {
|
||||||
|
const { service, claim, events } = setup();
|
||||||
|
Object.assign(claim, { claimId: 100, dmgCaseId: 200, expertiseId: 300 });
|
||||||
|
expect(
|
||||||
|
await service.submitFanavaranExpertiseV2("claim-1", "parsian"),
|
||||||
|
).toMatchObject({ Id: 300 });
|
||||||
|
expect(events).toEqual(["attachments"]);
|
||||||
|
expect(service.executeFanavaranExpertiseSubmit).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not repeat any completed stage on the next submit call", async () => {
|
||||||
|
const { service, events } = setup();
|
||||||
|
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
|
||||||
|
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
|
||||||
|
expect(events).toEqual([
|
||||||
|
"baseClaim",
|
||||||
|
"damageCase",
|
||||||
|
"attachments",
|
||||||
|
"expertise",
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
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({
|
||||||
|
statusCode: 400,
|
||||||
|
code: "FANAVARAN_CLIENT_INVALID",
|
||||||
|
field: "client",
|
||||||
|
allowedClients: FANAVARAN_CLIENT_SWAGGER_ENUM,
|
||||||
|
message: "شرکت بیمه انتخابشده برای سرویس فناوران معتبر نیست.",
|
||||||
|
});
|
||||||
|
return normalizeFanavaranClientKey(client);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
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";
|
||||||
|
import { localizeErrorPayload } from "src/common/errors/persian-errors";
|
||||||
|
|
||||||
|
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.toMatchObject({
|
||||||
|
response: expect.objectContaining({
|
||||||
|
code: "FANAVARAN_HULL_EXPERTISE_ID_MISSING",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
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("keeps the local/external claim ID distinction visible after the global error filter", async () => {
|
||||||
|
const service = context();
|
||||||
|
let error: any;
|
||||||
|
try {
|
||||||
|
await service.getFanavaranHullReadContext("5190845", "parsian", actor);
|
||||||
|
} catch (caught) {
|
||||||
|
error = caught;
|
||||||
|
}
|
||||||
|
expect(error).toBeDefined();
|
||||||
|
const response = localizeErrorPayload(
|
||||||
|
error.getResponse(),
|
||||||
|
error.getStatus(),
|
||||||
|
);
|
||||||
|
expect(response).toMatchObject({
|
||||||
|
code: "FANAVARAN_LOCAL_CLAIM_ID_INVALID",
|
||||||
|
field: "claimCaseId",
|
||||||
|
});
|
||||||
|
expect(response.message).toContain("شناسه داخلی");
|
||||||
|
expect(service.claimCaseDbService.findById).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
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");
|
||||||
|
let wrongProduct: any;
|
||||||
|
try {
|
||||||
|
await service.getFanavaranHullReadContext(localId, "parsian", actor);
|
||||||
|
} catch (error) {
|
||||||
|
wrongProduct = error;
|
||||||
|
}
|
||||||
|
const localized = localizeErrorPayload(wrongProduct.getResponse(), 400);
|
||||||
|
expect(localized).toMatchObject({
|
||||||
|
code: "FANAVARAN_HULL_CLAIM_REQUIRED",
|
||||||
|
actualProduct: "third-party",
|
||||||
|
expectedProduct: "car-body",
|
||||||
|
});
|
||||||
|
expect(localized.message).toContain("شخص ثالث");
|
||||||
|
await expect(
|
||||||
|
service.getFanavaranHullReadContext(localId, "parsian", actor),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({
|
||||||
|
code: "FANAVARAN_HULL_CLAIM_REQUIRED",
|
||||||
|
actualProduct: "third-party",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
service.resolveFanavaranClaimProduct.mockResolvedValue("car-body");
|
||||||
|
service.claimCaseDbService.findById.mockResolvedValue({
|
||||||
|
claimNo: 123,
|
||||||
|
owner: { clientId: "tenant-1" },
|
||||||
|
});
|
||||||
|
await expect(
|
||||||
|
service.getFanavaranHullReadContext(localId, "parsian", actor),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
response: expect.objectContaining({
|
||||||
|
code: "FANAVARAN_HULL_CLAIM_NOT_SUBMITTED",
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
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({
|
||||||
|
statusCode: 400,
|
||||||
|
code: "FANAVARAN_HULL_EXPERTISE_ID_MISSING",
|
||||||
|
field: "expertiseId",
|
||||||
|
message:
|
||||||
|
"کد کارشناسی فناوران در این پرونده ثبت نشده است؛ کد کارشناسی قبلی را در پارامتر مربوط وارد کنید یا ابتدا کارشناسی را ارسال کنید.",
|
||||||
|
});
|
||||||
|
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({
|
||||||
|
statusCode: 400,
|
||||||
|
code:
|
||||||
|
field === "fileId"
|
||||||
|
? "FANAVARAN_HULL_FILE_ID_INVALID"
|
||||||
|
: "FANAVARAN_HULL_EXPERTISE_ID_INVALID",
|
||||||
|
field,
|
||||||
|
message:
|
||||||
|
field === "fileId"
|
||||||
|
? "کد فایل فناوران باید یک عدد صحیح مثبت باشد."
|
||||||
|
: "کد کارشناسی فناوران باید یک عدد صحیح مثبت باشد.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
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",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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",
|
||||||
@@ -283,7 +283,7 @@ export class FanavaranController {
|
|||||||
@ApiOperation({
|
@ApiOperation({
|
||||||
summary: "Submit Fanavaran expertise request",
|
summary: "Submit Fanavaran expertise request",
|
||||||
description:
|
description:
|
||||||
"Swagger JSON body is optional. Always rebuilds GEN.08 from the local expert reply and lookups, then POSTs that rebuilt payload. Pasting a previous preview JSON does not skip rebuild. Only money/date fields are taken from the body. DmgCaseId, ClaimExpertId, and DmgSections in pasted JSON are ignored.",
|
"Completes missing prerequisite stages in order before expertise: base claim, third-party damage case when applicable, then all pending attachments. Skipped images are retried; any image without a saved Fanavaran file ID blocks expertise with stage and pendingFiles details. Existing IDs/receipts are reused; existing expertise is not duplicated. Optional JSON overrides only allowed money/date fields; the GEN.08 third-party or GEN.06 hull payload is rebuilt from the expert reply and live lookups.",
|
||||||
})
|
})
|
||||||
@ApiParam({
|
@ApiParam({
|
||||||
name: "client",
|
name: "client",
|
||||||
|
|||||||
@@ -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 {}
|
||||||
|
|||||||
Reference in New Issue
Block a user