Compare commits

..
6 Commits
16 changed files with 704 additions and 99 deletions
+1
View File
@@ -24,6 +24,7 @@ source: fanavaran-module-docs
| Missing PolicyId | No/expired policies messages | Block submit; preview may leave null | Manual after data fix | Stage fail history | Admin | | Missing PolicyId | No/expired policies messages | Block submit; preview may leave null | Manual after data fix | Stage fail history | Admin |
| Duplicate create | Local `claimId`/`claimNo` exists | Skip create; use follow-ups | N/A | skipReason | — | | Duplicate create | Local `claimId`/`claimNo` exists | Skip create; use follow-ups | N/A | skipReason | — |
| Invalid FileTypeId | `نوع فايل با منبع لوکاپ مطابقت ندارد` | Set `ClaimFileTypeId` from tenant `file-types` (Parsian **63**) | After config fix | Attachment stage | Ops | | Invalid FileTypeId | `نوع فايل با منبع لوکاپ مطابقت ندارد` | Set `ClaimFileTypeId` from tenant `file-types` (Parsian **63**) | After config fix | Attachment stage | Ops |
| Invalid file bytes | `فرمت فایل معتبر نیست` | File is not a real JPEG/PNG/PDF (wrong magic bytes / empty / WEBP-as-jpg). YARA now sniffs magic + sets multipart `contentType` before upload | After replacing the file | Attachment stage | Ops / user re-upload |
| Expertise not ready | `Fanavaran expertise payload is not ready` + warnings | Wait for priced parts / factor | Auto when ready | — | Expert UI | | Expertise not ready | `Fanavaran expertise payload is not ready` + warnings | Wait for priced parts / factor | Auto when ready | — | Expert UI |
| Network / 5xx | Axios / gateway errors | Stage failed + schedule retry | Up to `maxRetries` (2) | Audit | Ops | | Network / 5xx | Axios / gateway errors | Stage failed + schedule retry | Up to `maxRetries` (2) | Audit | Ops |
| Max retries exhausted | Logged warn | Manual submit only | Stop auto | Stage status | Ops | | Max retries exhausted | Logged warn | Manual submit only | Stop auto | Stage status | Ops |
+9 -2
View File
@@ -82,8 +82,15 @@ Existing claim/damage IDs and successful image receipts are reused. A previously
skipped attachment stage is retried. Completion is checked against a fresh read 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 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 attachment stage's status or an upload response saying success. Missing local
files, rejected uploads, and unconfirmed receipts stop expertise submission. files, non-format rejected uploads, and unconfirmed receipts stop expertise
If there are no local attachment candidates, there is nothing to upload. submission. If there are no local attachment candidates, there is nothing to
upload.
Invalid file format (`فرمت فایل معتبر نیست` / local magic-byte rejection) is
retried once in the same submit. If the second attempt still fails, the file is
permanently waived (`FANAVARAN_ATTACHMENT_FORMAT_WAIVED` on the skipped attempt).
Waived files count as handled: they are not re-uploaded and do not block
expertise or later stages.
Errors identify `stage` (`baseClaim`, `damageCase`, or `attachments`) and preserve Errors identify `stage` (`baseClaim`, `damageCase`, or `attachments`) and preserve
vendor details. An attachment failure includes: vendor details. An attachment failure includes:
+1 -1
View File
@@ -142,7 +142,7 @@ Not ثالث GEN.08: no `DmgCaseId`, `InspectionPlaceId`, `RepairWage` on the ro
| DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** | | DmgSections[].WasteValue | داغی ردیف | number | **no** | **user** |
| DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` | | DmgSections[].AccessoryKindId | نوع قطعه کاتالوگ | number | preferred | **user** `partId` · lookup `car-components` |
| DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | Current `vehicle-hull-dmg-kind` API row caption تخریب; no numeric fallback | | DmgSections[].DmgKindId | نوع آسیب بدنه | number | **no** | Current `vehicle-hull-dmg-kind` API row caption تخریب; no numeric fallback |
| DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | **no** | Current policy `dmg-accessories`: match `AccessoryKindId`, else that policy's factory bundle; warn and block submission if unresolved | | DmgSections[].VehicleHullAccessoryId | شناسه لوازم بدنه | number | preferred | Current policy `dmg-accessories`: exact `AccessoryKindId` or caption match; else the «کليه قطعات فابريک» factory-bundle row `Id`. Keep selected car-components `AccessoryKindId` + part `Desc` |
| DmgSections[].DmgSectionCosts[].Caption | عنوان هزینه | string | **no** | **user** label | | DmgSections[].DmgSectionCosts[].Caption | عنوان هزینه | string | **no** | **user** label |
| DmgSections[].DmgSectionCosts[].Amount | مبلغ (قطعه+اجرت) | number | **no** | **user** | | DmgSections[].DmgSectionCosts[].Amount | مبلغ (قطعه+اجرت) | number | **no** | **user** |
| DmgSections[].DmgSectionCosts[].DmgCostKindId | نوع هزینه | number | **no** | Current `vehicle-hull-dmg-cost-kinds` API row caption مجموع لوازم; no numeric fallback | | DmgSections[].DmgSectionCosts[].DmgCostKindId | نوع هزینه | number | **no** | Current `vehicle-hull-dmg-cost-kinds` API row caption مجموع لوازم; no numeric fallback |
+12 -5
View File
@@ -155,7 +155,7 @@ The returned attachment Id is saved as fileId; it is not FileTypeId.
| Request field | Lookup/source | Current handling | | Request field | Lookup/source | Current handling |
|---|---|---| |---|---|---|
| DmgSections[].AccessoryKindId | car-components | Selected part ID, live checked | | DmgSections[].AccessoryKindId | car-components | Selected part ID, live checked |
| DmgSections[].VehicleHullAccessoryId | Current hull policy dmg-accessories | Exact matching accessory or that policy's factory bundle; live checked; never a shared fixed record ID | | DmgSections[].VehicleHullAccessoryId | Current hull policy dmg-accessories | Exact `AccessoryKindId` (or caption) match on one policy row. If missing, use the policy «کليه قطعات فابريک» row `Id` (factory bundle) while keeping the selected car-components `AccessoryKindId` and part `Desc` |
| DmgSections[].DmgKindId | vehicle-hull-dmg-kind | Response row caption تخریب; live checked, no numeric fallback | | DmgSections[].DmgKindId | vehicle-hull-dmg-kind | Response row caption تخریب; live checked, no numeric fallback |
| DmgSections[].DmgSectionCosts[].DmgCostKindId | vehicle-hull-dmg-cost-kinds | Response row caption مجموع لوازم; live checked, no numeric fallback | | DmgSections[].DmgSectionCosts[].DmgCostKindId | vehicle-hull-dmg-cost-kinds | Response row caption مجموع لوازم; live checked, no numeric fallback |
| ColorId | Policy vehicle GET ColorId | Inquiry-derived; not independently checked against a colour lookup | | ColorId | Policy vehicle GET ColorId | Inquiry-derived; not independently checked against a colour lookup |
@@ -170,10 +170,17 @@ Get the policy accessory rows using:
Upstream source: Upstream source:
`GET /car/vehicle-hull-policies/{policyId}/dmg-accessories` `GET /car/vehicle-hull-policies/{policyId}/dmg-accessories`
Use the row's Id for VehicleHullAccessoryId. Its PolicyId must be the claim's hull Use the row's Id for VehicleHullAccessoryId and that same row's AccessoryKindId.
PolicyId. A factory bundle may legitimately serve several different selected Fanavaran rule `CarDamageBdAsibdideSectionLookupFilterRule` rejects pairing a
car-components parts. Its bundle AccessoryKindId is not automatically the part ID local car-components part id with an unrelated policy accessory Id (including
to send for every damaged part. factory-bundle rows).
`car-components` is the full part catalogue (frontend picker). Policy
`dmg-accessories` is only what that hull policy registered — often a single
«کليه قطعات فابريک» OEM/factory coverage line (AccessoryKindId e.g. 112), not
every tyre/cap/electrical part. Unlisted parts map to that factory row's `Id`
as `VehicleHullAccessoryId`, keep the selected car-components `AccessoryKindId`,
and keep `Desc` from the car-components Caption when available.
Hull has no damage-case POST. DmgCaseId, InspectionPlaceId and DropAmountStatus Hull has no damage-case POST. DmgCaseId, InspectionPlaceId and DropAmountStatus
are not hull expertise fields. AccidentPercent is a percentage, not a lookup ID. are not hull expertise fields. AccidentPercent is a percentage, not a lookup ID.
@@ -16,7 +16,7 @@ import {
} from '@nestjs/common'; } from '@nestjs/common';
import { isAxiosError } from 'axios'; import { isAxiosError } from 'axios';
import { Types } from 'mongoose'; import { Types } from 'mongoose';
import { createReadStream, existsSync } from 'node:fs'; import { createReadStream, existsSync, openSync, readSync, closeSync, statSync } from 'node:fs';
import { basename, resolve } from 'node:path'; import { basename, resolve } from 'node:path';
import { BlameRequestType } from 'src/Types&Enums/blame-request-management/blameRequestType.enum'; import { BlameRequestType } from 'src/Types&Enums/blame-request-management/blameRequestType.enum';
import { CaseStatus as BlameCaseStatus } from 'src/Types&Enums/blame-request-management/caseStatus.enum'; import { CaseStatus as BlameCaseStatus } from 'src/Types&Enums/blame-request-management/caseStatus.enum';
@@ -213,9 +213,11 @@ import {
import { import {
FANAVARAN_HULL_DMG_COST_KIND_CAPTION, FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
FANAVARAN_HULL_DMG_KIND_CAPTION, FANAVARAN_HULL_DMG_KIND_CAPTION,
findLookupCaptionById,
findLookupIdByCaption, findLookupIdByCaption,
findHullFactoryBundleAccessory,
asHullDmgAccessoryRows, asHullDmgAccessoryRows,
resolveVehicleHullAccessoryId, resolveHullDmgSectionAccessory,
} from './fanavaran-hull-expertise-lookups'; } from './fanavaran-hull-expertise-lookups';
import { import {
validateFanavaranHullLookupIds, validateFanavaranHullLookupIds,
@@ -363,9 +365,16 @@ interface FanavaranAttachmentCandidate {
source: string; source: string;
content: Record<string, unknown>; content: Record<string, unknown>;
alreadySubmitted: boolean; alreadySubmitted: boolean;
/** Format rejected twice (or local invalid magic); treated as done for later stages. */
alreadyWaived?: boolean;
waivedReason?: string;
submittedFileId?: unknown; submittedFileId?: unknown;
} }
/** Persisted on skipped attempts so collect/ensure treat the file as handled. */
const FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX =
'FANAVARAN_ATTACHMENT_FORMAT_WAIVED:';
interface FanavaranClaimExpertContext { interface FanavaranClaimExpertContext {
initiatedByFieldExpertId?: unknown; initiatedByFieldExpertId?: unknown;
evaluation?: object; evaluation?: object;
@@ -2729,10 +2738,13 @@ export class ClaimRequestManagementService {
priceDropTotal: number; priceDropTotal: number;
priceDropCarPrice: unknown; priceDropCarPrice: unknown;
warnings: string[]; warnings: string[];
/** Non-blocking notices (factory-bundle fallbacks). Never gates submission. */
infoWarnings: string[];
replyKey?: string; replyKey?: string;
}): Promise<{ }): Promise<{
payload: Record<string, unknown>; payload: Record<string, unknown>;
warnings: string[]; warnings: string[];
infoWarnings: string[];
replyKey?: string; replyKey?: string;
}> { }> {
const policyId = this.parseHullClaimPolicyId(input.claimCase); const policyId = this.parseHullClaimPolicyId(input.claimCase);
@@ -2769,7 +2781,11 @@ export class ClaimRequestManagementService {
); );
let accessories = asHullDmgAccessoryRows([]); let accessories = asHullDmgAccessoryRows([]);
if (policyId == null && input.parts.length > 0) input.warnings.push('VehicleHullAccessoryId cannot be resolved: missing PolicyId.'); if (policyId == null && input.parts.length > 0) {
input.warnings.push(
'VehicleHullAccessoryId cannot be resolved: missing PolicyId for hull policy dmg-accessories.',
);
}
if (policyId != null && input.parts.length > 0) { if (policyId != null && input.parts.length > 0) {
try { try {
accessories = asHullDmgAccessoryRows( accessories = asHullDmgAccessoryRows(
@@ -2779,9 +2795,19 @@ export class ClaimRequestManagementService {
contractOptions, contractOptions,
), ),
); );
if (accessories.length === 0) {
input.warnings.push(
`VehicleHullAccessoryId cannot be resolved: policy ${policyId} dmg-accessories returned no rows.`,
);
}
} catch (error) { } catch (error) {
const message =
error instanceof Error ? error.message : String(error);
this.logger.warn( this.logger.warn(
`[buildCarBodyFanavaranExpertisePayload] policy ${policyId} dmg-accessories lookup failed: ${error instanceof Error ? error.message : error}`, `[buildCarBodyFanavaranExpertisePayload] policy ${policyId} dmg-accessories lookup failed: ${message}`,
);
input.warnings.push(
`VehicleHullAccessoryId cannot be resolved: policy ${policyId} dmg-accessories lookup failed (${message}).`,
); );
} }
} }
@@ -2828,14 +2854,41 @@ export class ClaimRequestManagementService {
0, 0,
); );
const hullSections = input.parts.map((part: any) => { const factoryBundle = findHullFactoryBundleAccessory(accessories);
const vehicleHullAccessoryId = resolveVehicleHullAccessoryId( const hullSections = input.parts.map((part: any, index: number) => {
const partKindId = parseFanavaranId(part?.partId);
// Prefer live car-components Caption so Desc matches the frontend catalogue.
const catalogueCaption = findLookupCaptionById(componentRows, partKindId);
const localLabel = this.fanavaranPartLabel(part);
const partLabel = catalogueCaption || localLabel;
const resolved = resolveHullDmgSectionAccessory(
accessories, accessories,
parseFanavaranId(part?.partId), partKindId,
partLabel,
); );
// No per-part policy row → cover under «کليه قطعات فابريک» Id (e.g. 3061139).
// Use the bundle's own AccessoryKindId (e.g. 112) so Fanavaran receives a
// coherent Id/AccessoryKindId pair from the policy row.
let vehicleHullAccessoryId = resolved?.vehicleHullAccessoryId ?? null;
let accessoryKindId: number | string | null | undefined =
resolved?.accessoryKindId ?? part?.partId;
if (!resolved && factoryBundle) {
vehicleHullAccessoryId = factoryBundle.vehicleHullAccessoryId;
// Replace the unrecognised per-part AccessoryKindId with the bundle's own
// kind (e.g. 112 = «کليه قطعات فابريک»). Fanavaran requires Id and
// AccessoryKindId to come from the same policy dmg-accessories row.
accessoryKindId = factoryBundle.accessoryKindId ?? accessoryKindId;
input.infoWarnings.push(
`DmgSections[${index}] (${partLabel || part?.partId || 'part'}): AccessoryKindId=${part?.partId ?? '(missing)'} is a fabrique part (no separate policy row); mapped to factory bundle VehicleHullAccessoryId=${factoryBundle.vehicleHullAccessoryId} AccessoryKindId=${accessoryKindId} («کليه قطعات فابريک»).`,
);
} else if (!resolved) {
input.warnings.push(
`DmgSections[${index}] (${partLabel || part?.partId || 'part'}): no matching row in policy ${policyId ?? '(missing)'} dmg-accessories for AccessoryKindId=${part?.partId ?? '(missing)'}. Leaving VehicleHullAccessoryId null.`,
);
}
return toFanavaranHullExpertiseDmgSection({ return toFanavaranHullExpertiseDmgSection({
partId: part?.partId, partId: accessoryKindId,
desc: this.fanavaranPartLabel(part), desc: partLabel,
wasteValue: this.fanavaranDaghiWasteValue(part?.daghi), wasteValue: this.fanavaranDaghiWasteValue(part?.daghi),
amount: amount:
this.parseFanavaranMoney(part?.price) + this.parseFanavaranMoney(part?.price) +
@@ -2882,6 +2935,7 @@ export class ClaimRequestManagementService {
return { return {
replyKey: input.replyKey, replyKey: input.replyKey,
warnings: input.warnings, warnings: input.warnings,
infoWarnings: input.infoWarnings,
payload, payload,
}; };
} }
@@ -5154,10 +5208,65 @@ export class ClaimRequestManagementService {
return submitted; return submitted;
} }
/**
* Files whose latest attempt is a permanent format waive after 2 failed uploads.
* Expertise and batch submit treat these as handled (no further upload / no block).
*/
private getWaivedFanavaranAttachmentFileNames(
claimCase: any,
): Map<string, string> {
const waived = new Map<string, string>();
const attempts = claimCase?.fanavaranSync?.attachments?.attempts;
if (!Array.isArray(attempts)) return waived;
const latest = new Map<string, { status?: string; error?: string }>();
for (const row of attempts) {
const fileName = (row as { fileName?: unknown })?.fileName;
if (typeof fileName !== 'string' || !fileName.trim()) continue;
latest.set(fileName, {
status: String((row as { status?: unknown })?.status ?? ''),
error:
typeof (row as { error?: unknown })?.error === 'string'
? ((row as { error: string }).error)
: undefined,
});
}
for (const [fileName, attempt] of latest) {
if (
attempt.status === 'skipped' &&
typeof attempt.error === 'string' &&
attempt.error.startsWith(FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX)
) {
waived.set(fileName, attempt.error);
}
}
return waived;
}
private isFanavaranAttachmentFormatError(
error: unknown,
warning: string,
): boolean {
if (warning.includes('فرمت فایل معتبر نیست')) return true;
if (warning.includes('FANAVARAN_ATTACHMENT_INVALID_FORMAT')) return true;
if (error instanceof BadRequestException) {
const body = error.getResponse();
if (
body &&
typeof body === 'object' &&
(body as { code?: string }).code === 'FANAVARAN_ATTACHMENT_INVALID_FORMAT'
) {
return true;
}
}
return false;
}
private appendFanavaranAttachmentCandidate( private appendFanavaranAttachmentCandidate(
candidates: FanavaranAttachmentCandidate[], candidates: FanavaranAttachmentCandidate[],
seen: Set<string>, seen: Set<string>,
submittedFiles: Map<string, unknown>, submittedFiles: Map<string, unknown>,
waivedFiles: Map<string, string>,
input: { path?: unknown; fileName?: unknown; source: string }, input: { path?: unknown; fileName?: unknown; source: string },
fileTypeId: number, fileTypeId: number,
): void { ): void {
@@ -5171,6 +5280,8 @@ export class ClaimRequestManagementService {
if (!path || !fileName || seen.has(fileName)) return; if (!path || !fileName || seen.has(fileName)) return;
seen.add(fileName); seen.add(fileName);
const waivedReason = waivedFiles.get(fileName);
const alreadyWaived = waivedReason != null;
candidates.push({ candidates.push({
path, path,
fileName, fileName,
@@ -5180,7 +5291,9 @@ export class ClaimRequestManagementService {
FileTypeId: fileTypeId, FileTypeId: fileTypeId,
Files: [{ FileName: fileName, FileTypeId: fileTypeId }], Files: [{ FileName: fileName, FileTypeId: fileTypeId }],
}, },
alreadySubmitted: submittedFiles.has(fileName), alreadySubmitted: submittedFiles.has(fileName) || alreadyWaived,
alreadyWaived,
waivedReason,
submittedFileId: submittedFiles.get(fileName), submittedFileId: submittedFiles.get(fileName),
}); });
} }
@@ -5202,6 +5315,7 @@ export class ClaimRequestManagementService {
const seen = new Set<string>(); const seen = new Set<string>();
const submittedFiles = const submittedFiles =
this.getSubmittedFanavaranAttachmentFileNames(claimCase); this.getSubmittedFanavaranAttachmentFileNames(claimCase);
const waivedFiles = this.getWaivedFanavaranAttachmentFileNames(claimCase);
const fileTypeId = profile.defaults.ClaimFileTypeId; const fileTypeId = profile.defaults.ClaimFileTypeId;
const documents = const documents =
@@ -5211,6 +5325,7 @@ export class ClaimRequestManagementService {
candidates, candidates,
seen, seen,
submittedFiles, submittedFiles,
waivedFiles,
{ {
path: (document as { path?: unknown }).path, path: (document as { path?: unknown }).path,
fileName: (document as { fileName?: unknown }).fileName, fileName: (document as { fileName?: unknown }).fileName,
@@ -5233,6 +5348,7 @@ export class ClaimRequestManagementService {
candidates, candidates,
seen, seen,
submittedFiles, submittedFiles,
waivedFiles,
{ {
path: capture?.path, path: capture?.path,
fileName: capture?.fileName, fileName: capture?.fileName,
@@ -5254,6 +5370,7 @@ export class ClaimRequestManagementService {
candidates, candidates,
seen, seen,
submittedFiles, submittedFiles,
waivedFiles,
{ {
path: capture?.path, path: capture?.path,
fileName: capture?.fileName, fileName: capture?.fileName,
@@ -5301,10 +5418,23 @@ export class ClaimRequestManagementService {
attachments: candidates.map(candidate => { attachments: candidates.map(candidate => {
const latestAttempt = uploadStatus?.attempts.filter(attempt => attempt.fileName === candidate.fileName).at(-1); const latestAttempt = uploadStatus?.attempts.filter(attempt => attempt.fileName === candidate.fileName).at(-1);
const localFileExists = existsSync(candidate.path); const localFileExists = existsSync(candidate.path);
const status = candidate.alreadyWaived
? 'skipped'
: candidate.alreadySubmitted
? 'success'
: !localFileExists
? 'skipped'
: latestAttempt?.status ?? 'pending';
return { return {
...candidate, fileId: candidate.submittedFileId ?? null, localFileExists, ...candidate, fileId: candidate.submittedFileId ?? null, localFileExists,
status: candidate.alreadySubmitted ? 'success' : !localFileExists ? 'skipped' : latestAttempt?.status ?? 'pending', status,
lastError: candidate.alreadySubmitted ? null : !localFileExists ? 'Local attachment file does not exist.' : latestAttempt?.error ?? null, lastError: candidate.alreadyWaived
? candidate.waivedReason ?? latestAttempt?.error ?? null
: candidate.alreadySubmitted
? null
: !localFileExists
? 'Local attachment file does not exist.'
: latestAttempt?.error ?? null,
}; };
}), }),
}; };
@@ -5401,6 +5531,8 @@ export class ClaimRequestManagementService {
options?: { options?: {
clientKey?: FanavaranClientKey; clientKey?: FanavaranClientKey;
auditSource?: FanavaranAuditSource; auditSource?: FanavaranAuditSource;
/** True on the immediate second try after a format rejection. */
formatRetryAttempted?: boolean;
}, },
): Promise<FanavaranAttachmentSubmitResult> { ): Promise<FanavaranAttachmentSubmitResult> {
const clientKey = options?.clientKey ?? resolveFanavaranClientKey(); const clientKey = options?.clientKey ?? resolveFanavaranClientKey();
@@ -5459,6 +5591,19 @@ export class ClaimRequestManagementService {
}; };
} }
const waivedReason =
this.getWaivedFanavaranAttachmentFileNames(claimCase).get(fileName);
if (waivedReason) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: waivedReason,
warning: waivedReason,
fileName,
};
}
if (!claimCase.claimId) { if (!claimCase.claimId) {
if (options?.clientKey) { if (options?.clientKey) {
await this.executeFanavaranV2Submit(claimCaseId, clientKey); await this.executeFanavaranV2Submit(claimCaseId, clientKey);
@@ -5650,6 +5795,36 @@ export class ClaimRequestManagementService {
); );
} }
// Invalid format: try once more immediately; if it still fails, waive permanently
// so expertise and later stages can continue without this file.
const formatError = this.isFanavaranAttachmentFormatError(error, warning);
if (formatError && !options?.formatRetryAttempted) {
this.logger.warn(
`${logPrefix} format rejected; retrying once fileName=${fileName}`,
);
return this.autoSubmitFanavaranAttachment(claimCaseId, file, {
...options,
formatRetryAttempted: true,
});
}
if (formatError && options?.formatRetryAttempted) {
const reason = `${FANAVARAN_ATTACHMENT_FORMAT_WAIVE_PREFIX} ${warning} (after 2 attempts); continuing without this file.`;
await this.recordSkippedFanavaranAttachment(
claimCaseId,
fileName,
file.source,
reason,
);
return {
attempted: true,
submitted: false,
skipped: true,
skipReason: reason,
warning: reason,
fileName,
};
}
// Schedule retry for attachments — never let retry bookkeeping fail the // 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 {
@@ -5899,10 +6074,19 @@ export class ClaimRequestManagementService {
catalogKey?: unknown; catalogKey?: unknown;
}; };
return String( return String(
d.label_fa ?? d.part ?? d.name ?? d.catalogKey ?? part?.partId ?? '', d.label_fa ??
d.part ??
d.name ??
d.catalogKey ??
part?.partName ??
part?.name ??
part?.partId ??
'',
); );
} }
return String(damage ?? part?.partId ?? ''); return String(
damage ?? part?.partName ?? part?.name ?? part?.partId ?? '',
);
} }
private fanavaranDaghiWasteValue(daghi: unknown): number { private fanavaranDaghiWasteValue(daghi: unknown): number {
@@ -5948,6 +6132,7 @@ export class ClaimRequestManagementService {
}): Promise<{ }): Promise<{
payload: Record<string, unknown>; payload: Record<string, unknown>;
warnings: string[]; warnings: string[];
infoWarnings: string[];
replyKey?: string; replyKey?: string;
}> { }> {
const profile = getFanavaranClientProfile(input.clientKey); const profile = getFanavaranClientProfile(input.clientKey);
@@ -5962,6 +6147,7 @@ export class ClaimRequestManagementService {
// GEN.08 / GEN.06 ClaimExpertId always from assigned assessor staff profile. // GEN.08 / GEN.06 ClaimExpertId always from assigned assessor staff profile.
const warnings: string[] = []; const warnings: string[] = [];
const infoWarnings: string[] = [];
let claimExpertId: number | null = null; let claimExpertId: number | null = null;
if (!blameForExpertIds) { if (!blameForExpertIds) {
const message = const message =
@@ -6023,7 +6209,7 @@ export class ClaimRequestManagementService {
clientKey: input.clientKey, claimCase: input.claimCase, clientKey: input.clientKey, claimCase: input.claimCase,
blame: blameForExpertIds, profile, parts, claimExpertId, blame: blameForExpertIds, profile, parts, claimExpertId,
submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice, submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice,
warnings, replyKey: active?.replyKey, warnings, infoWarnings, replyKey: active?.replyKey,
}); });
} }
@@ -6076,6 +6262,7 @@ export class ClaimRequestManagementService {
return { return {
replyKey: active?.replyKey, replyKey: active?.replyKey,
warnings, warnings,
infoWarnings,
payload, payload,
}; };
} }
@@ -6108,7 +6295,7 @@ export class ClaimRequestManagementService {
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');
const { payload, warnings, replyKey } = const { payload, warnings, infoWarnings, replyKey } =
await this.buildFanavaranExpertisePayload({ await this.buildFanavaranExpertisePayload({
claimCase, claimCase,
clientKey, clientKey,
@@ -6137,6 +6324,7 @@ export class ClaimRequestManagementService {
: null, : null,
ready: warnings.length === 0 && payload.ClaimExpertId != null, ready: warnings.length === 0 && payload.ClaimExpertId != null,
warnings: Array.from(new Set(warnings)), warnings: Array.from(new Set(warnings)),
infoWarnings: Array.from(new Set(infoWarnings)),
payload, payload,
}; };
} }
@@ -6251,12 +6439,16 @@ export class ClaimRequestManagementService {
this.assertFanavaranExpertisePayloadReady(payload, built.warnings, { this.assertFanavaranExpertisePayloadReady(payload, built.warnings, {
...hullExpertiseAssertFields(product), ...hullExpertiseAssertFields(product),
}); });
return await this.executeFanavaranExpertiseSubmit( const result = await this.executeFanavaranExpertiseSubmit(
claimCaseId, claimCaseId,
clientKey, clientKey,
payload, payload,
FanavaranAuditSource.SUBMIT, FanavaranAuditSource.SUBMIT,
); );
// Surface infoWarnings (e.g. factory-bundle fallbacks) on the success
// response so callers are informed, without ever blocking the submit.
const infoWarnings = Array.from(new Set(built.infoWarnings));
return infoWarnings.length > 0 ? { ...result, infoWarnings } : result;
} catch (error) { } catch (error) {
if (error instanceof HttpException) throw error; if (error instanceof HttpException) throw error;
this.logger.error( this.logger.error(
@@ -6808,6 +7000,67 @@ export class ClaimRequestManagementService {
} }
} }
/**
* Fanavaran GEN.05/07 rejects unknown binaries with «فرمت فایل معتبر نیست».
* Detect real JPEG/PNG/PDF from magic bytes (extension alone is not enough).
*/
private inspectFanavaranUploadFile(filePath: string): {
contentType: string;
extension: string;
} {
const absolute = resolve(filePath);
const size = existsSync(absolute) ? statSync(absolute).size : 0;
if (size <= 0) {
throw new BadRequestException({
code: 'FANAVARAN_ATTACHMENT_EMPTY',
message: `Attachment file is empty: ${filePath}`,
});
}
const fd = openSync(absolute, 'r');
const header = Buffer.alloc(16);
try {
readSync(fd, header, 0, 16, 0);
} finally {
closeSync(fd);
}
if (header[0] === 0xff && header[1] === 0xd8 && header[2] === 0xff) {
return { contentType: 'image/jpeg', extension: '.jpg' };
}
if (
header[0] === 0x89 &&
header[1] === 0x50 &&
header[2] === 0x4e &&
header[3] === 0x47
) {
return { contentType: 'image/png', extension: '.png' };
}
if (
header.slice(0, 4).toString('ascii') === '%PDF'
) {
return { contentType: 'application/pdf', extension: '.pdf' };
}
throw new BadRequestException({
code: 'FANAVARAN_ATTACHMENT_INVALID_FORMAT',
message: `Attachment is not a valid JPEG/PNG/PDF (Fanavaran «فرمت فایل معتبر نیست»). path=${filePath} magic=${header
.slice(0, 8)
.toString('hex')}`,
});
}
private fanavaranUploadFileName(
preferredName: string,
extension: string,
): string {
const base = basename(preferredName || 'upload');
const withoutExt = base.replace(/\.[^.]+$/, '') || 'upload';
const safe = withoutExt
.replace(/[^\w.-]+/g, '_')
.replace(/_+/g, '_')
.replace(/^_|_$/g, '')
.slice(0, 80);
return `${safe || 'upload'}${extension}`;
}
private async postFanavaranMultipart( private async postFanavaranMultipart(
url: string, url: string,
content: Record<string, unknown>, content: Record<string, unknown>,
@@ -6825,12 +7078,36 @@ export class ClaimRequestManagementService {
); );
const form = new FormData(); const form = new FormData();
const prepared = files.map((file) => {
const inspected = this.inspectFanavaranUploadFile(file.path);
const fileName = this.fanavaranUploadFileName(
file.fileName || basename(file.path),
inspected.extension,
);
return {
path: resolve(file.path),
fileName,
contentType: inspected.contentType,
};
});
// Keep Param.FileName / Files[].FileName aligned with the multipart filename.
if (prepared.length === 1) {
content.FileName = prepared[0].fileName;
if (Array.isArray(content.Files) && content.Files[0]) {
(content.Files[0] as Record<string, unknown>).FileName =
prepared[0].fileName;
}
}
form.append('Param', JSON.stringify(content), { form.append('Param', JSON.stringify(content), {
contentType: 'application/json', contentType: 'application/json',
}); });
for (const file of files) { for (const file of prepared) {
form.append('Param1', createReadStream(resolve(file.path)), { form.append('Param1', createReadStream(file.path), {
filename: file.fileName, filename: file.fileName,
contentType: file.contentType,
knownLength: statSync(file.path).size,
}); });
} }
@@ -6840,8 +7117,11 @@ export class ClaimRequestManagementService {
`-H 'CorpId: ${headers.CorpId}'`, `-H 'CorpId: ${headers.CorpId}'`,
`-H 'ContractId: ${headers.ContractId}'`, `-H 'ContractId: ${headers.ContractId}'`,
`-H 'Location: ${headers.Location}'`, `-H 'Location: ${headers.Location}'`,
`-F 'Param=${JSON.stringify(content)}'`, `-F 'Param=${JSON.stringify(content)};type=application/json'`,
...files.map((f) => `-F 'Param1=@${f.path};filename=${f.fileName}'`), ...prepared.map(
(f) =>
`-F 'Param1=@${f.path};filename=${f.fileName};type=${f.contentType}'`,
),
]; ];
this.logger.log( this.logger.log(
`\n====== COPY THIS CURL ======\n${curlParts.join(' \\\n ')}\n====== END CURL ======\n`, `\n====== COPY THIS CURL ======\n${curlParts.join(' \\\n ')}\n====== END CURL ======\n`,
@@ -63,6 +63,7 @@ describe("Fanavaran image upload persistence and visibility", () => {
.fn() .fn()
.mockImplementation(async () => { .mockImplementation(async () => {
const files = service.getSubmittedFanavaranAttachmentFileNames(claim); const files = service.getSubmittedFanavaranAttachmentFileNames(claim);
const waived = service.getWaivedFanavaranAttachmentFileNames(claim);
return { return {
claimCase: claim, claimCase: claim,
candidates: [ candidates: [
@@ -70,7 +71,9 @@ describe("Fanavaran image upload persistence and visibility", () => {
path, path,
fileName: "image.jpg", fileName: "image.jpg",
source: "capture:angle:front", source: "capture:angle:front",
alreadySubmitted: files.has("image.jpg"), alreadySubmitted: files.has("image.jpg") || waived.has("image.jpg"),
alreadyWaived: waived.has("image.jpg"),
waivedReason: waived.get("image.jpg"),
submittedFileId: files.get("image.jpg"), submittedFileId: files.get("image.jpg"),
}, },
], ],
@@ -171,6 +174,49 @@ describe("Fanavaran image upload persistence and visibility", () => {
expect(service.scheduleFanavaranRetry).not.toHaveBeenCalled(); expect(service.scheduleFanavaranRetry).not.toHaveBeenCalled();
}); });
it("retries invalid-format uploads once then waives so later stages can continue", async () => {
const { service, claim } = setup();
service.postFanavaranMultipart.mockRejectedValue(
new Error("فرمت فایل معتبر نیست"),
);
const result = await service.submitFanavaranAttachmentsV2(
"claim-1",
"parsian",
);
expect(service.postFanavaranMultipart).toHaveBeenCalledTimes(2);
expect(service.scheduleFanavaranRetry).not.toHaveBeenCalled();
expect(result[0]).toMatchObject({
submitted: false,
skipped: true,
skipReason: expect.stringContaining("FANAVARAN_ATTACHMENT_FORMAT_WAIVED"),
});
expect(claim.fanavaranSync.attachments.attempts).toEqual(
expect.arrayContaining([
expect.objectContaining({ status: "failed", error: "فرمت فایل معتبر نیست" }),
expect.objectContaining({
status: "skipped",
error: expect.stringContaining("FANAVARAN_ATTACHMENT_FORMAT_WAIVED"),
}),
]),
);
expect(
claim.fanavaranSync.attachments.attempts.filter(
(row: { status?: string }) => row.status === "failed",
),
).toHaveLength(2);
const second = await service.submitFanavaranAttachmentsV2(
"claim-1",
"parsian",
);
expect(service.postFanavaranMultipart).toHaveBeenCalledTimes(2);
expect(second).toMatchObject({
attempted: 0,
skipped: 1,
results: [],
});
});
it("exposes upload status before completion and reports mixed outcomes as partial", async () => { it("exposes upload status before completion and reports mixed outcomes as partial", async () => {
const { service, claim } = setup(); const { service, claim } = setup();
claim.status = "EXPERT_REVIEWING"; claim.status = "EXPERT_REVIEWING";
@@ -42,9 +42,12 @@ export function fanavaranAttachmentStatus(
const latest = new Map( const latest = new Map(
attempts.map((attempt) => [attempt.fileName, attempt]), attempts.map((attempt) => [attempt.fileName, attempt]),
); );
// Skipped (including format-waived) files are intentional omissions, not blockers.
const outstanding = [...latest.values()].filter( const outstanding = [...latest.values()].filter(
(attempt) => (attempt) =>
!uploadedNames.has(attempt.fileName) && attempt.status !== "success", !uploadedNames.has(attempt.fileName) &&
attempt.status !== "success" &&
attempt.status !== "skipped",
); );
const lastProblem = outstanding.at(-1); const lastProblem = outstanding.at(-1);
const status = lastProblem const status = lastProblem
@@ -4,7 +4,7 @@ function setup(product = "third-party") {
const service = Object.create(ClaimRequestManagementService.prototype) as any; const service = Object.create(ClaimRequestManagementService.prototype) as any;
const claim: any = { const claim: any = {
_id: "claim-1", _id: "claim-1",
fanavaranSync: { attachments: { files: [] } }, fanavaranSync: { attachments: { files: [], attempts: [] } },
}; };
const events: string[] = []; const events: string[] = [];
service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() }; service.logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
@@ -24,17 +24,23 @@ function setup(product = "third-party") {
}); });
service.collectFanavaranAttachmentCandidates = jest service.collectFanavaranAttachmentCandidates = jest
.fn() .fn()
.mockImplementation(async () => ({ .mockImplementation(async () => {
claimCase: claim, const waived = service.getWaivedFanavaranAttachmentFileNames(claim);
candidates: [ const uploaded = claim.fanavaranSync.attachments.files.length > 0;
{ return {
fileName: "image.jpg", claimCase: claim,
source: "capture:angle:front", candidates: [
path: "/tmp/image.jpg", {
alreadySubmitted: claim.fanavaranSync.attachments.files.length > 0, fileName: "image.jpg",
}, source: "capture:angle:front",
], path: "/tmp/image.jpg",
})); alreadySubmitted: uploaded || waived.has("image.jpg"),
alreadyWaived: waived.has("image.jpg"),
waivedReason: waived.get("image.jpg"),
},
],
};
});
service.submitFanavaranAttachmentsV2 = jest service.submitFanavaranAttachmentsV2 = jest
.fn() .fn()
.mockImplementation(async () => { .mockImplementation(async () => {
@@ -113,6 +119,29 @@ describe("expertise submit completes earlier Fanavaran stages", () => {
}, },
); );
it("continues to expertise when an invalid-format image was waived after 2 tries", async () => {
const { service, claim, events } = setup();
Object.assign(claim, { claimId: 100, dmgCaseId: 200 });
claim.fanavaranSync.attachments.attempts.push({
fileName: "image.jpg",
status: "skipped",
error:
"FANAVARAN_ATTACHMENT_FORMAT_WAIVED: فرمت فایل معتبر نیست (after 2 attempts); continuing without this file.",
});
service.submitFanavaranAttachmentsV2.mockImplementation(async () => {
events.push("attachments");
return {
attempted: 0,
submitted: 0,
skipped: 1,
results: [],
};
});
await service.submitFanavaranExpertiseV2("claim-1", "parsian");
expect(events).toEqual(["expertise"]);
expect(service.submitFanavaranAttachmentsV2).not.toHaveBeenCalled();
});
it("stops immediately if the base stage fails", async () => { it("stops immediately if the base stage fails", async () => {
const { service } = setup(); const { service } = setup();
service.executeFanavaranV2Submit.mockRejectedValue( service.executeFanavaranV2Submit.mockRejectedValue(
@@ -68,19 +68,31 @@ describe("hull expertise policy accessory mapping", () => {
); );
}); });
it("uses a factory bundle only when it belongs to the current policy", async () => { it("maps unmatched parts onto the policy factory-bundle VehicleHullAccessoryId", async () => {
const { build } = setup([ const { build } = setup([
{ Id: 900003, AccessoryDesc: "کليه قطعات فابريک" }, {
Id: 3061139,
AccessoryKindId: 112,
AccessoryDesc: "کليه قطعات فابريک",
},
]); ]);
const { payload } = await build(); const { payload, warnings } = await build();
expect( expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId), payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([900003, 900003]); ).toEqual([3061139, 3061139]);
expect(payload.DmgSections.map((row: any) => row.AccessoryKindId)).toEqual([
9, 13,
]);
expect(warnings).toEqual(
expect.arrayContaining([
expect.stringContaining("using factory bundle VehicleHullAccessoryId=3061139"),
]),
);
}); });
it("does not replace unavailable lookup values with 5485 or 1", async () => { it("does not replace unavailable lookup values with 5485 or 1", async () => {
const { service, build } = setup([ const { service, build } = setup([
{ Id: 2810613, AccessoryDesc: "کليه قطعات فابريک" }, { Id: 2810613, AccessoryKindId: 9, AccessoryDesc: "سپر جلو" },
]); ]);
service.getFanavaranLookupRows.mockResolvedValue([]); service.getFanavaranLookupRows.mockResolvedValue([]);
const { payload, warnings } = await build(); const { payload, warnings } = await build();
@@ -103,7 +115,12 @@ describe("hull expertise policy accessory mapping", () => {
expect( expect(
payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId), payload.DmgSections.map((row: any) => row.VehicleHullAccessoryId),
).toEqual([null, null]); ).toEqual([null, null]);
expect(warnings).toHaveLength(2); expect(warnings).toEqual(
expect.arrayContaining([
expect.stringContaining("dmg-accessories lookup failed"),
expect.stringContaining("Leaving VehicleHullAccessoryId null"),
]),
);
}); });
it("reports a missing hull PolicyId instead of using the claim ID as a policy", async () => { it("reports a missing hull PolicyId instead of using the claim ID as a policy", async () => {
@@ -130,9 +147,28 @@ describe("hull expertise policy accessory mapping", () => {
).toEqual([null, null]); ).toEqual([null, null]);
expect(warnings).toEqual( expect(warnings).toEqual(
expect.arrayContaining([ expect.arrayContaining([
expect.stringContaining("VehicleHullAccessoryId"), expect.stringMatching(
/VehicleHullAccessoryId|Leaving VehicleHullAccessoryId null/,
),
]), ]),
); );
}, },
); );
it("matches by part caption and keeps AccessoryKindId from that policy row", async () => {
const { build } = setup([
{
Id: 900010,
AccessoryKindId: 44,
AccessoryDesc: "سپر جلو",
},
]);
const { payload, warnings } = await build();
expect(payload.DmgSections[0]).toMatchObject({
VehicleHullAccessoryId: 900010,
AccessoryKindId: 44,
});
expect(payload.DmgSections[1].VehicleHullAccessoryId).toBeNull();
expect(warnings.some((w) => w.includes("چراغ جلو چپ"))).toBe(true);
});
}); });
@@ -128,7 +128,7 @@ export function toFanavaranHullBaseClaimPayload(
// Fanavaran conditional: >10y since issue → 1; else null (never 0). // Fanavaran conditional: >10y since issue → 1; else null (never 0).
if ( if (
Object.prototype.hasOwnProperty.call(built, key) && Object.prototype.hasOwnProperty.call(built, key) &&
(built[key] === 1 || built[key] === null) (built[key] === 1 || built[key] === 0 || built[key] === null)
) { ) {
next[key] = built[key]; next[key] = built[key];
} else { } else {
@@ -31,53 +31,124 @@ export function asHullDmgAccessoryRows(
return asLookupRows(value) as FanavaranHullDmgAccessoryRow[]; return asLookupRows(value) as FanavaranHullDmgAccessoryRow[];
} }
function normalizeLookupCaption(raw: unknown): string {
return String(raw ?? "")
.replace(/ي/g, "ی")
.replace(/ك/g, "ک")
.replace(/\u200c/g, " ")
.replace(/\s*([()])\s*/g, "$1")
.replace(/\s+/g, " ")
.trim();
}
export function findLookupIdByCaption( export function findLookupIdByCaption(
rows: unknown, rows: unknown,
caption: string, caption: string,
): number | null { ): number | null {
const normalize = (raw: unknown) => const target = normalizeLookupCaption(caption);
String(raw ?? "")
.replace(/ي/g, "ی")
.replace(/ك/g, "ک")
.replace(/\u200c/g, " ")
.replace(/\s*([()])\s*/g, "$1")
.replace(/\s+/g, " ")
.trim();
const target = normalize(caption);
for (const row of asLookupRows(rows)) { for (const row of asLookupRows(rows)) {
if ( if (
row.IsActive === false || row.IsActive === false ||
(row.IsActive != null && Number(row.IsActive) === 0) (row.IsActive != null && Number(row.IsActive) === 0)
) )
continue; continue;
if (normalize(row.Caption) !== target) continue; if (normalizeLookupCaption(row.Caption) !== target) continue;
const id = parseFanavaranId(row.Id); const id = parseFanavaranId(row.Id);
if (id != null) return id; if (id != null) return id;
} }
return null; return null;
} }
function isFactoryDefaultAccessoryRow( /** Caption from car-components (or any Id/Caption lookup) for a selected part Id. */
row: FanavaranHullDmgAccessoryRow, export function findLookupCaptionById(
): boolean { rows: unknown,
const desc = String(row.AccessoryDesc ?? "").trim(); id: number | null,
return ( ): string | null {
desc.includes("کليه قطعات فابريک") || if (id == null) return null;
desc.includes("کلیه قطعات فابریک") || for (const row of asLookupRows(rows)) {
desc.includes("کليه قطعات") || if (
desc.includes("فابريک") row.IsActive === false ||
); (row.IsActive != null && Number(row.IsActive) === 0)
)
continue;
if (parseFanavaranId(row.Id) !== id) continue;
const caption = normalizeLookupCaption(row.Caption);
return caption || null;
}
return null;
} }
export type HullFactoryBundleAccessory = {
vehicleHullAccessoryId: number;
/** Present on most factory rows (e.g. 112); not written onto unmatched DmgSections. */
accessoryKindId: number | null;
};
/** /**
* GEN.06 VehicleHullAccessoryId from policy dmg-accessories. * Policy row for «کليه قطعات فابريک» — OEM/factory-fitted coverage bundle.
* 1) Match AccessoryKindId to car-components part id. * Many hull policies list only this row instead of every car-components part.
* 2) Else factory bundle row (app default outer parts map here on Parsian). *
* Uses exact match first to avoid selecting «غير فابريک» which also contains
* «فابریک» as a substring but is specifically the NON-factory accessory row.
*/ */
export function resolveVehicleHullAccessoryId( export function findHullFactoryBundleAccessory(
accessories: FanavaranHullDmgAccessoryRow[],
): HullFactoryBundleAccessory | null {
// Pass 1: exact match after normalisation (handles ي/ک variants and ZWNJ).
for (const row of accessories) {
const desc = normalizeAccessoryCaption(row.AccessoryDesc);
if (desc !== "کليه قطعات فابریک") continue;
const vehicleHullAccessoryId = parseFanavaranId(row.Id);
if (vehicleHullAccessoryId == null) continue;
return {
vehicleHullAccessoryId,
accessoryKindId: parseFanavaranId(row.AccessoryKindId),
};
}
// Pass 2: starts-with fallback for minor suffix variations.
// «غير فابريک» starts with «غير» so it will never match here.
for (const row of accessories) {
const desc = normalizeAccessoryCaption(row.AccessoryDesc);
if (
!desc.startsWith("کليه قطعات فابریک") &&
!desc.startsWith("کلیه قطعات فابریک")
) continue;
const vehicleHullAccessoryId = parseFanavaranId(row.Id);
if (vehicleHullAccessoryId == null) continue;
return {
vehicleHullAccessoryId,
accessoryKindId: parseFanavaranId(row.AccessoryKindId),
};
}
return null;
}
function normalizeAccessoryCaption(value: unknown): string {
return String(value ?? "")
.replace(/ي/g, "ی")
.replace(/ك/g, "ک")
.replace(/\u200c/g, " ")
.replace(/\s+/g, " ")
.trim();
}
export type ResolvedHullDmgAccessory = {
vehicleHullAccessoryId: number;
/** Must come from the same policy dmg-accessories row (Fanavaran filter rule). */
accessoryKindId: number;
};
/**
* GEN.06 accessory pair from `GET …/vehicle-hull-policies/{policyId}/dmg-accessories`.
* Only returns a coherent Id + AccessoryKindId from one policy row.
* Exact/caption match only. Factory-bundle fallback for unmatched parts is applied
* by the expertise builder (VehicleHullAccessoryId from «کليه قطعات فابريک»).
*/
export function resolveHullDmgSectionAccessory(
accessories: FanavaranHullDmgAccessoryRow[], accessories: FanavaranHullDmgAccessoryRow[],
accessoryKindId: number | null, accessoryKindId: number | null,
): number | null { partCaption?: string | null,
): ResolvedHullDmgAccessory | null {
if (accessories.length === 0) return null; if (accessories.length === 0) return null;
if (accessoryKindId != null) { if (accessoryKindId != null) {
@@ -85,12 +156,39 @@ export function resolveVehicleHullAccessoryId(
(row) => parseFanavaranId(row.AccessoryKindId) === accessoryKindId, (row) => parseFanavaranId(row.AccessoryKindId) === accessoryKindId,
); );
const exactId = parseFanavaranId(exact?.Id); const exactId = parseFanavaranId(exact?.Id);
if (exactId != null) return exactId; const exactKind = parseFanavaranId(exact?.AccessoryKindId);
if (exactId != null && exactKind != null) {
return { vehicleHullAccessoryId: exactId, accessoryKindId: exactKind };
}
} }
const factory = accessories.find(isFactoryDefaultAccessoryRow); const wanted = normalizeAccessoryCaption(partCaption);
const factoryId = parseFanavaranId(factory?.Id); if (wanted) {
if (factoryId != null) return factoryId; // Do not fuzzy-match onto «کليه قطعات فابريک» — that would pair the factory
// Id with a different local part kind and fail Fanavaran's filter rule.
const byDesc = accessories.find((row) => {
const desc = normalizeAccessoryCaption(row.AccessoryDesc);
if (desc.includes("فابریک") && desc !== wanted) return false;
return desc === wanted || desc.includes(wanted) || wanted.includes(desc);
});
const descId = parseFanavaranId(byDesc?.Id);
const descKind = parseFanavaranId(byDesc?.AccessoryKindId);
if (descId != null && descKind != null) {
return { vehicleHullAccessoryId: descId, accessoryKindId: descKind };
}
}
return null; return null;
} }
/** @deprecated Prefer {@link resolveHullDmgSectionAccessory} — keeps Id/kind coherent. */
export function resolveVehicleHullAccessoryId(
accessories: FanavaranHullDmgAccessoryRow[],
accessoryKindId: number | null,
partCaption?: string | null,
): number | null {
return (
resolveHullDmgSectionAccessory(accessories, accessoryKindId, partCaption)
?.vehicleHullAccessoryId ?? null
);
}
@@ -169,4 +169,42 @@ describe("fanavaran hull expertise", () => {
"DmgSections[1].AccidentLevel is required.", "DmgSections[1].AccidentLevel is required.",
]); ]);
}); });
it("allows null VehicleHullAccessoryId on hull readiness when AccessoryKindId is set", () => {
const payload = toFanavaranHullExpertisePayload({
claimExpertId: 29,
dmgAssessmentDate: "1405/06/24",
inspectionTime: "10:41",
wage: 0,
componentReplacementCost: 5000000,
wasteValue: 0,
dropAmount: 0,
vehicleCurrentValue: null,
vehicle: {
motorNo: "1",
chassisNo: "2",
vin: "3",
plaqueNo: "56د394",
plaqueSerial: "66",
builtYear: 1389,
},
dmgSections: [
toFanavaranHullExpertiseDmgSection({
partId: 17,
desc: "لاستيک جلو چپ",
wasteValue: 0,
amount: 5000000,
dmgKindId: 5485,
dmgCostKindId: 1,
vehicleHullAccessoryId: null,
}),
],
});
expect(
collectFanavaranExpertiseReadinessWarnings(
payload,
hullExpertiseAssertFields("car-body"),
),
).toEqual([]);
});
}); });
@@ -196,7 +196,17 @@ export function collectFanavaranExpertiseReadinessWarnings(
} }
for (const [index, section] of sections.entries()) { for (const [index, section] of sections.entries()) {
const row = section as Record<string, unknown>; const row = section as Record<string, unknown>;
if (!thirdPartyLookups) continue; if (!thirdPartyLookups) {
// VehicleHullAccessoryId may be null: many hull policies only list the
// factory bundle (کليه قطعات فابريک), not every car-components part.
// Do not invent a factory Id with a mismatched AccessoryKindId.
if (row.AccessoryKindId == null || row.AccessoryKindId === "") {
warnings.push(
`DmgSections[${index}].AccessoryKindId is required from car-components (selected part).`,
);
}
continue;
}
if (!row.DmgSectionId) { if (!row.DmgSectionId) {
warnings.push(`DmgSections[${index}].DmgSectionId is required.`); warnings.push(`DmgSections[${index}].DmgSectionId is required.`);
} }
@@ -1,6 +1,10 @@
import { asLookupRows } from "./fanavaran-hull-expertise-lookups"; import { asLookupRows } from "./fanavaran-hull-expertise-lookups";
export type HullLookupStage = "baseClaim" | "expertise" | "files"; export type HullLookupStage = "baseClaim" | "expertise" | "files";
/** Default AccidentCauseId (عدم رعايت حق تقدم) used when the case-selected value
* is not present in the live Fanavaran accident-causes lookup. */
export const FANAVARAN_HULL_FALLBACK_ACCIDENT_CAUSE_ID = 6;
type LookupField = { type LookupField = {
row: Record<string, unknown>; row: Record<string, unknown>;
key: string; key: string;
@@ -61,11 +65,13 @@ export async function validateFanavaranHullLookupIds(
"car-components", "car-components",
`${prefix}.AccessoryKindId`, `${prefix}.AccessoryKindId`,
); );
// Optional: policy often has only the factory-bundle row; null is allowed.
add( add(
row, row,
"VehicleHullAccessoryId", "VehicleHullAccessoryId",
"policy-dmg-accessories", "policy-dmg-accessories",
`${prefix}.VehicleHullAccessoryId`, `${prefix}.VehicleHullAccessoryId`,
false,
); );
add(row, "DmgKindId", "vehicle-hull-dmg-kind", `${prefix}.DmgKindId`); add(row, "DmgKindId", "vehicle-hull-dmg-kind", `${prefix}.DmgKindId`);
for (const [j, cost] of asLookupRows(row.DmgSectionCosts).entries()) for (const [j, cost] of asLookupRows(row.DmgSectionCosts).entries())
@@ -103,11 +109,32 @@ export async function validateFanavaranHullLookupIds(
(row.IsActive == null || Number(row.IsActive) !== 0), (row.IsActive == null || Number(row.IsActive) !== 0),
) )
: undefined; : undefined;
if (!matched) if (!matched) {
warnings.push( // For AccidentCauseId: auto-correct to the fallback instead of only warning,
`${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response.`, // because سنهاب rejects unrecognised cause IDs with a hard error.
); if (field.key === "AccidentCauseId" && stage === "baseClaim") {
else field.row[field.key] = Number(matched.Id); const fallbackId = FANAVARAN_HULL_FALLBACK_ACCIDENT_CAUSE_ID;
const fallbackRow = sources
.get(field.lookup)
?.find(
(row) =>
row.Id != null &&
Number(row.Id) === fallbackId &&
row.IsActive !== false &&
(row.IsActive == null || Number(row.IsActive) !== 0),
);
field.row[field.key] = fallbackId;
warnings.push(
`${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response; replaced with fallback AccidentCauseId=${fallbackId}${fallbackRow ? ` («${fallbackRow.Caption ?? fallbackRow.Name ?? fallbackId}»)` : ""}.`,
);
} else {
warnings.push(
`${field.path}=${raw ?? "(missing)"} is not in the current ${field.lookup} API response.`,
);
}
} else {
field.row[field.key] = Number(matched.Id);
}
} }
return warnings; return warnings;
} }
@@ -9,13 +9,20 @@ import type { FanavaranClaimProduct } from "./fanavaran-claim-product";
/** /**
* Fanavaran dummy licence issue date when `person.driverLicenseDate` is missing. * Fanavaran dummy licence issue date when `person.driverLicenseDate` is missing.
* Kept recent so hull `IsLicenseReplaced` stays null (see 10-year rule). * Set well in the past (> 3 years) so the new IsLicenseReplaced logic does not
* force an explicit 0 answer for a missing date, and < 10 years so it stays null.
*/ */
export const FANAVARAN_DUMMY_LICENCE_ISSU_DATE = "1404/08/20"; export const FANAVARAN_DUMMY_LICENCE_ISSU_DATE = "1400/01/01";
/** Years since issue after which hull/third-party "licence replaced?" becomes yes (1). */ /** Years since issue after which hull/third-party "licence replaced?" becomes yes (1). */
export const FANAVARAN_LICENCE_REPLACED_AFTER_YEARS = 10; export const FANAVARAN_LICENCE_REPLACED_AFTER_YEARS = 10;
/**
* Years since issue below which Fanavaran requires an explicit 0/1 answer
* for IsLicenseReplaced (rule: GovahiTamdidiMustBeRequiredWhenGovahiSodurDateYearIsLessThreeRule).
*/
export const FANAVARAN_LICENCE_REPLACED_REQUIRED_WITHIN_YEARS = 3;
/** /**
* True when `issueDate` is more than `years` before `referenceDate` (Jalali). * True when `issueDate` is more than `years` before `referenceDate` (Jalali).
* Used for Fanavaran IsLicenseReplaced / IsLicenseReplacement. * Used for Fanavaran IsLicenseReplaced / IsLicenseReplacement.
@@ -40,20 +47,36 @@ export function isJalaliDateOlderThanYears(
/** /**
* Hull `IsLicenseReplaced` / ثالث `IsLicenseReplacement`: * Hull `IsLicenseReplaced` / ثالث `IsLicenseReplacement`:
* - licence issue more than 10 years before accident → `1` * - licence issued more than 10 years before accident → `1` (replaced)
* - otherwise → `null` (never send `0`) * - licence issued less than 3 years before accident → `0` (not replaced, but
* Fanavaran rule GovahiTamdidiMustBeRequiredWhenGovahiSodurDateYearIsLessThreeRule
* requires an explicit answer, never null)
* - 3–10 years → `null` (field is optional in this range)
*/ */
export function resolveFanavaranIsLicenseReplaced( export function resolveFanavaranIsLicenseReplaced(
licenceIssuDate: unknown, licenceIssuDate: unknown,
accidentDate: unknown, accidentDate: unknown,
): 1 | null { ): 1 | 0 | null {
return isJalaliDateOlderThanYears( if (
licenceIssuDate, isJalaliDateOlderThanYears(
accidentDate, licenceIssuDate,
FANAVARAN_LICENCE_REPLACED_AFTER_YEARS, accidentDate,
) FANAVARAN_LICENCE_REPLACED_AFTER_YEARS,
? 1 )
: null; ) {
return 1;
}
// Newer than 3 years: Fanavaran requires explicit 0.
if (
!isJalaliDateOlderThanYears(
licenceIssuDate,
accidentDate,
FANAVARAN_LICENCE_REPLACED_REQUIRED_WITHIN_YEARS,
)
) {
return 0;
}
return null;
} }
export type FanavaranRoleIdentity = { export type FanavaranRoleIdentity = {
@@ -8,7 +8,7 @@ export const MUTUAL_AGREEMENT_EXPERT_DECISION_FIELDS = {
accidentWay: { id: 8, label: "جلو به عقب" }, accidentWay: { id: 8, label: "جلو به عقب" },
accidentReason: { accidentReason: {
id: 1, id: 1,
fanavaran: 1, fanavaran: 6,
label: label:
"عدم رعايت فاصله مناسب با وسيله نقليه و يا عدم توجه به جلو", "عدم رعايت فاصله مناسب با وسيله نقليه و يا عدم توجه به جلو",
}, },