Files
yara724api/src/claim-request-management/claim-request-management.service.ts
T
2026-11-21 12:48:06 +03:30

12634 lines
433 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { UserClaimBranchService, usesUserClaimBranch } from "src/client/user-claim-branch.service";
import {
hasReviewedTejaratNotifier,
isTejaratNotifierLookup,
} from 'src/fanavaran/tejarat-notifier';
import {
BadRequestException,
BadGatewayException,
ConflictException,
ForbiddenException,
HttpException,
HttpStatus,
Injectable,
InternalServerErrorException,
Logger,
NotFoundException,
} from '@nestjs/common';
import { isAxiosError } from 'axios';
import { Types } from 'mongoose';
import { createReadStream, existsSync, openSync, readSync, closeSync, statSync } from 'node:fs';
import { basename, resolve } from 'node:path';
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 { ClaimCaseStatus } from 'src/Types&Enums/claim-request-management/claim-case-status.enum';
import { ClaimWorkflowStep } from 'src/Types&Enums/claim-request-management/claim-workflow-steps.enum';
import { ClaimStatus } from 'src/Types&Enums/claim-request-management/claimStatus.enum';
import { FactorStatus } from 'src/Types&Enums/claim-request-management/factor-status.enum';
import { ClaimRequiredDocumentType } from 'src/Types&Enums/claim-request-management/required-document-type.enum';
import { ReqClaimStatus } from 'src/Types&Enums/claim-request-management/status.enum';
import { ClaimStepsEnum } from 'src/Types&Enums/claim-request-management/steps.enum';
import { RoleEnum } from 'src/Types&Enums/role.enum';
import { AiService } from 'src/ai/ai.service';
import { BranchDbService } from 'src/client/entities/db-service/branch.db.service';
import { InquiryParticipantRole } from 'src/common/dto/inquiry-participants.dto';
import { ListQueryV2Dto } from 'src/common/dto/list-query-v2.dto';
import {
resolveFileMakerStageOneExpertId,
resolveFileReviewerExpertiseExpertId,
type StaffFanavaranExpertiseCodes,
type StaffFanavaranStageOneCodes,
} from 'src/fanavaran/fanavaran-file-role-expert-ids';
import {
extractFanavaranOriginalMessage,
toFanavaranHttpException,
} from 'src/fanavaran/fanavaran-http-exception';
import { FanavaranLocationService } from 'src/fanavaran/fanavaran-location.service';
import {
canUserCreateClaim,
resolveClaimBeneficiary,
} from 'src/helpers/blame-claim-eligibility';
import {
resolveClaimOwnerFieldsFromBlame,
resolveClaimOwnerParty,
resolveDamagedPartyRow,
resolveDamagedPartyUserId,
} from 'src/helpers/blame-damaged-party';
import {
canonicalizeClaimCarAngleKey,
getClaimCarAngleCaptureBlob,
getDamagedPartCaptureBlob,
hasClaimCarAngleCapture,
hasDamagedPartCapture,
legacyAngleDamagedPartFieldKeysToUnset,
type ClaimCarAngleKey,
} from 'src/helpers/claim-car-angle-media';
import { serializeDamagedPartSelectionHistory } from 'src/helpers/claim-damaged-part-audit';
import { buildClaimDetailsV2OwnerGuidance } from 'src/helpers/claim-details-v2-owner-guidance';
import {
canFinalizeExpertResend,
documentKeyAllowedForExpertResend,
mapExpertResendCarPartsForClient,
normalizeResendDocumentKeys,
normalizeResendPartKeys,
partKeyAllowedForExpertResend,
} from 'src/helpers/claim-expert-resend';
import {
claimCaseStatusAllowsOwnerFactorUploadDuringRevision,
claimCaseStatusAllowsOwnerInsurerSignStep,
classifyV2ExpertPricingParts,
getActiveV2ExpertReply,
objectionDisallowedDueToOutstandingFactorWorkflow,
} from 'src/helpers/claim-v2-expert-reply-workflow';
import { partyPersonMatchesUser } from 'src/helpers/iran-mobile';
import {
applyListQueryV2,
isInListDateRange,
parseListDateRange,
} from 'src/helpers/list-query-v2';
import {
carPartDamageLabelForFactorRecord,
catalogItemToSelectedPart,
catalogLikeKeyFromPart,
coerceDamagedPartsMediaToArray,
migrateExpertReplyCarPartDamageToUnified,
normalizeDamageSelectedParts,
parseCatalogPartIdInput,
partLookupKey,
resolvePartCaptureIndex,
type DamageSelectedPartV2,
} from 'src/helpers/outer-damage-parts';
import {
buildBlamePartyAccessOrConditions,
collectUserIdVariants,
} from 'src/helpers/party-access-queries';
import { toPublicListItems } from 'src/helpers/public-list-response';
import {
claimCaseInitiatedByFieldExpert,
assertClaimCaseForTenant,
} from 'src/helpers/tenant-scope';
import { resolveUnifiedFileStatus } from 'src/helpers/unified-file-status';
import { buildFileLink, resolveStoredFileUrl } from 'src/helpers/urlCreator';
import {
buildOwnerUserIdAccessFilter,
ownerUserIdMatchesActor,
resolveLinkedUserIdStrings,
} from 'src/helpers/user-access-resolver';
import { BlameRequestDbService } from 'src/request-management/entities/db-service/blame-request.db.service';
import { PartyRole } from 'src/request-management/entities/schema/partyRole.enum';
import { CreationMethod } from 'src/request-management/entities/schema/request-management.schema';
import type { InquiryParticipantRoleAssignments } from 'src/request-management/inquiry-participant-resolver';
import { participantForStoredPartyRole } from 'src/request-management/inquiry-participant-resolver';
import { SandHubService } from 'src/sand-hub/sand-hub.service';
import {
ClaimVehicleTypeV2,
FANAVARAN_CAR_PARTS_CATALOG,
OuterPartCatalogItem,
} from 'src/static/outer-car-parts-catalog';
import { DamageExpertDbService } from 'src/users/entities/db-service/damage-expert.db.service';
import { ExpertDbService } from 'src/users/entities/db-service/expert.db.service';
import { FieldExpertDbService } from 'src/users/entities/db-service/field-expert.db.service';
import { FileMakerDbService } from 'src/users/entities/db-service/file-maker.db.service';
import { FileReviewerDbService } from 'src/users/entities/db-service/file-reviewer.db.service';
import { UserDbService } from 'src/users/entities/db-service/user.db.service';
import { PlateNormalizerService } from 'src/utils/plate-normalizer/plate-normalizer.service';
import { normalizeMoneyAmountString } from 'src/utils/unicode-digits';
import {
CapturePartV2Dto,
CapturePartV2ResponseDto,
VideoCaptureV2ResponseDto,
} from './dto/capture-part-v2.dto';
import { GetCaptureRequirementsV2ResponseDto } from './dto/capture-requirements-v2.dto';
import { CarDamagePartDto } from './dto/car-part.dto';
import { ClaimDetailsV2ResponseDto } from './dto/claim-details-v2.dto';
import { CreateClaimFromBlameResponseDto } from './dto/create-claim-v2.dto';
import {
ClaimListItemV2Dto,
GetMyClaimsV2ResponseDto,
} from './dto/my-claims-v2.dto';
import {
SelectOtherPartsV2Dto,
SelectOtherPartsV2ResponseDto,
} from './dto/select-other-parts-v2.dto';
import { SelectOtherPartsV3Dto } from './dto/select-other-parts-v3.dto';
import {
OuterPartCatalogItemDto,
SelectOuterPartsV2Dto,
SelectOuterPartsV2ResponseDto,
} from './dto/select-outer-parts-v2.dto';
import {
UploadRequiredDocumentV2Dto,
UploadRequiredDocumentV2ResponseDto,
} from './dto/upload-document-v2.dto';
import { UserObjectionV2Dto } from './dto/user-objection-v2.dto';
import { UserRatingDto } from './dto/user-rating.dto';
import { ClaimCaseDbService } from './entites/db-service/claim-case.db.service';
import { ClaimRequestManagementDbService } from './entites/db-service/claim-request-management.db.service';
import { ClaimRequiredDocumentDbService } from './entites/db-service/claim-required-document.db.service';
import { ClaimSignDbService } from './entites/db-service/claim-sign.db.service';
import { ClaimFactorsImageDbService } from './entites/db-service/factor-image.db.service';
import { VideoCaptureDbService } from './entites/db-service/video-capture.db.service';
import { UserClaimRating } from './entites/schema/claim-request-management.schema';
import { ImageRequiredModel } from './entites/schema/image-required.schema';
import {
FANAVARAN_HULL_NO_DAMAGE_CASE_REASON,
fanavaranClaimProductFromBlameType,
fanavaranClaimsBaseUrl,
fanavaranClaimStageUrl,
fanavaranHasDamageCaseStage,
fanavaranInsuranceLineIdForProduct,
fanavaranPartyInquirySources,
isFanavaranSubmitSupportedBlameType,
pickCarBodyPolicyNationalCode,
pickStoredCarBodyPolicyId,
type FanavaranClaimProduct,
} from './fanavaran-claim-product';
import { fanavaranClaimReferences } from './fanavaran-claim-references';
import { fanavaranAttachmentStatus } from './fanavaran-attachment-status';
import {
actualPremiumFromHullPolicyRecord,
authorityCulpritIdFromDetectionRows,
FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION,
FANAVARAN_HULL_CULPRIT_TYPE_CAPTION,
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
fanavaranHullNestedClaimId,
toFanavaranHullBaseClaimPayload,
} from './fanavaran-hull-base-claim';
import { toTejaratV15ThirdPartyBasePayload } from './fanavaran-v15-third-party-base';
import {
collectFanavaranExpertiseReadinessWarnings,
FANAVARAN_DEFAULT_HULL_REPAIR_DURATION,
hullExpertiseAssertFields,
mergeHullVehicleIdentityFromFanavaranVehicle,
pickHullVehicleIdentity,
toFanavaranHullExpertiseDmgSection,
toFanavaranHullExpertisePayload,
vehicleCurrentValueFromHullPolicyRecord,
} from './fanavaran-hull-expertise';
import {
FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
FANAVARAN_HULL_DMG_KIND_CAPTION,
findLookupCaptionById,
findLookupIdByCaption,
findHullFactoryBundleAccessory,
asHullDmgAccessoryRows,
resolveHullDmgSectionAccessory,
} from './fanavaran-hull-expertise-lookups';
import {
validateFanavaranHullLookupIds,
type HullLookupStage,
} from './fanavaran-hull-lookup-validation';
import {
activeStageLookupRows,
applyFanavaranStageFieldReview,
fanavaranFieldStageSent,
fanavaranStageFields,
type FanavaranFieldValues,
} from './fanavaran-stage-fields';
import FormData = require('form-data');
import { HttpService } from '@nestjs/axios';
import { firstValueFrom } from 'rxjs';
import {
fanavaranSubmitPath,
getFanavaranLookupBaseUrl,
getFanavaranClientProfile,
resolveFanavaranClientKey,
resolveFanavaranProductContractId,
type FanavaranClientKey,
} from 'src/core/config/fanavaran-client.config';
import { buildEnrichedDamagedParts } from 'src/expert-claim/dto/claim-damaged-part.enricher';
import { FanavaranAuditService } from 'src/fanavaran/fanavaran-audit.service';
import type { FanavaranAuditSession } from 'src/fanavaran/fanavaran-audit.types';
import { FanavaranAuthService } from 'src/fanavaran/fanavaran-auth.service';
import { FANAVARAN_REMOTE_LOOKUPS } from 'src/fanavaran/fanavaran-lookup.config';
import { FanavaranLookupService } from 'src/fanavaran/fanavaran-lookup.service';
import {
FanavaranAuditSource,
FanavaranAuditStatus,
FanavaranAuditStep,
} from 'src/fanavaran/schema/fanavaran-audit-log.schema';
import {
CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS,
capturePhaseSequenceMessage,
getClaimCaptureProgress,
GUILTY_DAMAGE_AREA_DOC_KEY,
isCapturePhaseDamagedPartyDocKey,
isClaimCaptureStepComplete,
OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5,
} from 'src/helpers/claim-capture-phase';
import {
applyFanavaranManualPayloadOverrides,
asObjectRecord,
asVehicleInquiryRows,
collectPartyVinCandidates,
completePlaqueParts,
FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS,
FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS,
FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS,
fanavaranVehicleMatchesDamagedIdentity,
normalizeVin,
parseFanavaranId,
pickFanavaranPlaqueLookupFields,
pickFanavaranVehicleFromInquiry,
pickVehicleId,
pickVinFromPartyVehicle,
resolveDamageCasePlaqueLookupIds,
selectFanavaranVehicleForDamageCase,
type FanavaranDamagedVehicleIdentity,
} from 'src/lookups/fanavaran-last-car-policy';
import {
selectAccidentVehicleUsedId,
vehicleGroupIdForKind,
} from './fanavaran-accident-vehicle-used';
import {
asPartyInquiryRows,
collectPersonBirthdays,
collectPersonNationalCodes,
parseJalaliDateParts,
pickPersonBirthday,
pickPersonNationalCode,
selectFanavaranDriverId,
selectFanavaranOtherPersonId,
selectFanavaranOwnerId,
} from './fanavaran-driver-inquiry';
import {
buildFanavaranOtherPeoplePayload,
pickFanavaranRecordId,
} from './fanavaran-other-people';
import {
FANAVARAN_DUMMY_LICENCE_ISSU_DATE,
resolveDriverFromParty,
resolveDriverIsOwner,
resolveFanavaranIsLicenseReplaced,
resolveFanavaranLicenceIssuDate,
resolveFanavaranLicenceNo,
resolveOwnerFromParty,
resolvePolicyholderFromParty,
resolveThirdPartyCulpritTypeId,
} from './fanavaran-party-roles';
import {
selectLatestActiveFanavaranPolicy,
selectFanavaranPolicyForAccident,
} from './fanavaran-policy-selection';
export interface FanavaranAutoSubmitResult {
attempted: boolean;
submitted: boolean;
skipped?: boolean;
skipReason?: string;
warning?: string;
claimNo?: number;
claimId?: number;
fanavaranResponse?: unknown;
}
export interface FanavaranDamageCaseSubmitResult {
attempted: boolean;
submitted: boolean;
skipped?: boolean;
skipReason?: string;
warning?: string;
claimId?: number;
dmgCaseId?: number;
fanavaranResponse?: unknown;
}
export interface FanavaranAttachmentSubmitResult {
attempted: boolean;
submitted: boolean;
skipped?: boolean;
skipReason?: string;
warning?: string;
claimId?: number;
fileId?: number;
fileName?: string;
fanavaranResponse?: unknown;
}
export interface FanavaranExpertiseSubmitResult {
attempted: boolean;
submitted: boolean;
skipped?: boolean;
skipReason?: string;
warning?: string;
claimId?: number;
dmgCaseId?: number;
expertiseId?: number;
fanavaranResponse?: unknown;
}
interface FanavaranAttachmentCandidate {
path: string;
fileName: string;
source: string;
content: Record<string, unknown>;
alreadySubmitted: boolean;
/** Format rejected twice (or local invalid magic); treated as done for later stages. */
alreadyWaived?: boolean;
waivedReason?: string;
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 {
initiatedByFieldExpertId?: unknown;
evaluation?: object;
workflow?: { assignedForReviewBy?: { actorId?: unknown } };
}
/**
* Returns today's Jalali date as a packed integer YYYYMMDD for cheap comparison.
* Uses the browser/Node `fa-IR` locale which is available everywhere Node runs.
*/
function jalaliDateToInt(d: Date): number {
const parts = d
.toLocaleDateString('fa-IR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
})
.split('/')
.map((p) =>
parseInt(
p.replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0)),
10,
),
);
return parts[0] * 10000 + parts[1] * 100 + parts[2];
}
/**
* Parses a Jalali date string in "YYYY/MM/DD" or "YYYY-MM-DD" form to the same
* packed integer YYYYMMDD. Returns null when the string cannot be parsed.
*/
function jalaliStringToInt(raw: string): number | null {
const m = raw.match(/(\d{4})[\/\-](\d{1,2})[\/\-](\d{1,2})/);
if (!m) return null;
const y = parseInt(m[1], 10);
const mo = parseInt(m[2], 10);
const d = parseInt(m[3], 10);
if (!y || !mo || !d) return null;
return y * 10000 + mo * 100 + d;
}
const FANAVARAN_ACCIDENT_LOCATION_ADDRESS = 'استان تهران شهر تهران';
const FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID = 6;
const FANAVARAN_DEFAULT_ACCIDENT_LEVEL = 5456;
const FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT = 1000;
/**
* Fanavaran sometimes rejects missing/empty/whitespace licence numbers.
* We always send either the user-entered value (from DB) or this 10-digit dummy.
*/
const FANAVARAN_DUMMY_LICENCE_NO =
process.env.FANAVARAN_DUMMY_LICENCE_NO?.trim() || '9705463515';
/** Local carType → Fanavaran vehicle-kind Caption keywords for matching. */
const VEHICLE_KIND_KEYWORDS: Record<ClaimVehicleTypeV2, string[]> = {
[ClaimVehicleTypeV2.SEDAN]: ['سواری', 'سواري', 'sedan'],
[ClaimVehicleTypeV2.SUV]: ['شاسی', 'شاسي', 'suv', 'بلند'],
[ClaimVehicleTypeV2.HATCHBACK]: ['هاچبک', 'هاچ بک', 'hatchback'],
[ClaimVehicleTypeV2.PICKUP]: ['وانت', 'پیکاپ', 'pick', 'pickup'],
[ClaimVehicleTypeV2.VAN]: ['ون', 'van'],
};
const FANAVARAN_PLATE_LETTER_CODE: Record<string, number> = {
الف: 1,
ب: 2,
پ: 3,
ج: 4,
د: 5,
س: 6,
ص: 7,
ط: 8,
ع: 9,
ق: 10,
ل: 11,
م: 12,
ن: 13,
و: 14,
ه: 15,
ی: 16,
ک: 17,
ژ: 18,
ت: 19,
ث: 20,
ز: 21,
ش: 22,
ف: 23,
گ: 24,
};
@Injectable()
export class ClaimRequestManagementService {
private readonly logger = new Logger(ClaimRequestManagementService.name);
private readonly PARSIAN_FANAVARAN_CONFIG = {
appName: 'ParsianService',
secret: 'P@r30@n$erv!ce',
username: 'ParsianServiceUser',
password: 'P@r30@n123',
corpId: '543',
contractId: '28',
location: '110011',
} as const;
/** Tejaratno hardcoded Fanavaran lookup defaults (legacy fallback only; no expert ids). */
private readonly TEJARATNO_FANAVARAN_DEFAULTS = {
AccidentCityId: 701,
AccidentReportTypeId: 155,
AccidentVehicleUsedId: 1,
CompensationReferenceId: 167,
CulpritLicenceTypeId: 2,
CulpritTypeId: 337,
} as const;
/** In-process dedupe for scheduleFanavaranRetry timers. */
private readonly fanavaranRetryTimers = new Map<string, NodeJS.Timeout>();
/** Prevent concurrent auto/manual runs of the same claim stage. */
private readonly fanavaranInFlightStages = new Set<string>();
constructor(
private readonly claimDbService: ClaimRequestManagementDbService,
private readonly claimCaseDbService: ClaimCaseDbService,
private readonly blameRequestDbService: BlameRequestDbService,
private readonly userDbService: UserDbService,
private readonly videoCaptureDbService: VideoCaptureDbService,
private readonly claimSignDbService: ClaimSignDbService,
private readonly aiService: AiService,
private readonly claimRequestManagementDbService: ClaimRequestManagementDbService,
private readonly claimFactorsImageDbService: ClaimFactorsImageDbService,
private readonly branchDbService: BranchDbService,
private readonly userClaimBranchService: UserClaimBranchService,
private readonly claimRequiredDocumentDbService: ClaimRequiredDocumentDbService,
private readonly sandHubService: SandHubService,
private readonly httpService: HttpService,
private readonly fanavaranAuditService: FanavaranAuditService,
private readonly fanavaranAuthService: FanavaranAuthService,
private readonly fanavaranLookupService: FanavaranLookupService,
private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService,
private readonly fieldExpertDbService: FieldExpertDbService,
private readonly expertDbService: ExpertDbService,
private readonly damageExpertDbService: DamageExpertDbService,
private readonly plateNormalizer: PlateNormalizerService,
private readonly fanavaranLocationService: FanavaranLocationService,
) {}
private requiredDocumentKeysV2(isCarBody: boolean): string[] {
const damagedPartyKeys = [
'damaged_driving_license_front',
'damaged_driving_license_back',
'damaged_chassis_number',
'damaged_engine_photo',
'damaged_car_card_front',
'damaged_car_card_back',
'damaged_metal_plate',
];
if (isCarBody) return damagedPartyKeys;
return [
...damagedPartyKeys,
'guilty_driving_license_front',
'guilty_driving_license_back',
'guilty_car_card_front',
'guilty_car_card_back',
'guilty_metal_plate',
];
}
private isRequiredDocumentUploadedOnClaim(
claimCase: any,
key: string,
): boolean {
const doc =
(claimCase.requiredDocuments as any)?.get?.(key) ??
(claimCase.requiredDocuments as any)?.[key];
return !!doc?.uploaded;
}
private allV2OwnerDocumentsComplete(
claimCase: any,
isCarBody: boolean,
assumeUploadedKey?: string,
): boolean {
for (const k of this.requiredDocumentKeysV2(isCarBody)) {
const ok =
k === assumeUploadedKey
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, k);
if (!ok) return false;
}
if (isCarBody) {
const g = ClaimRequiredDocumentType.CAR_GREEN_CARD;
const okGreen =
assumeUploadedKey === g
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, g);
if (!okGreen) return false;
}
return true;
}
/** V3 initial document step — excludes capture-phase vehicle evidence. */
private v3PreCaptureDocumentKeys(isCarBody: boolean): string[] {
return this.requiredDocumentKeysV2(isCarBody).filter(
(k) => !isCapturePhaseDamagedPartyDocKey(k),
);
}
private allV3PreCaptureDocumentsComplete(
claimCase: any,
isCarBody: boolean,
assumeUploadedKey?: string,
skipMetalPlate?: boolean,
): boolean {
for (const k of this.v3PreCaptureDocumentKeys(isCarBody)) {
if (
skipMetalPlate &&
OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)
)
continue;
const ok =
k === assumeUploadedKey
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, k);
if (!ok) return false;
}
if (isCarBody) {
const g = ClaimRequiredDocumentType.CAR_GREEN_CARD;
const ok =
assumeUploadedKey === g
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, g);
if (!ok) return false;
}
return true;
}
private countRemainingV3PreCaptureDocuments(
claimCase: any,
isCarBody: boolean,
assumeUploadedKey?: string,
skipMetalPlate?: boolean,
): number {
let n = 0;
for (const k of this.v3PreCaptureDocumentKeys(isCarBody)) {
if (
skipMetalPlate &&
OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)
)
continue;
const ok =
k === assumeUploadedKey
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, k);
if (!ok) n++;
}
if (isCarBody) {
const g = ClaimRequiredDocumentType.CAR_GREEN_CARD;
const ok =
assumeUploadedKey === g
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, g);
if (!ok) n++;
}
return n;
}
private countRemainingV2OwnerDocuments(
claimCase: any,
isCarBody: boolean,
assumeUploadedKey?: string,
): number {
let n = 0;
for (const k of this.requiredDocumentKeysV2(isCarBody)) {
const ok =
k === assumeUploadedKey
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, k);
if (!ok) n++;
}
if (isCarBody) {
const g = ClaimRequiredDocumentType.CAR_GREEN_CARD;
const okGreen =
assumeUploadedKey === g
? true
: this.isRequiredDocumentUploadedOnClaim(claimCase, g);
if (!okGreen) n++;
}
return n;
}
private parsePlateFromCompactString(plateId: string | undefined): {
leftDigits: number;
centerAlphabet: string;
centerDigits: number;
ir: number;
} | null {
if (!plateId) return null;
const parts = String(plateId).split('-');
if (parts.length !== 4) return null;
const [irRaw, leftRaw, alphaRaw, centerRaw] = parts;
const ir = Number(irRaw);
const leftDigits = Number(leftRaw);
const centerDigits = Number(centerRaw);
const centerAlphabet = this.plateNormalizer.normalizePlateText(
String(alphaRaw || ''),
);
if (
!Number.isFinite(ir) ||
!Number.isFinite(leftDigits) ||
!Number.isFinite(centerDigits) ||
!centerAlphabet
) {
return null;
}
return { leftDigits, centerAlphabet, centerDigits, ir };
}
private resolveOwnershipPlateForClaim(
claimCase: any,
blameRequest?: any,
): {
leftDigits: number;
centerAlphabet: string;
centerDigits: number;
ir: number;
} | null {
const p = claimCase?.vehicle?.plate;
if (
p &&
Number.isFinite(Number(p.leftDigits)) &&
Number.isFinite(Number(p.centerDigits)) &&
Number.isFinite(Number(p.ir)) &&
this.plateNormalizer.normalizePlateText(String(p.centerAlphabet || ''))
) {
return {
leftDigits: Number(p.leftDigits),
centerAlphabet: this.plateNormalizer.normalizePlateText(
String(p.centerAlphabet),
),
centerDigits: Number(p.centerDigits),
ir: Number(p.ir),
};
}
if (!blameRequest || !Array.isArray(blameRequest.parties)) return null;
const ownerUserId = claimCase?.owner?.userId?.toString?.();
const matchedParty =
blameRequest.parties.find(
(party: any) =>
String(party?.person?.userId || '') === String(ownerUserId || ''),
) ||
blameRequest.parties.find(
(party: any) => party?.role === PartyRole.FIRST,
);
const compactPlateId = matchedParty?.vehicle?.plateId;
return this.parsePlateFromCompactString(compactPlateId);
}
private resolveVehicleOwnerNationalCodeForClaim(
blameRequest: any,
): string | undefined {
const damagedParty = resolveDamagedPartyRow(blameRequest as any);
const owner = damagedParty
? participantForStoredPartyRole(
damagedParty as any,
InquiryParticipantRole.VEHICLE_OWNER,
)
: undefined;
const nationalCode = String(owner?.nationalCode ?? '').trim();
return nationalCode || undefined;
}
/**
* Outer-parts catalog returned to clients (user app + expert panel).
*
* Fetches the live `car/base-info/car-components` lookup from Fanavaran so
* the list always matches what Fanavaran accepts in DmgSections[].DmgSectionId.
* The lookup service handles caching to disk; `carType` is ignored because
* Fanavaran uses a single flat catalog across all vehicle types.
*/
async getOuterPartsCatalogV2(): Promise<OuterPartCatalogItemDto[]> {
const clientKey = resolveFanavaranClientKey();
const rows = await this.getFanavaranLookupRows(clientKey, 'car-components');
// Build today's Jalali date as a comparable integer (YYYYMMDD) so we can
// filter expired rows without any Jalali→Gregorian conversion risk.
const todayJalaliInt = jalaliDateToInt(new Date());
return rows
.filter(
(r): r is { Id: number; Caption: string } =>
!!r &&
typeof r === 'object' &&
typeof (r as any).Id === 'number' &&
typeof (r as any).Caption === 'string',
)
.filter((r) => {
const toDate = (r as any).ToDate;
if (!toDate) return true;
const toDateInt = jalaliStringToInt(String(toDate));
if (toDateInt === null) return true;
return toDateInt >= todayJalaliInt;
})
.map((r) => ({ id: r.Id, label_fa: r.Caption }));
}
/**
* Resolve the live Fanavaran car-components catalog as `OuterPartCatalogItem`
* rows for internal use (e.g. validating selectedPartIds).
* Falls back to the static snapshot when the remote lookup is unavailable.
*/
private async getLiveFanavaranCatalogItems(): Promise<
OuterPartCatalogItem[]
> {
const clientKey = resolveFanavaranClientKey();
const rows = await this.getFanavaranLookupRows(clientKey, 'car-components');
if (!rows.length) {
this.logger.warn(
'getLiveFanavaranCatalogItems: remote lookup returned empty, falling back to snapshot',
);
return FANAVARAN_CAR_PARTS_CATALOG;
}
return rows
.filter(
(r): r is { Id: number; Caption: string } =>
!!r &&
typeof r === 'object' &&
typeof (r as any).Id === 'number' &&
typeof (r as any).Caption === 'string',
)
.map(
(r): OuterPartCatalogItem => ({
id: r.Id,
key: String(r.Id),
titleFa: r.Caption,
side: '',
}),
);
}
private findTrueItems(userPartSelect: CarDamagePartDto) {
const trueItems = [];
for (const side in userPartSelect) {
for (const parts in userPartSelect[side]) {
if (userPartSelect[side][parts] === true) {
trueItems.push({ side, part: parts });
}
}
}
return trueItems;
}
/** One section of CarDamagePartDto: either a single object or an array of objects (legacy). */
private carPartDamageSectionToRows(
section: unknown,
): Record<string, unknown>[] {
if (section == null) return [];
if (Array.isArray(section)) {
return section.filter(
(row): row is Record<string, unknown> =>
!!row && typeof row === 'object',
);
}
if (typeof section === 'object') {
return [section as Record<string, unknown>];
}
return [];
}
private carPartDamageSectionHasTrue(section: unknown): boolean {
for (const row of this.carPartDamageSectionToRows(section)) {
for (const val of Object.values(row)) {
if (val === true) return true;
}
}
return false;
}
/**
* At most two of left, right, front, back may contain any damaged part (true).
* `top` and claim `otherParts` are not subject to this rule.
*/
private assertCarPartDamageAtMostTwoOfFourSides(dto: CarDamagePartDto): void {
const d = dto as unknown as Record<string, unknown>;
const quadrants = [
{ key: 'left', section: d.left },
{ key: 'right', section: d.right },
{ key: 'front', section: d.front },
{ key: 'back', section: d.back },
];
const used = quadrants.filter((q) =>
this.carPartDamageSectionHasTrue(q.section),
);
if (used.length > 2) {
throw new BadRequestException(
`At most two of the four sides (left, right, front, back) may include damaged parts. ` +
`Sides with selections: ${used.map((u) => u.key).join(', ')}.`,
);
}
}
/**
* Maps legacy expert CarDamagePartDto (nested booleans) to v2 outer part slugs (ClaimCase.damage.selectedParts).
*/
private carDamagePartDtoToOuterPartSlugs(dto: CarDamagePartDto): string[] {
const out = new Set<string>();
const add = (slug: string | undefined) => {
if (slug) out.add(slug);
};
const walkMainOnSide = (
side: 'left' | 'right',
items: unknown,
map: Record<string, string>,
) => {
for (const row of this.carPartDamageSectionToRows(items)) {
for (const [key, val] of Object.entries(row)) {
if (val !== true) continue;
const slug = map[`${side}_${key}`] ?? map[key];
add(slug);
}
}
};
// MainParts on left / right (side-specific door / fender)
walkMainOnSide('left', (dto as any).left, {
left_frontDoor: 'front_left_door',
left_backDoor: 'rear_left_door',
left_frontFender: 'front_left_fender',
left_backFender: 'rear_left_fender',
frontDoor: 'front_left_door',
backDoor: 'rear_left_door',
frontFender: 'front_left_fender',
backFender: 'rear_left_fender',
});
walkMainOnSide('right', (dto as any).right, {
right_frontDoor: 'front_right_door',
right_backDoor: 'rear_right_door',
right_frontFender: 'front_right_fender',
right_backFender: 'rear_right_fender',
frontDoor: 'front_right_door',
backDoor: 'rear_right_door',
frontFender: 'front_right_fender',
backFender: 'rear_right_fender',
});
const walkSimple = (items: unknown, keyToSlug: Record<string, string>) => {
for (const row of this.carPartDamageSectionToRows(items)) {
for (const [key, val] of Object.entries(row)) {
if (val === true) add(keyToSlug[key]);
}
}
};
walkSimple((dto as any).front, {
frontBumper: 'front_bumper',
carHood: 'hood',
});
walkSimple((dto as any).back, {
backBumper: 'rear_bumper',
carTrunk: 'trunk',
});
walkSimple((dto as any).top, {
roof: 'roof',
});
return Array.from(out);
}
/** Normalize expert DTO otherParts (strings or legacy { label: true }[]) to string[]. */
private normalizeExpertOtherPartsInput(raw: any[] | undefined): string[] {
if (!raw || !Array.isArray(raw)) return [];
const out: string[] = [];
for (const item of raw) {
if (typeof item === 'string' && item.trim()) {
out.push(item.trim());
continue;
}
if (item && typeof item === 'object') {
for (const [k, v] of Object.entries(item)) {
if (v === true && k) out.push(k);
}
}
}
return out;
}
private async assertFieldExpertInPersonBlameForClaimCase(
claimCase: any,
expert: any,
): Promise<void> {
const blameRequestId = claimCase?.blameRequestId?.toString?.();
if (!blameRequestId) {
throw new BadRequestException('Claim case has no linked blame request.');
}
const blameRequest =
await this.blameRequestDbService.findById(blameRequestId);
if (!blameRequest) {
throw new NotFoundException('Blame request not found for this claim.');
}
if (
!blameRequest.expertInitiated ||
blameRequest.creationMethod !== CreationMethod.IN_PERSON
) {
throw new BadRequestException(
'This endpoint is only for expert-initiated IN_PERSON claim files.',
);
}
if (!blameRequest.initiatedByFieldExpertId) {
throw new BadRequestException(
'Blame request is missing initiating field expert.',
);
}
if (String(blameRequest.initiatedByFieldExpertId) !== String(expert.sub)) {
throw new ForbiddenException(
'Only the initiating field expert can complete claim data for this file.',
);
}
}
async setCarPartDamageAndImage(cl, trueItems) {
cl.carPartDamage = trueItems;
const jsonTrueItems = JSON.parse(JSON.stringify(trueItems));
cl.imageRequired = new ImageRequiredModel(jsonTrueItems);
cl.save();
return cl.imageRequired;
}
/**
* Field expert completes claim-needed data for expert-initiated IN_PERSON files.
* Only the initiating field expert can call this. Accepts car part damage and/or sheba, nationalCodeOfInsurer, otherParts.
*
* V2: Resolves `ClaimCase` in `claimCases` collection (workflow). Legacy v1 claim documents are still supported.
*/
async expertCompleteClaimData(
claimRequestId: string,
expert: any,
dto: {
selectedPartIds?: number[];
carPartDamage?: CarDamagePartDto;
sheba?: string;
nationalCodeOfInsurer?: string;
otherParts?: any[];
},
): Promise<{ success: boolean; claimRequestId: string }> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (claimCase) {
return this.expertCompleteClaimDataForClaimCaseV2(
claimRequestId,
expert,
dto,
claimCase,
);
}
const claim = await this.claimDbService.findOne(claimRequestId);
if (!claim) {
throw new NotFoundException('Claim file not found');
}
const blameFile = claim.blameFile as any;
if (
!blameFile?.expertInitiated ||
blameFile?.creationMethod !== 'IN_PERSON'
) {
throw new BadRequestException(
'This endpoint is only for expert-initiated IN_PERSON claim files.',
);
}
if (String(blameFile.initiatedBy) !== expert.sub) {
throw new ForbiddenException(
'Only the initiating field expert can complete claim data for this file.',
);
}
if (dto.selectedPartIds?.length || dto.carPartDamage) {
if (claim.carPartDamage && (claim.carPartDamage as any[]).length > 0) {
throw new BadRequestException('Car part damage is already set.');
}
let trueItems: Array<Record<string, unknown>>;
if (dto.selectedPartIds?.length) {
const liveCatalog = await this.getLiveFanavaranCatalogItems();
const byId = new Map<number, OuterPartCatalogItem>(
liveCatalog.map((part) => [part.id, part]),
);
trueItems = dto.selectedPartIds.map((id) => {
const item = byId.get(id);
if (!item) {
throw new BadRequestException(
`Invalid outer part id: ${id}. Use GET outer-parts-catalog to see valid IDs.`,
);
}
return {
side: item.side || 'carDamage',
part: item.titleFa,
id: item.id,
label_fa: item.titleFa,
};
});
} else {
this.assertCarPartDamageAtMostTwoOfFourSides(dto.carPartDamage!);
trueItems = this.findTrueItems(dto.carPartDamage!);
}
const claimDoc = (await this.claimDbService.findOne(
claimRequestId,
)) as any;
if (claimDoc) {
await this.setCarPartDamageAndImage(claimDoc, trueItems);
}
await this.claimDbService.findAndUpdate(claimRequestId, {
currentStep: ClaimStepsEnum.SelectDamagePart,
nextStep: ClaimStepsEnum.SelectOtherParts,
$push: { steps: ClaimStepsEnum.SelectDamagePart },
});
}
const updates: Record<string, any> = {};
if (dto.sheba != null) updates.sheba = dto.sheba;
if (dto.nationalCodeOfInsurer != null)
updates.nationalCodeOfInsurer = dto.nationalCodeOfInsurer;
if (dto.otherParts != null) updates.otherParts = dto.otherParts;
if (Object.keys(updates).length > 0) {
await this.claimDbService.findAndUpdate(claimRequestId, {
$set: updates,
});
}
return { success: true, claimRequestId };
}
/**
* V2 ClaimCase: outer parts + optional bank/other parts (expert-initiated IN_PERSON only).
*/
private async expertCompleteClaimDataForClaimCaseV2(
claimRequestId: string,
expert: any,
dto: {
selectedPartIds?: number[];
carPartDamage?: CarDamagePartDto;
sheba?: string;
nationalCodeOfInsurer?: string;
otherParts?: any[];
},
claimCase: any,
): Promise<{ success: boolean; claimRequestId: string }> {
await this.assertFieldExpertInPersonBlameForClaimCase(claimCase, expert);
let working = claimCase;
if (dto.selectedPartIds?.length || dto.carPartDamage) {
if (
working.workflow?.currentStep !== ClaimWorkflowStep.SELECT_OUTER_PARTS
) {
throw new BadRequestException(
`Cannot set outer parts: workflow step must be ${ClaimWorkflowStep.SELECT_OUTER_PARTS}. Current: ${working.workflow?.currentStep}`,
);
}
if (
working.damage?.selectedParts &&
working.damage.selectedParts.length > 0
) {
throw new BadRequestException('Car part damage is already set.');
}
let selectedPartObjs: DamageSelectedPartV2[];
if (dto.selectedPartIds?.length) {
const liveCatalog = await this.getLiveFanavaranCatalogItems();
const byId = new Map<number, OuterPartCatalogItem>(
liveCatalog.map((part) => [part.id, part]),
);
const selectedItems = dto.selectedPartIds.map((id) => {
const item = byId.get(id);
if (!item) {
throw new BadRequestException(
`Invalid outer part id: ${id}. Use GET outer-parts-catalog to see valid IDs.`,
);
}
return item;
});
selectedPartObjs = selectedItems.map((part) =>
catalogItemToSelectedPart(part, liveCatalog),
);
} else {
// Backward compatibility for older expert-panel clients.
this.assertCarPartDamageAtMostTwoOfFourSides(dto.carPartDamage!);
const selectedSlugStrings = this.carDamagePartDtoToOuterPartSlugs(
dto.carPartDamage!,
);
if (!selectedSlugStrings.length) {
throw new BadRequestException(
'No outer damaged parts could be derived from carPartDamage. Check part selections.',
);
}
selectedPartObjs = normalizeDamageSelectedParts(
selectedSlugStrings,
working.vehicle?.carType as ClaimVehicleTypeV2 | undefined,
undefined,
);
}
const damagedPartsStubs = selectedPartObjs.map((p) => ({
id: p.id ?? undefined,
name: p.name,
side: p.side,
label_fa: p.label_fa,
...(p.catalogKey ? { catalogKey: p.catalogKey } : {}),
}));
const updated = await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
{
'damage.selectedParts': selectedPartObjs,
'media.damagedParts': damagedPartsStubs,
status: ClaimCaseStatus.SELECTING_OTHER_PARTS,
'workflow.currentStep': ClaimWorkflowStep.SELECT_OTHER_PARTS,
'workflow.nextStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
$push: {
'workflow.completedSteps': ClaimWorkflowStep.SELECT_OUTER_PARTS,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(expert.sub),
actorName:
`${expert.firstName || ''} ${expert.lastName || ''}`.trim() ||
'field_expert',
actorType: 'field_expert',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.SELECT_OUTER_PARTS,
selectedParts: selectedPartObjs,
description: 'Field expert submitted outer damage parts',
},
},
},
},
);
if (!updated) {
throw new InternalServerErrorException('Failed to update claim case');
}
working = updated;
}
const hasBankOrOther =
dto.sheba != null ||
dto.nationalCodeOfInsurer != null ||
dto.otherParts != null;
if (hasBankOrOther) {
const fresh = await this.claimCaseDbService.findById(claimRequestId);
if (!fresh) throw new NotFoundException('Claim case not found');
if (
fresh.workflow?.currentStep !== ClaimWorkflowStep.SELECT_OTHER_PARTS
) {
throw new BadRequestException(
`Bank/other parts can only be set at ${ClaimWorkflowStep.SELECT_OTHER_PARTS}. Current: ${fresh.workflow?.currentStep}`,
);
}
const mergedSheba = dto.sheba != null ? dto.sheba : fresh.money?.sheba;
const mergedNational =
dto.nationalCodeOfInsurer != null
? dto.nationalCodeOfInsurer
: fresh.money?.nationalCodeOfInsurer;
if (
fresh.money?.sheba &&
dto.sheba != null &&
dto.sheba !== fresh.money.sheba
) {
throw new ConflictException('Sheba is already set for this claim.');
}
if (
fresh.money?.nationalCodeOfInsurer &&
dto.nationalCodeOfInsurer != null &&
dto.nationalCodeOfInsurer !== fresh.money.nationalCodeOfInsurer
) {
throw new ConflictException(
'National code of insurer is already set for this claim.',
);
}
const otherPartsArr = this.normalizeExpertOtherPartsInput(dto.otherParts);
const setPatch: Record<string, unknown> = {};
if (dto.sheba != null) setPatch['money.sheba'] = dto.sheba;
if (dto.nationalCodeOfInsurer != null) {
setPatch['money.nationalCodeOfInsurer'] = dto.nationalCodeOfInsurer;
}
if (dto.otherParts != null) {
setPatch['damage.otherParts'] =
otherPartsArr.length > 0 ? otherPartsArr : [];
}
const bankComplete =
mergedSheba &&
mergedNational &&
/^[0-9]{24}$/.test(String(mergedSheba).replace(/\s/g, '')) &&
/^[0-9]{10}$/.test(String(mergedNational).replace(/\s/g, ''));
if (bankComplete) {
const shebaNorm = String(mergedSheba).replace(/\s/g, '');
const nationalNorm = String(mergedNational).replace(/\s/g, '');
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
'money.sheba': shebaNorm,
'money.nationalCodeOfInsurer': nationalNorm,
...(dto.otherParts != null
? {
'damage.otherParts':
otherPartsArr.length > 0 ? otherPartsArr : [],
}
: {}),
status: ClaimCaseStatus.CAPTURING_PART_DAMAGES,
'workflow.currentStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
'workflow.nextStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
$push: {
'workflow.completedSteps': ClaimWorkflowStep.SELECT_OTHER_PARTS,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(expert.sub),
actorName:
`${expert.firstName || ''} ${expert.lastName || ''}`.trim() ||
'field_expert',
actorType: 'field_expert',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.SELECT_OTHER_PARTS,
description:
'Field expert submitted bank info and optional other parts',
},
},
},
});
} else {
if (Object.keys(setPatch).length === 0) {
throw new BadRequestException(
'Provide sheba (24 digits) and nationalCodeOfInsurer (10 digits) together to finish this step, or supply partial fields incrementally.',
);
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: setPatch,
});
}
}
return { success: true, claimRequestId };
}
private async createVideoCapture(fileDetail: any, requestId: string) {
const videoId = await this.videoCaptureDbService.create({
path: fileDetail.path,
filName: fileDetail.filename,
claimId: new Types.ObjectId(requestId),
});
return videoId;
}
/**
* V2 response mapper:
* - convert factorLink ObjectId -> public URL
* - enrich legacy daghi.branchId with branchName when available
*/
private async mapEvaluationForClient(
evaluation: any,
carType?: ClaimVehicleTypeV2,
): Promise<any | undefined> {
if (!evaluation) return undefined;
const mapReply = async (reply: any) => {
if (!reply) return reply;
const mapped = {
...(typeof reply?.toObject === 'function' ? reply.toObject() : reply),
};
const parts = Array.isArray(mapped.parts) ? mapped.parts : [];
const factorIds = new Set<string>();
const branchIds = new Set<string>();
for (const p of parts) {
if (p?.factorLink && Types.ObjectId.isValid(String(p.factorLink))) {
factorIds.add(String(p.factorLink));
}
const daghi = p?.daghi;
const rawBranchId =
daghi && typeof daghi === 'object'
? (daghi as any).branchId
: undefined;
if (rawBranchId && Types.ObjectId.isValid(String(rawBranchId))) {
branchIds.add(String(rawBranchId));
}
}
const factorMap = new Map<string, string>();
await Promise.all(
Array.from(factorIds).map(async (id) => {
const factorDoc = await this.claimFactorsImageDbService.findById(id);
if (factorDoc?.path) {
factorMap.set(id, buildFileLink(factorDoc.path));
}
}),
);
const branchMap = new Map<string, string>();
await Promise.all(
Array.from(branchIds).map(async (id) => {
const branch = await this.branchDbService.findById(id);
if (branch?.name) {
branchMap.set(id, branch.name);
}
}),
);
mapped.parts = parts.map((part: any) => {
const nextPart = { ...part };
if (
nextPart.factorLink &&
Types.ObjectId.isValid(String(nextPart.factorLink))
) {
const link = factorMap.get(String(nextPart.factorLink));
if (link) nextPart.factorLink = link;
}
const daghi = nextPart.daghi;
if (daghi && typeof daghi === 'object' && !Array.isArray(daghi)) {
const branchId = (daghi as any).branchId;
const branchName =
branchId && Types.ObjectId.isValid(String(branchId))
? branchMap.get(String(branchId))
: undefined;
nextPart.daghi = {
...daghi,
...(branchName ? { branchName } : {}),
};
}
if (nextPart.carPartDamage != null) {
nextPart.carPartDamage = migrateExpertReplyCarPartDamageToUnified(
nextPart.carPartDamage,
carType,
);
}
return nextPart;
});
return mapped;
};
// Resolve objection invoice paths to downloadable URLs (user-side view).
const objectionRaw = evaluation.objection;
let objection: any = objectionRaw
? typeof objectionRaw?.toObject === 'function'
? objectionRaw.toObject()
: { ...objectionRaw }
: undefined;
if (
objection &&
Array.isArray(objection.invoices) &&
objection.invoices.length > 0
) {
objection = {
...objection,
invoices: objection.invoices.map((inv: any) => ({
...inv,
url: inv.path ? buildFileLink(inv.path) : undefined,
})),
};
}
return {
...evaluation,
damageExpertReply: await mapReply(evaluation.damageExpertReply),
damageExpertReplyFinal: await mapReply(evaluation.damageExpertReplyFinal),
...(objection !== undefined ? { objection } : {}),
};
}
/**
* V2: Upload repair factor file for a part marked `factorNeeded` on the expert reply (ClaimCase).
* Same behavior as v1 {@link uploadClaimFactor} but uses `evaluation.damageExpertReply` / `damageExpertReplyFinal`.
*/
async uploadClaimFactorV2(
claimRequestId: string,
partId: string,
file: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
) {
try {
if (!file) {
throw new BadRequestException('A factor file is required for upload.');
}
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException('Claim not found');
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claim,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claim,
effectiveUserId,
actor as { username?: string },
'You do not have access to this claim file',
);
const replyKey = claim.evaluation?.damageExpertReplyFinal
? 'damageExpertReplyFinal'
: 'damageExpertReply';
const finalReply =
replyKey === 'damageExpertReplyFinal'
? claim.evaluation?.damageExpertReplyFinal
: claim.evaluation?.damageExpertReply;
if (!finalReply?.parts?.length) {
throw new BadRequestException('No expert reply found in this claim.');
}
const part = finalReply.parts.find(
(p) => String(p.partId) === String(partId),
);
if (!part) {
throw new BadRequestException(
"The specified part was not found in the expert's reply.",
);
}
if (!part.factorNeeded) {
throw new BadRequestException(
'This part does not require a factor upload.',
);
}
if (part.factorLink) {
throw new ConflictException(
'A factor has already been uploaded for this part.',
);
}
if (!claimCaseStatusAllowsOwnerFactorUploadDuringRevision(claim.status)) {
throw new BadRequestException(
'Factors can only be uploaded while the claim is in a repair-factor upload phase (see ClaimCaseStatus).',
);
}
if (claim.claimStatus !== ClaimStatus.NEEDS_REVISION) {
throw new BadRequestException(
'Factors can only be uploaded while the claim needs owner action (claimStatus NEEDS_REVISION).',
);
}
if (
claim.workflow?.currentStep !==
ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS
) {
throw new BadRequestException(
`Repair factors are uploaded at workflow step ${ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS} (after accepting priced lines when applicable). Current: ${String(claim.workflow?.currentStep ?? '')}.`,
);
}
const flowParts = finalReply.parts ?? [];
const pricingShape = classifyV2ExpertPricingParts(flowParts);
if (
pricingShape.mixedFactorAndPrice &&
!claim.evaluation?.ownerPricedPartsApproval?.signedAt
) {
throw new BadRequestException(
'Sign acceptance of the priced repair lines first (`PUT .../owner-insurer-approval/sign` while claimStatus is NEEDS_REVISION at INSURER_REVIEW), then upload factors for factor-needed parts.',
);
}
const partNameForRecord =
carPartDamageLabelForFactorRecord(part.carPartDamage) ||
String(part.partId ?? '');
const factorRecord = await this.claimFactorsImageDbService.create({
claimId: new Types.ObjectId(claimRequestId),
partId: String(partId),
partName: partNameForRecord,
path: file.path,
fileName: file.filename,
uploadedAt: new Date(),
});
const pathPrefix = `evaluation.${replyKey}.parts`;
const updatedClaim = await this.claimCaseDbService.findOneAndUpdate(
{
_id: new Types.ObjectId(claimRequestId),
[`${pathPrefix}.partId`]: partId,
},
{
$set: {
[`${pathPrefix}.$.factorLink`]: factorRecord._id,
[`${pathPrefix}.$.factorStatus`]: FactorStatus.PENDING,
},
},
);
if (!updatedClaim) {
throw new NotFoundException(
'Could not find the specific part to update in the database.',
);
}
await this.checkAndTransitionStatusAfterFactorUploadV2(claimRequestId);
return {
message: 'Factor uploaded successfully. Awaiting expert validation.',
factorId: factorRecord._id,
url: buildFileLink(file.path),
};
} catch (error) {
this.logger.error(
`Error during V2 factor upload for claim ${claimRequestId}:`,
error instanceof Error ? error.stack : String(error),
);
if (error instanceof HttpException) {
throw error;
}
throw new HttpException(
'An internal server error occurred during factor upload.',
HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
/**
* When every `factorNeeded` part on the active expert reply has a `factorLink`, move claim toward expert validation (v1: PendingFactorValidation).
*/
private async checkAndTransitionStatusAfterFactorUploadV2(
claimRequestId: string,
): Promise<void> {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim?.evaluation) {
return;
}
const finalReply =
claim.evaluation.damageExpertReplyFinal ||
claim.evaluation.damageExpertReply;
if (!finalReply?.parts) {
return;
}
const requiredFactorParts = finalReply.parts.filter(
(p) => p.factorNeeded === true,
);
if (requiredFactorParts.length === 0) {
return;
}
const allFactorsAreUploaded = requiredFactorParts.every(
(p) => !!p.factorLink,
);
if (!allFactorsAreUploaded) {
return;
}
this.logger.log(
`All required factors for claim case ${claimRequestId} are uploaded (V2). Setting claim status for validation.`,
);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS,
claimStatus: ClaimStatus.UNDER_REVIEW,
'workflow.currentStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION,
'workflow.nextStep': ClaimWorkflowStep.INSURER_REVIEW,
},
$push: {
history: {
type: 'ALL_FACTORS_UPLOADED_PENDING_VALIDATION',
timestamp: new Date(),
metadata: { claimRequestId },
},
},
});
}
private async resendCarParts(claimFile, query, file) {
if (!Object.keys(query).includes('partId')) {
throw new HttpException(
'use resendCarParts query string',
HttpStatus.BAD_REQUEST,
);
}
if (!Object.keys(query).includes('side')) {
throw new HttpException(
'side is required for car parts',
HttpStatus.BAD_REQUEST,
);
}
const fileRequired = claimFile.damageExpertResend.resendCarParts.map(
(r) => r.partId,
);
if (!fileRequired.includes(query.partId)) {
throw new HttpException('wrong required file', HttpStatus.BAD_REQUEST);
}
try {
const fileEntry = {
[query.partId]: {
link: buildFileLink(file.path),
side: query.side,
},
};
const updated = await this.claimRequestManagementDbService.findAndUpdate(
String(claimFile._id),
{ $push: { 'userResendDocuments.carParts': fileEntry } },
{ new: true },
);
const existingKeys = updated.userResendDocuments.carParts.flatMap(
Object.keys,
);
const allExist = fileRequired.every((key) => existingKeys.includes(key));
if (allExist) {
await this.claimRequestManagementDbService.findAndUpdate(
String(claimFile._id),
{ $set: { claimStatus: ReqClaimStatus.CheckAgain } },
);
}
return {
allExist,
updated: updated.userResendDocuments.carParts,
fileRequired,
};
} catch (err) {
this.logger.error(err);
return new HttpException(
err instanceof HttpException ? err.message : String(err),
err instanceof HttpException
? err.getStatus()
: HttpStatus.INTERNAL_SERVER_ERROR,
);
}
}
async retrieveInsuranceBranches(insuranceId: string) {
return await this.branchDbService.findAll(insuranceId);
}
/**
* Convert Gregorian date to Persian date format (1404/08/13)
*/
private convertToPersianDate(date: Date | string): string {
const d = new Date(date);
const persianDate = new Date(d).toLocaleDateString('fa-IR', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
// Convert Persian digits to English and format as YYYY/MM/DD
const persianToEnglish: { [key: string]: string } = {
'۰': '0',
'۱': '1',
'۲': '2',
'۳': '3',
'۴': '4',
'۵': '5',
'۶': '6',
'۷': '7',
'۸': '8',
'۹': '9',
};
return persianDate
.split('/')
.map((part) =>
part
.split('')
.map((char) => persianToEnglish[char] || char)
.join(''),
)
.join('/');
}
/**
* Get time in 24-hour format (HH:mm) from date
*/
private getTime24Hour(date: Date | string): string {
const d = new Date(date);
const hours = d.getHours().toString().padStart(2, '0');
const minutes = d.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
}
/**
* Calculate EstimateAmount from damageExpertReply parts
*/
private calculateEstimateAmount(parts: any[]): number {
if (!parts || !Array.isArray(parts) || parts.length === 0) {
return 0;
}
return parts.reduce((sum, part) => {
const totalPayment = part.totalPayment
? parseFloat(part.totalPayment.toString())
: 0;
return sum + (isNaN(totalPayment) ? 0 : totalPayment);
}, 0);
}
private normalizeFanavaranEstimateAmount(amount: number): number {
return amount > 0 ? amount : FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT;
}
/**
* Extract digits-only licence number from a possibly-null/empty value.
* Returns `null` when the value is "null", "undefined", "", '' or whitespace.
*/
private extractNonEmptyLicenceDigits(value: unknown): string | null {
if (value === null || value === undefined) return null;
const asString = typeof value === 'number' ? String(value) : String(value);
const trimmed = asString.trim();
if (!trimmed) return null;
const lowered = trimmed.toLowerCase();
if (lowered === 'null' || lowered === 'undefined') return null;
const digits = trimmed.replace(/[^\d]/g, '');
return digits ? digits : null;
}
/**
* Resolve licence number to send to Fanavaran.
* Preference order:
* - driver participant / person.driverLicense (and insurerLicense as legacy)
* - else the configured 10-digit dummy
*/
private resolveFanavaranLicenceNoFromParty(input: {
driverIsInsurer?: boolean;
driverLicense?: unknown;
insurerLicense?: unknown;
/** Optional already-resolved digits from participants. */
resolvedLicenseNo?: string | null;
}): string {
const fromResolved = this.extractNonEmptyLicenceDigits(
input.resolvedLicenseNo,
);
if (fromResolved) return fromResolved;
const { driverLicense, insurerLicense } = input;
for (const c of [driverLicense, insurerLicense]) {
const digits = this.extractNonEmptyLicenceDigits(c);
if (digits) return digits;
}
return FANAVARAN_DUMMY_LICENCE_NO;
}
/** Last-resort sanitization for payload values coming from manual overrides. */
private ensureFanavaranNonEmptyLicenceNo(value: unknown): string {
return (
this.extractNonEmptyLicenceDigits(value) ?? FANAVARAN_DUMMY_LICENCE_NO
);
}
private applyFanavaranDefaultFields(result: Record<string, unknown>): void {
result.ActualPremium = null;
result.ArchiveNo = null;
result.AuthorityCulpritId = null;
result.AccidentCulpritId = null;
result.ClaimCompletionDate = null;
result.CostSeparationToDmgSections = null;
result.CouponNo = null;
result.CourtArchiveNo = null;
result.CustomerFaultPercent = null;
result.CulpritLicenceCityId = null;
result.CulpritLicenceCountryId = null;
result.CulpritLicenceForeignCityName = null;
// Overwritten later from person.driverLicenseDate when present.
result.CulpritLicenceIssuDate = FANAVARAN_DUMMY_LICENCE_ISSU_DATE;
// Must never be empty/null.
result.CulpritLicenceNo = FANAVARAN_DUMMY_LICENCE_NO;
result.DamagedCount = 1;
result.DmgAssessorFirstCreationTime = null;
result.EntryDate = null;
result.GlassBreakReasonId = null;
result.IsLicenseMatchWithVehicleKind = 1;
result.HasOtherCulprit = 0;
result.IsAccidentOutOfBorder = 0;
result.IsFatalAccident = 0;
result.IsOwnerChanged = null;
result.IsPlaqueChanged = 0;
result.IsSurplusArticleEighthLaw = null;
result.PlaqueCityId = null;
result.PlaqueKindId = null;
result.PlaqueLeftNo = null;
result.PlaqueMiddleCodeId = null;
result.PlaqueNo = null;
result.PlaqueRightNo = null;
result.PlaqueSampleId = null;
result.PlaqueSerial = null;
result.PoliceOfficerId = 1;
result.PoliceReportDesc = 'شرح گزارش';
result.PoliceReportSeri = null;
result.PoliceReportSerial = null;
result.PolicyId = null;
result.PreviousPolicyEndDate = '';
result.StatusChangeDate = null;
result.TrackingCode = null;
// ثالث field name; hull remaps to IsLicenseReplaced. Filled after licence date.
result.IsLicenseReplacement = null;
result.UnknownCulpritCauseId = null;
}
private async buildFanavaranSubmitPayload(input: {
accidentReason?: { id?: string | number | null; fanavaran?: number | null };
createdAt?: Date | string;
location?: { lat?: number; lon?: number; address?: string };
damageParts?: any[];
resolvePolicyId: () => Promise<number | null>;
logPrefix: string;
/** When false, missing PolicyId is left null (preview-only). Default true. */
requirePolicyId?: boolean;
defaults?: {
AccidentCityId: number;
AccidentReportTypeId: number;
AccidentVehicleUsedId: number;
CompensationReferenceId: number;
CulpritLicenceTypeId: number;
CulpritTypeId: number;
};
}): Promise<Record<string, unknown>> {
const lookupDefaults =
input.defaults ??
this.fanavaranPayloadDefaultsWithoutExpertIds(
this.TEJARATNO_FANAVARAN_DEFAULTS as unknown as Record<string, unknown>,
);
const accidentCauseFromCase = Number(input.accidentReason?.fanavaran);
const result: Record<string, unknown> = {
...lookupDefaults,
AccidentCauseId:
Number.isFinite(accidentCauseFromCase) && accidentCauseFromCase > 0
? accidentCauseFromCase
: FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID,
};
if (!input.accidentReason) {
this.logger.error(
`${input.logPrefix} expert decision / accidentReason is missing`,
);
}
if (input.createdAt) {
result.AccidentDate = this.convertToPersianDate(input.createdAt);
result.AnnouncementDate = result.AccidentDate;
result.DocReceivedDate = result.AccidentDate;
result.AccidentTime = this.getTime24Hour(input.createdAt);
}
result.AccidentLocationAddress = input.location?.address?.trim() || FANAVARAN_ACCIDENT_LOCATION_ADDRESS;
result.EstimateAmount = this.normalizeFanavaranEstimateAmount(
input.damageParts ? this.calculateEstimateAmount(input.damageParts) : 0,
);
this.applyFanavaranDefaultFields(result);
const policyId = await input.resolvePolicyId();
if (
(policyId === undefined || policyId === null) &&
input.requirePolicyId !== false
) {
throw new BadRequestException(
`${input.logPrefix} PolicyId is required for Fanavaran submit. Policy inquiry returned no valid policy; contact the administrator.`,
);
}
result.PolicyId = policyId ?? null;
return result;
}
private formatFanavaranSelectedPartsDesc(selectedParts: unknown[]): string {
const labels = selectedParts
.map((part) => {
if (typeof part === 'string') return part;
if (part && typeof part === 'object') {
const p = part as {
label_fa?: unknown;
titleFa?: unknown;
name?: unknown;
catalogKey?: unknown;
};
return p.label_fa ?? p.titleFa ?? p.name ?? p.catalogKey;
}
return null;
})
.filter(
(label): label is string => typeof label === 'string' && !!label.trim(),
)
.map((label) => label.trim());
return labels.length ? labels.join('/') : 'موارد آسیب دیده خودرو';
}
private getFanavaranPlateMiddleCode(
centerAlphabet?: string | number | null,
): number | null {
if (centerAlphabet == null) return null;
const raw = String(centerAlphabet).trim();
if (!raw) return null;
const normalized = this.plateNormalizer.normalizePlateText(raw);
const asNumber = Number(normalized);
if (Number.isFinite(asNumber)) return asNumber;
return this.plateNormalizer.resolvePlateLetterCode(
normalized,
FANAVARAN_PLATE_LETTER_CODE,
);
}
private formatFanavaranPlateNo(
plate: {
leftDigits: number;
centerAlphabet: string;
centerDigits: number;
ir: number;
} | null,
): string | null {
if (!plate) return null;
return `${plate.centerDigits}${plate.centerAlphabet}${plate.leftDigits}`;
}
/** First non-empty string from party vehicle.inquiry mapped/raw (ESG + Tejarat aliases). */
private pickPartyInquiryField(
mapped: Record<string, any> | null | undefined,
raw: Record<string, any> | null | undefined,
keys: string[],
): string | null {
for (const key of keys) {
const value = mapped?.[key] ?? raw?.[key];
if (value == null) continue;
const text = String(value).trim();
if (text) return text;
}
return null;
}
private resolvePlateFromPartyInquiry(
mapped: Record<string, any> | null | undefined,
raw: Record<string, any> | null | undefined,
): {
leftDigits: number;
centerAlphabet: string;
centerDigits: number;
ir: number;
} | null {
const left = this.pickPartyInquiryField(mapped, raw, ['plk1', 'Plk1']);
const middle = this.pickPartyInquiryField(mapped, raw, ['plk2', 'Plk2']);
const right = this.pickPartyInquiryField(mapped, raw, ['plk3', 'Plk3']);
const serial = this.pickPartyInquiryField(mapped, raw, [
'plksrl',
'PlkSrl',
]);
if (!left || !middle || !right || !serial) return null;
const leftDigits = Number(left);
const centerDigits = Number(right);
const ir = Number(serial);
const centerAlphabet = this.plateNormalizer.normalizePlateText(middle);
if (
!Number.isFinite(leftDigits) ||
!Number.isFinite(centerDigits) ||
!Number.isFinite(ir) ||
!centerAlphabet
) {
return null;
}
return { leftDigits, centerAlphabet, centerDigits, ir };
}
private async resolveVehicleKindId(
clientKey: FanavaranClientKey,
carType?: string,
): Promise<number | null> {
if (!carType) return null;
const vehicleType = carType as ClaimVehicleTypeV2;
const keywords = VEHICLE_KIND_KEYWORDS[vehicleType];
if (!keywords) return null;
try {
const lookup = this.fanavaranLookupService;
const definition = FANAVARAN_REMOTE_LOOKUPS.find(
(l) => l.name === 'vehicle-kinds',
);
if (!definition) return null;
const data = (await lookup.getRemoteLookup(
clientKey,
definition.url,
definition.cacheFile,
)) as Array<{ Id?: number; Caption?: string; IsActive?: number }>;
if (!Array.isArray(data)) return null;
const normalizedKeywords = keywords.map((k) => k.toLowerCase());
const match = data.find((item) => {
if (!item.Caption || item.IsActive === 0) return false;
const caption = item.Caption.toLowerCase();
return normalizedKeywords.some((kw) => caption.includes(kw));
});
return match?.Id ?? null;
} catch {
this.logger.warn(
`Failed to resolve VehicleKindId for carType=${carType}`,
);
return null;
}
}
private async resolveAccidentVehicleUsedFromVehicleKind(
clientKey: FanavaranClientKey,
vehicleKindId: number | null,
preferredId: number | null,
): Promise<number | null> {
if (vehicleKindId == null) return preferredId;
try {
const [kinds, useTypes] = await Promise.all([
this.getFanavaranLookupRows(clientKey, 'vehicle-kinds'),
this.getFanavaranLookupRows(clientKey, 'vehicle-use-types'),
]);
const groupId = vehicleGroupIdForKind(kinds, vehicleKindId);
const usedId = selectAccidentVehicleUsedId(
useTypes,
groupId,
preferredId,
);
this.logger.log(
`Resolved AccidentVehicleUsedId=${usedId} from VehicleKindId=${vehicleKindId} VehicleGroupId=${groupId ?? 'none'} (UsedId=${preferredId ?? 'none'})`,
);
return usedId;
} catch (error) {
this.logger.warn(
`Failed to resolve AccidentVehicleUsedId from VehicleKindId=${vehicleKindId}: ${
error instanceof Error ? error.message : error
}`,
);
return preferredId;
}
}
/**
* GEN.03 lookup-filter: AccidentVehicleUsedId comes from Fanavaran vehicle
* UsedId (VIN inquiry or vehicle GET), not Mongo tenant defaults.
*/
private async resolveAccidentVehicleUsedFromVehicleRecord(
clientKey: FanavaranClientKey,
vehicle: Record<string, unknown> | null,
): Promise<{ usedId: number | null; vehicleKindId: number | null }> {
const vehicleKindId = parseFanavaranId(vehicle?.VehicleKindId);
const vehicleUsedId = parseFanavaranId(vehicle?.UsedId);
const usedId = await this.resolveAccidentVehicleUsedFromVehicleKind(
clientKey,
vehicleKindId,
vehicleUsedId,
);
return { usedId, vehicleKindId };
}
private async resolveAccidentVehicleUsedFromVin(
clientKey: FanavaranClientKey,
vin: string,
vehicleId?: number | null,
): Promise<{ usedId: number | null; vehicleKindId: number | null }> {
try {
const vehicle = await this.fetchFanavaranVehicleByVin(
clientKey,
vin,
vehicleId,
);
if (!vehicle) {
this.logger.warn(`VIN inquiry for ${vin} returned no vehicle`);
return { usedId: null, vehicleKindId: null };
}
this.logger.log(
`VIN inquiry ${vin} VehicleId=${pickVehicleId(vehicle) ?? 'none'} VehicleKindId=${parseFanavaranId(vehicle.VehicleKindId) ?? 'none'} UsedId=${parseFanavaranId(vehicle.UsedId) ?? 'none'} PlaqueKindId=${parseFanavaranId(vehicle.PlaqueKindId) ?? 'none'}`,
);
return this.resolveAccidentVehicleUsedFromVehicleRecord(
clientKey,
vehicle,
);
} catch (error) {
this.logger.warn(
`Failed to resolve AccidentVehicleUsedId from VIN=${vin}: ${
error instanceof Error ? error.message : error
}`,
);
return { usedId: null, vehicleKindId: null };
}
}
private async fetchFanavaranVehicleByVin(
clientKey: FanavaranClientKey,
vin: string,
vehicleId?: number | null,
): Promise<Record<string, unknown> | null> {
const inquired = await this.fanavaranLookupService.inquiryByVin(
clientKey,
vin,
);
return pickFanavaranVehicleFromInquiry(inquired, vehicleId);
}
/**
* Damaged-car VIN inquiry: keep only rows that match VIN/plate/chassis.
* Then GET that VehicleId so PlaqueKindId is the current version, not a
* leftover row that merely had some PlaqueKindId.
*/
private async fetchFanavaranVehicleByVinCandidates(
clientKey: FanavaranClientKey,
vins: string[],
identity: FanavaranDamagedVehicleIdentity,
product: FanavaranClaimProduct = 'third-party',
): Promise<Record<string, unknown> | null> {
const requestOptions = {
contractIdOverride: resolveFanavaranProductContractId(clientKey, product),
};
let matched: Record<string, unknown> | null = null;
for (const vin of vins) {
try {
const inquired = await this.fanavaranLookupService.inquiryByVin(
clientKey,
vin,
requestOptions,
);
const rows = asVehicleInquiryRows(inquired);
if (rows.length === 0) {
this.logger.warn(
`[buildFanavaranDamageCasePayload] VIN inquiry for ${vin} returned no vehicle`,
);
continue;
}
const selected = selectFanavaranVehicleForDamageCase(rows, identity);
if (!selected) {
this.logger.warn(
`[buildFanavaranDamageCasePayload] VIN inquiry ${vin} returned ${rows.length} row(s) but none matched damaged VIN/plate/chassis`,
);
continue;
}
const plaqueKindId = pickFanavaranPlaqueLookupFields(selected).kindId;
this.logger.log(
`[buildFanavaranDamageCasePayload] VIN inquiry ${vin} matched VehicleId=${pickVehicleId(selected) ?? 'none'} VehicleKindId=${parseFanavaranId(selected.VehicleKindId) ?? 'none'} UsedId=${parseFanavaranId(selected.UsedId) ?? 'none'} PlaqueKindId=${plaqueKindId ?? 'none'} VersionNo=${parseFanavaranId(selected.VersionNo) ?? 'none'}`,
);
matched = selected;
break;
} catch (error) {
this.logger.warn(
`[buildFanavaranDamageCasePayload] VIN inquiry failed for ${vin}: ${
error instanceof Error ? error.message : error
}`,
);
}
}
if (!matched) return null;
const vehicleId = pickVehicleId(matched);
const versionNo = parseFanavaranId(matched.VersionNo);
if (vehicleId == null) return matched;
try {
const fetched = asObjectRecord(
await this.fanavaranLookupService.vehicleById(
clientKey,
vehicleId,
versionNo ?? undefined,
requestOptions,
),
);
if (
fetched &&
fanavaranVehicleMatchesDamagedIdentity(fetched, identity)
) {
this.logger.log(
`[buildFanavaranDamageCasePayload] vehicle GET ${vehicleId} confirmed identity PlaqueKindId=${pickFanavaranPlaqueLookupFields(fetched).kindId ?? 'none'} VehicleKindId=${parseFanavaranId(fetched.VehicleKindId) ?? 'none'}`,
);
return fetched;
}
if (fetched) {
this.logger.warn(
`[buildFanavaranDamageCasePayload] vehicle GET ${vehicleId} did not match damaged identity; keeping VIN-inquiry row`,
);
}
} catch (error) {
this.logger.warn(
`[buildFanavaranDamageCasePayload] vehicle GET failed for VehicleId=${vehicleId}: ${
error instanceof Error ? error.message : error
}`,
);
}
return matched;
}
/**
* Fallback when VIN is missing: policy GET → vehicle GET → UsedId/VehicleKindId.
*/
private async resolveAccidentVehicleUsedFromPolicy(
clientKey: FanavaranClientKey,
policyId: number,
product: FanavaranClaimProduct = 'third-party',
): Promise<{ usedId: number | null; vehicleKindId: number | null }> {
try {
const requestOptions = {
contractIdOverride: resolveFanavaranProductContractId(
clientKey,
product,
),
};
const policy = asObjectRecord(
product === 'car-body'
? await this.fanavaranLookupService.bodyPolicyById(
clientKey,
policyId,
requestOptions,
)
: await this.fanavaranLookupService.thirdPartyPolicyById(
clientKey,
policyId,
requestOptions,
),
);
const vehicleId = pickVehicleId(policy?.VehicleId ?? policy?.vehicleId);
if (vehicleId === null) {
this.logger.warn(`Policy ${policyId} has no VehicleId`);
return { usedId: null, vehicleKindId: null };
}
const versionNo = parseFanavaranId(policy?.VehicleVersionNo);
const vehicle = asObjectRecord(
await this.fanavaranLookupService.vehicleById(
clientKey,
vehicleId,
versionNo ?? undefined,
requestOptions,
),
);
this.logger.log(
`Policy ${policyId} VehicleId=${vehicleId} version=${versionNo ?? 'latest'} VehicleKindId=${parseFanavaranId(vehicle?.VehicleKindId) ?? 'none'} UsedId=${parseFanavaranId(vehicle?.UsedId) ?? 'none'}`,
);
if (product === 'car-body') {
// The hull claim belongs to this policy's exact vehicle version.
// A generic lookup's first/personal row is not an inquiry result.
return {
usedId: parseFanavaranId(vehicle?.UsedId),
vehicleKindId: parseFanavaranId(vehicle?.VehicleKindId),
};
}
return this.resolveAccidentVehicleUsedFromVehicleRecord(
clientKey,
vehicle,
);
} catch (error) {
this.logger.warn(
`Failed to resolve AccidentVehicleUsedId from PolicyId=${policyId}: ${
error instanceof Error ? error.message : error
}`,
);
return { usedId: null, vehicleKindId: null };
}
}
private async resolveAccidentVehicleUsedFromApis(input: {
clientKey: FanavaranClientKey;
parties: unknown[];
guiltyPartyId?: unknown;
policyId?: number | null;
product?: FanavaranClaimProduct;
}): Promise<{
usedId: number | null;
vehicleKindId: number | null;
source: 'vin-inquiry' | 'policy-vehicle' | null;
}> {
if (input.product === 'car-body') {
if (typeof input.policyId !== 'number') {
return { usedId: null, vehicleKindId: null, source: null };
}
const resolved = await this.resolveAccidentVehicleUsedFromPolicy(
input.clientKey,
input.policyId,
'car-body',
);
return {
...resolved,
source: resolved.usedId == null ? null : 'policy-vehicle',
};
}
const guiltyParty = (input.parties ?? []).find(
(party: any) =>
String(party?.person?.userId ?? '') ===
String(input.guiltyPartyId ?? ''),
);
const vin = pickVinFromPartyVehicle(guiltyParty);
if (vin) {
const fromVin = await this.resolveAccidentVehicleUsedFromVin(
input.clientKey,
vin,
);
if (fromVin.usedId != null) {
return { ...fromVin, source: 'vin-inquiry' };
}
}
if (typeof input.policyId === 'number') {
const fromPolicy = await this.resolveAccidentVehicleUsedFromPolicy(
input.clientKey,
input.policyId,
input.product ?? 'third-party',
);
if (fromPolicy.usedId != null) {
return { ...fromPolicy, source: 'policy-vehicle' };
}
}
return { usedId: null, vehicleKindId: null, source: null };
}
private parseJalaliBirthday(
birthday: string | number | Record<string, unknown> | null | undefined,
): { year: number; month: number; day: number } | null {
return parseJalaliDateParts(birthday);
}
private async tejaratNotifierAllowedIds(
clientKey: FanavaranClientKey,
): Promise<{ types: number[]; relations: number[] }> {
const [types, relations] = await Promise.all([
this.getFanavaranLookupRows(clientKey, 'notifier-type'),
this.getFanavaranLookupRows(clientKey, 'notifier-relation'),
]);
const ids = (rows: unknown[]) =>
rows
.map((row) => Number((row as { Id?: unknown })?.Id))
.filter((id) => Number.isInteger(id) && id > 0);
return { types: ids(types), relations: ids(relations) };
}
/**
* V15 GEN.03 announcer: guilty insurer, RoleId 161 then 166.
* Missing people are registered with GEN.44 (mobile comes from the user profile).
*/
private async resolveTejaratNotifierPartyId(input: {
clientKey: FanavaranClientKey;
blameCase: {
parties?: Array<{ person?: any }>;
expert?: { decision?: { guiltyPartyId?: unknown } };
};
claimCaseId?: string;
}): Promise<number | null> {
const parties = input.blameCase.parties ?? [];
const guiltyPartyId = this.resolveGuiltyPartyIdV2(
parties as any,
input.blameCase.expert?.decision?.guiltyPartyId as any,
);
const guilty = parties.find(
(party) =>
String(party?.person?.userId ?? '') === String(guiltyPartyId ?? ''),
);
const person = guilty?.person;
const nationalCode =
pickPersonNationalCode(person) ??
this.getNationalCodeOfInsurerForGuiltyPartyV2(
parties as any,
guiltyPartyId as any,
);
const birthday = pickPersonBirthday(person);
const existing = await this.resolveDriverFanavaranId(
input.clientKey,
nationalCode,
birthday,
true,
);
if (existing != null) return existing;
if (!person) return null;
return this.registerFanavaranOtherPerson({
clientKey: input.clientKey,
person,
claimCaseId: input.claimCaseId,
});
}
private async resolveDriverFanavaranId(
clientKey: FanavaranClientKey,
nationalCode: string | null | undefined,
driverBirthday: string | number | null | undefined,
driverIsInsurer: boolean | undefined,
): Promise<number | null> {
if (!nationalCode) {
this.logger.warn(
`[resolveDriverFanavaranId] SKIP: no nationalCode provided`,
);
return null;
}
const parsed = this.parseJalaliBirthday(driverBirthday);
if (!parsed) {
this.logger.warn(
`[resolveDriverFanavaranId] SKIP: could not parse driverBirthday "${driverBirthday}" for nationalCode=${nationalCode}`,
);
return null;
}
const targetRoleId = driverIsInsurer ? 161 : 166;
this.logger.log(
`[resolveDriverFanavaranId] QUERYING Fanavaran: nationalCode=${nationalCode} birthday=${parsed.year}/${parsed.month}/${parsed.day} driverIsInsurer=${driverIsInsurer} targetRoleId=${targetRoleId}`,
);
try {
const response =
await this.fanavaranLookupService.inquiryByUniqueIdentifier(clientKey, {
nationalCode,
birthYear: parsed.year,
birthMonth: parsed.month,
birthDay: parsed.day,
});
this.logger.log(
`[resolveDriverFanavaranId] RESPONSE: ${JSON.stringify(response)}`,
);
const driverId = selectFanavaranDriverId(response, driverIsInsurer);
if (driverId != null) {
const rows = asPartyInquiryRows(response);
const match = rows.find((row) => Number(row.Id) === driverId);
this.logger.log(
`[resolveDriverFanavaranId] MATCH: Id=${driverId} RoleId=${match?.RoleId ?? 'none'} name=${match?.Name ?? ''} ${match?.LastName ?? ''} for nationalCode=${nationalCode}`,
);
return driverId;
}
this.logger.warn(
`[resolveDriverFanavaranId] NO acceptable RoleId 161/166 for nationalCode=${nationalCode} driverIsInsurer=${driverIsInsurer}. ` +
`Available entries: ${asPartyInquiryRows(response)
.map(
(e) =>
`{Id=${e.Id}, RoleId=${e.RoleId}, Name=${e.Name} ${e.LastName}}`,
)
.join('; ')} — submit will register GEN.44 other-people`,
);
return null;
} catch (error) {
this.logger.error(
`[resolveDriverFanavaranId] API ERROR for nationalCode=${nationalCode}: ${error instanceof Error ? error.message : JSON.stringify(error)}`,
);
return null;
}
}
/** Best-effort OwnerId from parties inquiry (RoleId 161/166 only; GEN.44 on submit). */
private async resolveOwnerFanavaranId(
clientKey: FanavaranClientKey,
nationalCode: string | null | undefined,
birthday: string | number | null | undefined,
): Promise<number | null> {
if (!nationalCode) return null;
const parsed = this.parseJalaliBirthday(birthday);
if (!parsed) return null;
try {
const response =
await this.fanavaranLookupService.inquiryByUniqueIdentifier(clientKey, {
nationalCode,
birthYear: parsed.year,
birthMonth: parsed.month,
birthDay: parsed.day,
});
const ownerId = selectFanavaranOwnerId(response);
if (ownerId != null) {
this.logger.log(
`[resolveOwnerFanavaranId] MATCH: Id=${ownerId} for nationalCode=${nationalCode}`,
);
return ownerId;
}
this.logger.warn(
`[resolveOwnerFanavaranId] NO acceptable RoleId 161/166 for nationalCode=${nationalCode}. ` +
`Available: ${asPartyInquiryRows(response)
.map((e) => `{Id=${e.Id}, RoleId=${e.RoleId}}`)
.join('; ')} — submit will register GEN.44 other-people`,
);
return null;
} catch (error) {
this.logger.warn(
`[resolveOwnerFanavaranId] inquiry failed for nationalCode=${nationalCode}: ${
error instanceof Error ? error.message : error
}`,
);
return null;
}
}
/** Resolve the actual hull driver as سایر; policyholder membership alone is insufficient. */
private async resolveHullDriverFanavaranId(input: {
clientKey: FanavaranClientKey;
person: any;
claimCaseId?: string;
registerMissingDriver?: boolean;
cachedRegistration?: {
otherPersonId?: number;
otherPersonNationalCode?: string;
otherPersonBirthday?: string;
};
}): Promise<number | null> {
const nationalCode = pickPersonNationalCode(input.person);
const birthday = pickPersonBirthday(input.person);
const parsed = parseJalaliDateParts(birthday);
if (!nationalCode || !parsed) return null;
const birthdayKey = `${parsed.year}/${parsed.month}/${parsed.day}`;
const inquire = () =>
this.fanavaranLookupService.inquiryByUniqueIdentifier(input.clientKey, {
nationalCode,
birthYear: parsed.year,
birthMonth: parsed.month,
birthDay: parsed.day,
});
// Failed inquiry is not evidence that a role is missing: never create blindly.
let rows: unknown;
try {
rows = await inquire();
} catch (error) {
this.logger.warn(
`[hull driver] Person inquiry unavailable: ${error instanceof Error ? error.message : String(error)}`,
);
return null;
}
const existingId = selectFanavaranOtherPersonId(rows);
if (existingId != null) return existingId;
if (!input.registerMissingDriver) return null;
const cached = input.cachedRegistration;
if (
cached?.otherPersonId &&
cached.otherPersonNationalCode === nationalCode &&
cached.otherPersonBirthday === birthdayKey
) {
// GEN.44 already succeeded. Wait for the role to become visible instead of duplicating it.
return null;
}
const registeredId = await this.registerFanavaranOtherPerson({
clientKey: input.clientKey,
person: input.person,
claimCaseId: input.claimCaseId,
requiredRoleId: 166,
});
if (registeredId == null) return null;
if (input.claimCaseId) {
await this.claimCaseDbService.findByIdAndUpdate(input.claimCaseId, {
$set: {
'fanavaranSync.baseClaim.otherPersonId': registeredId,
'fanavaranSync.baseClaim.otherPersonNationalCode': nationalCode,
'fanavaranSync.baseClaim.otherPersonBirthday': birthdayKey,
},
});
}
try {
return selectFanavaranOtherPersonId(await inquire());
} catch (error) {
this.logger.warn(
`[hull driver] Registration awaits role-166 verification: ${error instanceof Error ? error.message : String(error)}`,
);
return null;
}
}
/** GEN.03 hull: TotalPremium + parties inquiry (AccidentCulpritId) before hull field whitelist. */
private async enrichCarBodyHullBaseClaimPayload(input: {
clientKey: FanavaranClientKey;
payload: Record<string, unknown>;
blameCase: { parties?: unknown[] };
/** Blame `Party` row (FIRST party for CAR_BODY); person shape is read via pickPerson* helpers. */
firstParty?: { person?: unknown };
logPrefix: string;
claimCaseId?: string;
registerMissingDriver?: boolean;
cachedRegistration?: {
otherPersonId?: number;
otherPersonNationalCode?: string;
otherPersonBirthday?: string;
};
}): Promise<void> {
const policyId = parseFanavaranId(input.payload.PolicyId);
if (policyId == null) return;
let policyRecord: Record<string, unknown> | null = null;
try {
policyRecord = asObjectRecord(
await this.fanavaranLookupService.bodyPolicyById(
input.clientKey,
policyId,
{
contractIdOverride: resolveFanavaranProductContractId(
input.clientKey,
'car-body',
),
},
),
);
} catch (error) {
this.logger.warn(
`${input.logPrefix} hull base claim body policy GET ${policyId} failed: ${
error instanceof Error ? error.message : error
}`,
);
}
const actualPremium = actualPremiumFromHullPolicyRecord(policyRecord);
if (actualPremium != null) {
input.payload.ActualPremium = actualPremium;
}
const vehicleValue = vehicleCurrentValueFromHullPolicyRecord(policyRecord);
if (vehicleValue != null && input.claimCaseId) {
await this.claimCaseDbService.findByIdAndUpdate(input.claimCaseId, {
$set: { 'vehicle.carPrice': vehicleValue },
});
}
const person = input.firstParty?.person as
| {
driverIsInsurer?: boolean;
nationalCodeOfDriver?: unknown;
nationalCodeOfInsurer?: unknown;
nationalCode?: unknown;
birthday?: unknown;
driverBirthday?: unknown;
insurerBirthday?: unknown;
}
| undefined;
const driverIdentity = resolveDriverFromParty(input.firstParty as any);
const nationalCode =
driverIdentity.nationalCode ??
(person?.driverIsInsurer ? pickPersonNationalCode(person) : null);
const birthday =
driverIdentity.birthday ??
(person?.driverIsInsurer ? pickPersonBirthday(person) : null);
// Always use the actual driver identity; CustomerId identifies the policyholder.
input.payload.AccidentCulpritId = await this.resolveHullDriverFanavaranId({
clientKey: input.clientKey,
person: {
...person,
nationalCodeOfDriver: nationalCode,
nationalCodeOfInsurer: undefined,
nationalCode,
driverBirthday: birthday,
insurerBirthday: undefined,
birthday,
driverIsInsurer: false,
},
claimCaseId: input.claimCaseId,
registerMissingDriver: input.registerMissingDriver,
cachedRegistration: input.cachedRegistration,
});
input.payload.CulpritLicenceNo = resolveFanavaranLicenceNo(
driverIdentity,
FANAVARAN_DUMMY_LICENCE_NO,
);
input.payload.CulpritLicenceIssuDate =
resolveFanavaranLicenceIssuDate(driverIdentity);
const licenseReplaced = resolveFanavaranIsLicenseReplaced(
input.payload.CulpritLicenceIssuDate,
input.payload.AccidentDate,
);
input.payload.IsLicenseReplaced = licenseReplaced;
input.payload.IsLicenseReplacement = licenseReplaced;
input.payload.CustomerFaultPercent =
FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT;
const [accidentTypes, culpritTypes, authorities] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-types', true),
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-accident-culprit-type', true),
this.getFanavaranLookupRows(input.clientKey, 'detection-accident-culprits', true),
]);
input.payload.AccidentTypeId ??= findLookupIdByCaption(accidentTypes, FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION);
if (input.payload.CulpritTypeId == null || input.payload.CulpritTypeId === 337)
input.payload.CulpritTypeId = findLookupIdByCaption(culpritTypes, FANAVARAN_HULL_CULPRIT_TYPE_CAPTION);
input.payload.AuthorityCulpritId ??= authorityCulpritIdFromDetectionRows(authorities);
}
/** GEN.06: VehicleCurrentValue from hull policy when price-drop / frontend value is missing. */
private async resolveHullVehicleCurrentValueFromPolicy(
clientKey: FanavaranClientKey,
claimCase: {
fanavaranSync?: {
baseClaim?: {
policyId?: unknown;
lastPayload?: { PolicyId?: unknown };
};
};
},
): Promise<number | null> {
const policyId = parseFanavaranId(
claimCase?.fanavaranSync?.baseClaim?.policyId ??
claimCase?.fanavaranSync?.baseClaim?.lastPayload?.PolicyId,
);
if (policyId == null) return null;
try {
const policy = asObjectRecord(
await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId, {
contractIdOverride: resolveFanavaranProductContractId(
clientKey,
'car-body',
),
}),
);
return vehicleCurrentValueFromHullPolicyRecord(policy);
} catch (error) {
this.logger.warn(
`[resolveHullVehicleCurrentValueFromPolicy] body policy GET ${policyId} failed: ${
error instanceof Error ? error.message : error
}`,
);
return null;
}
}
private parseHullClaimPolicyId(claimCase: {
fanavaranSync?: {
baseClaim?: { policyId?: unknown; lastPayload?: { PolicyId?: unknown } };
};
}): number | null {
return parseFanavaranId(
claimCase?.fanavaranSync?.baseClaim?.policyId ??
claimCase?.fanavaranSync?.baseClaim?.lastPayload?.PolicyId,
);
}
private async buildCarBodyFanavaranExpertisePayload(input: {
clientKey: FanavaranClientKey;
claimCase: any;
blame: { parties?: unknown[] } | null;
profile: ReturnType<typeof getFanavaranClientProfile>;
parts: any[];
claimExpertId: number;
submittedAt: Date;
priceDropTotal: number;
priceDropCarPrice: unknown;
warnings: string[];
/** Non-blocking notices (factory-bundle fallbacks). Never gates submission. */
infoWarnings: string[];
replyKey?: string;
}): Promise<{
payload: Record<string, unknown>;
warnings: string[];
infoWarnings: string[];
replyKey?: string;
}> {
const policyId = this.parseHullClaimPolicyId(input.claimCase);
const contractOptions = {
contractIdOverride: resolveFanavaranProductContractId(
input.clientKey,
'car-body',
),
};
const [dmgKindRows, dmgCostKindRows, policyRecord, componentRows] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind', true),
this.getFanavaranLookupRows(
input.clientKey,
'vehicle-hull-dmg-cost-kinds',
true,
),
policyId != null
? this.fanavaranLookupService.bodyPolicyById(
input.clientKey,
policyId,
contractOptions,
)
: Promise.resolve(null),
input.parts.length ? this.getFanavaranLookupRows(input.clientKey, 'car-components', true) : Promise.resolve([]),
]);
const dmgKindId =
findLookupIdByCaption(dmgKindRows, FANAVARAN_HULL_DMG_KIND_CAPTION);
const dmgCostKindId =
findLookupIdByCaption(
dmgCostKindRows,
FANAVARAN_HULL_DMG_COST_KIND_CAPTION,
);
let accessories = asHullDmgAccessoryRows([]);
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) {
try {
accessories = asHullDmgAccessoryRows(
await this.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId(
input.clientKey,
policyId,
contractOptions,
),
);
if (accessories.length === 0) {
input.warnings.push(
`VehicleHullAccessoryId cannot be resolved: policy ${policyId} dmg-accessories returned no rows.`,
);
}
} catch (error) {
const message =
error instanceof Error ? error.message : String(error);
this.logger.warn(
`[buildCarBodyFanavaranExpertisePayload] policy ${policyId} dmg-accessories lookup failed: ${message}`,
);
input.warnings.push(
`VehicleHullAccessoryId cannot be resolved: policy ${policyId} dmg-accessories lookup failed (${message}).`,
);
}
}
let vehicle = pickHullVehicleIdentity(input.blame);
let colorId: number | null = null;
const policy = asObjectRecord(policyRecord);
const vehicleId = pickVehicleId(policy?.VehicleId ?? policy?.vehicleId);
const versionNo = parseFanavaranId(policy?.VehicleVersionNo);
if (vehicleId != null) {
try {
const vehicleRow = asObjectRecord(
await this.fanavaranLookupService.vehicleById(
input.clientKey,
vehicleId,
versionNo ?? undefined,
contractOptions,
),
);
vehicle = mergeHullVehicleIdentityFromFanavaranVehicle(
vehicle,
vehicleRow,
);
colorId = parseFanavaranId(vehicleRow.ColorId);
} catch (error) {
this.logger.warn(
`[buildCarBodyFanavaranExpertisePayload] vehicle GET ${vehicleId} failed: ${
error instanceof Error ? error.message : error
}`,
);
}
}
const wage = input.parts.reduce(
(sum, part) => sum + this.parseFanavaranMoney(part?.salary),
0,
);
const componentReplacementCost = input.parts.reduce(
(sum, part) => sum + this.parseFanavaranMoney(part?.price),
0,
);
const wasteValue = input.parts.reduce(
(sum, part) => sum + this.fanavaranDaghiWasteValue(part?.daghi),
0,
);
const factoryBundle = findHullFactoryBundleAccessory(accessories);
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,
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({
partId: accessoryKindId,
desc: partLabel,
wasteValue: this.fanavaranDaghiWasteValue(part?.daghi),
amount:
this.parseFanavaranMoney(part?.price) +
this.parseFanavaranMoney(part?.salary),
dmgKindId,
dmgCostKindId,
vehicleHullAccessoryId,
});
});
let vehicleCurrentValue =
this.parseFanavaranMoney(input.claimCase?.vehicle?.carPrice) ||
this.parseFanavaranMoney(input.claimCase?.vehicle?.price) ||
this.parseFanavaranMoney(input.priceDropCarPrice) ||
null;
if (vehicleCurrentValue == null) {
vehicleCurrentValue = vehicleCurrentValueFromHullPolicyRecord(policy);
}
vehicleCurrentValue =
input.claimCase?.fanavaranFieldReview?.values?.VehicleCurrentValue ??
vehicleCurrentValue;
const repairDuration =
input.claimCase?.fanavaranFieldReview?.values?.RepairDuration ??
FANAVARAN_DEFAULT_HULL_REPAIR_DURATION;
const payload = toFanavaranHullExpertisePayload({
claimExpertId: input.claimExpertId,
dmgAssessmentDate: this.convertToPersianDate(input.submittedAt),
inspectionTime: this.getTime24Hour(input.submittedAt),
wage, componentReplacementCost, wasteValue,
dropAmount: input.priceDropTotal || 0,
vehicleCurrentValue, vehicle, colorId, repairDuration,
dmgSections: hullSections,
});
const sources = {
'vehicle-hull-dmg-kind': dmgKindRows,
'vehicle-hull-dmg-cost-kinds': dmgCostKindRows,
'car-components': componentRows,
'policy-dmg-accessories': accessories,
};
input.warnings.push(...await validateFanavaranHullLookupIds(payload, 'expertise', async lookup => sources[lookup] ?? []));
return {
replyKey: input.replyKey,
warnings: input.warnings,
infoWarnings: input.infoWarnings,
payload,
};
}
private async buildFanavaranDamageCasePayload(input: {
claimCase: any;
blameCase?: any;
selectedParts: unknown[];
clientKey: FanavaranClientKey;
defaults: {
AccidentVehicleUsedId: number;
CulpritLicenceTypeId: number;
DmgCaseTypeId: number;
DmgHistoryStatus: number;
PlaqueKindId: number;
PlaqueSampleId: number;
DriverIsOwner: number;
FaultPercent: number;
};
/** GEN.44 write: register the damaged party in Fanavaran when inquiry misses. */
registerMissingPerson?: boolean;
}): Promise<Record<string, unknown>> {
const damagedParty = this.pickDamagedPartyForFanavaran(
input.blameCase,
input.claimCase,
);
const person = damagedParty?.person ?? {};
const vehicle = damagedParty?.vehicle ?? {};
const insurance = damagedParty?.insurance ?? {};
const driverIdentity = resolveDriverFromParty(damagedParty);
const ownerIdentity = resolveOwnerFromParty(damagedParty);
const driverIsOwner = resolveDriverIsOwner(damagedParty);
const product = fanavaranClaimProductFromBlameType(input.blameCase?.type);
const { mapped: inquiryMapped, raw: inquiryRawPayload } =
fanavaranPartyInquirySources(product, damagedParty);
const inquiryRaw = inquiryRawPayload ?? {};
const plate =
this.resolveOwnershipPlateForClaim(input.claimCase, input.blameCase) ??
this.resolvePlateFromPartyInquiry(inquiryMapped, inquiryRaw);
this.logger.log(
`[buildFanavaranDamageCasePayload] damagedParty resolved: userId=${damagedParty?.person?.userId ?? 'NONE'}, ` +
`driverNationalCode=${driverIdentity.nationalCode ?? 'MISSING'}, ` +
`ownerNationalCode=${ownerIdentity.nationalCode ?? 'MISSING'}, ` +
`nationalCodeOfDriver=${person.nationalCodeOfDriver ?? 'MISSING'}, ` +
`nationalCodeOfInsurer=${person.nationalCodeOfInsurer ?? 'MISSING'}, ` +
`driverBirthday=${driverIdentity.birthday ?? 'MISSING'}, ` +
`driverIsOwner=${driverIsOwner}, ` +
`driverLicense=${driverIdentity.licenseNo ?? person.driverLicense ?? 'MISSING'}, ` +
`driverLicenseDate=${driverIdentity.licenseIssuDate ?? 'MISSING'}`,
);
if (!damagedParty) {
this.logger.warn(
`[buildFanavaranDamageCasePayload] No matching party found for claimCase.owner.userId=${input.claimCase?.owner?.userId}. ` +
`Blame parties: ${input.blameCase?.parties?.map((p: any) => `userId=${p?.person?.userId}`).join(', ') ?? 'EMPTY'}`,
);
}
// Policy document / unique code / coverage dates from damaged party's plate inquiry
const policyNo =
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'PrntCmpDocNo',
'PrntPlcyCmpDocNo',
'printNumber',
'insuranceNumber',
]) ??
insurance.policyNumber ??
null;
const policyCINumber = this.pickPartyInquiryField(
inquiryMapped,
inquiryRaw,
['PlcyUnqCod', 'ThirdPolicyCode'],
);
const beginDate =
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'HBgnDte',
'StartDate',
'persianStartDate',
'SatrtDate',
]) ??
insurance.startDate ??
null;
const endDate =
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'HEndDte',
'EndDate',
'persianEndDate',
]) ??
insurance.endDate ??
null;
const builtYearRaw = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'PrdDte',
'ModelField',
'ModelCii',
]);
const builtYearFromInquiry = builtYearRaw
? Number(builtYearRaw) || null
: null;
const damagedVin =
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'VIN',
'vin',
'VinNumberField',
]) ??
collectPartyVinCandidates(damagedParty)[0] ??
null;
const damagedChassis = this.pickPartyInquiryField(
inquiryMapped,
inquiryRaw,
['ShsNum', 'ChassisNumberField', 'shsNam'],
);
const damagedIdentity: FanavaranDamagedVehicleIdentity = {
vin: damagedVin,
chassis: damagedChassis,
plaque: plate
? completePlaqueParts({
plaqueLeft: String(plate.leftDigits),
plaqueLetter: plate.centerAlphabet,
plaqueRight: String(plate.centerDigits),
plaqueSerial: String(plate.ir),
})
: null,
policyCINumber,
};
const damagedVinCandidates: string[] = [];
const seenVins = new Set<string>();
for (const value of [
...collectPartyVinCandidates(damagedParty),
damagedVin,
damagedChassis,
]) {
const vin = normalizeVin(value);
if (!vin || seenVins.has(vin)) continue;
seenVins.add(vin);
damagedVinCandidates.push(vin);
}
const cachedDamage =
(input.claimCase as any)?.fanavaranSync?.damageCase ?? {};
this.logger.log(
`[buildFanavaranDamageCasePayload] identity VIN=${damagedIdentity.vin ?? 'none'} chassis=${damagedIdentity.chassis ?? 'none'} plate=${damagedIdentity.plaque ? `${damagedIdentity.plaque.right}${damagedIdentity.plaque.letter}${damagedIdentity.plaque.left}/${damagedIdentity.plaque.serial}` : 'none'} CI=${damagedIdentity.policyCINumber ?? 'none'} VIN candidates=${damagedVinCandidates.join(',') || 'none'}`,
);
const apiVehicle = await this.fetchFanavaranVehicleByVinCandidates(
input.clientKey,
damagedVinCandidates,
damagedIdentity,
product,
);
const apiPlaque = pickFanavaranPlaqueLookupFields(apiVehicle);
const plaqueLookup = resolveDamageCasePlaqueLookupIds(apiVehicle);
const plaqueKindId = plaqueLookup.kindId;
const plaqueSampleId = plaqueLookup.sampleId;
const plaqueKindSource = plaqueLookup.source;
const plaqueSampleSource = plaqueLookup.source;
if (plaqueLookup.source !== 'vehicle-inquiry') {
this.logger.log(
`[buildFanavaranDamageCasePayload] PlaqueKindId not on a matched Fanavaran vehicle; using national-plate default ${plaqueKindId}/${plaqueSampleId}`,
);
}
const builtYear =
parseFanavaranId(apiVehicle?.BuiltYear) ?? builtYearFromInquiry;
const carType = input.claimCase?.vehicle?.carType as string | undefined;
const approvedVehicleKindId = this.firstPositiveFanavaranId(
input.claimCase?.fanavaranVehicleReview?.vehicleKind?.id,
);
let vehicleKindId =
approvedVehicleKindId ??
this.firstPositiveFanavaranId(apiVehicle?.VehicleKindId);
let vehicleKindSource:
| 'expert-review'
| 'vehicle-inquiry'
| 'car-type-lookup'
| null =
approvedVehicleKindId != null
? 'expert-review'
: parseFanavaranId(apiVehicle?.VehicleKindId) != null
? 'vehicle-inquiry'
: null;
if (vehicleKindId == null) {
vehicleKindId = await this.resolveVehicleKindId(input.clientKey, carType);
if (vehicleKindId != null) vehicleKindSource = 'car-type-lookup';
}
let driverFanavaranId: number | null = null;
if (driverIdentity.nationalCode && driverIdentity.birthday) {
driverFanavaranId = await this.resolveDriverFanavaranId(
input.clientKey,
driverIdentity.nationalCode,
driverIdentity.birthday,
false,
);
}
if (driverFanavaranId == null) {
driverFanavaranId = await this.resolveDriverFanavaranIdFromBlameCase(
input.clientKey,
input.blameCase?.parties ?? [],
person,
input.claimCase,
);
}
let otherPersonId = this.firstPositiveFanavaranId(
cachedDamage.otherPersonId,
);
if (driverFanavaranId) {
this.logger.log(
`[buildFanavaranDamageCasePayload] DriverId=${driverFanavaranId} from live parties inquiry`,
);
} else if (otherPersonId) {
driverFanavaranId = otherPersonId;
this.logger.log(
`[buildFanavaranDamageCasePayload] Parties inquiry missed; reusing GEN.44 otherPersonId=${otherPersonId}`,
);
} else if (input.registerMissingPerson) {
const registered = await this.registerFanavaranOtherPerson({
clientKey: input.clientKey,
person: {
...person,
nationalCodeOfDriver:
driverIdentity.nationalCode ?? person.nationalCodeOfDriver,
driverBirthday: driverIdentity.birthday ?? person.driverBirthday,
driverIsInsurer: false,
},
claimCaseId: input.claimCase?._id
? String(input.claimCase._id)
: undefined,
});
if (registered != null) {
driverFanavaranId = registered;
otherPersonId = registered;
}
}
let ownerFanavaranId: number | null = null;
if (
ownerIdentity.nationalCode &&
ownerIdentity.nationalCode === driverIdentity.nationalCode &&
driverFanavaranId != null
) {
ownerFanavaranId = driverFanavaranId;
} else if (ownerIdentity.nationalCode && ownerIdentity.birthday) {
ownerFanavaranId = await this.resolveOwnerFanavaranId(
input.clientKey,
ownerIdentity.nationalCode,
ownerIdentity.birthday,
);
}
if (
ownerFanavaranId == null &&
input.registerMissingPerson &&
ownerIdentity.nationalCode &&
ownerIdentity.birthday
) {
const registeredOwner = await this.registerFanavaranOtherPerson({
clientKey: input.clientKey,
person: {
nationalCode: ownerIdentity.nationalCode,
nationalCodeOfDriver: ownerIdentity.nationalCode,
birthday: ownerIdentity.birthday,
driverBirthday: ownerIdentity.birthday,
driverIsInsurer: false,
fullName: (damagedParty as any)?.person?.fullName,
phoneNumber: (damagedParty as any)?.person?.phoneNumber,
userId: (damagedParty as any)?.person?.userId,
},
claimCaseId: input.claimCase?._id
? String(input.claimCase._id)
: undefined,
});
if (registeredOwner != null) {
ownerFanavaranId = registeredOwner;
if (otherPersonId == null) otherPersonId = registeredOwner;
this.logger.log(
`[buildFanavaranDamageCasePayload] OwnerId=${ownerFanavaranId} from GEN.44 other-people`,
);
}
}
if (driverFanavaranId && input.blameCase?._id && damagedParty) {
const partyIndex = (input.blameCase.parties ?? []).findIndex(
(p: any) =>
p === damagedParty ||
String(p?.person?.userId ?? '') ===
String(damagedParty?.person?.userId ?? ''),
);
if (partyIndex >= 0) {
await this.blameRequestDbService.findByIdAndUpdate(
String(input.blameCase._id),
{
$set: {
[`parties.${partyIndex}.person.fanavaranDriverId`]:
driverFanavaranId,
},
},
);
this.logger.log(
`[buildFanavaranDamageCasePayload] stored DriverId=${driverFanavaranId} on blameCase=${input.blameCase._id} party[${partyIndex}]`,
);
}
}
const insuranceCorpId =
await this.fanavaranLookupService.resolveInsuranceCorpId(input.clientKey);
const approvedVehicleUseTypeId = this.firstPositiveFanavaranId(
input.claimCase?.fanavaranVehicleReview?.vehicleUseType?.id,
);
let accidentVehicleUsedId: number | null = approvedVehicleUseTypeId;
let usedSource:
| 'expert-review'
| 'vin-inquiry'
| 'policy-vehicle'
| 'vehicle-inquiry'
| null = approvedVehicleUseTypeId != null ? 'expert-review' : null;
if (accidentVehicleUsedId == null && apiVehicle) {
const fromDamagedVehicle =
await this.resolveAccidentVehicleUsedFromVehicleRecord(
input.clientKey,
apiVehicle,
);
accidentVehicleUsedId = fromDamagedVehicle.usedId;
if (accidentVehicleUsedId != null) usedSource = 'vehicle-inquiry';
}
if (accidentVehicleUsedId == null) {
accidentVehicleUsedId =
await this.resolveAccidentVehicleUsedFromVehicleKind(
input.clientKey,
vehicleKindId,
parseFanavaranId(apiVehicle?.UsedId),
);
if (accidentVehicleUsedId != null && usedSource == null) {
usedSource = apiVehicle ? 'vehicle-inquiry' : null;
}
}
if (accidentVehicleUsedId == null) {
accidentVehicleUsedId = input.defaults.AccidentVehicleUsedId;
this.logger.log(
`[buildFanavaranDamageCasePayload] AccidentVehicleUsedId API miss; using config default ${accidentVehicleUsedId}`,
);
}
this.logger.log(
`[buildFanavaranDamageCasePayload] Final DriverId=${driverFanavaranId ?? 'NULL'} OwnerId=${ownerFanavaranId ?? 'NULL'} for driverNationalCode=${driverIdentity.nationalCode ?? 'MISSING'}, ` +
`PolicyNo=${policyNo ?? 'NULL'}, PolicyCINumber=${policyCINumber ?? 'NULL'}`,
);
const payload = {
BeginDate: beginDate,
BuiltYear: builtYear,
ChassisNo:
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'ShsNum',
'ChassisNumberField',
'shsNam',
]) ??
(typeof apiVehicle?.ChassisNo === 'string'
? apiVehicle.ChassisNo
: null),
DmgHistoryStatus:
input.claimCase?.fanavaranFieldReview?.values?.DmgHistoryStatus ??
input.defaults.DmgHistoryStatus,
Desc: this.formatFanavaranSelectedPartsDesc(input.selectedParts),
DmgCaseTypeId: input.defaults.DmgCaseTypeId,
DriverId: driverFanavaranId ?? null,
EndDate: endDate,
EstimateAmount: FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT,
FaultPercent: input.defaults.FaultPercent,
InsuranceCorpId: insuranceCorpId,
DriverIsOwner: driverIsOwner ? 1 : 0,
LicenceCityId: null,
LicenceCountryId: null,
LicenceForeignCityName: null,
LicenceIssuDate: resolveFanavaranLicenceIssuDate(driverIdentity),
// Must never be empty/null; prefer stored DB value, else use dummy.
LicenceNo: this.resolveFanavaranLicenceNoFromParty({
driverIsInsurer: person.driverIsInsurer,
driverLicense: person.driverLicense,
insurerLicense: person.insurerLicense,
resolvedLicenseNo: driverIdentity.licenseNo,
}),
LicenceTypeId: input.defaults.CulpritLicenceTypeId,
MotorNo:
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'MtrNum',
'EngineNumberField',
'mtrnum',
]) ??
(typeof apiVehicle?.MotorNo === 'string' ? apiVehicle.MotorNo : null),
OwnerId: ownerFanavaranId,
PlaqueCityId: apiPlaque.cityId,
PlaqueKindId: plaqueKindId,
PlaqueLeftNo:
apiPlaque.leftNo ?? (plate ? String(plate.leftDigits) : null),
PlaqueMiddleCodeId:
apiPlaque.middleCodeId ??
this.getFanavaranPlateMiddleCode(plate?.centerAlphabet),
PlaqueNo:
apiPlaque.plaqueNo ??
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, ['Plk']) ??
this.formatFanavaranPlateNo(plate),
PlaqueRightNo:
apiPlaque.rightNo ?? (plate ? String(plate.centerDigits) : null),
PlaqueSampleId: plaqueSampleId,
PlaqueSerial: apiPlaque.serial ?? (plate ? String(plate.ir) : null),
PolicyNo: policyNo,
PreviousPolicyEndDate: endDate ?? '',
VehicleKindId: vehicleKindId,
VIN:
this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [
'VIN',
'vin',
'VinNumberField',
]) ?? (typeof apiVehicle?.VIN === 'string' ? apiVehicle.VIN : null),
AccidentVehicleUsedId: accidentVehicleUsedId,
PolicyCINumber: policyCINumber,
};
const persistedPayload = payload;
// Persist Fanavaran-sourced IDs + last payload for reuse on later preview/submit
if (input.claimCase?._id) {
await this.claimCaseDbService.findByIdAndUpdate(
String(input.claimCase._id),
{
$set: {
'fanavaranSync.damageCase.lastPayload': persistedPayload,
'fanavaranSync.damageCase.lastPayloadBuiltAt': new Date(),
...(driverFanavaranId != null
? { 'fanavaranSync.damageCase.driverId': driverFanavaranId }
: {}),
...(otherPersonId != null
? { 'fanavaranSync.damageCase.otherPersonId': otherPersonId }
: {}),
...(vehicleKindId != null
? {
'fanavaranSync.damageCase.vehicleKindId': vehicleKindId,
'fanavaranSync.damageCase.vehicleKindSource':
vehicleKindSource ?? 'car-type-lookup',
}
: {}),
'fanavaranSync.damageCase.plaqueKindId': plaqueKindId,
'fanavaranSync.damageCase.plaqueKindSource': plaqueKindSource,
'fanavaranSync.damageCase.plaqueSampleId': plaqueSampleId,
'fanavaranSync.damageCase.plaqueSampleSource': plaqueSampleSource,
...(accidentVehicleUsedId != null
? {
'fanavaranSync.damageCase.accidentVehicleUsedId':
accidentVehicleUsedId,
...(usedSource
? {
'fanavaranSync.damageCase.accidentVehicleUsedSource':
usedSource,
}
: {}),
}
: {}),
...(insuranceCorpId != null
? { 'fanavaranSync.damageCase.insuranceCorpId': insuranceCorpId }
: {}),
},
},
);
}
return persistedPayload;
}
private resolveClientKeyFromAuthConfig(config: {
appName: string;
}): FanavaranClientKey {
if (config.appName === this.PARSIAN_FANAVARAN_CONFIG.appName) {
return 'parsian';
}
return resolveFanavaranClientKey();
}
private async resolveFanavaranClaimProduct(
claimCaseId?: string,
blameCase?: { type?: string } | null,
): Promise<FanavaranClaimProduct> {
if (blameCase?.type) {
return fanavaranClaimProductFromBlameType(blameCase.type);
}
if (!claimCaseId) return 'third-party';
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase?.blameRequestId) return 'third-party';
const blame = await this.blameRequestDbService.findById(
String(claimCase.blameRequestId),
);
return fanavaranClaimProductFromBlameType(blame?.type);
}
private async fanavaranClaimsUrlForClaim(
claimCaseId?: string,
blameCase?: { type?: string } | null,
): Promise<string> {
return fanavaranClaimsBaseUrl(
await this.resolveFanavaranClaimProduct(claimCaseId, blameCase),
resolveFanavaranClientKey(),
);
}
/** 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(
clientKey: FanavaranClientKey,
auditSession?: FanavaranAuditSession,
claimCaseId?: string,
) {
const caseId = claimCaseId ?? auditSession?.claimCaseId;
const locationOverride = caseId
? await this.resolveFanavaranLocationForClaim(caseId, clientKey)
: undefined;
const product = await this.resolveFanavaranClaimProduct(caseId);
return this.fanavaranAuthService.getRequestHeaders(clientKey, {
auditSession,
locationOverride,
contractIdOverride: resolveFanavaranProductContractId(clientKey, product),
});
}
/**
* Fanavaran HTTP Location from assigned staff `locations[].id`
* (file-maker / file-reviewer / field / blame / damage expert), for every
* tenant. Prefer the claim creator, then the originating file's staff.
* Missing staff configuration must not submit a claim to a default branch.
*/
private async resolveFanavaranLocationForClaim(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<string> {
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
throw new NotFoundException('Claim case not found');
}
const blame = claimCase.blameRequestId
? await this.blameRequestDbService.findById(String(claimCase.blameRequestId))
: null;
return this.fanavaranLocationService.resolveBusinessLocation({
clientKey,
requireStaffLocation: true,
staffCandidateIds: [
claimCase.initiatedByFieldExpertId,
blame?.initiatedByFieldExpertId,
this.fanavaranDamageReplyActorId(claimCase),
claimCase.workflow?.assignedForReviewBy?.actorId,
blame?.assignedFileReviewerId,
blame?.expert?.assignedExpertId,
blame?.expert?.decision?.decidedByExpertId,
].map((id) => (id == null ? undefined : String(id))),
});
}
private fanavaranPayloadDefaultsWithoutExpertIds(
defaults: Record<string, unknown>,
): Record<string, unknown> {
const {
ClaimExpertId: _claimExpertId,
ExpertiseClaimExpertId: _expertiseClaimExpertId,
...rest
} = defaults;
return rest;
}
private staffFanavaranCodesFromDoc(
doc: unknown,
): (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) | null {
if (!doc || typeof doc !== 'object') return null;
const plain =
typeof (doc as { toObject?: () => Record<string, unknown> }).toObject ===
'function'
? (doc as { toObject: () => Record<string, unknown> }).toObject()
: (doc as Record<string, unknown>);
return {
ThirdPartyClaimExpertId:
plain.ThirdPartyClaimExpertId != null
? String(plain.ThirdPartyClaimExpertId)
: undefined,
CarBodyClaimExpertId:
plain.CarBodyClaimExpertId != null
? String(plain.CarBodyClaimExpertId)
: undefined,
ThirdPartyExpertiseClaim:
plain.ThirdPartyExpertiseClaim != null
? String(plain.ThirdPartyExpertiseClaim)
: undefined,
CarBodyExpertiseClaim:
plain.CarBodyExpertiseClaim != null
? String(plain.CarBodyExpertiseClaim)
: undefined,
};
}
private async findStaffDocumentById(
staffId: string,
): Promise<
(StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) | null
> {
const loaders = [
() => this.expertDbService.findById(staffId),
() => this.damageExpertDbService.findById(staffId),
() => this.fieldExpertDbService.findById(staffId),
() => this.fileMakerDbService.findById(staffId),
() => this.fileReviewerDbService.findById(staffId),
];
for (const load of loaders) {
try {
const doc = await load();
const codes = this.staffFanavaranCodesFromDoc(doc);
if (codes) return codes;
} catch {
// invalid ObjectId / cast errors — try next collection
}
}
return null;
}
private async tryResolveFanavaranBaseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown;
expert?: {
assignedExpertId?: unknown;
decision?: { decidedByExpertId?: unknown };
};
},
claimCase?: FanavaranClaimExpertContext | null,
): Promise<{
claimExpertId: number | null;
code: string | null;
message: string | null;
candidatesTried: string[];
}> {
const fieldName =
blame?.type === BlameRequestType.CAR_BODY
? 'CarBodyClaimExpertId'
: 'ThirdPartyClaimExpertId';
if (blame?.type == null) {
return {
claimExpertId: null,
code: 'FANAVARAN_CLAIM_EXPERT_ID_MISSING',
message:
'ClaimExpertId unresolved: blame.type is missing, so the product line expert code cannot be chosen.',
candidatesTried: [],
};
}
if (blame.isMadeByFileMaker && blame.initiatedByFieldExpertId) {
const fileMakerId = String(blame.initiatedByFieldExpertId);
const fileMaker = await this.fileMakerDbService.findById(fileMakerId);
if (!fileMaker) {
return {
claimExpertId: null,
code: 'FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING',
message: `ClaimExpertId unresolved: FileMaker ${fileMakerId} was not found.`,
candidatesTried: [fileMakerId],
};
}
const id = resolveFileMakerStageOneExpertId(fileMaker, blame.type);
if (id == null) {
return {
claimExpertId: null,
code: 'FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING',
message: `ClaimExpertId unresolved: FileMaker ${fileMakerId} has empty ${fieldName}.`,
candidatesTried: [fileMakerId],
};
}
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: [fileMakerId],
};
}
// User-created claims may have no blame expert. Their damage reviewer is
// still staff attached to this file and can supply the stage-1 product code.
const candidateIds = [
...new Set(
[
blame.initiatedByFieldExpertId,
blame.expert?.assignedExpertId,
blame.expert?.decision?.decidedByExpertId,
claimCase?.initiatedByFieldExpertId,
this.fanavaranDamageReplyActorId(claimCase),
claimCase?.workflow?.assignedForReviewBy?.actorId,
]
.filter((value) => value != null && String(value).trim() !== '')
.map((value) => String(value)),
),
];
const missingOnStaff: string[] = [];
for (const staffId of candidateIds) {
const staff = await this.findStaffDocumentById(staffId);
if (!staff) {
missingOnStaff.push(
`${staffId} (staff not found in expert/damage/field/fileMaker/fileReviewer)`,
);
continue;
}
const rawValue = (staff as Record<string, unknown>)[fieldName];
const id = resolveFileMakerStageOneExpertId(staff, blame.type);
if (id != null) {
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: candidateIds,
};
}
missingOnStaff.push(
`${staffId} (${fieldName}=${rawValue == null || rawValue === '' ? 'empty' : JSON.stringify(rawValue)})`,
);
}
return {
claimExpertId: null,
code: 'FANAVARAN_CLAIM_EXPERT_ID_MISSING',
message:
candidateIds.length === 0
? `ClaimExpertId unresolved: this claim/blame has no assigned staff id (checked initiatedByFieldExpertId, expert.assignedExpertId, expert.decision.decidedByExpertId, evaluation.damageExpertReplyFinal/damageExpertReply.actorDetail.actorId, workflow.assignedForReviewBy.actorId). Assign staff with ${fieldName} to this file.`
: `ClaimExpertId unresolved: checked assigned staff [${missingOnStaff.join('; ')}]. Your ${fieldName} must be on THAT assigned staff document, not a different user.`,
candidatesTried: candidateIds,
};
}
/**
* GEN.03 ClaimExpertId from the staff assigned to this file (never tenant defaults).
* Preview may pass `{ required: false }` to keep building the payload with null.
*/
private async resolveFanavaranBaseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown;
expert?: {
assignedExpertId?: unknown;
decision?: { decidedByExpertId?: unknown };
};
},
claimCase?: FanavaranClaimExpertContext | null,
options?: { required?: boolean },
): Promise<number | null> {
const resolved = await this.tryResolveFanavaranBaseClaimExpertId(
blame,
claimCase,
);
if (resolved.claimExpertId != null) return resolved.claimExpertId;
if (options?.required === false) return null;
throw new BadRequestException({
code: resolved.code ?? 'FANAVARAN_CLAIM_EXPERT_ID_MISSING',
message:
resolved.message ??
'ClaimExpertId unresolved on the assigned expert profile.',
});
}
private fanavaranDamageReplyActorId(
claimCase?: { evaluation?: object } | null,
): unknown {
const evaluation = claimCase?.evaluation as
| {
damageExpertReplyFinal?: { actorDetail?: { actorId?: unknown } };
damageExpertReply?: { actorDetail?: { actorId?: unknown } };
}
| undefined;
const active = getActiveV2ExpertReply({
evaluation: claimCase?.evaluation as Record<string, unknown> | undefined,
});
return (
(active?.reply as { actorDetail?: { actorId?: unknown } } | undefined)
?.actorDetail?.actorId ??
evaluation?.damageExpertReplyFinal?.actorDetail?.actorId ??
evaluation?.damageExpertReply?.actorDetail?.actorId
);
}
private async tryResolveFanavaranExpertiseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
assignedFileReviewerId?: unknown;
},
claimCase: { evaluation?: Record<string, unknown> } | null | undefined,
): Promise<{
claimExpertId: number | null;
code: string | null;
message: string | null;
candidatesTried: string[];
}> {
const fieldName =
blame?.type === BlameRequestType.CAR_BODY
? 'CarBodyExpertiseClaim'
: 'ThirdPartyExpertiseClaim';
if (blame?.type == null) {
return {
claimExpertId: null,
code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message: 'Expertise ClaimExpertId unresolved: blame.type is missing.',
candidatesTried: [],
};
}
if (blame.isMadeByFileMaker) {
if (!blame.assignedFileReviewerId) {
return {
claimExpertId: null,
code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING',
message:
'Expertise ClaimExpertId unresolved: no assignedFileReviewerId on this FileMaker file.',
candidatesTried: [],
};
}
const fileReviewerId = String(blame.assignedFileReviewerId);
const fileReviewer =
await this.fileReviewerDbService.findById(fileReviewerId);
if (!fileReviewer) {
return {
claimExpertId: null,
code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING',
message: `Expertise ClaimExpertId unresolved: FileReviewer ${fileReviewerId} was not found.`,
candidatesTried: [fileReviewerId],
};
}
const id = resolveFileReviewerExpertiseExpertId(fileReviewer, blame.type);
if (id == null) {
return {
claimExpertId: null,
code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING',
message: `Expertise ClaimExpertId unresolved: FileReviewer ${fileReviewerId} has empty ${fieldName}.`,
candidatesTried: [fileReviewerId],
};
}
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: [fileReviewerId],
};
}
const actorId = this.fanavaranDamageReplyActorId(claimCase);
if (actorId == null || String(actorId).trim() === '') {
return {
claimExpertId: null,
code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message:
'Expertise ClaimExpertId unresolved: no damage-expert reply actorDetail.actorId on this claim.',
candidatesTried: [],
};
}
const staffId = String(actorId);
const staff = await this.findStaffDocumentById(staffId);
if (!staff) {
return {
claimExpertId: null,
code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message: `Expertise ClaimExpertId unresolved: staff ${staffId} was not found.`,
candidatesTried: [staffId],
};
}
const id = resolveFileReviewerExpertiseExpertId(staff, blame.type);
if (id == null) {
return {
claimExpertId: null,
code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message: `Expertise ClaimExpertId unresolved: staff ${staffId} has empty ${fieldName}.`,
candidatesTried: [staffId],
};
}
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: [staffId],
};
}
/**
* GEN.08 / GEN.06 ClaimExpertId from the assessor assigned to this file (never tenant defaults).
* Preview may pass `{ required: false }` to keep building the payload with null.
*/
private async resolveFanavaranExpertiseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
assignedFileReviewerId?: unknown;
},
claimCase: { evaluation?: Record<string, unknown> } | null | undefined,
options?: { required?: boolean },
): Promise<number | null> {
const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId(
blame,
claimCase,
);
if (resolved.claimExpertId != null) return resolved.claimExpertId;
if (options?.required === false) return null;
throw new BadRequestException({
code: resolved.code ?? 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message:
resolved.message ??
'Expertise ClaimExpertId unresolved on the assigned assessor profile.',
});
}
/** @deprecated Use resolveFanavaranBaseClaimExpertId / resolveFanavaranExpertiseClaimExpertId */
private async resolveFanavaranFileRoleExpertIdsForBlame(blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown;
expert?: {
assignedExpertId?: unknown;
decision?: { decidedByExpertId?: unknown };
};
}): Promise<{
baseClaimExpertId: number | null;
expertiseClaimExpertId: number | null;
} | null> {
if (blame?.type == null) return null;
try {
const baseClaimExpertId =
await this.resolveFanavaranBaseClaimExpertId(blame);
let expertiseClaimExpertId: number | null = null;
try {
expertiseClaimExpertId =
await this.resolveFanavaranExpertiseClaimExpertId(blame, null);
} catch {
expertiseClaimExpertId = null;
}
return { baseClaimExpertId, expertiseClaimExpertId };
} catch {
return null;
}
}
private async getPolicyIdFromNationalCode(
nationalCodeOfInsurer: string,
config: {
appName: string;
secret: string;
username: string;
password: string;
corpId: string;
contractId: string;
location: string;
},
logPrefix: string,
auditSession?: FanavaranAuditSession,
options?: {
clientKey?: FanavaranClientKey;
claimCaseId?: string;
product?: FanavaranClaimProduct;
insuranceLineId?: number;
accidentDate?: Date | string;
},
): Promise<number | null> {
const clientKey =
options?.clientKey ?? this.resolveClientKeyFromAuthConfig(config);
const product =
options?.product ??
(await this.resolveFanavaranClaimProduct(options?.claimCaseId));
const insuranceLineId =
options?.insuranceLineId ?? fanavaranInsuranceLineIdForProduct(product);
const policyInquiryUrl = `${getFanavaranLookupBaseUrl(clientKey)}/common/Policies/inquiry-my-policies?InsuranceLineId=${insuranceLineId}&NationalCode=${nationalCodeOfInsurer}`;
const startedAt = Date.now();
const requestMeta = {
corpId: config.corpId,
contractId: resolveFanavaranProductContractId(clientKey, product),
location: config.location,
nationalCode: this.fanavaranAuditService.maskNationalCode(
nationalCodeOfInsurer,
),
InsuranceLineId: insuranceLineId,
};
try {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
options?.claimCaseId,
);
const requestHeaders = {
...headers,
'Content-Type': 'application/json',
};
requestMeta.location = headers.Location;
if (auditSession) {
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.STARTED,
requestUrl: policyInquiryUrl,
requestMethod: 'GET',
requestHeaders,
requestMeta,
});
}
this.logger.log(
`${logPrefix} Calling policy inquiry API for nationalCode: ${nationalCodeOfInsurer}`,
);
const response = await firstValueFrom(
this.httpService.get(policyInquiryUrl, {
headers: requestHeaders,
timeout: 15000,
}),
);
const policyCount = Array.isArray(response.data)
? response.data.length
: 0;
this.logger.log(
`${logPrefix} Policy inquiry response status=${response.status} count=${policyCount}`,
);
const selectedPolicy =
product === 'car-body'
? selectFanavaranPolicyForAccident(response.data, options?.accidentDate)
: selectLatestActiveFanavaranPolicy(response.data);
this.logger.log(
`${logPrefix} Selected latest active policy PolicyId=${selectedPolicy.policyId} EndDate=${selectedPolicy.endDate}`,
);
if (options?.claimCaseId && selectedPolicy.policyId != null) {
await this.claimCaseDbService.findByIdAndUpdate(options.claimCaseId, {
$set: {
'fanavaranSync.baseClaim.policyId': selectedPolicy.policyId,
},
});
}
this.fanavaranAuthService.clearBackoff(clientKey);
if (auditSession) {
const exchange = this.fanavaranAuditService.captureAxiosExchange(
response,
requestHeaders,
);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: policyInquiryUrl,
requestMethod: 'GET',
httpStatus: response.status,
requestHeaders: exchange.requestHeaders,
requestMeta,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
responseMeta: {
policyId: selectedPolicy.policyId,
policyEndDate: selectedPolicy.endDate,
policyEndDateGregorian: selectedPolicy.endDateGregorian,
policyCount,
fromCache: false,
},
durationMs: Date.now() - startedAt,
});
}
return selectedPolicy.policyId;
} catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error);
const errorMessage =
error instanceof Error ? error.message : 'unknown policy inquiry error';
if (auditSession) {
const exchange = this.fanavaranAuditService.captureAxiosExchange(error);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.POLICY_INQUIRY,
status: FanavaranAuditStatus.FAILURE,
requestUrl: policyInquiryUrl,
requestMethod: 'GET',
httpStatus: exchange.httpStatus,
requestHeaders: exchange.requestHeaders,
requestMeta,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
errorMessage,
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
}
this.logger.warn(`${logPrefix} Policy inquiry failed: ${errorMessage}`);
if (error instanceof BadRequestException) {
throw error;
}
return null;
}
}
private firstPositiveFanavaranId(...values: unknown[]): number | null {
for (const value of values) {
const id = parseFanavaranId(value);
if (id != null) return id;
}
return null;
}
private async resolveDriverFanavaranIdFromPerson(
clientKey: FanavaranClientKey,
person:
| {
driverIsInsurer?: boolean;
nationalCodeOfDriver?: unknown;
nationalCodeOfInsurer?: unknown;
nationalCode?: unknown;
driverBirthday?: unknown;
birthday?: unknown;
insurerBirthday?: unknown;
}
| null
| undefined,
): Promise<number | null> {
const codes = collectPersonNationalCodes(person);
const birthdays = collectPersonBirthdays(person);
for (const nationalCode of codes) {
for (const birthday of birthdays) {
const driverId = await this.resolveDriverFanavaranId(
clientKey,
nationalCode,
birthday,
person?.driverIsInsurer,
);
if (driverId != null) return driverId;
}
}
return null;
}
private async resolveDriverFanavaranIdFromBlameCase(
clientKey: FanavaranClientKey,
parties: any[],
preferredPerson: any,
claimCase?: any,
): Promise<number | null> {
const people = [
preferredPerson,
...parties.map((party) => party?.person),
].filter(Boolean);
this.logger.log(
`[resolveDriverFanavaranIdFromBlameCase] trying ${people.length} people then leftover codes`,
);
for (const person of people) {
const driverId = await this.resolveDriverFanavaranIdFromPerson(
clientKey,
person,
);
if (driverId != null) return driverId;
}
const leftoverCodes = [
...(claimCase?.money?.nationalCodeOfInsurer
? collectPersonNationalCodes({
nationalCodeOfInsurer: claimCase.money.nationalCodeOfInsurer,
})
: []),
];
const leftoverBirthdays: Array<string | number> = [];
const seenBirthdays = new Set<string>();
for (const person of people) {
for (const birthday of collectPersonBirthdays(person)) {
const parsed = parseJalaliDateParts(birthday);
const key = parsed
? `${parsed.year}-${parsed.month}-${parsed.day}`
: String(birthday);
if (seenBirthdays.has(key)) continue;
seenBirthdays.add(key);
leftoverBirthdays.push(birthday);
}
}
this.logger.log(
`[resolveDriverFanavaranIdFromBlameCase] leftover codes=${leftoverCodes.join(',') || 'none'} birthdays=${leftoverBirthdays.join(',') || 'none'}`,
);
for (const nationalCode of leftoverCodes) {
for (const birthday of leftoverBirthdays) {
const driverId = await this.resolveDriverFanavaranId(
clientKey,
nationalCode,
birthday,
preferredPerson?.driverIsInsurer,
);
if (driverId != null) return driverId;
}
}
return null;
}
private async loadFanavaranOtherPeopleLookups(
clientKey: FanavaranClientKey,
): Promise<{
cities: unknown[];
gender: unknown[];
maritalStatus: unknown[];
ans: unknown[];
countries: unknown[];
personKind: unknown[];
}> {
const [cities, gender, maritalStatus, ans, countries, personKind] =
await Promise.all([
this.getFanavaranLookupRows(clientKey, 'cities'),
this.getFanavaranLookupRows(clientKey, 'gender'),
this.getFanavaranLookupRows(clientKey, 'marital-status'),
this.getFanavaranLookupRows(clientKey, 'ans'),
this.getFanavaranLookupRows(clientKey, 'countries'),
this.getFanavaranLookupRows(clientKey, 'person-kind'),
]);
return { cities, gender, maritalStatus, ans, countries, personKind };
}
/**
* GEN.44: create the damaged party in Fanavaran when parties inquiry has no
* RoleId 161/166 row (missing entirely, or only e.g. 162 بیمه‌شده).
* Failures stay best-effort — GEN.12 submit continues without DriverId.
*/
private async registerFanavaranOtherPerson(input: {
clientKey: FanavaranClientKey;
person: any;
claimCaseId?: string;
requiredRoleId?: 166;
}): Promise<number | null> {
const nationalCode = pickPersonNationalCode(input.person);
const birthday = pickPersonBirthday(input.person);
const parsedBirthday = parseJalaliDateParts(birthday);
if (!nationalCode || !parsedBirthday) {
this.logger.warn(
`[registerFanavaranOtherPerson] SKIP: missing nationalCode or birthday`,
);
return null;
}
let user: {
fullName?: string;
mobile?: string;
city?: string;
address?: string;
gender?: string;
} | null = null;
const userId = input.person?.userId;
if (userId && Types.ObjectId.isValid(String(userId))) {
try {
user = await this.userDbService.findOne({
_id: new Types.ObjectId(String(userId)),
});
} catch (error) {
this.logger.warn(
`[registerFanavaranOtherPerson] user lookup failed: ${
error instanceof Error ? error.message : error
}`,
);
}
}
/** Seed GEN.44 from parties inquiry when the person exists under a non-driver role. */
let inquirySeed: {
name?: string;
lastName?: string;
fatherName?: string;
genderId?: number;
identityNo?: string;
} = {};
try {
const inquiryRows =
await this.fanavaranLookupService.inquiryByUniqueIdentifier(
input.clientKey,
{
nationalCode,
birthYear: parsedBirthday.year,
birthMonth: parsedBirthday.month,
birthDay: parsedBirthday.day,
},
);
if (input.requiredRoleId === 166) {
const existingId = selectFanavaranOtherPersonId(inquiryRows);
if (existingId != null) return existingId;
}
const parties = asPartyInquiryRows(inquiryRows);
const seedRow =
parties.find(
(row) =>
(typeof row.Name === 'string' && row.Name.trim()) ||
(typeof row.LastName === 'string' && row.LastName.trim()),
) ?? parties[0];
if (seedRow) {
const roleId = Number(seedRow.RoleId);
this.logger.log(
`[registerFanavaranOtherPerson] inquiry seed Id=${seedRow.Id} RoleId=${roleId} — creating GEN.44 سایر (adds RoleId 166 entry; existing roles stay)`,
);
inquirySeed = {
name: typeof seedRow.Name === 'string' ? seedRow.Name : undefined,
lastName:
typeof seedRow.LastName === 'string' ? seedRow.LastName : undefined,
fatherName:
typeof seedRow.FatherName === 'string'
? seedRow.FatherName
: undefined,
genderId: (() => {
const g = Number(seedRow.GenderId);
return Number.isFinite(g) && g > 0 ? g : undefined;
})(),
identityNo:
typeof seedRow.IdentityNo === 'string'
? seedRow.IdentityNo
: undefined,
};
}
} catch (error) {
this.logger.warn(
`[registerFanavaranOtherPerson] pre-create inquiry failed (${input.requiredRoleId === 166 ? 'registration deferred' : 'continuing with local data'}): ${
error instanceof Error ? error.message : error
}`,
);
if (input.requiredRoleId === 166) return null;
}
const lookups = await this.loadFanavaranOtherPeopleLookups(input.clientKey);
const payload = buildFanavaranOtherPeoplePayload(
{
nationalCode,
birthday,
fullName: input.person?.fullName ?? user?.fullName,
name: inquirySeed.name,
lastName: inquirySeed.lastName,
fatherName: inquirySeed.fatherName,
identityNo: inquirySeed.identityNo,
genderId: inquirySeed.genderId,
mobile: input.person?.phoneNumber ?? user?.mobile,
address: user?.address,
cityName: user?.city,
gender: user?.gender,
},
lookups,
);
if (!payload) {
this.logger.warn(
`[registerFanavaranOtherPerson] SKIP: could not build GEN.44 payload for nationalCode=${nationalCode}`,
);
return null;
}
const url = `${getFanavaranLookupBaseUrl(input.clientKey)}/common/other-people`;
const startedAt = Date.now();
const auditSession: FanavaranAuditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey: input.clientKey,
source: FanavaranAuditSource.AUTO_SUBMIT,
claimCaseId: input.claimCaseId,
};
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.CREATE_OTHER_PERSON,
status: FanavaranAuditStatus.STARTED,
requestUrl: url,
requestMethod: 'POST',
requestBody: payload,
requestMeta: { nationalCode },
});
try {
const response = await this.postFanavaranJson(
url,
payload,
input.clientKey,
auditSession,
input.claimCaseId,
);
const created = response.data;
const personId = pickFanavaranRecordId(created);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.CREATE_OTHER_PERSON,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: url,
requestMethod: 'POST',
requestBody: payload,
responseBody: created,
responseMeta: { otherPersonId: personId, nationalCode },
durationMs: Date.now() - startedAt,
});
if (personId != null) {
this.logger.log(
`[registerFanavaranOtherPerson] CREATED Id=${personId} for nationalCode=${nationalCode}`,
);
return personId;
}
this.logger.warn(
`[registerFanavaranOtherPerson] create returned no Id for nationalCode=${nationalCode}; retrying inquiry`,
);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.CREATE_OTHER_PERSON,
status: FanavaranAuditStatus.FAILURE,
requestUrl: url,
requestMethod: 'POST',
requestBody: payload,
errorMessage: message,
durationMs: Date.now() - startedAt,
});
this.logger.warn(
`[registerFanavaranOtherPerson] CREATE failed for nationalCode=${nationalCode}: ${message}; retrying inquiry`,
);
}
if (input.requiredRoleId === 166) {
try {
return selectFanavaranOtherPersonId(
await this.fanavaranLookupService.inquiryByUniqueIdentifier(
input.clientKey,
{
nationalCode,
birthYear: parsedBirthday.year,
birthMonth: parsedBirthday.month,
birthDay: parsedBirthday.day,
},
),
);
} catch {
return null;
}
}
return this.resolveDriverFanavaranId(
input.clientKey,
nationalCode,
birthday,
input.person?.driverIsInsurer,
);
}
/**
* زیان‌دیده for GEN.12: claim owner when linked to a blame party,
* else the party that is not the guilty one.
*/
private pickDamagedPartyForFanavaran(
blameCase: any,
claimCase: any,
): any | null {
const parties: any[] = Array.isArray(blameCase?.parties)
? blameCase.parties
: [];
if (parties.length === 0) return null;
if (
blameCase?.type === BlameRequestType.CAR_BODY ||
blameCase?.type === 'CAR_BODY'
) {
return resolveDamagedPartyRow(blameCase) ?? parties[0] ?? null;
}
const ownerId = claimCase?.owner?.userId;
if (ownerId) {
const byOwner = parties.find(
(party) => String(party?.person?.userId ?? '') === String(ownerId),
);
if (byOwner) return byOwner;
}
const guiltyPartyId = this.resolveGuiltyPartyIdV2(
parties,
blameCase?.expert?.decision?.guiltyPartyId,
);
if (guiltyPartyId) {
const injured = parties.find(
(party) =>
String(party?.person?.userId ?? '') !== String(guiltyPartyId),
);
if (injured) return injured;
}
return (
parties.find((party) => party?.role === PartyRole.FIRST) ?? parties[0]
);
}
private getNationalCodeOfInsurerForGuiltyPartyV2(
parties: Array<{
role?: PartyRole;
person?: { userId?: Types.ObjectId; nationalCodeOfInsurer?: string };
participants?: Array<Record<string, any>>;
participantRoles?: Partial<InquiryParticipantRoleAssignments>;
statement?: { admitsGuilt?: boolean };
}>,
guiltyPartyId?: Types.ObjectId | string | null,
): string | null {
if (!guiltyPartyId) {
return null;
}
const guiltyParty = parties.find(
(party) => party.person?.userId?.toString() === guiltyPartyId.toString(),
);
if (!guiltyParty) return null;
return (
resolvePolicyholderFromParty(guiltyParty, 'third-party').nationalCode ??
guiltyParty.person?.nationalCodeOfInsurer ??
null
);
}
private resolveGuiltyPartyIdV2(
parties: Array<{
role?: PartyRole;
person?: { userId?: Types.ObjectId };
statement?: { admitsGuilt?: boolean };
}>,
decisionGuiltyPartyId?: Types.ObjectId | string | null,
): Types.ObjectId | string | null {
if (decisionGuiltyPartyId) {
return decisionGuiltyPartyId;
}
const admitsGuiltParty = parties.find(
(party) => party.statement?.admitsGuilt && party.person?.userId,
);
if (admitsGuiltParty?.person?.userId) {
return admitsGuiltParty.person.userId;
}
// Legacy-compatible safety fallback: when no explicit guilty marker exists,
// use FIRST party if available (same heuristic used by older flows).
const firstParty = parties.find(
(party) => party.role === PartyRole.FIRST && party.person?.userId,
);
return firstParty?.person?.userId ?? null;
}
/**
* Build Fanavaran GEN.03 payload from local claim/blame data.
*
* HTTP preview/submit always pass forceRefreshPolicy + forceRefreshUsedId,
* so PolicyId and AccidentVehicleUsedId are re-inquired every call.
* Auth still uses the shared midnight-TTL token cache (not a new login per preview).
*/
async previewFanavaranSubmitV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
options?: {
debug?: boolean;
/** Bust cached PolicyId and inquire again. */
forceRefreshPolicy?: boolean;
/** @deprecated Use forceRefreshPolicy. When true with no cache, inquired; kept for submit. */
resolvePolicy?: boolean;
/** When true (submit), missing PolicyId throws. Preview keeps payload even if inquiry fails. */
requirePolicyId?: boolean;
/** Only submission may register the hull driver through GEN.44. */
registerMissingHullDriver?: boolean;
/**
* When false (HTTP preview), missing staff ClaimExpertId stays null and is
* reported in previewWarnings instead of throwing.
* Submit keeps the default (required).
*/
requireClaimExpertId?: boolean;
auditSession?: FanavaranAuditSession;
/** Persist built payload onto fanavaranSync.baseClaim.lastPayload (default true). */
persistPayload?: boolean;
/**
* Re-run VIN inquiry / vehicle GET for AccidentVehicleUsedId.
* Hull always reads UsedId from the policy's vehicle version; unresolved
* hull values produce a preview warning and block submit.
*/
forceRefreshUsedId?: boolean;
},
): Promise<any> {
const profile = getFanavaranClientProfile(clientKey);
const payloadDefaults = this.fanavaranPayloadDefaultsWithoutExpertIds(
profile.defaults as unknown as Record<string, unknown>,
);
const logPrefix = `[Fanavaran ${clientKey} V2] claimCaseId=${claimCaseId}`;
const forceRefreshPolicy = options?.forceRefreshPolicy === true;
const forceRefreshUsedId = options?.forceRefreshUsedId === true;
const requirePolicyId = options?.requirePolicyId === true;
const requireClaimExpertId = options?.requireClaimExpertId !== false;
const persistPayload = options?.persistPayload !== false;
const previewWarnings: Array<{
code: string;
message: string;
field: string;
candidatesTried?: string[];
}> = [];
const auditSession =
options?.auditSession ??
({
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey,
source: FanavaranAuditSource.PREVIEW,
claimCaseId,
} satisfies FanavaranAuditSession);
try {
const debug = {
clientKey,
claimCaseId,
forceRefreshPolicy,
steps: {
claimCaseFound: false,
blameRequestLinked: false,
blameCaseFound: false,
expertDecisionFound: false,
accidentReasonFound: false,
firstPartyFound: false,
firstPartyLocationFound: false,
damageReplyFound: false,
guiltyPartyIdFound: false,
nationalCodeOfInsurerFound: false,
policyIdFromCache: false,
policyInquiryAttempted: false,
policyInquirySucceeded: false,
accidentReasonFallbackFromSnapshot: false,
guiltyPartyFallbackUsed: false,
},
values: {
blameRequestId: null as string | null,
guiltyPartyId: null as string | null,
nationalCodeOfInsurer: null as string | null,
policyId: null as number | null,
estimateAmount: null as number | null,
},
failureReason: null as string | null,
note: 'HTTP preview/submit always re-inquire PolicyId and AccidentVehicleUsedId. Auth token is shared until Tehran midnight.',
};
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
throw new NotFoundException('Claim case not found');
}
debug.steps.claimCaseFound = true;
if (!claimCase.blameRequestId) {
debug.failureReason = 'claimCase.blameRequestId is missing';
throw new BadRequestException('Blame case not linked to claim case');
}
debug.steps.blameRequestLinked = true;
debug.values.blameRequestId = claimCase.blameRequestId.toString();
const blameCase = await this.blameRequestDbService.findById(
claimCase.blameRequestId,
);
if (!blameCase) {
throw new NotFoundException('Blame case not found');
}
debug.steps.blameCaseFound = true;
const expertDecision = blameCase.expert?.decision;
debug.steps.expertDecisionFound = !!expertDecision;
const fallbackAccidentReason =
claimCase.snapshot?.accident?.classification?.accidentReason;
if (!expertDecision?.fields?.accidentReason && fallbackAccidentReason) {
debug.steps.accidentReasonFallbackFromSnapshot = true;
}
const selectedAccidentReason =
expertDecision?.fields?.accidentReason ?? fallbackAccidentReason;
debug.steps.accidentReasonFound = !!selectedAccidentReason;
const firstParty = blameCase.parties?.find(
(party) => party.role === PartyRole.FIRST,
);
debug.steps.firstPartyFound = !!firstParty;
debug.steps.firstPartyLocationFound = !!firstParty?.location;
const activeExpertReply = getActiveV2ExpertReply(
claimCase as unknown as { evaluation?: Record<string, unknown> },
);
const damageParts = activeExpertReply?.parts;
debug.steps.damageReplyFound = !!damageParts?.length;
if (options?.debug) {
debug.values.estimateAmount = damageParts
? this.calculateEstimateAmount(damageParts)
: 0;
}
const cachedPolicyId =
(claimCase as any)?.fanavaranSync?.baseClaim?.policyId ??
(claimCase as any)?.fanavaranSync?.baseClaim?.lastPayload?.PolicyId ??
null;
const accidentAt =
blameCase.type === BlameRequestType.CAR_BODY
? ((firstParty as { statement?: { accidentDate?: Date } })?.statement
?.accidentDate ?? (blameCase as { createdAt?: Date }).createdAt)
: (blameCase as { createdAt?: Date }).createdAt;
const payload = await this.buildFanavaranSubmitPayload({
accidentReason: selectedAccidentReason,
createdAt: accidentAt,
location: firstParty?.location,
damageParts,
defaults: payloadDefaults as {
AccidentCityId: number;
AccidentReportTypeId: number;
AccidentVehicleUsedId: number;
CompensationReferenceId: number;
CulpritLicenceTypeId: number;
CulpritTypeId: number;
},
logPrefix,
requirePolicyId,
resolvePolicyId: async () => {
const product = fanavaranClaimProductFromBlameType(blameCase.type);
if (cachedPolicyId != null && !forceRefreshPolicy) {
debug.steps.policyIdFromCache = true;
debug.values.policyId = Number(cachedPolicyId);
return Number(cachedPolicyId);
}
if (product === 'car-body') {
const storedPolicyId = pickStoredCarBodyPolicyId(blameCase);
if (storedPolicyId != null) {
debug.values.policyId = storedPolicyId;
debug.steps.policyInquirySucceeded = true;
return storedPolicyId;
}
const nationalCodeOfInsurer =
pickCarBodyPolicyNationalCode(blameCase);
debug.steps.nationalCodeOfInsurerFound = !!nationalCodeOfInsurer;
debug.values.nationalCodeOfInsurer = nationalCodeOfInsurer;
if (!nationalCodeOfInsurer) {
this.logger.warn(
`${logPrefix} car-body policyholder national code is missing`,
);
debug.failureReason =
'car-body policyholder national code is missing';
return null;
}
debug.steps.policyInquiryAttempted = true;
const policyId = await this.getPolicyIdFromNationalCode(
nationalCodeOfInsurer,
profile.auth,
logPrefix,
auditSession,
{
clientKey,
claimCaseId,
product: 'car-body',
accidentDate: firstParty?.statement?.accidentDate,
},
);
debug.values.policyId = policyId;
debug.steps.policyInquirySucceeded = policyId !== null;
if (policyId === null) {
debug.failureReason =
debug.failureReason ??
'car-body policy inquiry returned no PolicyId (timeout, network error, empty response, or backoff)';
}
return policyId;
}
const guiltyPartyId = this.resolveGuiltyPartyIdV2(
blameCase.parties ?? [],
expertDecision?.guiltyPartyId,
);
if (!expertDecision?.guiltyPartyId && guiltyPartyId) {
debug.steps.guiltyPartyFallbackUsed = true;
}
debug.steps.guiltyPartyIdFound = !!guiltyPartyId;
debug.values.guiltyPartyId = guiltyPartyId
? guiltyPartyId.toString()
: null;
const nationalCodeOfInsurer =
this.getNationalCodeOfInsurerForGuiltyPartyV2(
blameCase.parties ?? [],
guiltyPartyId,
);
debug.steps.nationalCodeOfInsurerFound = !!nationalCodeOfInsurer;
debug.values.nationalCodeOfInsurer = nationalCodeOfInsurer;
if (!guiltyPartyId) {
this.logger.warn(
`${logPrefix} guiltyPartyId not found in expert.decision`,
);
debug.failureReason = 'expert.decision.guiltyPartyId is missing';
return null;
}
if (!nationalCodeOfInsurer) {
this.logger.warn(
`${logPrefix} nationalCodeOfInsurer not found for guiltyPartyId: ${guiltyPartyId}`,
);
debug.failureReason =
'nationalCodeOfInsurer not found for guilty party in blameCase.parties';
return null;
}
debug.steps.policyInquiryAttempted = true;
const policyId = await this.getPolicyIdFromNationalCode(
nationalCodeOfInsurer,
profile.auth,
logPrefix,
auditSession,
{ clientKey, claimCaseId, product: 'third-party' },
);
debug.values.policyId = policyId;
debug.steps.policyInquirySucceeded = policyId !== null;
if (policyId === null) {
debug.failureReason =
debug.failureReason ??
'policy inquiry returned no PolicyId (timeout, network error, empty response, or backoff)';
}
return policyId;
},
});
// GEN.03 CulpritLicence* + CulpritTypeId: guilty-party DRIVER for THIRD_PARTY,
// FIRST-party DRIVER for CAR_BODY. CulpritTypeId uses accident-culprit-type
// (337 بیمه‌گذار / 338 راننده غير از بيمه گذار) — hull remaps separately.
{
const culpritParty =
blameCase.type === BlameRequestType.CAR_BODY
? firstParty
: (() => {
const guiltyPartyId = this.resolveGuiltyPartyIdV2(
blameCase.parties ?? [],
expertDecision?.guiltyPartyId,
);
return (blameCase.parties ?? []).find(
(party: any) =>
String(party?.person?.userId ?? '') ===
String(guiltyPartyId ?? ''),
);
})();
const culpritDriver = resolveDriverFromParty(culpritParty as any);
payload.CulpritLicenceNo = resolveFanavaranLicenceNo(
culpritDriver,
FANAVARAN_DUMMY_LICENCE_NO,
);
payload.CulpritLicenceIssuDate =
resolveFanavaranLicenceIssuDate(culpritDriver);
const licenseReplaced = resolveFanavaranIsLicenseReplaced(
payload.CulpritLicenceIssuDate,
payload.AccidentDate,
);
payload.IsLicenseReplacement = licenseReplaced;
payload.IsLicenseReplaced = licenseReplaced;
if (blameCase.type !== BlameRequestType.CAR_BODY) {
payload.CulpritTypeId = resolveThirdPartyCulpritTypeId(
culpritParty as any,
);
}
}
const carBodyAccidentTime = (
firstParty as { statement?: { accidentTime?: string } } | undefined
)?.statement?.accidentTime;
if (
blameCase.type === BlameRequestType.CAR_BODY &&
typeof carBodyAccidentTime === 'string' &&
carBodyAccidentTime.trim()
) {
payload.AccidentTime = carBodyAccidentTime.trim();
}
const isHull = blameCase.type === BlameRequestType.CAR_BODY;
const cachedUsedId =
forceRefreshUsedId || forceRefreshPolicy
? null
: (claimCase as any)?.fanavaranSync?.baseClaim?.accidentVehicleUsedId;
const cachedUsedSource = (claimCase as any)?.fanavaranSync?.baseClaim
?.accidentVehicleUsedSource;
const canReuseApiUsedId =
!isHull &&
!forceRefreshUsedId &&
!forceRefreshPolicy &&
cachedUsedId != null &&
Number(cachedUsedId) > 0 &&
(cachedUsedSource === 'vin-inquiry' ||
cachedUsedSource === 'policy-vehicle');
delete payload.AccidentVehicleUsedId;
let usedSource:
| 'expert-review'
| 'vin-inquiry'
| 'policy-vehicle'
| null = null;
if (canReuseApiUsedId) {
payload.AccidentVehicleUsedId = Number(cachedUsedId);
usedSource = cachedUsedSource;
} else {
const guiltyPartyIdForVin = this.resolveGuiltyPartyIdV2(
blameCase.parties ?? [],
expertDecision?.guiltyPartyId,
);
const resolved = await this.resolveAccidentVehicleUsedFromApis({
clientKey,
parties: blameCase.parties ?? [],
guiltyPartyId: guiltyPartyIdForVin,
policyId:
typeof payload.PolicyId === 'number' ? payload.PolicyId : null,
product: fanavaranClaimProductFromBlameType(blameCase.type),
});
if (resolved.usedId != null) {
payload.AccidentVehicleUsedId = resolved.usedId;
usedSource = resolved.source;
}
}
const approvedUseTypeId = Number(
(claimCase as any)?.fanavaranVehicleReview?.vehicleUseType?.id,
);
if (
!isHull &&
Number.isInteger(approvedUseTypeId) &&
approvedUseTypeId > 0
) {
payload.AccidentVehicleUsedId = approvedUseTypeId;
usedSource = 'expert-review';
}
if (parseFanavaranId(payload.AccidentVehicleUsedId) == null) {
if (isHull) {
payload.AccidentVehicleUsedId = null;
const warning = {
code: 'FANAVARAN_HULL_VEHICLE_USE_UNRESOLVED',
message: `AccidentVehicleUsedId unresolved: policy ${payload.PolicyId ?? 'unknown'} vehicle inquiry did not return UsedId. Read the hull policy VehicleId/VehicleVersionNo and retry the vehicle inquiry.`,
field: 'AccidentVehicleUsedId',
};
previewWarnings.push(warning);
if (requirePolicyId) throw new BadRequestException(warning);
} else {
payload.AccidentVehicleUsedId =
profile.defaults.AccidentVehicleUsedId;
this.logger.log(
`${logPrefix} AccidentVehicleUsedId API miss; using config default ${payload.AccidentVehicleUsedId}`,
);
}
}
Object.assign(debug.values, {
accidentVehicleUsedId: payload.AccidentVehicleUsedId,
accidentVehicleUsedSource: usedSource,
});
if (fanavaranClaimProductFromBlameType(blameCase.type) === 'car-body') {
await this.enrichCarBodyHullBaseClaimPayload({
clientKey,
payload,
blameCase,
firstParty,
logPrefix,
claimCaseId,
registerMissingDriver: options?.registerMissingHullDriver === true,
cachedRegistration: claimCase.fanavaranSync?.baseClaim,
});
if (payload.AccidentCulpritId == null) {
const warning = {
code: 'FANAVARAN_HULL_DRIVER_ROLE_REQUIRED',
field: 'AccidentCulpritId',
message:
'راننده بیمه بدنه باید در فناوران با نقش سایر (166) ثبت و تأیید شود. ثبت شخص هنگام ارسال انجام می‌شود.',
};
if (requirePolicyId) throw new BadRequestException(warning);
previewWarnings.push(warning);
}
applyFanavaranStageFieldReview(
payload,
claimCase,
'car-body',
'baseClaim',
clientKey,
);
delete payload.IsLicenseReplacement;
const hull = toFanavaranHullBaseClaimPayload(payload, clientKey);
for (const key of Object.keys(payload)) delete payload[key];
Object.assign(payload, hull);
try {
await this.assertFanavaranHullApiValues(
`${getFanavaranLookupBaseUrl(clientKey)}/car/vehicle-hull-claims`,
payload, clientKey, claimCaseId,
);
} catch (error) {
if (requirePolicyId) throw error;
previewWarnings.push({
code: 'FANAVARAN_HULL_LOOKUP_INVALID', field: 'lookups',
message: error instanceof Error ? error.message : String(error),
});
}
}
if (
fanavaranClaimProductFromBlameType(blameCase.type) === 'third-party'
) {
applyFanavaranStageFieldReview(
payload,
claimCase,
'third-party',
'baseClaim',
clientKey,
);
if (clientKey === 'tejaratno') {
const notifierPartyId = await this.resolveTejaratNotifierPartyId({
clientKey,
blameCase,
claimCaseId,
});
if (requirePolicyId && notifierPartyId == null) {
throw new ConflictException({
code: 'FANAVARAN_NOTIFIER_PARTY_REQUIRED',
message:
'اعلام‌کننده خسارت در فناوران پیدا نشد. کد ملی، تاریخ تولد و موبایل بیمه‌گذار مقصر برای ثبت شخص لازم است.',
});
}
const v15 = toTejaratV15ThirdPartyBasePayload(
payload,
notifierPartyId,
);
for (const key of Object.keys(payload)) delete payload[key];
Object.assign(payload, v15);
}
}
const claimExpertResolution =
await this.tryResolveFanavaranBaseClaimExpertId(blameCase, claimCase);
payload.ClaimExpertId = claimExpertResolution.claimExpertId;
(debug as any).steps.claimExpertIdResolved =
claimExpertResolution.claimExpertId != null;
(debug as any).values.claimExpertId = claimExpertResolution.claimExpertId;
(debug as any).values.claimExpertIdCandidatesTried =
claimExpertResolution.candidatesTried;
if (claimExpertResolution.claimExpertId == null) {
const warning = {
code:
claimExpertResolution.code ?? 'FANAVARAN_CLAIM_EXPERT_ID_MISSING',
message:
claimExpertResolution.message ??
'ClaimExpertId unresolved on the assigned expert profile.',
field: 'ClaimExpertId',
candidatesTried: claimExpertResolution.candidatesTried,
};
previewWarnings.push(warning);
(debug as any).values.claimExpertIdWarning = warning.message;
if (requireClaimExpertId) {
throw new BadRequestException({
code: warning.code,
message: warning.message,
});
}
}
if (persistPayload) {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.baseClaim.lastPayload': payload,
'fanavaranSync.baseClaim.lastPayloadBuiltAt': new Date(),
...(payload.PolicyId != null
? { 'fanavaranSync.baseClaim.policyId': payload.PolicyId }
: {}),
...(isHull
? {
'fanavaranSync.baseClaim.accidentVehicleUsedId':
payload.AccidentVehicleUsedId,
'fanavaranSync.baseClaim.accidentVehicleUsedSource':
usedSource,
}
: typeof payload.AccidentVehicleUsedId === 'number'
? {
'fanavaranSync.baseClaim.accidentVehicleUsedId':
payload.AccidentVehicleUsedId,
...(usedSource
? {
'fanavaranSync.baseClaim.accidentVehicleUsedSource':
usedSource,
}
: {}),
}
: {}),
},
});
}
if (options?.debug) {
return {
clientKey,
payload,
debug,
previewWarnings,
};
}
if (previewWarnings.length > 0) {
return {
payload,
previewWarnings,
};
}
return payload;
} catch (error) {
this.logger.error(
`Error in previewFanavaranSubmitV2 (${clientKey})`,
error,
);
throw error;
}
}
/**
* Submit Fanavaran data (V2 claimCases + blameCases) for a specific client.
*/
async submitFanavaranV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>,
): Promise<any> {
try {
return await this.executeFanavaranV2Submit(
claimCaseId,
clientKey,
bodyOverride,
FanavaranAuditSource.SUBMIT,
);
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error(
`[Fanavaran ${clientKey} V2] Error submitting to Fanavaran`,
error,
);
throw toFanavaranHttpException(error, {
fallback: 'Failed to submit data to Fanavaran API',
});
}
}
async previewFanavaranDamageCaseV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<any> {
const profile = getFanavaranClientProfile(clientKey);
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
throw new NotFoundException('Claim case not found');
}
if (!claimCase.blameRequestId) {
throw new BadRequestException('Blame case not linked to claim case');
}
const blameCase = await this.blameRequestDbService.findById(
claimCase.blameRequestId,
);
if (!blameCase) {
throw new NotFoundException('Blame case not found');
}
if (!isFanavaranSubmitSupportedBlameType(blameCase.type)) {
throw new BadRequestException(
'Fanavaran damage-case submit only applies to THIRD_PARTY and CAR_BODY claims',
);
}
const product = fanavaranClaimProductFromBlameType(blameCase.type);
if (!fanavaranHasDamageCaseStage(product)) {
return {
clientKey,
claimCaseId,
claimId: claimCase.claimId ?? null,
dmgCaseId: claimCase.dmgCaseId ?? null,
submitUrl: null,
skipped: true,
skipReason: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON,
warning: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON,
payload: null,
};
}
const payload = await this.buildFanavaranDamageCasePayload({
claimCase,
blameCase,
selectedParts: claimCase.damage?.selectedParts ?? [],
clientKey,
defaults: profile.defaults,
});
const warnings: string[] = [];
if (!claimCase.claimId) {
warnings.push('Fanavaran base claimId is required before submit.');
}
if (payload.DriverId == null) {
warnings.push(
'Damaged party has no Fanavaran RoleId 161/166 yet; submit will register them via other-people (GEN.44).',
);
}
return {
clientKey,
claimCaseId,
claimId: claimCase.claimId ?? null,
dmgCaseId: claimCase.dmgCaseId ?? null,
submitUrl: claimCase.claimId
? fanavaranClaimStageUrl(
product,
'damage-case',
claimCase.claimId,
clientKey,
)
: null,
warning: warnings.length ? warnings.join(' ') : undefined,
payload,
};
}
async submitFanavaranDamageCaseV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>,
): Promise<any> {
try {
return await this.executeFanavaranDamageCaseSubmit(
claimCaseId,
clientKey,
undefined,
FanavaranAuditSource.SUBMIT,
bodyOverride,
);
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error(
`[Fanavaran ${clientKey} V2] Error submitting damage case to Fanavaran`,
error,
);
throw toFanavaranHttpException(error, {
fallback: 'Failed to submit data to Fanavaran API',
});
}
}
private getSubmittedFanavaranAttachmentFileNames(
claimCase: any,
): Map<string, unknown> {
const submitted = new Map<string, unknown>();
const files = claimCase?.fanavaranSync?.attachments?.files;
if (!Array.isArray(files)) return submitted;
for (const file of files) {
const fileName = (file as { fileName?: unknown })?.fileName;
const fileId = pickFanavaranRecordId((file as { fileId?: unknown })?.fileId);
if (typeof fileName === 'string' && fileName.trim() && fileId != null) {
submitted.set(fileName, fileId);
}
}
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(
candidates: FanavaranAttachmentCandidate[],
seen: Set<string>,
submittedFiles: Map<string, unknown>,
waivedFiles: Map<string, string>,
input: { path?: unknown; fileName?: unknown; source: string },
fileTypeId: number,
): void {
const path = typeof input.path === 'string' ? input.path : '';
const fileName =
typeof input.fileName === 'string' && input.fileName.trim()
? input.fileName
: path
? basename(path)
: '';
if (!path || !fileName || seen.has(fileName)) return;
seen.add(fileName);
const waivedReason = waivedFiles.get(fileName);
const alreadyWaived = waivedReason != null;
candidates.push({
path,
fileName,
source: input.source,
content: {
FileName: fileName,
FileTypeId: fileTypeId,
Files: [{ FileName: fileName, FileTypeId: fileTypeId }],
},
alreadySubmitted: submittedFiles.has(fileName) || alreadyWaived,
alreadyWaived,
waivedReason,
submittedFileId: submittedFiles.get(fileName),
});
}
private async collectFanavaranAttachmentCandidates(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<{
claimCase: any;
candidates: FanavaranAttachmentCandidate[];
}> {
const profile = getFanavaranClientProfile(clientKey);
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
throw new NotFoundException('Claim case not found');
}
const candidates: FanavaranAttachmentCandidate[] = [];
const seen = new Set<string>();
const submittedFiles =
this.getSubmittedFanavaranAttachmentFileNames(claimCase);
const waivedFiles = this.getWaivedFanavaranAttachmentFileNames(claimCase);
const fileTypeId = profile.defaults.ClaimFileTypeId;
const documents =
await this.claimRequiredDocumentDbService.findByClaimId(claimCaseId);
for (const document of documents) {
this.appendFanavaranAttachmentCandidate(
candidates,
seen,
submittedFiles,
waivedFiles,
{
path: (document as { path?: unknown }).path,
fileName: (document as { fileName?: unknown }).fileName,
source: `document:${String((document as { documentType?: unknown }).documentType ?? 'unknown')}`,
},
fileTypeId,
);
}
const carAngles = claimCase.media?.carAngles;
const angleEntries =
carAngles instanceof Map
? Array.from(carAngles.entries())
: carAngles && typeof carAngles === 'object'
? Object.entries(carAngles)
: [];
for (const [angleKey, image] of angleEntries) {
const capture = image as { path?: unknown; fileName?: unknown };
this.appendFanavaranAttachmentCandidate(
candidates,
seen,
submittedFiles,
waivedFiles,
{
path: capture?.path,
fileName: capture?.fileName,
source: `capture:angle:${angleKey}`,
},
fileTypeId,
);
}
const damagedParts = claimCase.media?.damagedParts;
const partEntries = Array.isArray(damagedParts)
? damagedParts.map((part, index) => [String(index), part] as const)
: damagedParts && typeof damagedParts === 'object'
? Object.entries(damagedParts)
: [];
for (const [partKey, image] of partEntries) {
const capture = image as { path?: unknown; fileName?: unknown };
this.appendFanavaranAttachmentCandidate(
candidates,
seen,
submittedFiles,
waivedFiles,
{
path: capture?.path,
fileName: capture?.fileName,
source: `capture:part:${partKey}`,
},
fileTypeId,
);
}
return { claimCase, candidates };
}
async previewFanavaranAttachmentsV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<any> {
const { claimCase, candidates } =
await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey);
const claimsUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId);
const uploadStatus = fanavaranAttachmentStatus(claimCase.fanavaranSync?.attachments) ?? {
status: 'not_recorded', uploadedCount: 0, files: [], attempts: [], lastError: null,
};
return {
clientKey,
claimCaseId,
claimId: claimCase.claimId ?? null,
claimNo: claimCase.claimNo ?? null,
dmgCaseId: claimCase.dmgCaseId ?? null,
fileIds: [...new Set(uploadStatus?.files.map(file => file.fileId) ?? [])],
uploadStatus,
submitUrl: claimCase.claimId
? `${claimsUrl}/${claimCase.claimId}/files`
: null,
warning: claimCase.claimId
? undefined
: 'Fanavaran base claimId is required before attachment submit.',
totalLocalImages: candidates.length,
alreadySubmitted: candidates.filter(
(candidate) => candidate.alreadySubmitted,
).length,
pendingSubmit: candidates.filter(
(candidate) => !candidate.alreadySubmitted,
).length,
attachments: candidates.map(candidate => {
const latestAttempt = uploadStatus?.attempts.filter(attempt => attempt.fileName === candidate.fileName).at(-1);
const localFileExists = existsSync(candidate.path);
const status = candidate.alreadyWaived
? 'skipped'
: candidate.alreadySubmitted
? 'success'
: !localFileExists
? 'skipped'
: latestAttempt?.status ?? 'pending';
return {
...candidate, fileId: candidate.submittedFileId ?? null, localFileExists,
status,
lastError: candidate.alreadyWaived
? candidate.waivedReason ?? latestAttempt?.error ?? null
: candidate.alreadySubmitted
? null
: !localFileExists
? 'Local attachment file does not exist.'
: latestAttempt?.error ?? null,
};
}),
};
}
async submitFanavaranAttachmentsV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<any> {
const { claimCase: initialClaim, candidates } =
await this.collectFanavaranAttachmentCandidates(claimCaseId, clientKey);
const pending = candidates.filter(candidate => !candidate.alreadySubmitted);
const skippedAlreadySubmitted = candidates.length - pending.length;
if (!pending.length) {
return {
clientKey, claimCaseId, totalLocalImages: candidates.length,
skippedAlreadySubmitted, attempted: 0, submitted: 0, failed: 0,
skipped: candidates.length, results: [],
};
}
const skipPending = async (warning: string) => {
await Promise.all(pending.map(candidate => this.recordSkippedFanavaranAttachment(
claimCaseId, candidate.fileName, candidate.source, warning,
)));
return {
clientKey, claimCaseId, totalLocalImages: candidates.length,
skippedAlreadySubmitted, attempted: 0, submitted: 0, failed: 0,
skipped: pending.length, warning,
results: pending.map(candidate => ({
attempted: false, submitted: false, skipped: true,
skipReason: warning, fileName: candidate.fileName,
})),
};
};
let nestedClaimId: number | null;
try {
let claimCase = initialClaim;
this.assertFanavaranVehicleReviewApproved(claimCase);
if (!claimCase?.claimId) {
await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, FanavaranAuditSource.SUBMIT);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
}
if (!claimCase?.claimId) return skipPending('Fanavaran base claimId is missing');
await this.syncFanavaranHullBaseClaim(claimCaseId, clientKey);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
nestedClaimId = fanavaranHullNestedClaimId({ claimId: claimCase?.claimId, claimNo: claimCase?.claimNo });
if (nestedClaimId == null) return skipPending('Fanavaran base claimId is missing');
} catch (error) {
return skipPending(this.extractFanavaranErrorMessage(error));
}
const url = `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${nestedClaimId}/files`;
const results: any[] = [];
for (let i = 0; i < pending.length; i++) {
const candidate = pending[i];
const result = await this.autoSubmitFanavaranAttachment(
claimCaseId,
{ path: candidate.path, fileName: candidate.fileName, source: candidate.source },
{ clientKey, auditSource: FanavaranAuditSource.SUBMIT },
);
results.push({ ...result, claimId: nestedClaimId, submitUrl: url });
if (i < pending.length - 1) {
await new Promise((resolve) => setTimeout(resolve, 1_000));
}
}
return results;
}
private async recordSkippedFanavaranAttachment(
claimCaseId: string,
fileName: string,
source: string | undefined,
reason: string,
): Promise<void> {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.attachments.status': 'skipped',
'fanavaranSync.attachments.lastTriedAt': new Date(),
'fanavaranSync.attachments.lastError': reason,
},
$push: { 'fanavaranSync.attachments.attempts': {
fileName, source, status: 'skipped', error: reason, attemptedAt: new Date(),
} },
});
}
async autoSubmitFanavaranAttachment(
claimCaseId: string,
file: { path?: string | null; fileName?: string | null; source?: string },
options?: {
clientKey?: FanavaranClientKey;
auditSource?: FanavaranAuditSource;
/** True on the immediate second try after a format rejection. */
formatRetryAttempted?: boolean;
},
): Promise<FanavaranAttachmentSubmitResult> {
const clientKey = options?.clientKey ?? resolveFanavaranClientKey();
const auditSource =
options?.auditSource ?? FanavaranAuditSource.AUTO_SUBMIT;
const logPrefix = `[Fanavaran ${clientKey} V2 Attachment Auto] claimCaseId=${claimCaseId}`;
const filePath = file.path ? String(file.path) : '';
const fileName = file.fileName
? String(file.fileName)
: filePath
? basename(filePath)
: '';
const profile = getFanavaranClientProfile(clientKey);
let url = '';
let content: Record<string, unknown> = {};
let auditSession: FanavaranAuditSession | undefined;
try {
if (!filePath || !fileName) {
await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, 'Attachment file path or filename is missing');
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: 'Attachment file path or filename is missing',
};
}
if (!existsSync(filePath)) {
await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, `Attachment file does not exist: ${filePath}`);
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: `Attachment file does not exist: ${filePath}`,
fileName,
};
}
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
return {
attempted: false,
submitted: false,
warning: 'Claim case not found for Fanavaran attachment submit.',
fileName,
};
}
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),
};
}
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 (options?.clientKey) {
await this.executeFanavaranV2Submit(claimCaseId, clientKey);
} else {
await this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId);
}
claimCase = await this.claimCaseDbService.findById(claimCaseId);
}
if (!claimCase?.claimId) {
const warning =
'Fanavaran base claim is missing, so attachment was not submitted.';
await this.recordSkippedFanavaranAttachment(claimCaseId, fileName, file.source, warning);
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: warning,
warning,
fileName,
};
}
url = `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/files`;
content = {
FileName: fileName,
FileTypeId: profile.defaults.ClaimFileTypeId,
Files: [
{ FileName: fileName, FileTypeId: profile.defaults.ClaimFileTypeId },
],
...((await this.resolveFanavaranClaimProduct(claimCaseId)) ===
'car-body'
? { ClaimId: claimCase.claimId }
: {}),
};
auditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey,
source: auditSource,
claimCaseId,
};
const startedAt = Date.now();
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_ATTACHMENT,
status: FanavaranAuditStatus.STARTED,
requestUrl: url,
requestMethod: 'POST',
requestBody: content,
requestMeta: {
claimId: claimCase.claimId,
claimNo: claimCase.claimNo,
dmgCaseId: claimCase.dmgCaseId,
fileName,
source: file.source,
},
});
const response = await this.postFanavaranMultipart(
url,
content,
[{ path: filePath, fileName }],
clientKey,
auditSession,
);
this.logger.log(
`${logPrefix} Fanavaran response: ${JSON.stringify(response.data)}`,
);
const fileId = pickFanavaranRecordId(response.data);
if (fileId == null) {
throw new BadGatewayException({
code: 'FANAVARAN_ATTACHMENT_ID_MISSING',
message: 'Fanavaran returned no attachment Id; upload receipt could not be confirmed.',
});
}
const exchange =
this.fanavaranAuditService.captureAxiosExchange(response);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_ATTACHMENT,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: url,
requestMethod: 'POST',
httpStatus: response.status,
requestBody: content,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
responseMeta: { claimId: claimCase.claimId, fileId, fileName },
durationMs: Date.now() - startedAt,
});
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.attachments.status': 'success',
'fanavaranSync.attachments.lastTriedAt': new Date(),
'fanavaranSync.attachments.claimId': claimCase.claimId,
'fanavaranSync.attachments.response': response.data,
'fanavaranSync.attachments.lastError': null,
},
$push: {
'fanavaranSync.attachments.attempts': {
fileId, fileName, source: file.source, status: 'success',
attemptedAt: new Date(), trackingCode: auditSession.trackingCode,
},
'fanavaranSync.attachments.files': {
fileId,
fileName,
source: file.source,
response: response.data,
submittedAt: new Date(),
},
history: {
type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_SUCCEEDED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: {
clientKey,
claimId: claimCase.claimId,
fileId,
fileName,
source: file.source,
},
},
},
});
return {
attempted: true,
submitted: true,
claimId: claimCase.claimId,
fileId,
fileName,
fanavaranResponse: response.data,
};
} catch (error) {
const warning = this.extractFanavaranErrorMessage(error);
this.logger.warn(`${logPrefix} Fanavaran error: ${warning}`);
if (auditSession) {
try {
const exchange = this.fanavaranAuditService.captureAxiosExchange(error);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_ATTACHMENT,
status: FanavaranAuditStatus.FAILURE,
requestUrl: url, requestMethod: 'POST', requestBody: content,
httpStatus: exchange.httpStatus, responseBody: exchange.responseBody,
requestMeta: { fileName, source: file.source }, errorMessage: warning,
});
} catch (auditError) {
this.logger.warn(`${logPrefix} Failed to record upload audit failure`, auditError);
}
}
try {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.attachments.status': 'failed',
'fanavaranSync.attachments.lastTriedAt': new Date(),
'fanavaranSync.attachments.lastError': warning,
},
$push: {
'fanavaranSync.attachments.attempts': {
fileName, source: file.source, status: 'failed',
error: warning, attemptedAt: new Date(), trackingCode: auditSession?.trackingCode,
},
history: {
type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: {
clientKey,
error: warning,
fileName,
source: file.source,
},
},
},
});
} catch (historyError) {
this.logger.error(
`${logPrefix} Failed to record Fanavaran attachment failure history`,
historyError,
);
}
// 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
// caller: local media/docs are already persisted before this submit.
try {
const missingId = error instanceof BadGatewayException &&
typeof error.getResponse() === 'object' &&
(error.getResponse() as { code?: string }).code === 'FANAVARAN_ATTACHMENT_ID_MISSING';
if (!missingId) await this.scheduleFanavaranRetry(
claimCaseId,
'attachments',
() => this.autoSubmitFanavaranAttachment(claimCaseId, file, options),
logPrefix,
{ error, clientKey },
);
} catch (retryScheduleError) {
this.logger.error(
`${logPrefix} Failed to schedule Fanavaran attachment retry`,
retryScheduleError,
);
}
return {
attempted: true,
submitted: false,
warning,
fileName,
};
}
}
private fanavaranLookupDefinition(name: string) {
const definition = FANAVARAN_REMOTE_LOOKUPS.find(
(item) => item.name === name,
);
if (!definition) {
throw new Error(`Unknown Fanavaran lookup definition: ${name}`);
}
return definition;
}
/** Read-only panel context. Does not create a remote claim or persist a preview. */
async getFanavaranStageFieldsContext(claim: any, blame: any) {
if (!blame || !isFanavaranSubmitSupportedBlameType(blame.type)) {
throw new BadRequestException(
'Fanavaran field review only applies to third-party and car-body claims.',
);
}
const product = fanavaranClaimProductFromBlameType(blame.type);
const clientKey = resolveFanavaranClientKey();
const defaults = getFanavaranClientProfile(clientKey).defaults;
const definitions = fanavaranStageFields(product, clientKey);
const options = new Map<string, ReturnType<typeof activeStageLookupRows>>();
await Promise.all(
definitions
.filter((field) => field.lookup)
.map(async (field) => {
options.set(
field.lookup,
activeStageLookupRows(
await this.getFanavaranLookupRows(clientKey, field.lookup),
),
);
}),
);
const initial: FanavaranFieldValues = {
AccidentLocationAddress: blame.parties?.find((party: any) => party.role === 'FIRST')?.location?.address?.trim() || blame.parties?.find((party: any) => party.location?.address?.trim())?.location.address.trim() || FANAVARAN_ACCIDENT_LOCATION_ADDRESS,
AccidentCityId: defaults.AccidentCityId,
AccidentReportTypeId: defaults.AccidentReportTypeId,
DmgHistoryStatus: defaults.DmgHistoryStatus,
InspectionPlaceId: 282,
AccidentTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-types') ?? [], FANAVARAN_HULL_ACCIDENT_TYPE_CAPTION),
CulpritTypeId: findLookupIdByCaption(options.get('vehicle-hull-accident-culprit-type') ?? [], FANAVARAN_HULL_CULPRIT_TYPE_CAPTION),
AuthorityCulpritId: authorityCulpritIdFromDetectionRows(
options.get('detection-accident-culprits') ?? [],
),
CustomerFaultPercent: FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT,
RepairDuration: FANAVARAN_DEFAULT_HULL_REPAIR_DURATION,
};
if (product === 'car-body') {
const price =
this.parseFanavaranMoney(claim?.vehicle?.carPrice) ||
this.parseFanavaranMoney(claim?.vehicle?.price) ||
this.parseFanavaranMoney(claim?.evaluation?.priceDrop?.carPrice) ||
(await this.resolveHullVehicleCurrentValueFromPolicy(clientKey, claim));
if (price > 0) initial.VehicleCurrentValue = price;
}
return {
product,
clientKey,
version: claim.fanavaranFieldReview?.version ?? 0,
reviewedAt: claim.fanavaranFieldReview?.reviewedAt,
reviewedByActorName: claim.fanavaranFieldReview?.reviewedByActorName,
fields: definitions.map((field) => {
const sent = fanavaranFieldStageSent(claim, field.stage);
const sentValue = sent
? (claim.fanavaranSync?.[field.stage]?.lastPayload?.[field.key] ??
claim.fanavaranSync?.[field.stage]?.lastPayload
?.DmgNotifications?.[0]?.[field.key])
: undefined;
const reviewedValue = claim.fanavaranFieldReview?.values?.[field.key];
const value = sentValue ?? reviewedValue ?? initial[field.key] ?? null;
const rows = field.lookup
? (options.get(field.lookup) ?? [])
: undefined;
return {
...field,
value,
source:
sentValue != null
? 'submitted'
: reviewedValue != null
? 'reviewed'
: 'default',
editable: !sent,
...(field.lookup
? {
options: rows,
lookupUnavailable: !rows.length,
caption:
rows.find((row) => row.Id === value)?.Caption ??
(reviewedValue === value
? claim.fanavaranFieldReview?.captions?.[field.key]
: undefined),
}
: {}),
};
}),
};
}
private async assertFanavaranHullApiValues(
url: string,
payload: Record<string, unknown>,
clientKey: FanavaranClientKey,
claimCaseId?: string,
): Promise<void> {
if (!/\/car\/vehicle-hull-claims(?:\/|$)/.test(url)) return;
const stage: HullLookupStage = url.endsWith('/expertise')
? 'expertise'
: url.endsWith('/files') ? 'files' : 'baseClaim';
const warnings = await validateFanavaranHullLookupIds(
payload, stage, async (lookup) => {
if (lookup !== 'policy-dmg-accessories') {
return this.getFanavaranLookupRows(clientKey, lookup, true);
}
const claim = claimCaseId
? await this.claimCaseDbService.findById(claimCaseId)
: null;
const policyId = this.parseHullClaimPolicyId(claim);
if (policyId == null) return [];
return this.fanavaranLookupService.vehicleHullDmgAccessoriesByPolicyId(
clientKey, policyId, {
contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
},
);
},
);
if (stage === 'baseClaim') {
const policyId = parseFanavaranId(payload.PolicyId);
try {
const policy = policyId == null ? null : asObjectRecord(
await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId, {
contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
}),
);
const premium = actualPremiumFromHullPolicyRecord(policy);
if (premium == null) warnings.push('ActualPremium could not be resolved from the current hull policy API response.');
else payload.ActualPremium = premium;
} catch {
warnings.push('Hull policy API is unavailable; policy values could not be verified.');
}
}
if (warnings.length) {
throw new BadRequestException({
code: 'FANAVARAN_HULL_LOOKUP_INVALID',
message: 'Hull submission requires valid values from the current Fanavaran API responses.',
warnings,
});
}
}
private async getFanavaranLookupRows(
clientKey: FanavaranClientKey,
name: string,
requireRemote = false,
): Promise<unknown[]> {
if (
!requireRemote && clientKey === 'tejaratno' && isTejaratNotifierLookup(name)
) {
const stored = await this.fanavaranLookupService.readStoredLookup(name);
let rows: unknown = stored;
for (
let level = 0;
level < 3 && rows && !Array.isArray(rows) && typeof rows === 'object';
level++
) {
rows = (rows as { data?: unknown }).data;
}
return Array.isArray(rows) ? rows : [];
}
const definition = this.fanavaranLookupDefinition(name);
try {
const data = requireRemote
? await this.fanavaranLookupService.fetchFromFanavaran(clientKey, definition.url, {
contractIdOverride: resolveFanavaranProductContractId(clientKey, 'car-body'),
})
: await this.fanavaranLookupService.getRemoteLookup(
clientKey,
definition.url,
definition.cacheFile,
);
let rows: unknown = data;
for (
let level = 0;
level < 3 && rows && !Array.isArray(rows) && typeof rows === 'object';
level++
) {
rows = (rows as { data?: unknown }).data;
}
return Array.isArray(rows) ? rows : [];
} catch {
this.logger.warn(
`Lookup "${name}" unavailable for ${clientKey}; returning empty.`,
);
return [];
}
}
private parseFanavaranMoney(value: unknown): number {
if (value == null || value === '') return 0;
if (typeof value === 'number' && Number.isFinite(value)) return value;
const normalized = String(value)
.replace(/[۰-۹]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 1728))
.replace(/[٠-٩]/g, (d) => String.fromCharCode(d.charCodeAt(0) - 1632))
.replace(/,/g, '')
.trim();
const parsed = Number(normalized);
return Number.isFinite(parsed) ? parsed : 0;
}
private fanavaranPartLabel(part: any): string {
const damage = part?.carPartDamage;
if (damage && typeof damage === 'object') {
const d = damage as {
label_fa?: unknown;
part?: unknown;
name?: unknown;
catalogKey?: unknown;
};
return String(
d.label_fa ??
d.part ??
d.name ??
d.catalogKey ??
part?.partName ??
part?.name ??
part?.partId ??
'',
);
}
return String(
damage ?? part?.partName ?? part?.name ?? part?.partId ?? '',
);
}
private fanavaranDaghiWasteValue(daghi: unknown): number {
if (!daghi || typeof daghi !== 'object')
return this.parseFanavaranMoney(daghi);
const d = daghi as { price?: unknown };
return this.parseFanavaranMoney(d.price);
}
private buildFanavaranExpertiseDmgSection(input: {
part: any;
warnings: string[];
}): Record<string, unknown> {
const partId = parseCatalogPartIdInput(input.part?.partId);
const accidentLevel =
typeof input.part?.typeOfDamage === 'number'
? input.part.typeOfDamage
: typeof input.part?.typeOfDamage === 'string' &&
/^\d+$/.test(input.part.typeOfDamage)
? Number(input.part.typeOfDamage)
: FANAVARAN_DEFAULT_ACCIDENT_LEVEL;
const label = this.fanavaranPartLabel(input.part);
if (partId == null) {
input.warnings.push(`No DmgSectionId (partId) for part "${label}".`);
}
return {
Desc: input.part?.typeOfDamage ?? label,
DmgSectionId: partId,
AccidentLevel: accidentLevel,
ComponentReplacementCost: this.parseFanavaranMoney(input.part?.price),
RepairWage: this.parseFanavaranMoney(input.part?.salary),
WasteValue: this.fanavaranDaghiWasteValue(input.part?.daghi),
};
}
private async buildFanavaranExpertisePayload(input: {
claimCase: any;
clientKey: FanavaranClientKey;
/** Preview keeps null ClaimExpertId; submit requires it. Default true. */
requireClaimExpertId?: boolean;
}): Promise<{
payload: Record<string, unknown>;
warnings: string[];
infoWarnings: string[];
replyKey?: string;
}> {
const profile = getFanavaranClientProfile(input.clientKey);
const active = getActiveV2ExpertReply(input.claimCase as any);
const requireClaimExpertId = input.requireClaimExpertId !== false;
const blameForExpertIds = input.claimCase?.blameRequestId
? await this.blameRequestDbService.findById(
String(input.claimCase.blameRequestId),
)
: null;
// GEN.08 / GEN.06 ClaimExpertId always from assigned assessor staff profile.
const warnings: string[] = [];
const infoWarnings: string[] = [];
let claimExpertId: number | null = null;
if (!blameForExpertIds) {
const message =
'Expertise ClaimExpertId unresolved: linked blame case was not found.';
if (requireClaimExpertId) {
throw new BadRequestException({
code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message,
});
}
warnings.push(message);
} else {
const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId(
blameForExpertIds as {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
assignedFileReviewerId?: unknown;
},
input.claimCase,
);
claimExpertId = resolved.claimExpertId;
if (resolved.claimExpertId == null) {
const message =
resolved.message ??
'Expertise ClaimExpertId unresolved on the assigned assessor profile.';
if (requireClaimExpertId) {
throw new BadRequestException({
code:
resolved.code ?? 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING',
message,
});
}
warnings.push(message);
}
}
if (!active?.parts?.length) {
warnings.push('No active damage expert reply with priced parts exists.');
}
const reply = active?.reply as any;
const parts = (active?.parts ?? []).filter((part: any) => {
if (part.factorNeeded !== true) return true;
return this.parseFanavaranMoney(part.totalPayment) > 0;
}) as any[];
if (!parts.length) {
warnings.push('No submit-ready expert pricing lines exist yet.');
}
const priceDrop = input.claimCase.evaluation?.priceDrop ?? {};
const priceDropTotal = this.parseFanavaranMoney(priceDrop?.total);
const submittedAt = reply?.submittedAt ?? new Date();
const product = await this.resolveFanavaranClaimProduct(
input.claimCase?._id ? String(input.claimCase._id) : undefined,
);
if (product === 'car-body') {
return this.buildCarBodyFanavaranExpertisePayload({
clientKey: input.clientKey, claimCase: input.claimCase,
blame: blameForExpertIds, profile, parts, claimExpertId,
submittedAt, priceDropTotal, priceDropCarPrice: priceDrop?.carPrice,
warnings, infoWarnings, replyKey: active?.replyKey,
});
}
const [inspectionPlaces, dropAmountStatuses] = await Promise.all([
this.getFanavaranLookupRows(input.clientKey, 'inspection-place'),
this.getFanavaranLookupRows(input.clientKey, 'drop-amount-status'),
]);
const inspectionPlaceId =
input.claimCase?.fanavaranFieldReview?.values?.InspectionPlaceId ?? 282;
const dropAmountStatus = 5458;
const dmgSections = parts.map((part) =>
this.buildFanavaranExpertiseDmgSection({
part,
warnings,
}),
);
const repairWage = dmgSections.reduce(
(sum, section) => sum + this.parseFanavaranMoney(section.RepairWage),
0,
);
const componentReplacementCost = dmgSections.reduce(
(sum, section) =>
sum + this.parseFanavaranMoney(section.ComponentReplacementCost),
0,
);
const wasteValue = dmgSections.reduce(
(sum, section) => sum + this.parseFanavaranMoney(section.WasteValue),
0,
);
const payload: Record<string, unknown> = {
ClaimExpertId: claimExpertId,
ComponentReplacementCost: componentReplacementCost,
DmgAssessmentDate: this.convertToPersianDate(submittedAt),
InspectionPlaceId: inspectionPlaceId,
InspectionTime: this.getTime24Hour(submittedAt),
RepairWage: repairWage,
WasteValue: wasteValue,
WentDistanceByExpert: null,
DropAmountStatus: dropAmountStatus,
DropAmountAdditionsDeductions: priceDropTotal || 0,
ComponentReplacementTaxAndToll: 0,
DamagedVehicleCurrentPrice:
this.parseFanavaranMoney(priceDrop?.carPrice) || null,
DmgSections: dmgSections,
};
payload.DmgCaseId = input.claimCase.dmgCaseId ?? null;
return {
replyKey: active?.replyKey,
warnings,
infoWarnings,
payload,
};
}
private assertFanavaranExpertisePayloadReady(
payload: Record<string, unknown>,
warnings: string[],
options?: {
requireDmgCaseId?: boolean;
requireThirdPartyLookups?: boolean;
},
): void {
const readyWarnings = collectFanavaranExpertiseReadinessWarnings(
payload,
options,
);
const allWarnings = Array.from(new Set([...warnings, ...readyWarnings]));
if (allWarnings.length) {
throw new BadRequestException({
message: 'Fanavaran expertise payload is not ready.',
warnings: allWarnings,
});
}
}
async previewFanavaranExpertiseV2(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<any> {
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) throw new NotFoundException('Claim case not found');
const { payload, warnings, infoWarnings, replyKey } =
await this.buildFanavaranExpertisePayload({
claimCase,
clientKey,
requireClaimExpertId: false,
});
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.expertise.lastPayload': payload,
'fanavaranSync.expertise.lastPayloadBuiltAt': new Date(),
},
});
const attachments = fanavaranAttachmentStatus(claimCase.fanavaranSync?.attachments);
return {
clientKey,
claimCaseId,
claimId: claimCase.claimId ?? null,
dmgCaseId: claimCase.dmgCaseId ?? null,
expertiseId: claimCase.expertiseId ?? null,
fileIds: [...new Set(attachments?.files.map(file => file.fileId) ?? [])],
attachments,
replyKey,
submitUrl: claimCase.claimId
? `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/expertise`
: null,
ready: warnings.length === 0 && payload.ClaimExpertId != null,
warnings: Array.from(new Set(warnings)),
infoWarnings: Array.from(new Set(infoWarnings)),
payload,
};
}
/** 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(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>,
): Promise<any> {
try {
await this.completeFanavaranExpertisePrerequisites(
claimCaseId,
clientKey,
FanavaranAuditSource.SUBMIT,
);
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
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 built = await this.buildFanavaranExpertisePayload({
claimCase,
clientKey,
});
const payload = applyFanavaranManualPayloadOverrides(
built.payload,
bodyOverride,
FANAVARAN_EXPERTISE_MANUAL_OVERRIDE_KEYS,
);
this.assertFanavaranExpertisePayloadReady(payload, built.warnings, {
...hullExpertiseAssertFields(product),
});
const result = await this.executeFanavaranExpertiseSubmit(
claimCaseId,
clientKey,
payload,
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) {
if (error instanceof HttpException) throw error;
this.logger.error(
`[Fanavaran ${clientKey} V2] Error submitting expertise to Fanavaran`,
error,
);
throw toFanavaranHttpException(error, {
fallback: 'Failed to submit data to Fanavaran API',
});
}
}
private async executeFanavaranExpertiseSubmit(
claimCaseId: string,
clientKey: FanavaranClientKey,
payload: Record<string, unknown>,
auditSource: FanavaranAuditSource,
): Promise<any> {
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) throw new NotFoundException('Claim case not found');
this.assertFanavaranVehicleReviewApproved(claimCase);
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
if (
!claimCase?.claimId ||
(fanavaranHasDamageCaseStage(product) && claimCase.dmgCaseId == null)
) {
await this.ensureFanavaranDamageCase(claimCaseId, clientKey, auditSource);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
}
if (!claimCase?.claimId) {
throw new BadRequestException(
'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) {
this.logger.log(
`[executeFanavaranExpertiseSubmit] Already have expertiseId=${claimCase.expertiseId}; skipping Fanavaran POST`,
);
// Product decision: completing the final Fanavaran stage must not send SMS.
return (
(claimCase as any)?.fanavaranSync?.expertise?.response ?? {
Id: claimCase.expertiseId,
}
);
}
await this.syncFanavaranHullBaseClaim(claimCaseId, clientKey);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
const nestedClaimId = fanavaranHullNestedClaimId({
claimId: claimCase?.claimId,
claimNo: claimCase?.claimNo,
});
if (nestedClaimId == null) {
throw new BadRequestException(
'Fanavaran claimId is required before submitting expertise',
);
}
const url = `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${nestedClaimId}/expertise`;
const startedAt = Date.now();
const auditSession: FanavaranAuditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey,
source: auditSource,
claimCaseId,
};
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_EXPERTISE,
status: FanavaranAuditStatus.STARTED,
requestUrl: url,
requestMethod: 'POST',
requestBody: payload,
requestMeta: { claimId: claimCase.claimId },
});
try {
const response = await this.postFanavaranJson(
url,
payload,
clientKey,
auditSession,
);
const expertiseId = response.data?.Id;
const exchange =
this.fanavaranAuditService.captureAxiosExchange(response);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_EXPERTISE,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: url,
requestMethod: 'POST',
httpStatus: response.status,
requestBody: payload,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
responseMeta: { claimId: claimCase.claimId, expertiseId },
durationMs: Date.now() - startedAt,
});
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
...(expertiseId !== undefined ? { expertiseId } : {}),
'fanavaranSync.expertise': {
status: 'success',
lastTriedAt: new Date(),
claimId: claimCase.claimId,
dmgCaseId: payload.DmgCaseId,
expertiseId,
response: response.data,
},
},
});
// Product decision: completing the final Fanavaran stage must not send SMS.
return response.data;
} catch (error) {
const exchange = this.fanavaranAuditService.captureAxiosExchange(error);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_EXPERTISE,
status: FanavaranAuditStatus.FAILURE,
requestUrl: url,
requestMethod: 'POST',
httpStatus: exchange.httpStatus,
requestBody: payload,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
errorMessage: this.fanavaranAuditService.extractErrorMessage(error),
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
throw error;
}
}
async autoSubmitFanavaranExpertiseOnExpertReply(
claimCaseId: string,
): Promise<FanavaranExpertiseSubmitResult> {
const clientKey = resolveFanavaranClientKey();
const logPrefix = `[Fanavaran ${clientKey} V2 Expertise Auto] claimCaseId=${claimCaseId}`;
try {
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
return {
attempted: false,
submitted: false,
warning: 'Claim case not found for Fanavaran expertise submit.',
};
}
if (claimCase.expertiseId != null) {
// Product decision: an already-completed Fanavaran stage must not send SMS.
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: 'Expertise already submitted to Fanavaran',
claimId: claimCase.claimId,
dmgCaseId: claimCase.dmgCaseId,
expertiseId: claimCase.expertiseId,
};
}
// Same ordered soft-ensure as manual expertise submit: base → damage → files.
await this.completeFanavaranExpertisePrerequisites(
claimCaseId,
clientKey,
FanavaranAuditSource.AUTO_SUBMIT,
);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
const { payload, warnings } = await this.buildFanavaranExpertisePayload({
claimCase,
clientKey,
});
this.assertFanavaranExpertisePayloadReady(payload, warnings, {
...hullExpertiseAssertFields(product),
});
const fanavaranResponse = await this.executeFanavaranExpertiseSubmit(
claimCaseId,
clientKey,
payload,
FanavaranAuditSource.AUTO_SUBMIT,
);
const expertiseId = fanavaranResponse?.Id;
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$push: {
history: {
type: 'FANAVARAN_EXPERTISE_AUTO_SUBMIT_SUCCEEDED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: {
clientKey,
claimId: claimCase?.claimId,
dmgCaseId: claimCase?.dmgCaseId,
expertiseId,
},
},
},
});
return {
attempted: true,
submitted: true,
claimId: claimCase?.claimId,
dmgCaseId: claimCase?.dmgCaseId,
expertiseId,
fanavaranResponse,
};
} catch (error) {
const warning = this.extractFanavaranErrorMessage(error);
this.logger.warn(`${logPrefix} Expertise auto-submit failed: ${warning}`);
try {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.expertise.status': 'failed',
'fanavaranSync.expertise.lastTriedAt': new Date(),
'fanavaranSync.expertise.lastError': warning,
},
$push: {
history: {
type: 'FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: { clientKey, error: warning },
},
},
});
} catch (historyError) {
this.logger.error(
`${logPrefix} Failed to record Fanavaran expertise failure history`,
historyError,
);
}
// Schedule retry for expertise
await this.scheduleFanavaranRetry(
claimCaseId,
'expertise',
() => this.autoSubmitFanavaranExpertiseOnExpertReply(claimCaseId),
logPrefix,
{ error, clientKey },
);
return {
attempted: true,
submitted: false,
warning,
};
}
}
private withFanavaranAutoSubmitMessage(
baseMessage: string,
fanavaran: FanavaranAutoSubmitResult,
): string {
if (fanavaran.submitted) {
return `${baseMessage} The initial Fanavaran case was sent successfully.`;
}
if (fanavaran.warning) {
return `${baseMessage} ${fanavaran.warning}`;
}
return baseMessage;
}
private assertFanavaranVehicleReviewApproved(claimCase: any): void {
const review = claimCase?.fanavaranVehicleReview;
const ids = [
review?.vehicleGroup?.id,
review?.vehicleUseType?.id,
review?.vehicleSystem?.id,
review?.vehicleKind?.id,
];
if (
review?.approved !== true ||
ids.some((id) => !Number.isInteger(Number(id)) || Number(id) <= 0)
) {
throw new ConflictException({
code: 'FANAVARAN_VEHICLE_REVIEW_REQUIRED',
message:
'An expert must review and approve the vehicle group, use type, system, and kind before any data can be sent to Fanavaran.',
});
}
}
private async getFanavaranAutoSubmitSkipReason(
claimCase: any,
): Promise<string | null> {
if (claimCase.claimId != null || claimCase.claimNo != null) {
return 'Already submitted to Fanavaran';
}
// GEN.03 base claim is sent as soon as the local claim exists.
// Vehicle review remains required for damage / attachments / expertise only.
const clientKey = resolveFanavaranClientKey();
const notifierAllowed =
clientKey === 'tejaratno'
? await this.tejaratNotifierAllowedIds(clientKey)
: undefined;
if (
!hasReviewedTejaratNotifier(
claimCase.fanavaranFieldReview?.values,
clientKey,
notifierAllowed,
)
) {
return 'نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران انتخاب شوند.';
}
if (!claimCase.blameRequestId) {
return 'Blame case not linked to claim case';
}
const blameCase = await this.blameRequestDbService.findById(
claimCase.blameRequestId,
);
if (!blameCase) {
return 'Blame case not found';
}
if (!isFanavaranSubmitSupportedBlameType(blameCase.type)) {
return 'Fanavaran submit only applies to THIRD_PARTY and CAR_BODY claims';
}
return null;
}
/**
* Soft-ensure Fanavaran base claim exists before a later stage (damage /
* attachments / expertise). Reuses claimId when present; otherwise submits
* GEN.03 once. Does not invent a fake claimId on failure.
*/
private async ensureFanavaranBaseClaim(
claimCaseId: string,
clientKey: FanavaranClientKey,
auditSource: FanavaranAuditSource,
): Promise<{ claimId: number; claimNo?: string; created: boolean }> {
const existing = await this.claimCaseDbService.findById(claimCaseId);
if (!existing) {
throw new NotFoundException('Claim case not found');
}
if (existing.claimId != null) {
return {
claimId: Number(existing.claimId),
claimNo:
existing.claimNo != null ? String(existing.claimNo) : undefined,
created: false,
};
}
this.logger.log(
`[Fanavaran ${clientKey}] Soft-ensuring base claim before next stage claimCaseId=${claimCaseId}`,
);
await this.executeFanavaranV2Submit(
claimCaseId,
clientKey,
undefined,
auditSource,
);
const refreshed = await this.claimCaseDbService.findById(claimCaseId);
if (refreshed?.claimId == null) {
throw new BadRequestException(
'Fanavaran base claim is missing and could not be created before the next stage. Fix base claim first.',
);
}
return {
claimId: Number(refreshed.claimId),
claimNo:
refreshed.claimNo != null ? String(refreshed.claimNo) : undefined,
created: true,
};
}
/**
* Soft-ensure damage case exists (creates base claim first if needed).
*/
private async ensureFanavaranDamageCase(
claimCaseId: string,
clientKey: FanavaranClientKey,
auditSource: FanavaranAuditSource,
selectedParts?: unknown[],
): Promise<{
claimId: number;
dmgCaseId: number | null;
created: boolean;
}> {
await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource);
const existing = await this.claimCaseDbService.findById(claimCaseId);
if (existing?.dmgCaseId != null && existing.claimId != null) {
return {
claimId: Number(existing.claimId),
dmgCaseId: Number(existing.dmgCaseId),
created: false,
};
}
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
if (!fanavaranHasDamageCaseStage(product)) {
if (existing?.claimId == null) {
throw new BadRequestException(
'Fanavaran claimId is required before the next hull stage.',
);
}
return {
claimId: Number(existing.claimId),
dmgCaseId: null,
created: false,
};
}
this.logger.log(
`[Fanavaran ${clientKey}] Soft-ensuring damage case before next stage claimCaseId=${claimCaseId}`,
);
await this.executeFanavaranDamageCaseSubmit(
claimCaseId,
clientKey,
selectedParts ?? existing?.damage?.selectedParts ?? [],
auditSource,
);
const refreshed = await this.claimCaseDbService.findById(claimCaseId);
if (refreshed?.claimId == null || refreshed.dmgCaseId == null) {
throw new BadRequestException(
'Fanavaran damage case is missing and could not be created before the next stage.',
);
}
return {
claimId: Number(refreshed.claimId),
dmgCaseId: Number(refreshed.dmgCaseId),
created: true,
};
}
private async postFanavaranJson(
url: string,
payload: Record<string, unknown>,
clientKey: FanavaranClientKey,
auditSession?: FanavaranAuditSession,
claimCaseId?: string,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
claimCaseId,
);
try {
const response = await firstValueFrom(
this.httpService.post(url, payload, {
headers: {
...headers,
'Content-Type': 'application/json',
},
}),
);
this.fanavaranAuthService.clearBackoff(clientKey);
return response;
} catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error);
throw error;
}
}
private async putFanavaranJson(
url: string,
payload: Record<string, unknown>,
clientKey: FanavaranClientKey,
auditSession?: FanavaranAuditSession,
claimCaseId?: string,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, payload, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
claimCaseId,
);
try {
const response = await firstValueFrom(
this.httpService.put(url, payload, {
headers: {
...headers,
'Content-Type': 'application/json',
},
}),
);
this.fanavaranAuthService.clearBackoff(clientKey);
return response;
} catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error);
throw error;
}
}
/**
* Nested hull files/expertise look up a بدنه پرونده. Create often echoed a ثالث-shaped
* body; PUT the GEN.03 hull shape onto the existing Id before follow-up stages.
*/
private async syncFanavaranHullBaseClaim(
claimCaseId: string,
clientKey: FanavaranClientKey,
): Promise<void> {
const product = await this.resolveFanavaranClaimProduct(claimCaseId);
if (product !== 'car-body') return;
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
const nestedId = fanavaranHullNestedClaimId({
claimId: claimCase?.claimId,
claimNo: claimCase?.claimNo,
});
if (nestedId == null) return;
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true,
registerMissingHullDriver: true,
persistPayload: true,
});
const hull = toFanavaranHullBaseClaimPayload(
built && typeof built === 'object' && 'payload' in built
? (built as { payload: Record<string, unknown> }).payload
: built,
clientKey,
);
const url = `${fanavaranClaimsBaseUrl('car-body', clientKey)}/${nestedId}`;
this.logger.log(
`[Fanavaran hull sync] PUT ${url} keys=${Object.keys(hull).join(',')}`,
);
try {
await this.putFanavaranJson(url, hull, clientKey, undefined, claimCaseId);
} catch (error) {
// Parsian bonyan often has no PUT route on vehicle-hull-claims/{Id}
// ("No HTTP resource was found.../vehicle-hull-claims/{Id}"). Do not
// block GEN.05 files / GEN.06 expertise on that.
this.logger.warn(
`[Fanavaran hull sync] PUT ${url} failed; continuing with nested stages: ${
error instanceof Error ? error.message : error
}`,
);
}
}
/**
* 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(
url: string,
content: Record<string, unknown>,
files: Array<{ path: string; fileName: string }>,
clientKey: FanavaranClientKey,
auditSession?: FanavaranAuditSession,
claimCaseId?: string,
) {
this.fanavaranAuthService.assertNotInBackoff(clientKey);
await this.assertFanavaranHullApiValues(url, content, clientKey, claimCaseId ?? auditSession?.claimCaseId);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
claimCaseId,
);
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), {
contentType: 'application/json',
});
for (const file of prepared) {
form.append('Param1', createReadStream(file.path), {
filename: file.fileName,
contentType: file.contentType,
knownLength: statSync(file.path).size,
});
}
const curlParts = [
`curl -X POST '${url}'`,
`-H 'authenticationToken: ${headers.authenticationToken}'`,
`-H 'CorpId: ${headers.CorpId}'`,
`-H 'ContractId: ${headers.ContractId}'`,
`-H 'Location: ${headers.Location}'`,
`-F 'Param=${JSON.stringify(content)};type=application/json'`,
...prepared.map(
(f) =>
`-F 'Param1=@${f.path};filename=${f.fileName};type=${f.contentType}'`,
),
];
this.logger.log(
`\n====== COPY THIS CURL ======\n${curlParts.join(' \\\n ')}\n====== END CURL ======\n`,
);
const logPrefix = `[Fanavaran Multipart]`;
this.logger.log(
`${logPrefix} REQUEST: url=${url} | Param=${JSON.stringify(content)} | files=[${files.map((f) => f.fileName).join(', ')}] | fileCount=${files.length}`,
);
try {
const response = await firstValueFrom(
this.httpService.post(url, form, {
headers: {
...form.getHeaders(),
...headers,
},
maxBodyLength: Infinity,
maxContentLength: Infinity,
}),
);
this.logger.log(
`${logPrefix} RESPONSE: status=${response.status} | body=${JSON.stringify(response.data)}`,
);
this.fanavaranAuthService.clearBackoff(clientKey);
return response;
} catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error);
throw error;
}
}
private async executeFanavaranDamageCaseSubmit(
claimCaseId: string,
clientKey: FanavaranClientKey,
selectedParts?: unknown[],
auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT,
bodyOverride?: Record<string, unknown>,
): Promise<any> {
const profile = getFanavaranClientProfile(clientKey);
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
throw new NotFoundException('Claim case not found');
}
this.assertFanavaranVehicleReviewApproved(claimCase);
if (!claimCase.claimId) {
await this.ensureFanavaranBaseClaim(claimCaseId, clientKey, auditSource);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase?.claimId) {
throw new BadRequestException(
'Fanavaran claimId is required before submitting damage case',
);
}
}
if (claimCase.dmgCaseId != null) {
this.logger.log(
`[executeFanavaranDamageCaseSubmit] Already have dmgCaseId=${claimCase.dmgCaseId}; skipping Fanavaran POST`,
);
return (
(claimCase as any)?.fanavaranSync?.damageCase?.response ?? {
Id: claimCase.dmgCaseId,
}
);
}
if (!claimCase.blameRequestId) {
throw new BadRequestException('Blame case not linked to claim case');
}
const blameCase = await this.blameRequestDbService.findById(
claimCase.blameRequestId,
);
if (!blameCase) {
throw new NotFoundException('Blame case not found');
}
if (!isFanavaranSubmitSupportedBlameType(blameCase.type)) {
throw new BadRequestException(
'Fanavaran damage-case submit only applies to THIRD_PARTY and CAR_BODY claims',
);
}
const product = fanavaranClaimProductFromBlameType(blameCase.type);
const url = fanavaranClaimStageUrl(
product,
'damage-case',
claimCase.claimId,
clientKey,
);
if (url == null) {
this.logger.log(
`[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} skipping hull dmg-cases`,
);
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.damageCase': {
status: 'skipped',
lastTriedAt: new Date(),
lastError: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON,
claimId: claimCase.claimId,
},
},
});
return {
skipped: true,
skipReason: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON,
claimId: claimCase.claimId,
};
}
const builtPayload = await this.buildFanavaranDamageCasePayload({
claimCase,
blameCase,
selectedParts: selectedParts ?? claimCase.damage?.selectedParts ?? [],
clientKey,
defaults: profile.defaults,
registerMissingPerson: true,
});
const payload = applyFanavaranManualPayloadOverrides(
builtPayload,
bodyOverride,
FANAVARAN_DAMAGE_MANUAL_OVERRIDE_KEYS,
);
// Guardrail: never send empty/null licence fields even if manual overrides arrive.
payload.LicenceNo = this.ensureFanavaranNonEmptyLicenceNo(
payload.LicenceNo,
);
this.logger.log(
`[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? 'NULL'} payload keys=${Object.keys(payload).join(', ')}`,
);
const startedAt = Date.now();
const auditSession: FanavaranAuditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey,
source: auditSource,
claimCaseId,
};
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE,
status: FanavaranAuditStatus.STARTED,
requestUrl: url,
requestMethod: 'POST',
requestBody: payload,
requestMeta: { claimId: claimCase.claimId },
});
try {
const response = await this.postFanavaranJson(
url,
payload,
clientKey,
auditSession,
);
const dmgCaseId = response.data?.Id;
const exchange =
this.fanavaranAuditService.captureAxiosExchange(response);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: url,
requestMethod: 'POST',
httpStatus: response.status,
requestBody: payload,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
responseMeta: { dmgCaseId, claimId: claimCase.claimId },
durationMs: Date.now() - startedAt,
});
if (dmgCaseId !== undefined) {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
dmgCaseId,
'fanavaranSync.damageCase': {
status: 'success',
lastTriedAt: new Date(),
claimId: claimCase.claimId,
dmgCaseId,
response: response.data,
},
},
});
}
return response.data;
} catch (error) {
const errDetail = isAxiosError(error)
? `status=${error.response?.status} data=${JSON.stringify(error.response?.data)}`
: error instanceof Error
? error.message
: String(error);
this.logger.error(
`[executeFanavaranDamageCaseSubmit] FAILED claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? 'NULL'} error: ${errDetail}`,
);
const exchange = this.fanavaranAuditService.captureAxiosExchange(error);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE,
status: FanavaranAuditStatus.FAILURE,
requestUrl: url,
requestMethod: 'POST',
httpStatus: exchange.httpStatus,
requestBody: payload,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
errorMessage: this.fanavaranAuditService.extractErrorMessage(error),
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
throw error;
}
}
async autoSubmitFanavaranDamageCaseOnOuterPartsSelected(
claimCaseId: string,
selectedParts: unknown[],
): Promise<FanavaranDamageCaseSubmitResult> {
const clientKey = resolveFanavaranClientKey();
const logPrefix = `[Fanavaran ${clientKey} V2 DamageCase Auto] claimCaseId=${claimCaseId}`;
try {
let claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
return {
attempted: false,
submitted: false,
warning: 'Claim case not found for Fanavaran damage-case submit.',
};
}
if (claimCase.dmgCaseId != null) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: 'Damage case already submitted to Fanavaran',
claimId: claimCase.claimId,
dmgCaseId: claimCase.dmgCaseId,
};
}
if (!claimCase.claimId) {
await this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId);
claimCase = await this.claimCaseDbService.findById(claimCaseId);
}
if (!claimCase?.claimId) {
const warning =
'Fanavaran base claim is missing, so damage case was not submitted.';
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.damageCase': {
status: 'skipped',
lastTriedAt: new Date(),
lastError: warning,
},
},
});
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: warning,
warning,
};
}
const fanavaranResponse = await this.executeFanavaranDamageCaseSubmit(
claimCaseId,
clientKey,
selectedParts,
);
if (fanavaranResponse?.skipped) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason:
fanavaranResponse.skipReason ??
FANAVARAN_HULL_NO_DAMAGE_CASE_REASON,
claimId: claimCase.claimId,
};
}
const dmgCaseId = fanavaranResponse?.Id;
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$push: {
history: {
type: 'FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_SUCCEEDED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: {
clientKey,
claimId: claimCase.claimId,
dmgCaseId,
},
},
},
});
return {
attempted: true,
submitted: true,
claimId: claimCase.claimId,
dmgCaseId,
fanavaranResponse,
};
} catch (error) {
const warning = this.extractFanavaranErrorMessage(error);
this.logger.warn(
`${logPrefix} Damage-case auto-submit failed: ${warning}`,
);
try {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.damageCase.status': 'failed',
'fanavaranSync.damageCase.lastTriedAt': new Date(),
'fanavaranSync.damageCase.lastError': warning,
},
$push: {
history: {
type: 'FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_FAILED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: { clientKey, error: warning },
},
},
});
} catch (historyError) {
this.logger.error(
`${logPrefix} Failed to record Fanavaran damage-case failure history`,
historyError,
);
}
// Schedule retry for damage case
await this.scheduleFanavaranRetry(
claimCaseId,
'damageCase',
() =>
this.autoSubmitFanavaranDamageCaseOnOuterPartsSelected(
claimCaseId,
selectedParts,
),
logPrefix,
{ error, clientKey },
);
return {
attempted: true,
submitted: false,
warning,
};
}
}
/**
* Auto-submit the minimum Fanavaran claim as soon as the local
* claim case exists. This preserves progress in Fanavaran even if parties stop
* later in the damage-assessment flow.
*/
async autoSubmitToFanavaranV2OnClaimCreated(
claimCaseId: string,
): Promise<FanavaranAutoSubmitResult> {
const clientKey = resolveFanavaranClientKey();
const logPrefix = `[Fanavaran ${clientKey} V2 Early Auto] claimCaseId=${claimCaseId}`;
const locked = await this.withFanavaranStageLock(
claimCaseId,
'baseClaim',
async () => {
try {
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
return {
attempted: false,
submitted: false,
warning:
'Claim case not found for Fanavaran early submit. Retry manually when available.',
};
}
const skipReason =
await this.getFanavaranAutoSubmitSkipReason(claimCase);
if (skipReason) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason,
claimId: claimCase.claimId,
claimNo: claimCase.claimNo,
};
}
const fanavaranResponse = await this.executeFanavaranV2Submit(
claimCaseId,
clientKey,
undefined,
FanavaranAuditSource.AUTO_SUBMIT,
);
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$push: {
history: {
type: 'FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: {
clientKey,
claimNo: fanavaranResponse?.ClaimNo,
claimId: fanavaranResponse?.Id,
},
},
},
});
return {
attempted: true,
submitted: true,
claimNo: fanavaranResponse?.ClaimNo,
claimId: fanavaranResponse?.Id,
fanavaranResponse,
};
} catch (error) {
const warning = this.extractFanavaranErrorMessage(error);
this.logger.warn(`${logPrefix} Early auto-submit failed: ${warning}`);
try {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
'fanavaranSync.baseClaim.status': 'failed',
'fanavaranSync.baseClaim.lastTriedAt': new Date(),
'fanavaranSync.baseClaim.lastError': warning,
},
$push: {
history: {
type: 'FANAVARAN_EARLY_AUTO_SUBMIT_FAILED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: { clientKey, error: warning },
},
},
});
} catch (historyError) {
this.logger.error(
`${logPrefix} Failed to record Fanavaran early auto-submit failure history`,
historyError,
);
}
await this.scheduleFanavaranRetry(
claimCaseId,
'baseClaim',
() => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId),
logPrefix,
{ error, clientKey },
);
return {
attempted: true,
submitted: false,
warning: `${warning} Initial case was not sent to Fanavaran. Retry manually via POST ${fanavaranSubmitPath(clientKey, claimCaseId)}.`,
};
}
},
);
if (
locked &&
typeof locked === 'object' &&
'skipped' in locked &&
locked.skipped
) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason: locked.skipReason,
};
}
return locked as FanavaranAutoSubmitResult;
}
/**
* Auto-submit to Fanavaran when a claim case reaches COMPLETED.
* Uses FANAVARAN_CLIENT env (or CLIENT_ID fallback) to pick the tenant.
* Never throws — failures are returned as warnings so the main flow continues.
*/
async autoSubmitToFanavaranV2OnClaimCompleted(
claimCaseId: string,
): Promise<FanavaranAutoSubmitResult> {
const clientKey = resolveFanavaranClientKey();
const logPrefix = `[Fanavaran ${clientKey} V2 Auto] claimCaseId=${claimCaseId}`;
try {
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
if (!claimCase) {
return {
attempted: false,
submitted: false,
warning:
'Claim case not found for Fanavaran auto-submit. Retry manually when available.',
};
}
// V5 flow: FileMaker approval required before fanavaran.
// Cross-check the blame record — only V5 blame files carry requiresFileMakerApproval.
// V4 claims may have the flag set from an old bug; we ignore it if the blame
// itself does not carry the flag.
if ((claimCase as any).requiresFileMakerApproval) {
const blameId = (claimCase as any).blameRequestId;
const blame = blameId
? await this.blameRequestDbService.findById(String(blameId))
: null;
const isV5 = !!(blame as any)?.requiresFileMakerApproval;
if (isV5) {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: { status: ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL },
$push: {
history: {
type: 'V5_HELD_FOR_FILE_MAKER_APPROVAL',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: { claimCaseId },
},
},
});
return {
attempted: false,
submitted: false,
skipped: true,
skipReason:
'V5 flow: FileMaker approval required before Fanavaran submission. ' +
'Claim is now in WAITING_FOR_FILE_MAKER_APPROVAL.',
};
}
// V4 claim with stale flag — clear it so this path is not hit again.
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$unset: { requiresFileMakerApproval: '' },
});
}
const skipReason = await this.getFanavaranAutoSubmitSkipReason(claimCase);
if (skipReason) {
return {
attempted: false,
submitted: false,
skipped: true,
skipReason,
claimId: claimCase.claimId,
claimNo: claimCase.claimNo,
};
}
const fanavaranResponse = await this.executeFanavaranV2Submit(
claimCaseId,
clientKey,
);
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$push: {
history: {
type: 'FANAVARAN_AUTO_SUBMIT_SUCCEEDED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: {
clientKey,
claimNo: fanavaranResponse?.ClaimNo,
claimId: fanavaranResponse?.Id,
},
},
},
});
return {
attempted: true,
submitted: true,
claimNo: fanavaranResponse?.ClaimNo,
claimId: fanavaranResponse?.Id,
fanavaranResponse,
};
} catch (error) {
const warning = this.extractFanavaranErrorMessage(error);
this.logger.warn(`${logPrefix} Auto-submit failed: ${warning}`);
try {
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$push: {
history: {
type: 'FANAVARAN_AUTO_SUBMIT_FAILED',
actor: { actorType: 'system' },
timestamp: new Date(),
metadata: { clientKey, error: warning },
},
},
});
} catch (historyError) {
this.logger.error(
`${logPrefix} Failed to record Fanavaran auto-submit failure history`,
historyError,
);
}
// Schedule retry for base claim
await this.scheduleFanavaranRetry(
claimCaseId,
'baseClaim',
() => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId),
logPrefix,
{ error, clientKey },
);
return {
attempted: true,
submitted: false,
warning: `${warning} Case was not sent to Fanavaran. Retry manually via POST ${fanavaranSubmitPath(clientKey, claimCaseId)}.`,
};
}
}
private extractFanavaranErrorMessage(error: unknown): string {
return extractFanavaranOriginalMessage(
error,
'Failed to submit data to Fanavaran API',
);
}
private static readonly FANAVARAN_RETRY_DELAY_MS = 5 * 60 * 1000; // 5 minutes
private static readonly FANAVARAN_TRANSIENT_RETRY_DELAY_MS = 10 * 60 * 1000; // 10 minutes
private static readonly FANAVARAN_MAX_RETRIES = 2;
private fanavaranRetryKey(
claimCaseId: string,
stage: 'baseClaim' | 'damageCase' | 'attachments' | 'expertise',
): string {
return `${claimCaseId}:${stage}`;
}
private async withFanavaranStageLock<T>(
claimCaseId: string,
stage: string,
fn: () => Promise<T>,
): Promise<T | { skipped: true; skipReason: string }> {
const key = `${claimCaseId}:${stage}`;
if (this.fanavaranInFlightStages.has(key)) {
this.logger.warn(
`[Fanavaran] Skipping concurrent ${stage} for claimCaseId=${claimCaseId}`,
);
return {
skipped: true,
skipReason: `Fanavaran ${stage} already in flight for this claim`,
};
}
this.fanavaranInFlightStages.add(key);
try {
return await fn();
} finally {
this.fanavaranInFlightStages.delete(key);
}
}
/**
* After a Fanavaran stage failure, schedule a single deferred retry.
* Dedupes in-process timers and Mongo `nextRetryAt` so concurrent failures
* cannot enqueue multiple setTimeouts for the same claim/stage.
*/
private async scheduleFanavaranRetry(
claimCaseId: string,
stage: 'baseClaim' | 'damageCase' | 'attachments' | 'expertise',
retryFn: () => Promise<any>,
logPrefix: string,
options?: { error?: unknown; clientKey?: FanavaranClientKey },
): Promise<boolean> {
const key = this.fanavaranRetryKey(claimCaseId, stage);
const claimCase = await this.claimCaseDbService.findById(claimCaseId);
const syncStage = (claimCase as any)?.fanavaranSync?.[stage];
const retryCount = syncStage?.retryCount ?? 0;
const maxRetries =
syncStage?.maxRetries ??
ClaimRequestManagementService.FANAVARAN_MAX_RETRIES;
if (retryCount >= maxRetries) {
this.logger.warn(
`${logPrefix} Max retries (${maxRetries}) exhausted for ${stage}.`,
);
return false;
}
// Already scheduled in DB for the future — do not add another timer.
const existingNext = syncStage?.nextRetryAt
? new Date(syncStage.nextRetryAt).getTime()
: 0;
if (syncStage?.status === 'pending' && existingNext > Date.now() + 5_000) {
this.logger.log(
`${logPrefix} Retry already pending for ${stage} at ${new Date(existingNext).toISOString()}; skipping duplicate schedule.`,
);
return false;
}
// In-process timer already armed for this key.
if (this.fanavaranRetryTimers.has(key)) {
this.logger.log(
`${logPrefix} In-process retry timer already exists for ${stage}; skipping duplicate.`,
);
return false;
}
const transient = FanavaranAuthService.isTransientTryLaterError(
options?.error,
);
const delayMs = transient
? ClaimRequestManagementService.FANAVARAN_TRANSIENT_RETRY_DELAY_MS
: ClaimRequestManagementService.FANAVARAN_RETRY_DELAY_MS;
if (options?.clientKey && options?.error) {
this.fanavaranAuthService.registerFailure(
options.clientKey,
options.error,
);
}
const nextRetryCount = retryCount + 1;
const nextRetryAt = new Date(Date.now() + delayMs);
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: {
[`fanavaranSync.${stage}.retryCount`]: nextRetryCount,
[`fanavaranSync.${stage}.maxRetries`]: maxRetries,
[`fanavaranSync.${stage}.nextRetryAt`]: nextRetryAt,
[`fanavaranSync.${stage}.status`]: 'pending',
[`fanavaranSync.${stage}.lastTriedAt`]: new Date(),
...(options?.error
? {
[`fanavaranSync.${stage}.lastError`]:
this.extractFanavaranErrorMessage(options.error),
}
: {}),
},
});
this.logger.log(
`${logPrefix} Scheduling retry ${nextRetryCount}/${maxRetries} for ${stage} at ${nextRetryAt.toISOString()} (delay=${delayMs}ms${transient ? ', transient backoff' : ''})`,
);
const timer = setTimeout(async () => {
this.fanavaranRetryTimers.delete(key);
try {
const fresh = await this.claimCaseDbService.findById(claimCaseId);
const freshStage = (fresh as any)?.fanavaranSync?.[stage];
if (freshStage?.status === 'pending') {
await retryFn();
}
} catch (retryError) {
this.logger.error(
`${logPrefix} Retry ${nextRetryCount}/${maxRetries} for ${stage} failed`,
retryError,
);
}
}, delayMs);
this.fanavaranRetryTimers.set(key, timer);
return true;
}
private async executeFanavaranV2Submit(
claimCaseId: string,
clientKey: FanavaranClientKey,
bodyOverride?: Record<string, unknown>,
auditSource: FanavaranAuditSource = FanavaranAuditSource.AUTO_SUBMIT,
): Promise<any> {
const logPrefix = `[Fanavaran ${clientKey} V2]`;
this.logger.log(
`${logPrefix} Starting submission for claimCaseId: ${claimCaseId}`,
);
const existing = await this.claimCaseDbService.findById(claimCaseId);
if (existing?.claimId != null) {
this.logger.log(
`${logPrefix} Base claim already exists claimId=${existing.claimId}; skipping Fanavaran POST`,
);
return (
(existing as any)?.fanavaranSync?.baseClaim?.response ?? {
Id: existing.claimId,
ClaimNo: existing.claimNo,
}
);
}
if (!existing) throw new NotFoundException('Claim case not found');
// Vehicle review is not required for GEN.03 base — only for later stages.
const notifierAllowed =
clientKey === 'tejaratno'
? await this.tejaratNotifierAllowedIds(clientKey)
: undefined;
if (
!hasReviewedTejaratNotifier(
existing.fanavaranFieldReview?.values,
clientKey,
notifierAllowed,
)
) {
throw new ConflictException({
code: 'FANAVARAN_NOTIFIER_REVIEW_REQUIRED',
message:
'نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران بررسی و انتخاب شوند.',
});
}
const auditSession: FanavaranAuditSession = {
trackingCode: this.fanavaranAuditService.generateTrackingCode(),
clientKey,
source: auditSource,
claimCaseId,
};
const built = await this.previewFanavaranSubmitV2(claimCaseId, clientKey, {
requirePolicyId: true,
registerMissingHullDriver: true,
auditSession,
persistPayload: true,
forceRefreshPolicy: true,
forceRefreshUsedId: true,
});
const fanavaranData = applyFanavaranManualPayloadOverrides(
built,
bodyOverride,
FANAVARAN_BASE_MANUAL_OVERRIDE_KEYS,
);
// Guardrail: never send empty/null licence fields even if manual overrides arrive.
fanavaranData.CulpritLicenceNo = this.ensureFanavaranNonEmptyLicenceNo(
fanavaranData.CulpritLicenceNo,
);
this.logger.log(
`${logPrefix} Mapped data prepared:`,
JSON.stringify(fanavaranData, null, 2),
);
if (
fanavaranData.AccidentCauseId === undefined ||
fanavaranData.AccidentCauseId === null
) {
this.logger.error(
`${logPrefix} CRITICAL: AccidentCauseId is missing or null!`,
);
} else {
this.logger.log(
`${logPrefix} AccidentCauseId validated: ${fanavaranData.AccidentCauseId}`,
);
}
this.fanavaranAuthService.assertNotInBackoff(clientKey);
const headers = await this.getFanavaranAuthHeaders(
clientKey,
auditSession,
claimCaseId,
);
const submitUrl = await this.fanavaranClaimsUrlForClaim(claimCaseId);
await this.assertFanavaranHullApiValues(submitUrl, fanavaranData, clientKey, claimCaseId);
const requestHeaders = {
...headers,
'Content-Type': 'application/json',
};
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_CLAIM,
status: FanavaranAuditStatus.STARTED,
requestUrl: submitUrl,
requestMethod: 'POST',
requestHeaders,
requestBody: fanavaranData,
requestMeta: { policyId: fanavaranData?.PolicyId ?? null },
});
const startedAt = Date.now();
try {
const response = await firstValueFrom(
this.httpService.post(submitUrl, fanavaranData, {
headers: requestHeaders,
}),
);
this.logger.log(`${logPrefix} API Response Status: ${response.status}`);
this.logger.log(
`${logPrefix} API Response Data:`,
JSON.stringify(response.data, null, 2),
);
this.fanavaranAuthService.clearBackoff(clientKey);
const exchange = this.fanavaranAuditService.captureAxiosExchange(
response,
requestHeaders,
);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_CLAIM,
status: FanavaranAuditStatus.SUCCESS,
requestUrl: submitUrl,
requestMethod: 'POST',
httpStatus: response.status,
requestHeaders: exchange.requestHeaders,
requestBody: fanavaranData,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
responseMeta: {
claimId: response.data?.Id,
claimNo: response.data?.ClaimNo,
},
durationMs: Date.now() - startedAt,
});
if (response.data) {
const claimNo = response.data.ClaimNo;
const claimId = response.data.Id;
const updateData: any = { $set: {} as Record<string, unknown> };
if (claimNo !== undefined) {
updateData.$set.claimNo = claimNo;
}
if (claimId !== undefined) {
updateData.$set.claimId = claimId;
}
updateData.$set['fanavaranSync.baseClaim.status'] = 'success';
updateData.$set['fanavaranSync.baseClaim.lastTriedAt'] = new Date();
updateData.$set['fanavaranSync.baseClaim.claimId'] = claimId;
updateData.$set['fanavaranSync.baseClaim.claimNo'] = claimNo;
updateData.$set['fanavaranSync.baseClaim.response'] = response.data;
if (fanavaranData?.PolicyId != null) {
updateData.$set['fanavaranSync.baseClaim.policyId'] =
fanavaranData.PolicyId;
}
await this.claimCaseDbService.findByIdAndUpdate(
claimCaseId,
updateData,
);
}
return response.data;
} catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error);
const exchange = this.fanavaranAuditService.captureAxiosExchange(
error,
requestHeaders,
);
await this.fanavaranAuditService.recordStep({
session: auditSession,
step: FanavaranAuditStep.SUBMIT_CLAIM,
status: FanavaranAuditStatus.FAILURE,
requestUrl: submitUrl,
requestMethod: 'POST',
httpStatus: exchange.httpStatus,
requestHeaders: exchange.requestHeaders,
requestBody: fanavaranData,
responseHeaders: exchange.responseHeaders,
responseBody: exchange.responseBody,
errorMessage: this.fanavaranAuditService.extractErrorMessage(error),
errorDetails: this.fanavaranAuditService.sanitizeErrorDetails(error),
durationMs: Date.now() - startedAt,
});
throw error;
}
}
/**
* V2: Create claim request from completed blame case
* Only damaged party can create claim after both parties accept expert decision
*/
async createClaimFromBlameV2(
blameRequestId: string,
currentUserId: string,
): Promise<CreateClaimFromBlameResponseDto> {
try {
// 1. Fetch blame request from new blameCases collection
const blameRequest =
await this.blameRequestDbService.findById(blameRequestId);
if (!blameRequest) {
throw new NotFoundException('Blame request not found');
}
if (blameRequest.status !== BlameCaseStatus.COMPLETED) {
throw new BadRequestException(
'Blame request must be completed before creating a claim',
);
}
const beneficiary = resolveClaimBeneficiary(blameRequest);
if (!beneficiary) {
throw new BadRequestException(
'The damaged party could not be determined from this blame request',
);
}
if (String(beneficiary.person!.userId) !== currentUserId) {
throw new ForbiddenException(
'Only the damaged party can create a claim from this blame request',
);
}
if (!canUserCreateClaim(blameRequest, currentUserId)) {
throw new BadRequestException(
'Both parties must sign and accept the decision before creating a claim',
);
}
const currentUserParty = beneficiary;
// 6. Validate no existing claim for this blame
const existingClaim = await this.claimCaseDbService.findOne({
blameRequestId: new Types.ObjectId(blameRequestId),
});
if (existingClaim) {
throw new ConflictException(
'A claim request for this blame case already exists',
);
}
const selectedBranchId = usesUserClaimBranch(blameRequest)
? await this.userClaimBranchService.validate(blameRequest, (blameRequest as any).branchId?.toString())
: (blameRequest as any).branchId?.toString();
// 7. Generate claim number
const claimNo = await this.generateUniqueClaimNumber();
// 8. Create claim case
const ownerParty = resolveClaimOwnerParty(blameRequest);
if (!ownerParty?.person?.userId) {
throw new BadRequestException(
'Could not resolve claim owner from blame parties',
);
}
const damagedUserId = String(beneficiary.person!.userId);
const newClaim = await this.claimCaseDbService.create({
requestNo: claimNo,
publicId: blameRequest.publicId,
blameRequestId: new Types.ObjectId(blameRequestId),
blameRequestNo: blameRequest.requestNo,
...(selectedBranchId ? { branchId: new Types.ObjectId(selectedBranchId) } : {}),
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING,
inquiries: (blameRequest as any).inquiries ?? {},
workflow: {
currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS,
nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS,
completedSteps: [ClaimWorkflowStep.CLAIM_CREATED],
locked: false,
},
...(damagedUserId
? { damagedPartyUserId: new Types.ObjectId(damagedUserId) }
: {}),
owner: (() => {
const cid = ownerParty.person.clientId;
return {
userId: new Types.ObjectId(String(beneficiary.person!.userId)),
userRole: beneficiary.role as any,
fullName: currentUserParty.person?.fullName,
userClientKey: cid ? String(cid) : undefined,
...(cid ? { clientId: new Types.ObjectId(String(cid)) } : {}),
};
})(),
history: [
{
type: 'CLAIM_CREATED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: currentUserParty.person?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
blameRequestId,
blamePublicId: blameRequest.publicId,
},
},
],
} as any);
this.logger.log(
`Claim created: ${newClaim._id} from blame: ${blameRequestId}`,
);
// Flow 1 defers Fanavaran submission to the later staged hooks.
// Flow 6 and expert/registrar-created cases retain early submission.
const deferFanavaran =
usesUserClaimBranch(blameRequest) && !blameRequest.callCenterInitiated;
const fanavaran: FanavaranAutoSubmitResult = deferFanavaran
? {
attempted: false,
submitted: false,
skipped: true,
skipReason: 'Flow 1 defers Fanavaran submission until a later stage',
}
: await this.autoSubmitToFanavaranV2OnClaimCreated(String(newClaim._id));
const message = this.withFanavaranAutoSubmitMessage(
'Claim request created successfully',
fanavaran,
);
return {
claimRequestId: String(newClaim._id),
publicId: blameRequest.publicId,
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
message,
fanavaran,
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error(
'createClaimFromBlameV2 failed',
blameRequestId,
error instanceof Error ? error.stack : String(error),
);
throw new InternalServerErrorException(
error instanceof Error
? error.message
: 'Failed to create claim request',
);
}
}
/**
* V2: Field expert creates a claim from an expert-initiated IN_PERSON completed blame.
* Owner: damaged party `userId` (SMS / user actions), guilty party `clientId` (insurer queue).
*/
async createClaimFromBlameForExpertV2(
blameRequestId: string,
expert: { sub: string; firstName?: string; lastName?: string },
): Promise<CreateClaimFromBlameResponseDto> {
const blameRequest =
await this.blameRequestDbService.findById(blameRequestId);
if (!blameRequest) {
throw new NotFoundException('Blame request not found');
}
// if (blameRequest.status !== BlameCaseStatus.COMPLETED) {
// throw new BadRequestException(
// `Blame request must be COMPLETED. Current status: ${blameRequest.status}`,
// );
// }
if (
!blameRequest.expertInitiated ||
blameRequest.creationMethod !== 'IN_PERSON' ||
!blameRequest.initiatedByFieldExpertId
) {
throw new BadRequestException(
'This endpoint is only for expert-initiated IN_PERSON blame files.',
);
}
if (String(blameRequest.initiatedByFieldExpertId) !== String(expert.sub)) {
throw new ForbiddenException(
'Only the field expert who created this blame file can create the claim.',
);
}
const ownerFields = resolveClaimOwnerFieldsFromBlame(blameRequest);
if (!ownerFields) {
throw new BadRequestException(
'Could not resolve claim owner (damaged party) from blame',
);
}
const existingClaim = await this.claimCaseDbService.findOne({
blameRequestId: new Types.ObjectId(blameRequestId),
});
if (existingClaim) {
throw new ConflictException('A claim for this blame case already exists');
}
const claimNo = await this.generateUniqueClaimNumber();
const newClaim = await this.claimCaseDbService.create({
requestNo: claimNo,
publicId: blameRequest.publicId,
blameRequestId: new Types.ObjectId(blameRequestId),
blameRequestNo: blameRequest.requestNo,
initiatedByFieldExpertId: new Types.ObjectId(expert.sub),
...((blameRequest as any).branchId
? {
branchId: new Types.ObjectId(
String((blameRequest as any).branchId),
),
}
: {}),
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING,
inquiries: (blameRequest as any).inquiries ?? {},
workflow: {
currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS,
nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS,
completedSteps: [ClaimWorkflowStep.CLAIM_CREATED],
locked: false,
},
damagedPartyUserId: new Types.ObjectId(ownerFields.userId),
owner: {
userId: new Types.ObjectId(ownerFields.userId),
userRole: ownerFields.userRole as any,
...(ownerFields.clientId
? {
clientId: new Types.ObjectId(ownerFields.clientId),
userClientKey: ownerFields.clientId,
}
: {}),
},
history: [
{
type: 'CLAIM_CREATED',
actor: {
actorId: new Types.ObjectId(expert.sub),
actorName:
`${expert.firstName || ''} ${expert.lastName || ''}`.trim(),
actorType: 'field_expert',
},
timestamp: new Date(),
metadata: {
blameRequestId,
blamePublicId: blameRequest.publicId,
createdByExpert: true,
},
},
],
} as any);
this.logger.log(
`Claim created by field expert: ${newClaim._id} from blame: ${blameRequestId}`,
);
const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated(
String(newClaim._id),
);
const message = this.withFanavaranAutoSubmitMessage(
'Claim created successfully. You can now fill claim data on behalf of the damaged party.',
fanavaran,
);
return {
claimRequestId: String(newClaim._id),
publicId: blameRequest.publicId,
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
message,
fanavaran,
};
}
/**
* True when the actor appears as a non-owner (damaged) party on the claim's
* snapshot.parties. This is the fastest, blame-free fallback: the snapshot is
* written at claim-creation time and always holds the correct user IDs.
*
* Logic:
* - Any party whose person.userId is in linkedUserIds and is NOT the claim
* owner (guilty party) is considered the damaged party.
* - If owner.userId is unknown we accept any matching party (CAR_BODY flows).
*/
private claimSnapshotPartyMatchesAsDamagedParty(
claim: any,
linkedUserIdStrings: string[],
): boolean {
const parties: any[] = claim?.snapshot?.parties ?? [];
if (!parties.length) return false;
const ownerIdStr = claim?.owner?.userId ? String(claim.owner.userId) : null;
for (const party of parties) {
const partyUserId = party?.person?.userId;
if (partyUserId == null) continue;
const partyStr = String(partyUserId);
// Must be this actor
if (!linkedUserIdStrings.some((id) => id === partyStr)) continue;
// Must NOT be the guilty-owner (unless owner is unknown — CAR_BODY)
if (ownerIdStr && partyStr === ownerIdStr) continue;
return true;
}
return false;
}
private async assertEffectiveUserIsDamagedPartyOnClaim(
claimCase: any,
effectiveUserId: string,
actor?: { username?: string },
message = 'Only the damaged party can perform this action on the claim',
): Promise<void> {
const linkedUserIds = await resolveLinkedUserIdStrings(this.userDbService, {
sub: effectiveUserId,
username: actor?.username,
});
const actorCtx = { sub: effectiveUserId, username: actor?.username };
// The linked blame decision is authoritative for historical claims whose
// owner.userId may still point to the guilty party.
if (claimCase?.blameRequestId) {
const blame = await this.blameRequestDbService.findById(
String(claimCase.blameRequestId),
);
if (blame) {
const beneficiary = resolveClaimBeneficiary(blame);
if (
beneficiary &&
partyPersonMatchesUser(beneficiary.person, actorCtx, linkedUserIds)
)
return;
throw new ForbiddenException(message);
}
}
// A persisted beneficiary is authoritative when the source is unavailable.
if (ownerUserIdMatchesActor(claimCase?.damagedPartyUserId, linkedUserIds)) {
return;
}
if (claimCase?.damagedPartyUserId) throw new ForbiddenException(message);
// Standalone legacy claims have no blame source; their owner is the beneficiary.
if (
!claimCase?.blameRequestId &&
!claimCase?.snapshot?.parties?.length &&
ownerUserIdMatchesActor(claimCase?.owner?.userId, linkedUserIds)
) {
return;
}
// Snapshot party membership alone cannot establish liability: some older
// claims used the guilty party as owner, while in-person claims use the beneficiary.
throw new ForbiddenException(message);
}
private async assertActorCanViewClaimV2(
claim: any,
currentUserId: string,
actor?: { sub: string; role?: string; username?: string },
): Promise<void> {
const linkedUserIds = await resolveLinkedUserIdStrings(this.userDbService, {
sub: currentUserId,
username: actor?.username,
});
if (ownerUserIdMatchesActor(claim.owner?.userId, linkedUserIds)) {
return;
}
// damagedPartyUserId is set at claim-creation time — the most direct check.
if (ownerUserIdMatchesActor(claim.damagedPartyUserId, linkedUserIds)) {
return;
}
if (!actor?.role || actor.role === RoleEnum.USER) {
const userCtx = { sub: currentUserId, username: actor?.username };
// Any party on the linked blame can VIEW the claim.
// (Mutation guards use assertEffectiveUserIsDamagedPartyOnClaim which is
// stricter and only allows the damaged party to act.)
if (claim.blameRequestId) {
const blame = await this.blameRequestDbService.findById(
claim.blameRequestId.toString(),
);
if (blame) {
const parties: any[] = (blame as any).parties ?? [];
const isParty = parties.some((p: any) =>
partyPersonMatchesUser(p?.person, userCtx, linkedUserIds),
);
if (isParty) return;
}
}
// Snapshot-party fallback (reliable for claims with snapshot written).
if (this.claimSnapshotPartyMatchesAsDamagedParty(claim, linkedUserIds)) {
return;
}
}
if (actor?.role === RoleEnum.FIELD_EXPERT) {
const blame = claim.blameRequestId
? await this.blameRequestDbService.findById(
claim.blameRequestId.toString(),
)
: null;
if (
claimCaseInitiatedByFieldExpert(claim, { sub: currentUserId }, blame)
) {
return;
}
}
if (
(actor?.role === RoleEnum.FILE_MAKER ||
actor?.role === RoleEnum.FILE_REVIEWER) &&
claim.blameRequestId
) {
const blame = await this.blameRequestDbService.findById(
claim.blameRequestId.toString(),
);
const isV4OrV5File =
!!(blame as any)?.isMadeByFileMaker &&
blame?.expertInitiated &&
blame?.creationMethod === 'IN_PERSON';
if (
actor.role === RoleEnum.FILE_MAKER &&
isV4OrV5File &&
claimCaseInitiatedByFieldExpert(claim, { sub: currentUserId }, blame)
) {
return;
}
if (
actor.role === RoleEnum.FILE_REVIEWER &&
isV4OrV5File &&
String((blame as any)?.assignedFileReviewerId ?? '') ===
String(currentUserId)
) {
return;
}
}
if (actor?.role === RoleEnum.REGISTRAR && claim.blameRequestId) {
const blame = await this.blameRequestDbService.findById(
claim.blameRequestId.toString(),
);
if (
blame?.registrarInitiated &&
blame.initiatedByRegistrarId &&
String(blame.initiatedByRegistrarId) === currentUserId
) {
return;
}
}
throw new ForbiddenException('You do not have access to this claim');
}
/**
* Resolve effective user id for claim operations.
* For FIELD_EXPERT acting on expert-initiated IN_PERSON claim, returns the claim owner's id; otherwise returns currentUserId.
*/
private async resolveClaimEffectiveUserId(
claimCase: any,
currentUserId: string,
actorRole?: string,
): Promise<string> {
const isFieldLikeRole = [
RoleEnum.FIELD_EXPERT,
RoleEnum.REGISTRAR,
RoleEnum.FILE_MAKER,
RoleEnum.FILE_REVIEWER,
].includes(actorRole as any);
if (!isFieldLikeRole || !claimCase?.blameRequestId) {
return currentUserId;
}
const blameRequest = await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
);
if (!blameRequest || blameRequest.creationMethod !== 'IN_PERSON')
return currentUserId;
if (
actorRole === RoleEnum.FIELD_EXPERT ||
actorRole === RoleEnum.FILE_MAKER
) {
if (
!blameRequest.expertInitiated ||
!blameRequest.initiatedByFieldExpertId ||
String(blameRequest.initiatedByFieldExpertId) !== currentUserId
) {
return currentUserId;
}
} else if (actorRole === RoleEnum.REGISTRAR) {
if (
!blameRequest.registrarInitiated ||
!blameRequest.initiatedByRegistrarId ||
String(blameRequest.initiatedByRegistrarId) !== currentUserId
) {
return currentUserId;
}
}
// FILE_REVIEWER: no initiator-id check — they pick up any IN_PERSON expert
// file after the FileMaker seals it, so we resolve the owner unconditionally.
return (
resolveDamagedPartyUserId(blameRequest) ??
(claimCase.owner?.userId ? String(claimCase.owner.userId) : currentUserId)
);
}
async createClaimFromBlameForRegistrarV1(
blameRequestId: string,
registrar: { sub: string; firstName?: string; lastName?: string },
): Promise<CreateClaimFromBlameResponseDto> {
const blameRequest =
await this.blameRequestDbService.findById(blameRequestId);
if (!blameRequest) throw new NotFoundException('Blame request not found');
if (blameRequest.status !== BlameCaseStatus.COMPLETED) {
throw new BadRequestException(
`Blame request must be COMPLETED. Current status: ${blameRequest.status}`,
);
}
if (
!blameRequest.registrarInitiated ||
blameRequest.creationMethod !== 'IN_PERSON' ||
!blameRequest.initiatedByRegistrarId
) {
throw new BadRequestException(
'This endpoint is only for registrar-initiated IN_PERSON blame files.',
);
}
if (String(blameRequest.initiatedByRegistrarId) !== String(registrar.sub)) {
throw new ForbiddenException(
'Only the registrar who created this blame file can create the claim.',
);
}
const ownerFields = resolveClaimOwnerFieldsFromBlame(blameRequest);
if (!ownerFields) {
throw new BadRequestException(
'Could not resolve claim owner (damaged party) from blame',
);
}
const existingClaim = await this.claimCaseDbService.findOne({
blameRequestId: new Types.ObjectId(blameRequestId),
});
if (existingClaim)
throw new ConflictException('A claim for this blame case already exists');
const claimNo = await this.generateUniqueClaimNumber();
const newClaim = await this.claimCaseDbService.create({
requestNo: claimNo,
publicId: blameRequest.publicId,
blameRequestId: new Types.ObjectId(blameRequestId),
blameRequestNo: blameRequest.requestNo,
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING,
inquiries: (blameRequest as any).inquiries ?? {},
workflow: {
currentStep: ClaimWorkflowStep.SELECT_OUTER_PARTS,
nextStep: ClaimWorkflowStep.SELECT_OTHER_PARTS,
completedSteps: [ClaimWorkflowStep.CLAIM_CREATED],
locked: false,
},
damagedPartyUserId: new Types.ObjectId(ownerFields.userId),
owner: {
userId: new Types.ObjectId(ownerFields.userId),
userRole: ownerFields.userRole as any,
...(ownerFields.clientId
? {
clientId: new Types.ObjectId(ownerFields.clientId),
userClientKey: ownerFields.clientId,
}
: {}),
},
createdByRegistrarId: new Types.ObjectId(registrar.sub),
history: [
{
type: 'CLAIM_CREATED',
actor: {
actorId: new Types.ObjectId(registrar.sub),
actorName:
`${registrar.firstName || ''} ${registrar.lastName || ''}`.trim(),
actorType: 'registrar',
},
timestamp: new Date(),
metadata: {
blameRequestId,
blamePublicId: blameRequest.publicId,
createdByRegistrar: true,
},
},
],
} as any);
const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCreated(
String(newClaim._id),
);
const message = this.withFanavaranAutoSubmitMessage(
'Claim created successfully. Registrar can now fill claim data.',
fanavaran,
);
return {
claimRequestId: String(newClaim._id),
publicId: blameRequest.publicId,
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
message,
fanavaran,
};
}
/**
* V2 API: Select damaged outer car parts for claim (Step 2 of claim workflow)
*
* @param claimRequestId - The claim case ID
* @param body - Selected outer parts
* @param currentUserId - The current user's ID
* @returns Response with updated claim information
*
* Validations:
* - Claim case must exist
* - User must be the claim owner (damaged party)
* - Current workflow step must be CLAIM_CREATED (step 1)
* - Selected parts array must not be empty
* - Parts must not have been selected previously
*/
async selectOuterPartsV2(
claimRequestId: string,
body: SelectOuterPartsV2Dto,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<SelectOuterPartsV2ResponseDto> {
try {
// 1. Validate claim exists
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner (damaged party) can select damaged parts',
);
// 3. Validate workflow step is correct (should be at SELECT_OUTER_PARTS)
if (
claimCase.workflow?.currentStep !== ClaimWorkflowStep.SELECT_OUTER_PARTS
) {
throw new BadRequestException(
`Invalid workflow step. Expected ${ClaimWorkflowStep.SELECT_OUTER_PARTS}, but current step is ${claimCase.workflow?.currentStep}`,
);
}
// 4. Validate outer parts haven't been selected yet.
// For FILE_REVIEWER re-reviewing after a FileMaker rejection, the existing
// selection from the prior cycle is intentionally overwritten — skip this
// guard so the reviewer can update the damaged parts list.
const isFileReviewerReselect = actor?.role === RoleEnum.FILE_REVIEWER;
if (
!isFileReviewerReselect &&
claimCase.damage?.selectedParts &&
claimCase.damage.selectedParts.length > 0
) {
throw new ConflictException(
'Outer parts have already been selected for this claim',
);
}
// 5. Fetch the live Fanavaran catalog and resolve selected parts by ids
const selectedCarType = (body as any)?.carType as
| ClaimVehicleTypeV2
| undefined;
const liveCatalog = await this.getLiveFanavaranCatalogItems();
const byId = new Map<number, OuterPartCatalogItem>(
liveCatalog.map((p) => [p.id, p]),
);
const selectedFromIds: OuterPartCatalogItem[] = [];
if (
Array.isArray((body as any)?.selectedPartIds) &&
(body as any).selectedPartIds.length > 0
) {
for (const id of (body as any).selectedPartIds as number[]) {
const item = byId.get(id);
if (!item) {
throw new BadRequestException(
`Invalid outer part id: ${id}. Use GET outer-parts-catalog to see valid IDs.`,
);
}
selectedFromIds.push(item);
}
}
if (selectedFromIds.length === 0) {
throw new BadRequestException(
'selectedPartIds is required and must contain at least one valid Fanavaran part ID',
);
}
const selectedItems = selectedFromIds;
// DISABLED: At most two non-top sides allowed
// const sideSet = new Set(
// selectedItems
// .map((p) => p.side)
// .filter((s) => s !== "top"),
// );
// if (sideSet.size > 2) {
// throw new BadRequestException(
// `At most two of left/right/front/back can be selected. Selected: ${[...sideSet].join(", ")}`,
// );
// }
const selectedPartDocs = selectedItems.map((p) =>
catalogItemToSelectedPart(p, liveCatalog),
);
const damagedPartsInitial = selectedPartDocs.map((p) => ({
id: p.id ?? undefined,
name: p.name,
side: p.side,
label_fa: p.label_fa,
...(p.catalogKey ? { catalogKey: p.catalogKey } : {}),
}));
const selectedPartIds = selectedItems.map((p) => p.id);
// 6. Update claim case with selected parts and move to next step
const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
{
'damage.selectedParts': selectedPartDocs,
'media.damagedParts': damagedPartsInitial,
'vehicle.carType': selectedCarType,
status: ClaimCaseStatus.SELECTING_OTHER_PARTS,
'workflow.currentStep': ClaimWorkflowStep.SELECT_OTHER_PARTS,
'workflow.nextStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
$unset: { 'damage.selectedOuterParts': '' },
$push: {
'workflow.completedSteps': ClaimWorkflowStep.SELECT_OUTER_PARTS,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.SELECT_OUTER_PARTS,
selectedParts: selectedPartDocs,
selectedPartIds,
carType: selectedCarType,
partsCount: selectedPartDocs?.length,
description: `User selected ${selectedPartDocs?.length} damaged outer parts`,
},
},
},
},
);
if (!updatedClaim) {
throw new InternalServerErrorException('Failed to update claim case');
}
this.logger.log(
`Outer parts selected for claim ${claimRequestId}: ${selectedPartDocs?.length} parts`,
);
const fanavaranDamageCase =
await this.autoSubmitFanavaranDamageCaseOnOuterPartsSelected(
claimRequestId,
selectedPartDocs,
);
let message =
'Outer parts selected successfully. Please proceed to select other parts and provide bank information.';
if (fanavaranDamageCase.submitted) {
message += ' The damage case was sent to Fanavaran successfully.';
} else if (fanavaranDamageCase.warning) {
message += ` ${fanavaranDamageCase.warning}`;
}
// 7. Return response
return {
claimRequestId: updatedClaim._id.toString(),
publicId: updatedClaim.publicId,
selectedParts: selectedPartDocs,
selectedPartIds,
currentStep: ClaimWorkflowStep.SELECT_OTHER_PARTS,
nextStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
message,
fanavaranDamageCase,
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error(
'selectOuterPartsV2 failed',
claimRequestId,
error instanceof Error ? error.stack : String(error),
);
throw new InternalServerErrorException(
error instanceof Error ? error.message : 'Failed to select outer parts',
);
}
}
/**
* V2 API: Select other damaged parts and provide bank information (Step 3 of claim workflow)
*
* @param claimRequestId - The claim case ID
* @param body - Other parts, Sheba number, and national code
* @param currentUserId - The current user's ID
* @returns Response with updated claim information
*
* Validations:
* - Claim case must exist
* - User must be the claim owner (damaged party)
* - Current workflow step must be SELECT_OTHER_PARTS (step 3)
* - Other parts and bank info must not have been submitted previously
*/
async selectOtherPartsV2(
claimRequestId: string,
body: SelectOtherPartsV2Dto,
currentUserId: string,
actor?: { sub: string; role?: string },
file?: Express.Multer.File,
): Promise<SelectOtherPartsV2ResponseDto> {
try {
// 1. Validate claim exists
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
// 2. Validate user is the damaged party (or field expert for IN_PERSON claim)
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner (damaged party) can submit other parts and bank information',
);
// 3. Validate workflow step is correct (should be at SELECT_OTHER_PARTS)
if (
claimCase.workflow?.currentStep !==
ClaimWorkflowStep.SELECT_OTHER_PARTS &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new BadRequestException(
`Invalid workflow step. Expected ${ClaimWorkflowStep.SELECT_OTHER_PARTS}, but current step is ${claimCase.workflow?.currentStep}`,
);
}
// 4. Validate other parts and bank info haven't been submitted yet
if (
claimCase.money?.sheba &&
claimCase.money?.nationalCodeOfInsurer &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new ConflictException(
'Bank information has already been submitted for this claim',
);
}
// 5. Prepare data
// Backward compatibility aliases:
// - shebaNumber <- sheba
// - nationalCodeOfOwner <- nationalCodeOfInsurer
let otherParts = Array.isArray((body as any)?.otherParts)
? (body as any).otherParts
: [];
// Multipart clients may send otherParts as JSON string
if (
!Array.isArray((body as any)?.otherParts) &&
typeof (body as any)?.otherParts === 'string'
) {
try {
const parsed = JSON.parse((body as any).otherParts);
otherParts = Array.isArray(parsed) ? parsed : [];
} catch {
otherParts = [];
}
}
const shebaInput = String(
((body as any).shebaNumber ?? (body as any).sheba ?? '') as string,
).replace(/\s/g, '');
const shebaDigits = shebaInput.replace(/^IR/i, '');
const shebaNumber = `IR${shebaDigits}`;
const submittedNationalCode = String(
((body as any).nationalCodeOfOwner ??
(body as any).nationalCodeOfInsurer ??
'') as string,
).replace(/\s/g, '');
if (!/^[0-9]{24}$/.test(shebaDigits)) {
throw new BadRequestException(
'shebaNumber is required and must be valid (IR + 24 digits or only 24 digits)',
);
}
const blameRequest = claimCase.blameRequestId
? await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
)
: null;
const storedOwnerNationalCode =
this.resolveVehicleOwnerNationalCodeForClaim(blameRequest);
if (
storedOwnerNationalCode &&
submittedNationalCode &&
submittedNationalCode !== storedOwnerNationalCode
) {
throw new BadRequestException(
'Submitted national code does not match the vehicle owner saved on the blame case.',
);
}
const nationalCode = storedOwnerNationalCode ?? submittedNationalCode;
if (!/^[0-9]{10}$/.test(nationalCode)) {
throw new BadRequestException(
'Vehicle owner national code is unavailable; a 10-digit nationalCodeOfOwner is required only for legacy claims.',
);
}
const ownershipPlate = this.resolveOwnershipPlateForClaim(
claimCase,
blameRequest,
);
if (!ownershipPlate) {
throw new BadRequestException(
'Could not resolve vehicle plate for ownership validation.',
);
}
let step = claimCase.workflow?.currentStep;
// External inquiry checks before moving workflow:
// 1) ownership check for nationalCode + plate
// await this.sandHubService.getCarOwnershipInfo(ownershipPlate, nationalCode);
// 2) sheba check for nationalCode + sheba
await this.sandHubService.getShebaValidation(nationalCode, shebaNumber);
const updatePayload: any = {
'damage.otherParts': otherParts.length > 0 ? otherParts : undefined,
'money.sheba': shebaNumber,
'money.nationalCodeOfInsurer': nationalCode,
status: ClaimCaseStatus.CAPTURING_PART_DAMAGES,
'workflow.currentStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
'workflow.nextStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
$push: {
'workflow.completedSteps': ClaimWorkflowStep.SELECT_OTHER_PARTS,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.SELECT_OTHER_PARTS,
otherParts,
otherPartsCount: otherParts.length,
hasBankInfo: true,
hasGreenCardUpload: !!file,
description: `User selected ${otherParts.length} other damaged parts and provided bank information`,
},
},
},
};
if (file) {
const existingGreen =
(claimCase.requiredDocuments as any)?.get?.(
ClaimRequiredDocumentType.CAR_GREEN_CARD,
) ||
(claimCase.requiredDocuments as any)?.[
ClaimRequiredDocumentType.CAR_GREEN_CARD
];
if (existingGreen?.uploaded) {
throw new ConflictException(
'car_green_card has already been uploaded for this claim',
);
}
const docRef = await this.claimRequiredDocumentDbService.create({
path: file.path,
fileName: file.filename,
claimId: new Types.ObjectId(claimRequestId),
documentType: ClaimRequiredDocumentType.CAR_GREEN_CARD,
uploadedAt: new Date(),
});
updatePayload[
`requiredDocuments.${ClaimRequiredDocumentType.CAR_GREEN_CARD}`
] = {
fileId: docRef._id,
filePath: file.path,
fileName: file.filename,
uploaded: true,
uploadedAt: new Date(),
};
}
// 6. Update claim case with other parts, bank info and optional green card file
const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
updatePayload,
);
if (!updatedClaim) {
throw new InternalServerErrorException('Failed to update claim case');
}
this.logger.log(
`Other parts and bank info submitted for claim ${claimRequestId}: ${otherParts.length} parts`,
);
// 7. Mask sensitive data for response
const maskedSheba = `IR${shebaDigits.slice(0, 4)}************${shebaDigits.slice(-4)}`;
const maskedNationalCode = `${nationalCode.slice(0, 2)}******${nationalCode.slice(-2)}`;
// 8. Return response
return {
claimRequestId: updatedClaim._id.toString(),
publicId: updatedClaim.publicId,
otherParts: otherParts,
shebaNumber: maskedSheba,
nationalCodeOfOwner: maskedNationalCode,
currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
nextStep: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
message:
'Other parts and bank information saved successfully. Please capture car angles and damaged parts, then upload required documents.',
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error(
'selectOtherPartsV2 failed',
claimRequestId,
error instanceof Error ? error.stack : String(error),
);
throw new InternalServerErrorException(
error instanceof Error ? error.message : 'Failed to select other parts',
);
}
}
/**
* V2 API: Get capture requirements for claim (documents, angles, parts)
*/
async getCaptureRequirementsV2(
claimRequestId: string,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<GetCaptureRequirementsV2ResponseDto> {
try {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can view capture requirements',
);
// Build outer-parts lookup for resolving stored DB parts.
// Uses the static snapshot (FANAVARAN_CAR_PARTS_CATALOG) which is keyed
// by numeric id (key === String(id)). This is only needed for legacy
// migration of parts stored before the Fanavaran catalog change.
const catalogByKey = new Map<string, OuterPartCatalogItem>();
for (const item of FANAVARAN_CAR_PARTS_CATALOG) {
if (!catalogByKey.has(item.key)) catalogByKey.set(item.key, item);
}
// Required documents vary by claim type. The accident sketch is offered
// in every flow, but is excluded from every completion calculation.
const blameRequest = claimCase.blameRequestId
? await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
)
: null;
const isCarBody = blameRequest?.type === BlameRequestType.CAR_BODY;
const requiredDocsDefinition = [
{
key: ClaimRequiredDocumentType.ACCIDENT_SKETCH,
label_fa: 'کروکی',
label_en: 'Accident Sketch',
category: 'general',
required: false,
},
{
key: 'damaged_driving_license_front',
label_fa: 'گواهینامه طرف آسیب‌دیده - جلو',
label_en: 'Damaged Party License - Front',
category: 'damaged_party',
required: true,
},
{
key: 'damaged_driving_license_back',
label_fa: 'گواهینامه طرف آسیب‌دیده - پشت',
label_en: 'Damaged Party License - Back',
category: 'damaged_party',
required: true,
},
{
key: 'damaged_chassis_number',
label_fa: 'شماره شاسی',
label_en: 'Chassis Number',
category: 'damaged_party',
required: true,
},
{
key: 'damaged_engine_photo',
label_fa: 'عکس موتور',
label_en: 'Engine Photo',
category: 'damaged_party',
required: true,
},
{
key: 'damaged_car_card_front',
label_fa: 'کارت خودرو آسیب‌دیده - جلو',
label_en: 'Damaged Car Card - Front',
category: 'damaged_party',
required: true,
},
{
key: 'damaged_car_card_back',
label_fa: 'کارت خودرو آسیب‌دیده - پشت',
label_en: 'Damaged Car Card - Back',
category: 'damaged_party',
required: true,
},
{
key: 'damaged_metal_plate',
label_fa: 'پلاک فلزی آسیب‌دیده',
label_en: 'Damaged Metal Plate',
category: 'damaged_party',
required: true,
},
{
key: 'car_green_card',
label_fa: 'کارت سبز خودرو',
label_en: 'Car Green Card',
category: 'damaged_party',
required: true,
},
...(isCarBody
? []
: [
{
key: 'guilty_driving_license_front',
label_fa: 'گواهینامه طرف مقصر - جلو',
label_en: 'Guilty Party License - Front',
category: 'guilty_party',
required: true,
},
{
key: 'guilty_driving_license_back',
label_fa: 'گواهینامه طرف مقصر - پشت',
label_en: 'Guilty Party License - Back',
category: 'guilty_party',
required: true,
},
{
key: 'guilty_car_card_front',
label_fa: 'کارت خودرو مقصر - جلو',
label_en: 'Guilty Car Card - Front',
category: 'guilty_party',
required: true,
},
{
key: 'guilty_car_card_back',
label_fa: 'کارت خودرو مقصر - پشت',
label_en: 'Guilty Car Card - Back',
category: 'guilty_party',
required: true,
},
{
key: 'guilty_metal_plate',
label_fa: 'پلاک فلزی مقصر',
label_en: 'Guilty Metal Plate',
category: 'guilty_party',
required: true,
},
]),
];
const requiredDocuments = requiredDocsDefinition.map((doc) => {
const docData = (claimCase.requiredDocuments as any)?.get?.(doc.key) ??
(claimCase.requiredDocuments as any)?.[doc.key];
return {
key: doc.key,
label_fa: doc.label_fa,
label_en: doc.label_en,
category: doc.category,
required: doc.required,
uploaded: docData?.uploaded || false,
preferUploadDuringCapture: isCapturePhaseDamagedPartyDocKey(doc.key),
};
});
const hasCapture = (data: any, key: string) =>
data && (data instanceof Map ? data.get(key) : data[key]);
// Car angles
const carAngles = [
{ key: 'front', label_fa: 'جلوی ماشین', label_en: 'Front of the car' },
{ key: 'back', label_fa: 'عقب ماشین', label_en: 'Back of the car' },
{ key: 'left', label_fa: 'چپ ماشین', label_en: 'Left of the car' },
{ key: 'right', label_fa: 'راست ماشین', label_en: 'Right of the car' },
].map((angle) => ({
key: angle.key,
label_fa: angle.label_fa,
label_en: angle.label_en,
captured: hasClaimCarAngleCapture(
claimCase.media?.carAngles as any,
claimCase.media?.damagedParts as any,
angle.key as ClaimCarAngleKey,
),
}));
const carType = claimCase.vehicle?.carType as
| ClaimVehicleTypeV2
| undefined;
const selectedNorm = normalizeDamageSelectedParts(
claimCase.damage?.selectedParts,
carType,
(claimCase.damage as any)?.selectedOuterParts,
);
const damagedParts = selectedNorm.map((sp) => {
const catalogMeta = sp.catalogKey
? catalogByKey.get(sp.catalogKey)
: sp.name
? catalogByKey.get(catalogLikeKeyFromPart(sp))
: undefined;
const labelEnName = sp.name
.replace(/([a-z])([A-Z])/g, '$1 $2')
.replace(/_/g, ' ')
.trim()
.replace(/\b\w/g, (c) => c.toUpperCase());
const ck = sp.catalogKey ?? catalogLikeKeyFromPart(sp);
return {
id: sp.id ?? catalogMeta?.id,
key: sp.name,
name: sp.name,
side: sp.side,
label_fa: sp.label_fa,
label_en: labelEnName,
captured: hasDamagedPartCapture(
claimCase.media?.damagedParts as any,
ck,
selectedNorm,
),
};
});
// Calculate progress
const requiredDocumentItems = requiredDocuments.filter((d) => d.required);
const documentsUploaded = requiredDocumentItems.filter(
(d) => d.uploaded,
).length;
const anglesCaptured = carAngles.filter((a) => a.captured).length;
const partsCaptured = damagedParts.filter((p) => p.captured).length;
const captureProgress = getClaimCaptureProgress(claimCase);
const capturePhaseDocsRemaining =
captureProgress.capturePhaseDocsRemaining;
const partsRemaining = Math.max(
0,
captureProgress.partsTotal - captureProgress.partsCaptured,
);
const anglesRemaining = Math.max(
0,
captureProgress.anglesTotal - captureProgress.anglesCaptured,
);
const postCaptureDocsRemaining = requiredDocuments.filter(
(d) => d.required && !d.preferUploadDuringCapture && !d.uploaded,
).length;
const totalRemaining =
partsRemaining + anglesRemaining + capturePhaseDocsRemaining;
return {
claimRequestId: claimCase._id.toString(),
publicId: claimCase.publicId,
currentStep: claimCase.workflow?.currentStep || '',
captureSequencePhase: captureProgress.sequencePhase,
captureSequenceHint: capturePhaseSequenceMessage(
captureProgress.sequencePhase,
),
requiredDocuments,
carAngles,
damagedParts,
totalRemaining,
progress: {
documentsUploaded,
documentsTotal: requiredDocumentItems.length,
anglesCaptured,
anglesTotal: carAngles.length,
partsCaptured,
partsTotal: damagedParts.length,
capturePhaseDocsRemaining,
postCaptureDocumentsRemaining: postCaptureDocsRemaining,
},
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('getCaptureRequirementsV2 failed', error);
throw new InternalServerErrorException(
'Failed to get capture requirements',
);
}
}
/**
* When the owner has uploaded every expert-requested document/part (or acknowledged description-only resend),
* move the claim back to the damage expert queue (same posture as after initial submission).
*/
private async tryFinalizeExpertResendAfterUserAction(
claimRequestId: string,
actorUserId: string,
ownerDisplayName: string,
): Promise<void> {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim || !canFinalizeExpertResend(claim)) {
return;
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
claimStatus: ClaimStatus.PENDING,
'workflow.currentStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
'workflow.nextStep': ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
'evaluation.damageExpertResend.fulfilledAt': new Date(),
},
$push: {
history: {
type: 'EXPERT_RESEND_FULFILLED',
actor: {
actorId: new Types.ObjectId(actorUserId),
actorName: ownerDisplayName,
actorType: 'user',
},
timestamp: new Date(),
metadata: {},
},
},
});
}
/**
* V2: Owner acknowledges a description-only expert resend (no extra documents or part photos requested).
*/
async acknowledgeExpertResendInstructionsV2(
claimRequestId: string,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<{
claimRequestId: string;
status: string;
claimStatus: string;
currentStep: string;
message: string;
}> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can complete this step',
);
if (
claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND
) {
throw new BadRequestException(
`No expert resend step is active. Current step: ${claimCase.workflow?.currentStep ?? 'none'}`,
);
}
if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) {
throw new BadRequestException(
`Claim is not waiting for resend action. Current status: ${claimCase.status}`,
);
}
const r = claimCase.evaluation?.damageExpertResend;
if (!r || r.fulfilledAt) {
throw new BadRequestException(
'There is no active expert resend request to acknowledge.',
);
}
if (
normalizeResendDocumentKeys(r.resendDocuments).length > 0 ||
normalizeResendPartKeys(
r.resendCarParts,
claimCase.vehicle?.carType as ClaimVehicleTypeV2 | undefined,
claimCase.damage?.selectedParts,
).length > 0
) {
throw new BadRequestException(
'Upload all requested documents and part photos before completing the resend step.',
);
}
await this.tryFinalizeExpertResendAfterUserAction(
claimRequestId,
effectiveUserId,
claimCase.owner?.fullName || 'User',
);
const updated = await this.claimCaseDbService.findById(claimRequestId);
return {
claimRequestId,
status: String(updated?.status ?? ''),
claimStatus: String(updated?.claimStatus ?? ''),
currentStep: String(updated?.workflow?.currentStep ?? ''),
message: 'Claim returned to the damage expert queue.',
};
}
/** Reuse a confirmed stored document, never an uploaded flag without file evidence. */
private existingDocumentUploadResult(
claim: any,
key: string,
): UploadRequiredDocumentV2ResponseDto | undefined {
const doc =
claim.requiredDocuments?.get?.(key) ?? claim.requiredDocuments?.[key];
if (!doc?.uploaded) return undefined;
const path = typeof doc.filePath === 'string' ? doc.filePath.trim() : '';
const url = typeof doc.fileUrl === 'string' ? doc.fileUrl.trim() : '';
if (!path && !url) return undefined;
return {
claimRequestId: String(claim._id),
documentKey: key,
fileUrl: path ? buildFileLink(path) : url,
alreadyUploaded: true,
allDocumentsUploaded: (claim.workflow?.completedSteps ?? []).includes(
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
),
currentStep: claim.workflow?.currentStep ?? '',
message: 'تصویر این مدرک قبلاً ثبت شده است؛ می‌توانید ادامه دهید.',
};
}
/** V2 API: Upload required document. Initial-upload retries reuse stored evidence. */
async uploadRequiredDocumentV2(
claimRequestId: string,
body: UploadRequiredDocumentV2Dto,
file: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
options?: {
v3InPersonFlow?: boolean;
skipMetalPlate?: boolean;
requiresFileMakerApproval?: boolean;
includeGuiltyDamageArea?: boolean;
},
): Promise<UploadRequiredDocumentV2ResponseDto> {
try {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can upload documents',
);
const step = claimCase.workflow?.currentStep;
const isResendUpload = step === ClaimWorkflowStep.USER_EXPERT_RESEND;
if (
!isResendUpload &&
claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND &&
!options?.v3InPersonFlow
) {
const existing = this.existingDocumentUploadResult(claimCase, body.documentKey);
if (existing) return existing;
}
const isOptionalDocument =
body.documentKey === ClaimRequiredDocumentType.ACCIDENT_SKETCH;
const isCapturePhaseDocUpload =
step === ClaimWorkflowStep.CAPTURE_PART_DAMAGES &&
(isCapturePhaseDamagedPartyDocKey(body.documentKey) ||
(options?.includeGuiltyDamageArea &&
(body.documentKey as string) === GUILTY_DAMAGE_AREA_DOC_KEY));
if (!isResendUpload) {
if (
step === ClaimWorkflowStep.CAPTURE_PART_DAMAGES &&
!isCapturePhaseDocUpload
) {
throw new BadRequestException(
`During ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} only chassis, engine, and damaged metal plate photos may be uploaded here (${CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS.join(', ')}), and only after all damaged parts and car angles are captured.`,
);
}
if (isCapturePhaseDocUpload) {
const captureProgress = getClaimCaptureProgress(claimCase);
if (!captureProgress.partsComplete) {
throw new BadRequestException(
'Upload photos for all selected damaged parts before uploading chassis, engine, or metal plate photos.',
);
}
if (!captureProgress.anglesComplete) {
throw new BadRequestException(
'Capture all four car angles (front, back, left, right) before uploading chassis, engine, or metal plate photos.',
);
}
}
const allowedInitialUploadStep =
step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS ||
isCapturePhaseDocUpload ||
(isOptionalDocument &&
step === ClaimWorkflowStep.USER_SUBMISSION_COMPLETE);
if (!allowedInitialUploadStep) {
throw new BadRequestException(
`Invalid workflow step. Expected ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS}, ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} (capture-phase documents only), or ${ClaimWorkflowStep.USER_EXPERT_RESEND}, but current step is ${claimCase.workflow?.currentStep}`,
);
}
if (options?.v3InPersonFlow) {
if (
step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS &&
isCapturePhaseDamagedPartyDocKey(body.documentKey)
) {
const capturePartDone = (
claimCase.workflow?.completedSteps ?? []
).includes(ClaimWorkflowStep.CAPTURE_PART_DAMAGES);
if (!capturePartDone) {
throw new BadRequestException(
`Complete outer/other part selection and capture-part (damaged parts + car angles) before uploading chassis, engine, and metal plate photos (${CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS.join(', ')}).`,
);
}
throw new BadRequestException(
`Chassis, engine, and metal plate photos must be uploaded during ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} after parts and angles are captured.`,
);
}
}
}
if (isResendUpload) {
if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) {
throw new BadRequestException(
`Claim is not waiting for expert resend uploads. Status: ${claimCase.status}`,
);
}
if (!documentKeyAllowedForExpertResend(claimCase, body.documentKey)) {
throw new BadRequestException(
`Document "${body.documentKey}" was not requested by the damage expert for this resend.`,
);
}
}
// CAR_BODY claims only allow 7 document types (no guilty_*)
const blameForUpload = claimCase.blameRequestId
? await this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
)
: null;
const isCarBodyUpload =
blameForUpload?.type === BlameRequestType.CAR_BODY;
const guiltyKeys = [
'guilty_driving_license_front',
'guilty_driving_license_back',
'guilty_car_card_front',
'guilty_car_card_back',
'guilty_metal_plate',
];
if (isCarBodyUpload && guiltyKeys.includes(body.documentKey)) {
throw new BadRequestException(
`Document type ${body.documentKey} is not required for CAR_BODY claims`,
);
}
// A confirmed initial upload was returned above. Incomplete references may
// be repaired here; expert-requested resends and in-person replacements remain allowed.
const fileUrl = buildFileLink(file.path);
const docRef = await this.claimRequiredDocumentDbService.create({
path: file.path,
fileName: file.filename,
claimId: new Types.ObjectId(claimRequestId),
documentType: body.documentKey,
uploadedAt: new Date(),
});
// Base history entry for this upload
const uploadHistoryEntry = {
type: 'DOCUMENT_UPLOADED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
documentKey: body.documentKey,
fileName: file.filename,
fileId: docRef._id.toString(),
},
};
// Base $set — always applied
const $set: Record<string, unknown> = {
[`requiredDocuments.${body.documentKey}`]: {
fileId: docRef._id,
filePath: file.path,
fileName: file.filename,
uploaded: true,
uploadedAt: new Date(),
},
};
// History entries to push — always at least the upload entry
const historyEntries: unknown[] = [uploadHistoryEntry];
// completedSteps entries to push
const completedStepsEntries: string[] = [];
let allDocumentsUploaded = false;
let remaining = 0;
let captureStepCompletedOnThisUpload = false;
if (!isResendUpload && !isOptionalDocument) {
if (isCapturePhaseDocUpload) {
const afterThis = (k: string) =>
k === body.documentKey ||
this.isRequiredDocumentUploadedOnClaim(claimCase, k);
const captureKeysForCount: string[] = [
...CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS,
...(options?.includeGuiltyDamageArea
? [GUILTY_DAMAGE_AREA_DOC_KEY]
: []),
];
remaining = captureKeysForCount.filter((k) => {
if (
options?.skipMetalPlate &&
OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(k as any)
)
return false;
return !afterThis(k);
}).length;
if (remaining === 0) {
const progressAfterDoc = getClaimCaptureProgress(claimCase, {
assumeCapturePhaseDocKey: body.documentKey,
skipMetalPlate: options?.skipMetalPlate,
includeGuiltyDamageArea: options?.includeGuiltyDamageArea,
});
if (
progressAfterDoc.partsComplete &&
progressAfterDoc.anglesComplete &&
progressAfterDoc.capturePhaseDocsComplete
) {
captureStepCompletedOnThisUpload = true;
// Advance to walk-around video step (UPLOADING_REQUIRED_DOCUMENTS /
// UPLOAD_REQUIRED_DOCUMENTS). For V4/V5 the claim is finalised in
// setVideoCaptureV3 (car-capture), which is the last FileReviewer
// action before handing off to the damage expert.
$set['status'] = ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS;
$set['workflow.currentStep'] =
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS;
$set['workflow.nextStep'] =
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE;
completedStepsEntries.push(
ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
);
historyEntries.push({
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
description: options?.v3InPersonFlow
? 'V4/V5 capture docs complete. Upload walk-around video to finalise.'
: 'Angles, damaged parts, and capture-phase vehicle evidence are complete.',
},
});
}
}
} else {
const v3InitialDocsComplete =
!!options?.v3InPersonFlow &&
step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS &&
this.allV3PreCaptureDocumentsComplete(
claimCase,
isCarBodyUpload,
body.documentKey,
options?.skipMetalPlate,
);
allDocumentsUploaded = options?.v3InPersonFlow
? v3InitialDocsComplete
: this.allV2OwnerDocumentsComplete(
claimCase,
isCarBodyUpload,
body.documentKey,
);
remaining = options?.v3InPersonFlow
? this.countRemainingV3PreCaptureDocuments(
claimCase,
isCarBodyUpload,
body.documentKey,
options?.skipMetalPlate,
)
: this.countRemainingV2OwnerDocuments(
claimCase,
isCarBodyUpload,
body.documentKey,
);
if (allDocumentsUploaded) {
if (options?.v3InPersonFlow) {
// V4/V5 split flow: the status transition to WAITING_FOR_FILE_REVIEWER is
// deferred to a post-write re-check (see below) to eliminate the race
// condition where two concurrent uploads each see a stale snapshot and
// neither fires the transition. We skip adding it to $set here.
} else {
$set['status'] = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT;
$set['claimStatus'] = ClaimStatus.PENDING;
$set['workflow.currentStep'] =
ClaimWorkflowStep.USER_SUBMISSION_COMPLETE;
$set['workflow.nextStep'] =
ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT;
completedStepsEntries.push(
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
);
historyEntries.push(
{
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
description: 'All required documents uploaded',
},
},
{
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
description:
'User submission complete. Claim ready for damage expert review.',
},
},
);
}
}
}
}
if (!isResendUpload && isOptionalDocument) {
allDocumentsUploaded = options?.v3InPersonFlow
? this.allV3PreCaptureDocumentsComplete(
claimCase,
isCarBodyUpload,
undefined,
options?.skipMetalPlate,
)
: this.allV2OwnerDocumentsComplete(claimCase, isCarBodyUpload);
remaining = options?.v3InPersonFlow
? this.countRemainingV3PreCaptureDocuments(
claimCase,
isCarBodyUpload,
undefined,
options?.skipMetalPlate,
)
: this.countRemainingV2OwnerDocuments(claimCase, isCarBodyUpload);
}
// Build the final MongoDB update — all operators explicit and clean
const updatePayload: Record<string, unknown> = { $set };
const $push: Record<string, unknown> = {
history:
historyEntries.length === 1
? historyEntries[0]
: { $each: historyEntries },
};
if (completedStepsEntries.length === 1) {
$push['workflow.completedSteps'] = completedStepsEntries[0];
} else if (completedStepsEntries.length > 1) {
$push['workflow.completedSteps'] = { $each: completedStepsEntries };
}
updatePayload.$push = $push;
await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
updatePayload,
);
// ─── V4/V5 in-person flow: post-write race-safe status transition ──────
// After the write we re-read the actual DB state. If all pre-capture
// documents are now present but the status has not yet advanced (i.e. a
// concurrent request uploaded the last doc a split-second before us and
// the stale snapshot we read earlier missed it — or vice-versa), we apply
// WAITING_FOR_FILE_REVIEWER atomically using findOneAndUpdate with a status
// condition, so exactly one writer wins regardless of concurrency.
if (
options?.v3InPersonFlow &&
!isResendUpload &&
!isCapturePhaseDocUpload
) {
const afterWrite =
await this.claimCaseDbService.findById(claimRequestId);
if (afterWrite) {
const blameForRecheck = afterWrite.blameRequestId
? await this.blameRequestDbService.findById(
afterWrite.blameRequestId.toString(),
)
: null;
const isCarBodyRecheck =
blameForRecheck?.type === BlameRequestType.CAR_BODY;
const skipMetalPlateRecheck = !!(blameForRecheck as any)
?.isMadeByFileMaker;
const allDoneNow =
afterWrite.status ===
ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS &&
afterWrite.workflow?.currentStep ===
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS &&
this.allV3PreCaptureDocumentsComplete(
afterWrite,
isCarBodyRecheck,
undefined,
skipMetalPlateRecheck,
);
if (allDoneNow) {
// Atomic conditional update: only succeeds when status is still
// UPLOADING_REQUIRED_DOCUMENTS, preventing double-application.
const advanced = await this.claimCaseDbService.findOneAndUpdate(
{
_id: afterWrite._id,
status: ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
},
{
$set: {
status: ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER,
'workflow.nextStep': ClaimWorkflowStep.SELECT_OUTER_PARTS,
},
$push: {
'workflow.completedSteps':
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: afterWrite.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
description:
'FileMaker documents complete. File sealed — awaiting FileReviewer.',
v3InPersonFlow: true,
},
},
},
},
);
if (advanced) {
// This request won the race — reflect the final state in the response.
allDocumentsUploaded = true;
// Now that the FileMaker's document phase is complete, promote the
// blame file to WAITING_FOR_FILE_REVIEWER so the frontend shows the
// correct sealed state when the FileMaker returns.
const blameId = (afterWrite as any).blameRequestId;
if (blameId) {
await this.blameRequestDbService.findByIdAndUpdate(
String(blameId),
{
$set: { status: BlameCaseStatus.WAITING_FOR_FILE_REVIEWER },
},
);
}
}
} else if (
afterWrite.status === ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER ||
(afterWrite.workflow?.completedSteps ?? []).includes(
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
)
) {
// Another concurrent request already advanced the status — treat
// this upload as the completing upload for response purposes.
allDocumentsUploaded = true;
}
}
}
// Auto-submit Fanavaran attachments when all documents are uploaded
if (
allDocumentsUploaded &&
!isOptionalDocument &&
!isResendUpload &&
!options?.v3InPersonFlow
) {
this.submitFanavaranAttachmentsV2(
claimRequestId,
resolveFanavaranClientKey(),
).catch((err) =>
this.logger.warn(
`Fanavaran attachments auto-submit failed: ${err?.message}`,
),
);
}
if (isResendUpload) {
await this.tryFinalizeExpertResendAfterUserAction(
claimRequestId,
currentUserId,
claimCase.owner?.fullName || 'User',
);
const refreshed =
await this.claimCaseDbService.findById(claimRequestId);
const expertResendComplete =
!!refreshed?.evaluation?.damageExpertResend?.fulfilledAt;
const fanavaranAttachment = await this.autoSubmitFanavaranAttachment(
claimRequestId,
{
path: file.path,
fileName: file.filename,
source: `document:${body.documentKey}:resend`,
},
);
return {
claimRequestId: claimCase._id.toString(),
documentKey: body.documentKey,
fileUrl,
allDocumentsUploaded: false,
expertResendComplete,
currentStep:
refreshed?.workflow?.currentStep ||
ClaimWorkflowStep.USER_EXPERT_RESEND,
message: expertResendComplete
? 'Expert resend requirements are complete. Your claim is back in the damage expert queue.'
: 'Document uploaded for expert resend.',
fanavaranAttachment,
};
}
const message = isOptionalDocument
? 'Optional accident sketch uploaded successfully.'
: isCapturePhaseDocUpload
? captureStepCompletedOnThisUpload
? options?.v3InPersonFlow
? 'Capture-phase documents and all damage captures are complete. Upload the walk-around video (car-capture) to finalise.'
: 'Capture-phase documents and all damage captures are complete. Please proceed to upload the remaining required documents.'
: remaining > 0
? `Document saved. ${remaining} capture-phase document(s) still required (chassis, engine, metal plate).`
: capturePhaseSequenceMessage(
getClaimCaptureProgress(claimCase, {
assumeCapturePhaseDocKey: body.documentKey,
}).sequencePhase,
)
: allDocumentsUploaded
? options?.v3InPersonFlow
? 'All FileMaker documents uploaded. File is sealed and ready for FileReviewer pickup.'
: 'All documents uploaded successfully. Your claim is now ready for damage expert review.'
: `Document uploaded successfully. ${remaining} documents remaining.`;
return {
claimRequestId: claimCase._id.toString(),
documentKey: body.documentKey,
fileUrl,
allDocumentsUploaded,
currentStep: isOptionalDocument
? step || ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS
: isCapturePhaseDocUpload
? captureStepCompletedOnThisUpload
? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS
: ClaimWorkflowStep.CAPTURE_PART_DAMAGES
: allDocumentsUploaded
? options?.v3InPersonFlow
? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS
: ClaimWorkflowStep.USER_SUBMISSION_COMPLETE
: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
message,
fanavaranAttachment: await this.autoSubmitFanavaranAttachment(
claimRequestId,
{
path: file.path,
fileName: file.filename,
source: `document:${body.documentKey}`,
},
),
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('uploadRequiredDocumentV2 failed', error);
throw new InternalServerErrorException('Failed to upload document');
}
}
/**
* V2 API: Capture car angle or damaged part
*/
async capturePartV2(
claimRequestId: string,
body: CapturePartV2Dto,
file: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<CapturePartV2ResponseDto> {
try {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can capture parts',
);
const capStep = claimCase.workflow?.currentStep;
const isResendCapture = capStep === ClaimWorkflowStep.USER_EXPERT_RESEND;
if (
!isResendCapture &&
capStep !== ClaimWorkflowStep.CAPTURE_PART_DAMAGES
) {
throw new BadRequestException(
`Invalid workflow step. Expected ${ClaimWorkflowStep.CAPTURE_PART_DAMAGES} or ${ClaimWorkflowStep.USER_EXPERT_RESEND}, but current step is ${claimCase.workflow?.currentStep}`,
);
}
if (isResendCapture) {
if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) {
throw new BadRequestException(
`Claim is not waiting for expert resend uploads. Status: ${claimCase.status}`,
);
}
if (body.captureType !== 'part') {
throw new BadRequestException(
'During expert resend only damaged-part photos can be uploaded (not car angles).',
);
}
if (!partKeyAllowedForExpertResend(claimCase, body.captureKey)) {
throw new BadRequestException(
`Part "${body.captureKey}" was not requested by the damage expert for this resend.`,
);
}
if (canonicalizeClaimCarAngleKey(body.captureKey)) {
throw new BadRequestException(
'During expert resend only damaged-part photos are allowed, not car angles (front/back/left/right).',
);
}
}
if (!isResendCapture) {
const captureProgressBefore = getClaimCaptureProgress(claimCase);
const willBeAngle =
body.captureType === 'angle' ||
(body.captureType === 'part' &&
canonicalizeClaimCarAngleKey(body.captureKey) !== null);
if (willBeAngle && !captureProgressBefore.partsComplete) {
throw new BadRequestException(
'Upload photos for all selected damaged parts before capturing car angles.',
);
}
}
const angleCanon = canonicalizeClaimCarAngleKey(body.captureKey);
if (body.captureType === 'angle' && !angleCanon) {
throw new BadRequestException(
`Invalid angle captureKey "${body.captureKey}". Use one of: front, back, left, right.`,
);
}
const treatAsAngle =
!isResendCapture &&
(body.captureType === 'angle' ||
(body.captureType === 'part' && angleCanon !== null));
const fileUrl = buildFileLink(file.path);
const captureData = {
path: file.path,
fileName: file.filename,
url: fileUrl,
capturedAt: new Date(),
};
const updateData: any = {
$push: {
history: {
type: treatAsAngle ? 'ANGLE_CAPTURED' : 'PART_CAPTURED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
captureType: body.captureType,
captureKey: body.captureKey,
...(treatAsAngle && angleCanon
? { resolvedCarAngleKey: angleCanon }
: {}),
fileName: file.filename,
},
},
},
};
const carType = claimCase.vehicle?.carType as
| ClaimVehicleTypeV2
| undefined;
const selectedOuterLegacy = (claimCase.damage as any)?.selectedOuterParts;
const selectedBeforeNorm = normalizeDamageSelectedParts(
claimCase.damage?.selectedParts,
carType,
selectedOuterLegacy,
);
let nextSelected = [...selectedBeforeNorm];
let nextMedia = coerceDamagedPartsMediaToArray(
claimCase.media?.damagedParts,
nextSelected,
);
if (treatAsAngle && angleCanon) {
updateData[`media.carAngles.${angleCanon}`] = captureData;
if (!Array.isArray(claimCase.media?.damagedParts)) {
const unsetFieldKeys = legacyAngleDamagedPartFieldKeysToUnset(
angleCanon,
body.captureKey,
claimCase.damage?.selectedParts,
carType,
selectedOuterLegacy,
);
if (unsetFieldKeys.length) {
updateData.$unset = {};
for (const k of unsetFieldKeys) {
updateData.$unset[`media.damagedParts.${k}`] = '';
}
}
}
} else {
let idx = resolvePartCaptureIndex(
body.captureKey,
nextSelected,
nextMedia,
);
if (isResendCapture && body.captureType === 'part' && idx < 0) {
const added = normalizeDamageSelectedParts(
[body.captureKey],
carType,
undefined,
);
const row = added[0] || {
id: null,
name: body.captureKey,
side: '',
label_fa: body.captureKey,
catalogKey: body.captureKey,
};
nextSelected.push(row);
idx = nextSelected.length - 1;
nextMedia.push({});
}
if (idx < 0) {
throw new BadRequestException(
`Unknown damaged-part captureKey "${body.captureKey}". Use catalog id, 0-based index, or catalog key.`,
);
}
while (nextMedia.length <= idx) {
nextMedia.push({});
}
const base = nextSelected[idx] || {
id: null,
name: String(body.captureKey),
side: '',
label_fa: String(body.captureKey),
};
nextMedia[idx] = {
...(base.id != null ? { id: base.id } : {}),
name: base.name,
side: base.side,
label_fa: base.label_fa,
...(base.catalogKey ? { catalogKey: base.catalogKey } : {}),
...nextMedia[idx],
...captureData,
};
// Per-index $set avoids lost updates when clients upload multiple parts
// in parallel (whole-array replace raced with Fanavaran-awaited requests).
// Legacy object maps still need a full write to migrate to array shape.
if (!Array.isArray(claimCase.media?.damagedParts)) {
updateData['media.damagedParts'] = nextMedia;
} else {
updateData[`media.damagedParts.${idx}`] = nextMedia[idx];
}
if (
isResendCapture &&
nextSelected.length !== selectedBeforeNorm.length
) {
updateData['damage.selectedParts'] = nextSelected;
}
}
await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
updateData,
);
if (!treatAsAngle) {
await this.aiService.enqueue(claimRequestId, captureData);
}
// Re-read so capture-progress sees sibling concurrent part/angle writes.
const updatedClaim =
(await this.claimCaseDbService.findById(claimRequestId)) ?? claimCase;
if (isResendCapture) {
await this.tryFinalizeExpertResendAfterUserAction(
claimRequestId,
currentUserId,
claimCase.owner?.fullName || 'User',
);
const refreshed =
await this.claimCaseDbService.findById(claimRequestId);
const expertResendComplete =
!!refreshed?.evaluation?.damageExpertResend?.fulfilledAt;
const fanavaranAttachment = await this.autoSubmitFanavaranAttachment(
claimRequestId,
{
path: file.path,
fileName: file.filename,
source: `capture:${body.captureType}:${body.captureKey}:resend`,
},
);
return {
claimRequestId: claimCase._id.toString(),
captureType: body.captureType,
captureKey: body.captureKey,
fileUrl,
allCapturesComplete: expertResendComplete,
expertResendComplete,
currentStep:
refreshed?.workflow?.currentStep ||
ClaimWorkflowStep.USER_EXPERT_RESEND,
message: expertResendComplete
? 'Expert resend requirements are complete. Your claim is back in the damage expert queue.'
: 'Part photo uploaded for expert resend.',
fanavaranAttachment,
};
}
const captureProgress = getClaimCaptureProgress(updatedClaim);
const allCapturesComplete = isClaimCaptureStepComplete(updatedClaim);
if (allCapturesComplete) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
status: ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS,
'workflow.currentStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
'workflow.nextStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
$push: {
'workflow.completedSteps': ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
description:
'Angles, damaged parts, and capture-phase vehicle evidence (chassis, engine, metal plate) are complete. Please upload remaining required documents.',
},
},
},
});
}
const partsRemaining = Math.max(
0,
captureProgress.partsTotal - captureProgress.partsCaptured,
);
const anglesRemaining = Math.max(
0,
captureProgress.anglesTotal - captureProgress.anglesCaptured,
);
const remaining =
partsRemaining +
anglesRemaining +
captureProgress.capturePhaseDocsRemaining;
const message = allCapturesComplete
? 'All captures complete. Please proceed to upload the remaining required documents.'
: `${body.captureType === 'angle' ? 'Angle' : 'Part'} captured successfully. ${capturePhaseSequenceMessage(captureProgress.sequencePhase)} (${remaining} item(s) left in this step).`;
return {
claimRequestId: claimCase._id.toString(),
captureType: body.captureType,
captureKey: body.captureKey,
fileUrl,
allCapturesComplete,
currentStep: allCapturesComplete
? ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS
: ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
message,
fanavaranAttachment: await this.autoSubmitFanavaranAttachment(
claimRequestId,
{
path: file.path,
fileName: file.filename,
source: `capture:${body.captureType}:${body.captureKey}`,
},
),
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('capturePartV2 failed', error);
throw new InternalServerErrorException('Failed to capture part');
}
}
/**
* V2 API: Upload car walk-around video (same storage as v1: claim-video-capture + ClaimCase.media.videoCaptureId).
*/
async setVideoCaptureV2(
claimRequestId: string,
fileDetail: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<VideoCaptureV2ResponseDto> {
try {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can upload car capture video',
);
if (!fileDetail) {
throw new BadRequestException('Video file is required.');
}
if (
claimCase.workflow?.currentStep !==
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS
) {
throw new BadRequestException(
`Invalid workflow step. Expected ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS}, but current step is ${claimCase.workflow?.currentStep}`,
);
}
const captureProgress = getClaimCaptureProgress(claimCase);
if (!captureProgress.partsComplete) {
throw new BadRequestException(
'Upload photos for all selected damaged parts before uploading the walk-around video.',
);
}
if (!captureProgress.anglesComplete) {
throw new BadRequestException(
'Capture all four car angles (front, back, left, right) before uploading the walk-around video.',
);
}
if (claimCase.media?.videoCaptureId) {
throw new ConflictException(
'A video has already been uploaded for this claim.',
);
}
const videoDoc = await this.createVideoCapture(
fileDetail,
claimRequestId,
);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: { 'media.videoCaptureId': videoDoc._id },
$push: {
history: {
type: 'VIDEO_CAPTURE_UPLOADED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
videoId: videoDoc._id.toString(),
fileName: fileDetail.filename,
},
},
},
});
return {
claimRequestId: claimCase._id.toString(),
videoId: videoDoc._id.toString(),
message: 'Video capture uploaded successfully.',
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('setVideoCaptureV2 failed', error);
throw new InternalServerErrorException('Failed to upload video capture');
}
}
/**
* Whether an expert resend request exists (user is expected to respond).
*/
private claimCaseHasExpertResend(claimCase: any): boolean {
const r = claimCase?.evaluation?.damageExpertResend;
if (!r) return false;
if (
typeof r.resendDescription === 'string' &&
r.resendDescription.trim() !== ''
) {
return true;
}
if (Array.isArray(r.resendDocuments) && r.resendDocuments.length > 0)
return true;
if (Array.isArray(r.resendCarParts) && r.resendCarParts.length > 0)
return true;
return false;
}
/**
* V2 API: User objection (ClaimCase + evaluation.objection payload).
*
* Priced-flow: insurer-review post-expert statuses (`INSURER_REVIEW_AWAITING_OWNER_SIGN`, `INSURER_REVIEW_MIXED_FACTORS_PENDING`, or legacy `WAITING_FOR_INSURER_APPROVAL`) @ `INSURER_REVIEW` — either NEEDS_REVISION (mixed-priced gate before factor upload)
* or APPROVED (final totals after pricing / factor validation); never while uploading factors or while expert validates.
* Legacy: objection during unpaid expert resend (`WAITING_FOR_USER_RESEND` @ `USER_EXPERT_RESEND`).
* Post: resets owner signatures when applicable and returns claim to WAITING_FOR_DAMAGE_EXPERT.
*/
async handleUserObjectionV2(
claimRequestId: string,
body: UserObjectionV2Dto,
currentUserId: string,
actor?: { sub: string; role?: string },
invoiceFiles?: Express.Multer.File[],
) {
try {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can submit an objection',
);
if (claimCase.evaluation?.objection?.submittedAt) {
throw new ConflictException(
'An objection has already been submitted for this claim.',
);
}
const hasExpertResend = this.claimCaseHasExpertResend(claimCase);
const pendingResendGate =
hasExpertResend &&
claimCase.status === ClaimCaseStatus.WAITING_FOR_USER_RESEND &&
claimCase.workflow?.currentStep ===
ClaimWorkflowStep.USER_EXPERT_RESEND;
if (claimCase.evaluation?.damageExpertReplyFinal) {
throw new ConflictException(
'The expert already submitted the final reply after objection; submit accept/reject via the owner signer.',
);
}
const activeExpert = getActiveV2ExpertReply(
claimCase as unknown as { evaluation?: Record<string, unknown> },
);
const partsIn = body.objectionParts ?? [];
const newPartsIn = body.newParts ?? [];
if (partsIn.length === 0 && newPartsIn.length === 0) {
throw new BadRequestException(
'Provide at least one entry in objectionParts and/or newParts.',
);
}
let pricingObjectionEligible = false;
if (
claimCaseStatusAllowsOwnerInsurerSignStep(claimCase.status) &&
claimCase.workflow?.currentStep === ClaimWorkflowStep.INSURER_REVIEW &&
!claimCase.evaluation?.ownerInsurerApproval?.signedAt
) {
if (objectionDisallowedDueToOutstandingFactorWorkflow(claimCase)) {
throw new BadRequestException(
'Objections are paused while factor files are uploading or the expert is validating repair factors.',
);
}
const shape = classifyV2ExpertPricingParts(activeExpert?.parts ?? []);
const atMixedPartialGate =
claimCase.claimStatus === ClaimStatus.NEEDS_REVISION &&
shape.mixedFactorAndPrice &&
!claimCase.evaluation?.ownerPricedPartsApproval?.signedAt;
const atFinalPricingGate =
claimCase.claimStatus === ClaimStatus.APPROVED;
pricingObjectionEligible = atMixedPartialGate || atFinalPricingGate;
}
if (!(pendingResendGate || pricingObjectionEligible)) {
throw new BadRequestException(
'No open objection window. Use this after a priced insurer-review step without a recorded final approval, ' +
'or while completing an unpaid expert resend.',
);
}
if (
!pendingResendGate &&
pricingObjectionEligible &&
!activeExpert?.parts?.length
) {
throw new BadRequestException(
'A priced assessment is required before you can object.',
);
}
const pricedCatalogIds = activeExpert?.parts?.length
? new Set(
activeExpert.parts
.filter((p) => p.factorNeeded !== true)
.map((p) => parseCatalogPartIdInput(p.partId))
.filter((id): id is number => id != null),
)
: new Set<number>();
if (partsIn.length && pricingObjectionEligible) {
for (const op of partsIn) {
const catalogId = parseCatalogPartIdInput(op.partId);
if (catalogId == null || !pricedCatalogIds.has(catalogId)) {
throw new BadRequestException(
`Only priced repair lines can be disputed (${String(op.partId)} is factor-only or unknown).`,
);
}
}
}
const objectionParts = partsIn.map((p) => ({
partId: parseCatalogPartIdInput(p.partId)!,
reason: p.reason?.trim() || undefined,
partPrice:
p.partPrice != null && String(p.partPrice).trim() !== ''
? normalizeMoneyAmountString(String(p.partPrice))
: undefined,
partSalary:
p.partSalary != null && String(p.partSalary).trim() !== ''
? normalizeMoneyAmountString(String(p.partSalary))
: undefined,
typeOfDamage:
p.typeOfDamage != null ? String(p.typeOfDamage) : undefined,
carPartDamage: p.carPartDamage?.trim() || undefined,
side: p.side?.trim() || undefined,
}));
const newParts = newPartsIn.map((p) => ({
partId:
p.partId != null && parseCatalogPartIdInput(p.partId) != null
? parseCatalogPartIdInput(p.partId)!
: new Types.ObjectId().toString(),
partName: p.partName.trim(),
side: p.side?.trim() || undefined,
}));
const objectionCarType = claimCase.vehicle?.carType as
| ClaimVehicleTypeV2
| undefined;
const mergedNorm = normalizeDamageSelectedParts(
claimCase.damage?.selectedParts,
objectionCarType,
(claimCase.damage as any)?.selectedOuterParts,
);
const mergedKeys = new Set(mergedNorm.map((p) => partLookupKey(p)));
for (const np of newParts) {
const name = np.partName?.trim();
if (!name) continue;
const side = String(np.side ?? '').trim();
const row = {
id: null as number | null,
name,
side,
label_fa: name,
};
const k = partLookupKey(row);
if (!mergedKeys.has(k)) {
mergedNorm.push(row);
mergedKeys.add(k);
}
}
const invoices = (invoiceFiles ?? []).map((f) => ({
fileId: new Types.ObjectId(),
path: f.path,
fileName: f.filename,
uploadedAt: new Date(),
}));
const objectionPayload = {
objectionParts,
newParts,
submittedAt: new Date(),
...(invoices.length > 0 && { invoices }),
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
claimStatus: ClaimStatus.PENDING,
'workflow.locked': false,
'workflow.currentStep': ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
'workflow.nextStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION,
'evaluation.objection': objectionPayload,
'damage.selectedParts': mergedNorm,
...(pendingResendGate && {
'evaluation.damageExpertResend.fulfilledAt': new Date(),
}),
},
$unset: {
'evaluation.ownerPricedPartsApproval': '',
'evaluation.ownerInsurerApproval': '',
},
$push: {
history: {
type: 'USER_OBJECTION_SUBMITTED',
actor: {
actorId: new Types.ObjectId(effectiveUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {
objectionPartCount: objectionParts.length,
newPartCount: newParts.length,
invoiceCount: invoices.length,
},
},
},
});
return objectionPayload;
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('handleUserObjectionV2 failed', error);
throw new InternalServerErrorException('Failed to submit objection');
}
}
/**
* V2 API: User satisfaction rating for a completed claim case (same intent as v1 PUT …/request/:id/user-rating).
*/
async addUserRatingV2(
claimRequestId: string,
ratingDto: UserRatingDto,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<UserClaimRating> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner can submit a satisfaction rating.',
);
if (claimCase.status !== ClaimCaseStatus.COMPLETED) {
throw new BadRequestException(
'You can only rate a claim after it has been completed.',
);
}
if (claimCase.userRating?.createdAt) {
throw new ConflictException(
'A rating has already been submitted for this claim.',
);
}
const score = (n: number) => Number(n);
for (const [key, label] of [
[ratingDto.progressSpeed, 'progressSpeed'],
[ratingDto.registrationEase, 'registrationEase'],
[ratingDto.overallEvaluation, 'overallEvaluation'],
] as const) {
const v = score(key);
if (Number.isNaN(v) || v < 0 || v > 5) {
throw new BadRequestException(
`${label} must be a number between 0 and 5.`,
);
}
}
const userRating: UserClaimRating = {
progressSpeed: ratingDto.progressSpeed,
registrationEase: ratingDto.registrationEase,
overallEvaluation: ratingDto.overallEvaluation,
comment: ratingDto.comment,
createdAt: new Date(),
};
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: { userRating },
$push: {
history: {
type: 'USER_RATING_SUBMITTED',
actor: {
actorId: new Types.ObjectId(effectiveUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
},
timestamp: new Date(),
metadata: {},
},
},
});
return userRating;
}
/**
* V2: Claim owner signature on expert pricing.
*
* Phase 1 (mixed priced + factor-needed lines): `INSURER_REVIEW_MIXED_FACTORS_PENDING` (or legacy `WAITING_FOR_INSURER_APPROVAL`), NEEDS_REVISION, INSURER_REVIEW,
* owner has not yet accepted priced lines — agreeing records `evaluation.ownerPricedPartsApproval` and moves the
* workflow to OWNER_UPLOAD_FACTOR_DOCUMENTS. Rejecting rejects the whole case.
*
* Phase 2 (final): INSURER_REVIEW_AWAITING_OWNER_SIGN (or legacy WAITING_FOR_INSURER_APPROVAL), APPROVED, INSURER_REVIEW — full accept/reject completes the case.
*/
async submitOwnerInsurerApprovalSignV2(
claimRequestId: string,
agree: boolean,
signFile: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string; fullName?: string },
): Promise<{
message: string;
claimRequestId: string;
status: ClaimCaseStatus;
claimStatus: ClaimStatus;
currentStep?: ClaimWorkflowStep;
accepted: boolean;
phase?: 'PRICED_PARTS_FOR_FACTORS' | 'FINAL_APPROVAL';
fanavaran?: FanavaranAutoSubmitResult;
fanavaranExpertise?: FanavaranExpertiseSubmitResult;
}> {
if (!Types.ObjectId.isValid(claimRequestId)) {
throw new BadRequestException('Invalid claim request id');
}
if (!signFile) {
throw new BadRequestException('A signature file is required');
}
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException('Claim request not found');
}
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase,
effectiveUserId,
actor as { username?: string },
'Only the claim owner (damaged party) can sign at this step.',
);
if (!claimCaseStatusAllowsOwnerInsurerSignStep(claimCase.status)) {
throw new BadRequestException(
`Claim is not waiting for your insurer-approval signature. Current status: ${String(claimCase.status)}`,
);
}
if (claimCase.workflow?.currentStep !== ClaimWorkflowStep.INSURER_REVIEW) {
throw new BadRequestException(
`Signing is only allowed at workflow step ${ClaimWorkflowStep.INSURER_REVIEW}. Current: ${String(claimCase.workflow?.currentStep ?? '')}`,
);
}
const active =
claimCase.evaluation?.damageExpertReplyFinal ||
claimCase.evaluation?.damageExpertReply;
if (!active?.submittedAt) {
throw new BadRequestException(
'No expert reply is available to sign off on yet.',
);
}
const shape = classifyV2ExpertPricingParts(active.parts ?? []);
const isMixedPartialGate =
shape.mixedFactorAndPrice &&
claimCase.claimStatus === ClaimStatus.NEEDS_REVISION &&
!claimCase.evaluation?.ownerPricedPartsApproval?.signedAt;
const isFinalApprovalGate =
claimCase.claimStatus === ClaimStatus.APPROVED &&
!claimCase.evaluation?.ownerInsurerApproval?.signedAt;
if (!isMixedPartialGate && !isFinalApprovalGate) {
throw new BadRequestException(
'No owner signature action is available at this state. ' +
'If repair factors are pending upload, complete the priced-line signature first (when claimStatus is NEEDS_REVISION). ' +
'If you already completed the final approval signature, refresh the claim.',
);
}
if (
isMixedPartialGate &&
claimCase.evaluation?.ownerInsurerApproval?.signedAt
) {
throw new ConflictException(
'Claim already has a final approval record; refresh the claim state.',
);
}
if (
isFinalApprovalGate &&
claimCase.evaluation?.ownerInsurerApproval?.signedAt
) {
throw new ConflictException(
'You have already submitted a signature for this claim.',
);
}
const signDoc = await this.claimSignDbService.create({
fileName: signFile.filename,
userId: effectiveUserId,
path: signFile.path,
requestId: new Types.ObjectId(claimRequestId),
} as any);
const signId = new Types.ObjectId(String((signDoc as any)._id));
const signedAt = new Date();
const scopedApprovalPayload = {
agree,
signDetailId: signId,
signedAt,
};
const historyActor = {
actorId: new Types.ObjectId(effectiveUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'user',
};
/** Mixed reply: priced lines acceptance before factor uploads */
if (isMixedPartialGate) {
if (!agree) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
'evaluation.ownerPricedPartsApproval': scopedApprovalPayload,
'workflow.nextStep': null,
},
$push: {
history: {
type: 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Your rejection has been recorded. This claim is marked rejected and will not proceed.',
claimRequestId,
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
currentStep: claimCase.workflow?.currentStep,
accepted: false,
phase: 'PRICED_PARTS_FOR_FACTORS',
};
}
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
claimStatus: ClaimStatus.NEEDS_REVISION,
'evaluation.ownerPricedPartsApproval': scopedApprovalPayload,
'workflow.currentStep':
ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS,
'workflow.nextStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION,
},
$push: {
history: {
type: 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Priced repair lines accepted. Upload repair factor files for each factor-needed part; the claim will return to the damage expert for cost validation.',
claimRequestId,
status: claimCase.status,
claimStatus: ClaimStatus.NEEDS_REVISION,
currentStep: ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS,
accepted: true,
phase: 'PRICED_PARTS_FOR_FACTORS',
};
}
/** Final accept / reject (no outstanding factor gate at this step) */
if (!agree) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
'evaluation.ownerInsurerApproval': scopedApprovalPayload,
'workflow.nextStep': null,
},
$push: {
history: {
type: 'OWNER_REJECTED_INSURER_APPROVAL_PRICING',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
return {
message:
'Your rejection has been recorded. This claim is marked rejected and will not proceed.',
claimRequestId,
status: ClaimCaseStatus.REJECTED,
claimStatus: ClaimStatus.REJECTED,
currentStep: claimCase.workflow?.currentStep,
accepted: false,
phase: 'FINAL_APPROVAL',
};
}
// Submit Fanavaran expertise when owner accepts the expert reply
const fanavaranExpertise =
await this.autoSubmitFanavaranExpertiseOnExpertReply(claimRequestId);
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.COMPLETED,
claimStatus: ClaimStatus.APPROVED,
'evaluation.ownerInsurerApproval': scopedApprovalPayload,
'workflow.currentStep': ClaimWorkflowStep.CLAIM_COMPLETED,
'workflow.nextStep': ClaimWorkflowStep.CLAIM_COMPLETED,
},
$push: {
'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW,
history: {
type: 'OWNER_SIGNED_INSURER_APPROVAL',
actor: historyActor,
timestamp: signedAt,
metadata: {},
},
},
});
const fanavaran =
await this.autoSubmitToFanavaranV2OnClaimCompleted(claimRequestId);
let message = 'Your signature has been recorded. The claim is completed.';
if (fanavaran.submitted) {
message += ' The claim was sent to Fanavaran successfully.';
} else if (fanavaran.warning) {
message += ` ${fanavaran.warning}`;
}
return {
message,
claimRequestId,
status: ClaimCaseStatus.COMPLETED,
claimStatus: ClaimStatus.APPROVED,
currentStep: ClaimWorkflowStep.CLAIM_COMPLETED,
accepted: true,
phase: 'FINAL_APPROVAL',
fanavaran,
fanavaranExpertise,
};
}
/**
* V2 API: Get list of claims for current user (or for FIELD_EXPERT: claims from their expert-initiated IN_PERSON blame files).
*/
async getMyClaimsV2(
currentUserId: string,
actor?: { sub: string; role?: string },
query: ListQueryV2Dto = {},
): Promise<GetMyClaimsV2ResponseDto> {
try {
let claims: any[];
if (actor?.role === RoleEnum.FIELD_EXPERT) {
const expertOid = new Types.ObjectId(currentUserId);
const expertBlameIds = await this.blameRequestDbService
.find(
{
expertInitiated: true,
initiatedByFieldExpertId: expertOid,
},
{ select: '_id', lean: true },
)
.then((docs) => docs.map((d) => (d as any)._id));
const claimOr: Record<string, unknown>[] = [
{ initiatedByFieldExpertId: expertOid },
];
if (expertBlameIds.length > 0) {
claimOr.push({ blameRequestId: { $in: expertBlameIds } });
}
claims = await this.claimCaseDbService.find(
{ $or: claimOr },
{ lean: true },
);
} else if (actor?.role === RoleEnum.REGISTRAR) {
const registrarBlameIds = await this.blameRequestDbService
.find(
{
registrarInitiated: true,
creationMethod: 'IN_PERSON',
initiatedByRegistrarId: new Types.ObjectId(currentUserId),
},
{ select: '_id', lean: true },
)
.then((docs) => docs.map((d) => (d as any)._id));
claims = await this.claimCaseDbService.find(
{
$or: [
{ 'owner.userId': new Types.ObjectId(currentUserId) },
...(registrarBlameIds.length
? [{ blameRequestId: { $in: registrarBlameIds } }]
: []),
],
},
{ lean: true },
);
} else {
const linkedUserIds = await resolveLinkedUserIdStrings(
this.userDbService,
{
sub: currentUserId,
username: (actor as { username?: string })?.username,
},
);
const actorCtx = {
sub: currentUserId,
username: (actor as { username?: string })?.username,
};
const partyBlameOr = buildBlamePartyAccessOrConditions(
actorCtx,
linkedUserIds,
);
const idVariants = collectUserIdVariants(...linkedUserIds);
const ownerOr = buildOwnerUserIdAccessFilter(idVariants);
// damagedPartyUserId filter — direct match without blame lookup
const damagedOr =
idVariants.length === 1
? { damagedPartyUserId: idVariants[0] }
: idVariants.length > 1
? { damagedPartyUserId: { $in: idVariants } }
: null;
// Build snapshot-party query: claim.snapshot.parties.person.userId
// is the most direct and reliable path — it's copied from the blame
// at claim-creation time and always has the correct damaged-party userId.
const snapshotPartyFilter =
idVariants.length === 1
? { 'snapshot.parties.person.userId': idVariants[0] }
: idVariants.length > 1
? { 'snapshot.parties.person.userId': { $in: idVariants } }
: null;
const [
ownerClaims,
damagedDirectClaims,
snapshotClaims,
candidateBlames,
] = await Promise.all([
ownerOr
? this.claimCaseDbService.find(ownerOr as any, { lean: true })
: Promise.resolve([]),
damagedOr
? this.claimCaseDbService.find(damagedOr as any, { lean: true })
: Promise.resolve([]),
snapshotPartyFilter
? this.claimCaseDbService.find(snapshotPartyFilter as any, {
lean: true,
})
: Promise.resolve([]),
partyBlameOr.length
? this.blameRequestDbService.find(
partyBlameOr.length === 1
? (partyBlameOr[0] as any)
: ({ $or: partyBlameOr } as any),
{
lean: true,
select: 'type parties expert.decision blameStatus',
},
)
: Promise.resolve([]),
]);
// Any blame where the user is a party (not just damaged) surfaces
// the linked claim. Mutation guards protect against acting as the
// wrong party; viewing is intentionally open to all parties.
const partyBlameIds = (candidateBlames as any[]).map((b) => b._id);
const damagedClaims =
partyBlameIds.length > 0
? await this.claimCaseDbService.find(
{ blameRequestId: { $in: partyBlameIds } },
{ lean: true },
)
: [];
// Merge: owner claims + blame-resolved damaged claims + snapshot-party claims
// snapshotClaims may include guilty-owner claims too — filter them out here.
const snapshotDamagedClaims = (snapshotClaims as any[]).filter((c) => {
if (!c?.owner?.userId) return true; // unknown owner: allow
const ownerStr = String(c.owner.userId);
// Exclude if the user IS the owner (already in ownerClaims)
return !linkedUserIds.some((id) => id === ownerStr);
});
const byId = new Map<string, any>();
for (const c of [
...(ownerClaims as any[]),
...(damagedDirectClaims as any[]),
...(damagedClaims as any[]),
...snapshotDamagedClaims,
]) {
byId.set(String(c._id), c);
}
claims = [...byId.values()];
}
const blameIdsForList = [
...new Set(
(claims as any[])
.map((c) => c.blameRequestId?.toString())
.filter((id): id is string => !!id),
),
];
const blamesForList =
blameIdsForList.length > 0
? ((await this.blameRequestDbService.find(
{
_id: {
$in: blameIdsForList.map((id) => new Types.ObjectId(id)),
},
},
{ lean: true, select: 'type creationMethod status' },
)) as any[])
: [];
const blameByIdForList = new Map<string, any>(
blamesForList.map((b) => [String(b._id), b]),
);
const list = (claims as any[]).map((c) => {
const blameForItem = c.blameRequestId
? blameByIdForList.get(c.blameRequestId.toString())
: undefined;
return {
claimRequestId: c._id.toString(),
publicId: c.publicId,
requestNo: c.requestNo,
status: c.status,
claimStatus: c.claimStatus || 'PENDING',
currentStep: c.workflow?.currentStep || '',
createdAt: c.createdAt,
blameRequestId: c.blameRequestId?.toString(),
partyIdentities: c.parties ?? c.snapshot?.parties,
blameType: blameForItem?.type ?? undefined,
creationMethod: blameForItem?.creationMethod ?? undefined,
unifiedFileStatus: resolveUnifiedFileStatus({
blameStatus: blameForItem?.status,
claimStatus: c.status,
}),
};
}) as ClaimListItemV2Dto[];
let filtered = list;
if (query.unifiedStatus) {
filtered = filtered.filter(
(row) => row.unifiedFileStatus === query.unifiedStatus,
);
}
const { fromDate, toDate } = parseListDateRange(
query.startDate,
query.endDate,
);
if (fromDate || toDate) {
filtered = filtered.filter((row) =>
isInListDateRange(row.createdAt, fromDate, toDate),
);
}
const paged = applyListQueryV2(
filtered,
{
publicId: (r) => r.publicId,
createdAt: (r) => r.createdAt,
requestNo: (r) => r.requestNo,
status: (r) => r.unifiedFileStatus ?? r.status,
fileType: (r) => r.blameType,
searchExtras: (r) =>
[
r.claimRequestId,
r.claimStatus,
r.currentStep,
r.blameRequestId,
].filter(Boolean) as string[],
},
query,
);
return {
list: toPublicListItems(paged.list),
total: paged.total,
page: paged.page,
limit: paged.limit,
totalPages: paged.totalPages,
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('getMyClaimsV2 failed', error);
throw new InternalServerErrorException('Failed to get claims list');
}
}
/**
* V2 API: Get claim details by ID (owner — or FIELD_EXPERT with enriched money/rating fields).
* Owners receive `ownerGuidance` computed from workflow state.
*/
async getClaimDetailsV2(
claimRequestId: string,
currentUserId: string,
actor?: { sub: string; role?: string; username?: string },
): Promise<ClaimDetailsV2ResponseDto> {
try {
const claim = await this.claimCaseDbService.findById(claimRequestId);
if (!claim) {
throw new NotFoundException('Claim request not found');
}
await this.assertActorCanViewClaimV2(claim, currentUserId, actor);
const blameForDetail = claim.blameRequestId
? ((
await this.blameRequestDbService.find(
{ _id: new Types.ObjectId(claim.blameRequestId.toString()) },
{ lean: true, select: 'type creationMethod' },
)
)[0] ?? null)
: null;
const hasCapture = (data: any, key: string) =>
data && (data instanceof Map ? data.get(key) : data[key]);
const requiredDocs = claim.requiredDocuments as any;
const requiredDocumentsStatus: Record<
string,
{ uploaded: boolean; fileUrl?: string }
> = {};
if (requiredDocs) {
const keys =
requiredDocs instanceof Map
? Array.from(requiredDocs.keys())
: Object.keys(requiredDocs);
for (const k of keys) {
const doc =
requiredDocs instanceof Map ? requiredDocs.get(k) : requiredDocs[k];
requiredDocumentsStatus[k] = {
uploaded: !!doc?.uploaded,
fileUrl: doc?.filePath ? buildFileLink(doc.filePath) : undefined,
};
}
}
const carAnglesData = claim.media?.carAngles as any;
const damagedPartsForAngles = claim.media?.damagedParts as any;
const carAngles: Record<string, { captured: boolean; url?: string }> = {};
for (const k of ['front', 'back', 'left', 'right']) {
const cap = getClaimCarAngleCaptureBlob(
carAnglesData,
damagedPartsForAngles,
k as ClaimCarAngleKey,
) as { url?: string; path?: string } | undefined;
carAngles[k] = {
captured: !!cap,
url: resolveStoredFileUrl(cap),
};
}
const carTypeDetails = claim.vehicle?.carType as
| ClaimVehicleTypeV2
| undefined;
const selectedNormDetails = normalizeDamageSelectedParts(
claim.damage?.selectedParts,
carTypeDetails,
(claim.damage as any)?.selectedOuterParts,
);
const damagedPartsData = claim.media?.damagedParts as any;
const resendPartKeys = normalizeResendPartKeys(
claim.evaluation?.damageExpertResend?.resendCarParts,
carTypeDetails,
claim.damage?.selectedParts,
);
const displayParts = [...selectedNormDetails];
const seenDetailKeys = new Set(
selectedNormDetails.map((p) => partLookupKey(p)),
);
for (const rk of resendPartKeys) {
const extra = normalizeDamageSelectedParts(
[rk],
carTypeDetails,
undefined,
)[0] || {
id: null,
name: rk,
side: '',
label_fa: rk,
catalogKey: rk,
};
const k = partLookupKey(extra);
if (!seenDetailKeys.has(k)) {
displayParts.push(extra);
seenDetailKeys.add(k);
}
}
const damagedParts = buildEnrichedDamagedParts({
selectedParts: displayParts,
damagedPartsData: damagedPartsData,
evaluationBlock: (claim as any).evaluation,
expertAddedParts: (claim.damage as any)?.expertAddedParts ?? [],
getDamagedPartCaptureBlob,
hasDamagedPartCapture,
catalogLikeKeyFromPart,
buildFileLink,
});
const damagedPartsHistory = serializeDamagedPartSelectionHistory({
history: (claim.damage as any)?.partSelectionHistory,
currentSelectedParts: selectedNormDetails,
});
const er = claim.evaluation?.damageExpertResend;
const expertResend =
er &&
(er.resendDescription ||
(er.resendDocuments?.length ?? 0) > 0 ||
(er.resendCarParts?.length ?? 0) > 0)
? {
resendDescription: er.resendDescription,
resendDocuments: normalizeResendDocumentKeys(er.resendDocuments),
resendCarParts: mapExpertResendCarPartsForClient(
er.resendCarParts,
{
carType: carTypeDetails,
selectedParts: claim.damage?.selectedParts,
damagedPartsData: claim.media?.damagedParts,
buildUrl: (path) => buildFileLink(path),
},
),
fulfilledAt: er.fulfilledAt,
}
: undefined;
const maskSheba = (s?: string) =>
s ? s.replace(/^(.{4})(.*)(.{4})$/, 'IR$1************$3') : undefined;
const maskNationalCode = (s?: string) =>
s ? s.replace(/^(.{2})(.*)(.{2})$/, '$1******$3') : undefined;
const isExpertViewer =
actor?.role === RoleEnum.FIELD_EXPERT ||
actor?.role === RoleEnum.REGISTRAR;
let canAct = false;
try {
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claim,
currentUserId,
actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claim,
effectiveUserId,
actor,
);
canAct = true;
} catch (error) {
if (!(error instanceof ForbiddenException)) throw error;
}
const ownerData = claim.owner
? {
userId: claim.owner.userId?.toString(),
clientId: claim.owner.clientId?.toString(),
...(claim.owner.userClientKey
? { userClientKey: claim.owner.userClientKey.toString() }
: {}),
fullName: claim.owner.fullName,
}
: undefined;
const moneyForUser = claim.money
? {
sheba: maskSheba(claim.money.sheba),
nationalCodeOfOwner: maskNationalCode(
claim.money.nationalCodeOfInsurer,
),
}
: undefined;
const moneyForExpert = claim.money
? {
sheba: claim.money.sheba,
nationalCodeOfOwner: claim.money.nationalCodeOfInsurer,
}
: undefined;
const mappedEvaluation = await this.mapEvaluationForClient(
claim.evaluation,
claim.vehicle?.carType as ClaimVehicleTypeV2 | undefined,
);
return {
claimRequestId: claim._id.toString(),
canAct,
publicId: claim.publicId,
requestNo: claim.requestNo,
status: claim.status,
claimStatus: claim.claimStatus || 'PENDING',
currentStep: claim.workflow?.currentStep || '',
nextStep: claim.workflow?.nextStep,
blameRequestId: claim.blameRequestId?.toString(),
blameRequestNo: claim.blameRequestNo,
blameType: (blameForDetail as any)?.type ?? undefined,
creationMethod: (blameForDetail as any)?.creationMethod ?? undefined,
...(ownerData ? { owner: ownerData } : {}),
vehicle: claim.vehicle,
selectedParts: selectedNormDetails,
otherParts: claim.damage?.otherParts,
money: isExpertViewer ? moneyForExpert : moneyForUser,
requiredDocuments:
Object.keys(requiredDocumentsStatus).length > 0
? requiredDocumentsStatus
: undefined,
carAngles,
damagedParts,
damagedPartsHistory,
expertResend,
fanavaran: fanavaranClaimReferences(claim),
evaluation: mappedEvaluation
? {
damageExpertReply: mappedEvaluation.damageExpertReply,
damageExpertReplyFinal: mappedEvaluation.damageExpertReplyFinal,
}
: undefined,
...(!isExpertViewer && canAct
? {
ownerGuidance: buildClaimDetailsV2OwnerGuidance(
claim,
claim._id.toString(),
),
}
: {}),
...(isExpertViewer
? {
userRating: claim.userRating
? {
progressSpeed: claim.userRating.progressSpeed,
registrationEase: claim.userRating.registrationEase,
overallEvaluation: claim.userRating.overallEvaluation,
comment: claim.userRating.comment,
createdAt: claim.userRating.createdAt,
}
: undefined,
}
: {}),
createdAt: (claim as any).createdAt,
updatedAt: (claim as any).updatedAt,
};
} catch (error) {
if (error instanceof HttpException) throw error;
this.logger.error('getClaimDetailsV2 failed', error);
throw new InternalServerErrorException('Failed to get claim details');
}
}
private async generateUniqueClaimNumber(): Promise<string> {
const prefix = 'CL';
const randomPart = Math.floor(10000 + Math.random() * 90000); // 5 digits
return `${prefix}${randomPart}`;
}
private async loadBlameForV3Claim(claimCase: any) {
if (!claimCase?.blameRequestId) return null;
return this.blameRequestDbService.findById(
claimCase.blameRequestId.toString(),
);
}
private partyHasSignedOnBlame(blame: any, role: 'FIRST' | 'SECOND'): boolean {
const party = (blame.parties ?? []).find((p: any) => p?.role === role);
return !!party?.confirmation;
}
private assertV3ClaimDocumentsPhase(
blame: any,
options?: { skipAccidentFieldsCheck?: boolean },
): void {
if (
!options?.skipAccidentFieldsCheck &&
!(blame.expert?.decision as any)?.fields?.accidentWay
) {
throw new BadRequestException(
'Submit accident fields before uploading required documents.',
);
}
const isCarBody =
blame?.type === BlameRequestType.CAR_BODY || blame?.type === 'CAR_BODY';
if (isCarBody) {
if (!this.partyHasSignedOnBlame(blame, 'FIRST')) {
throw new BadRequestException(
'Upload documents after the party has signed.',
);
}
return;
}
if (
!this.partyHasSignedOnBlame(blame, 'FIRST') ||
!this.partyHasSignedOnBlame(blame, 'SECOND')
) {
throw new BadRequestException(
'Both parties must sign before uploading required documents.',
);
}
}
private assertV3ClaimPartsPhase(blame: any): void {
if (!(blame.expert?.decision as any)?.fields?.accidentWay) {
throw new BadRequestException(
'Submit accident fields before part selection.',
);
}
const isCarBody =
blame?.type === BlameRequestType.CAR_BODY || blame?.type === 'CAR_BODY';
if (isCarBody) {
if (!this.partyHasSignedOnBlame(blame, 'FIRST')) {
throw new BadRequestException(
'Part selection requires the party signature.',
);
}
return;
}
if (
!this.partyHasSignedOnBlame(blame, 'FIRST') ||
!this.partyHasSignedOnBlame(blame, 'SECOND')
) {
throw new BadRequestException(
'Both parties must sign before part selection.',
);
}
}
private claimV3StepCompleted(
claimCase: any,
step: ClaimWorkflowStep,
): boolean {
return (claimCase.workflow?.completedSteps ?? []).includes(step);
}
private assertV3ClaimWorkflowStep(
claimCase: any,
expected: ClaimWorkflowStep | ClaimWorkflowStep[],
hint?: string,
): void {
const allowed = Array.isArray(expected) ? expected : [expected];
const current = claimCase.workflow?.currentStep;
if (!allowed.includes(current)) {
throw new BadRequestException(
hint ??
`Invalid workflow step. Expected ${allowed.join(' or ')}, but current step is ${current}`,
);
}
}
private async advanceV3ClaimToOuterPartsIfReady(
claimCase: any,
blame: any,
): Promise<void> {
if (
claimCase.workflow?.currentStep === ClaimWorkflowStep.SELECT_OUTER_PARTS
) {
return;
}
const step = claimCase.workflow?.currentStep;
// UPLOAD_REQUIRED_DOCUMENTS: normal V3/V4 path after FileMaker docs.
// WAITING_FOR_FILE_REVIEWER (claim status): same DB step but with the new
// V4 claim status — FileReviewer is picking up the sealed file.
// USER_SUBMISSION_COMPLETE: can occur when documents were uploaded via a
// non-V3 path (e.g. generic v2 endpoint). Safe to advance as long as
// accident fields are set (checked just below).
// EXPERT_REVIEWING + EXPERT_DAMAGE_ASSESSMENT: FileReviewer re-entering
// after a FileMaker rejection. The claim was locked back to
// EXPERT_REVIEWING by the reviewer's lock call; the document phase was
// already completed in the prior cycle so it's safe to advance directly
// to part selection.
const isFileReviewerReentry =
claimCase.status === ClaimCaseStatus.EXPERT_REVIEWING &&
step === ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT &&
(blame as any)?.isMadeByFileMaker === true;
const canAdvance =
step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS ||
step === ClaimWorkflowStep.USER_SUBMISSION_COMPLETE ||
claimCase.status === ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER ||
isFileReviewerReentry;
if (!canAdvance) {
throw new BadRequestException(
`Complete required documents before selecting outer parts. Current step: ${step}`,
);
}
if (!(blame.expert?.decision as any)?.fields?.accidentWay) {
throw new BadRequestException(
'Submit accident fields before selecting outer parts.',
);
}
await this.claimCaseDbService.findByIdAndUpdate(String(claimCase._id), {
$set: {
status: ClaimCaseStatus.SELECTING_OUTER_PARTS,
claimStatus: ClaimStatus.PENDING,
'workflow.currentStep': ClaimWorkflowStep.SELECT_OUTER_PARTS,
'workflow.nextStep': ClaimWorkflowStep.SELECT_OTHER_PARTS,
},
});
}
private async assertV3InPersonClaim(claimCase: any) {
const blame = await this.loadBlameForV3Claim(claimCase);
if (!blame) {
throw new BadRequestException(
'V3 claim flow requires a linked blame file.',
);
}
if (blame.creationMethod !== CreationMethod.IN_PERSON) {
throw new BadRequestException(
'V3 claim flow is only for IN_PERSON blame files.',
);
}
if (!blame.expertInitiated) {
throw new BadRequestException(
'V3 claim flow requires an expert-initiated blame file.',
);
}
return blame;
}
private isV3InitialDocumentsPhase(claimCase: any): boolean {
const step = claimCase.workflow?.currentStep;
const capturePartDone = this.claimV3StepCompleted(
claimCase,
ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
);
return (
step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS && !capturePartDone
);
}
private shapeCaptureRequirementsForV3(
claimCase: any,
blame: any,
base: GetCaptureRequirementsV2ResponseDto,
): GetCaptureRequirementsV2ResponseDto {
const skipMetalPlate = !!(blame as any)?.isMadeByFileMaker;
// V4 = FileMaker flow without a secondary FileMaker approval step
const isV4 =
!!(blame as any)?.isMadeByFileMaker &&
!(claimCase as any)?.requiresFileMakerApproval;
const isCarBody =
blame?.type === BlameRequestType.CAR_BODY ||
(blame as any)?.type === 'CAR_BODY';
// For V4/V5 files strip metal-plate keys from the base response entirely
// so they never appear in any phase — the front-end should not show them.
if (skipMetalPlate) {
base = {
...base,
requiredDocuments: base.requiredDocuments.filter(
(d) => !OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(d.key as any),
),
};
}
const step = claimCase.workflow?.currentStep;
const capturePartDone = this.claimV3StepCompleted(
claimCase,
ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
);
if (this.isV3InitialDocumentsPhase(claimCase)) {
const preCaptureDocs = base.requiredDocuments.filter(
(d) => !d.preferUploadDuringCapture,
);
const requiredPreCaptureDocs = preCaptureDocs.filter((d) => d.required);
const remaining = requiredPreCaptureDocs.filter(
(d) => !d.uploaded,
).length;
return {
...base,
requiredDocuments: preCaptureDocs,
captureSequencePhase: 'parts',
captureSequenceHint:
'Upload initial required documents (licenses and car cards). Chassis, engine, and metal plate photos come after part selection, damaged-part photos, and car angles.',
damagedParts: [],
carAngles: base.carAngles.map((a) => ({ ...a, captured: false })),
totalRemaining: remaining,
progress: {
...base.progress,
documentsTotal: requiredPreCaptureDocs.length,
documentsUploaded: requiredPreCaptureDocs.filter((d) => d.uploaded)
.length,
partsCaptured: 0,
partsTotal: 0,
anglesCaptured: 0,
capturePhaseDocsRemaining: 0,
postCaptureDocumentsRemaining: remaining,
},
};
}
if (step === ClaimWorkflowStep.SELECT_OUTER_PARTS) {
return {
...base,
requiredDocuments: base.requiredDocuments.filter(
(d) => !d.preferUploadDuringCapture,
),
captureSequencePhase: 'parts',
captureSequenceHint: 'Select outer damaged parts before capture.',
totalRemaining: base.damagedParts.filter((p) => !p.captured).length,
};
}
if (step === ClaimWorkflowStep.SELECT_OTHER_PARTS) {
return {
...base,
requiredDocuments: base.requiredDocuments.filter(
(d) => !d.preferUploadDuringCapture,
),
captureSequencePhase: 'parts',
captureSequenceHint:
'Select other damaged parts (and car green card when required) before capture.',
};
}
if (step === ClaimWorkflowStep.CAPTURE_PART_DAMAGES) {
const capturePhaseDocs = base.requiredDocuments.filter(
(d) =>
d.preferUploadDuringCapture &&
!(
skipMetalPlate &&
OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5.includes(d.key as any)
),
);
// V4 THIRD_PARTY only: guilty_damage_area is uploaded via upload-document
// after all car angles are captured (last item in the documents phase).
// It also appears in damagedParts so the expert sees it labelled as a
// damaged-part capture.
if (isV4 && !isCarBody) {
const guiltyAreaUploaded = this.isRequiredDocumentUploadedOnClaim(
claimCase,
GUILTY_DAMAGE_AREA_DOC_KEY,
);
const guiltyAreaDoc = {
key: GUILTY_DAMAGE_AREA_DOC_KEY,
label_fa: 'تصویر نقطه آسیب‌دیده مقصر',
label_en: 'Guilty Car Damaged Area',
category: 'guilty_party',
required: true,
uploaded: guiltyAreaUploaded,
preferUploadDuringCapture: true,
};
const captureProgress = getClaimCaptureProgress(claimCase, {
skipMetalPlate,
includeGuiltyDamageArea: true,
});
return {
...base,
requiredDocuments: [...capturePhaseDocs, guiltyAreaDoc],
totalRemaining: captureProgress.capturePhaseDocsRemaining,
progress: {
...base.progress,
capturePhaseDocsRemaining:
captureProgress.capturePhaseDocsRemaining,
},
};
}
return {
...base,
requiredDocuments: capturePhaseDocs,
totalRemaining: base.progress.capturePhaseDocsRemaining,
};
}
if (
step === ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS &&
capturePartDone
) {
// car-capture not yet uploaded: next step is the walk-around video.
return {
...base,
requiredDocuments: [],
captureSequencePhase: 'complete',
captureSequenceHint:
'Upload the walk-around car video (car-capture), then the blame accident video.',
totalRemaining: claimCase.media?.videoCaptureId ? 0 : 1,
};
}
// V3 FIELD_EXPERT only: car-capture is done (step advanced to USER_SUBMISSION_COMPLETE
// in setVideoCaptureV3). The one remaining action is the blame accident video.
if (
step === ClaimWorkflowStep.USER_SUBMISSION_COMPLETE &&
!(blame as any).isMadeByFileMaker
) {
return {
...base,
requiredDocuments: [],
captureSequencePhase: 'complete',
captureSequenceHint:
'Walk-around video uploaded. Upload the blame accident video to finalise.',
totalRemaining: 0,
};
}
return base;
}
async uploadRequiredDocumentV3(
claimRequestId: string,
body: UploadRequiredDocumentV2Dto,
file: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<UploadRequiredDocumentV2ResponseDto> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const blame = await this.assertV3InPersonClaim(claimCase);
const skipMetalPlate = !!(blame as any).isMadeByFileMaker;
const isV4FileMaker =
!!(blame as any)?.isMadeByFileMaker &&
!(claimCase as any)?.requiresFileMakerApproval;
const isCarBodyBlame =
blame?.type === BlameRequestType.CAR_BODY ||
(blame as any)?.type === 'CAR_BODY';
// guilty_damage_area is an extra capture-phase doc key for V4 THIRD_PARTY
const isGuiltyDamageAreaDoc =
(body.documentKey as string) === GUILTY_DAMAGE_AREA_DOC_KEY &&
isV4FileMaker &&
!isCarBodyBlame;
const isCaptureDoc =
isCapturePhaseDamagedPartyDocKey(body.documentKey) ||
isGuiltyDamageAreaDoc;
// A response may have been lost after the last capture document advanced
// the workflow. Reuse that saved evidence after the usual owner/tenant checks.
if (
isCaptureDoc &&
claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND &&
claimCase.workflow?.currentStep !== ClaimWorkflowStep.CAPTURE_PART_DAMAGES &&
this.claimV3StepCompleted(claimCase, ClaimWorkflowStep.CAPTURE_PART_DAMAGES)
) {
const existing = this.existingDocumentUploadResult(claimCase, body.documentKey);
if (existing) {
const effectiveUserId = await this.resolveClaimEffectiveUserId(
claimCase, currentUserId, actor?.role,
);
await this.assertEffectiveUserIsDamagedPartyOnClaim(
claimCase, effectiveUserId, actor as { username?: string },
'Only the claim owner can upload documents',
);
return existing;
}
}
if (isCaptureDoc) {
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
claimCase,
ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
'Upload chassis and engine photos during capture after damaged-part photos and car angles.',
);
if (
!this.claimV3StepCompleted(
claimCase,
ClaimWorkflowStep.SELECT_OTHER_PARTS,
)
) {
throw new BadRequestException(
'Complete outer and other part selection before capture-phase vehicle documents.',
);
}
const captureProgress = getClaimCaptureProgress(claimCase, {
skipMetalPlate,
includeGuiltyDamageArea: isGuiltyDamageAreaDoc,
});
if (!captureProgress.partsComplete) {
throw new BadRequestException(
'Upload photos for all selected damaged parts before chassis or engine photos.',
);
}
if (!captureProgress.anglesComplete) {
throw new BadRequestException(
'Capture all four car angles before chassis or engine photos.',
);
}
} else {
this.assertV3ClaimDocumentsPhase(blame, {
skipAccidentFieldsCheck: actor?.role === 'file_maker',
});
if (!this.isV3InitialDocumentsPhase(claimCase)) {
throw new BadRequestException(
`Upload initial required documents during ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS} before part selection. Current step: ${claimCase.workflow?.currentStep}`,
);
}
}
// For V4 THIRD_PARTY files, guilty_damage_area must be counted in the
// capture-phase doc total for ALL capture uploads (not just the guilty_damage_area
// upload itself) so that the CAPTURE_PART_DAMAGES step is not marked complete
// until all three standard docs AND the guilty area photo are uploaded.
const includeGuiltyDamageArea = isV4FileMaker && !isCarBodyBlame;
return this.uploadRequiredDocumentV2(
claimRequestId,
body,
file,
currentUserId,
actor,
{
v3InPersonFlow: true,
skipMetalPlate,
requiresFileMakerApproval: !!(claimCase as any)
.requiresFileMakerApproval,
includeGuiltyDamageArea,
},
);
}
async getCaptureRequirementsV3(
claimRequestId: string,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<GetCaptureRequirementsV2ResponseDto> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const blame = await this.assertV3InPersonClaim(claimCase);
if (this.isV3InitialDocumentsPhase(claimCase)) {
this.assertV3ClaimDocumentsPhase(blame, {
skipAccidentFieldsCheck: actor?.role === 'file_maker',
});
} else if (
claimCase.workflow?.currentStep === ClaimWorkflowStep.CAPTURE_PART_DAMAGES
) {
this.assertV3ClaimPartsPhase(blame);
}
const base = await this.getCaptureRequirementsV2(
claimRequestId,
currentUserId,
actor,
);
return this.shapeCaptureRequirementsForV3(claimCase, blame, base);
}
async selectOuterPartsV3(
claimRequestId: string,
body: SelectOuterPartsV2Dto,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<SelectOuterPartsV2ResponseDto> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
await this.advanceV3ClaimToOuterPartsIfReady(claimCase, blame);
const refreshed = await this.claimCaseDbService.findById(claimRequestId);
this.assertV3ClaimWorkflowStep(
refreshed,
ClaimWorkflowStep.SELECT_OUTER_PARTS,
'Select outer parts after accident fields and required documents.',
);
const result = await this.selectOuterPartsV2(
claimRequestId,
body,
currentUserId,
actor,
);
return result;
}
async selectOtherPartsV3(
claimRequestId: string,
body: SelectOtherPartsV3Dto,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<SelectOtherPartsV2ResponseDto> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
claimCase,
ClaimWorkflowStep.SELECT_OTHER_PARTS,
'Select outer parts before other parts.',
);
if (
!this.claimV3StepCompleted(
claimCase,
ClaimWorkflowStep.SELECT_OUTER_PARTS,
)
) {
throw new BadRequestException(
'Complete outer part selection before selecting other parts.',
);
}
let otherParts = Array.isArray((body as any)?.otherParts)
? (body as any).otherParts
: [];
if (
!Array.isArray((body as any)?.otherParts) &&
typeof (body as any)?.otherParts === 'string'
) {
try {
const parsed = JSON.parse((body as any).otherParts);
otherParts = Array.isArray(parsed) ? parsed : [];
} catch {
otherParts = [];
}
}
const shebaNumber = claimCase.money?.sheba;
const nationalCode = claimCase.money?.nationalCodeOfInsurer;
const updatePayload: any = {
'damage.otherParts': otherParts.length > 0 ? otherParts : undefined,
status: ClaimCaseStatus.CAPTURING_PART_DAMAGES,
'workflow.currentStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
'workflow.nextStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
$push: {
'workflow.completedSteps': ClaimWorkflowStep.SELECT_OTHER_PARTS,
history: {
type: 'V3_STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'Actor',
actorType:
actor?.role === RoleEnum.REGISTRAR ? 'registrar' : 'field_expert',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.SELECT_OTHER_PARTS,
otherParts,
v3SelectionOnly: true,
},
},
},
};
const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate(
claimRequestId,
updatePayload,
);
if (!updatedClaim) {
throw new InternalServerErrorException('Failed to update claim case');
}
return {
claimRequestId: updatedClaim._id.toString(),
publicId: updatedClaim.publicId,
otherParts,
...(shebaNumber
? {
shebaNumber: String(shebaNumber).replace(
/^(.{4})(.*)(.{4})$/,
'IR$1************$3',
),
}
: {}),
...(nationalCode
? {
nationalCodeOfOwner: String(nationalCode).replace(
/^(.{2})(.*)(.{2})$/,
'$1******$3',
),
}
: {}),
currentStep: ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
nextStep: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
message:
'Other parts saved. Proceed to damaged-part photos and car angles (capture-part).',
};
}
async setVideoCaptureV3(
claimRequestId: string,
fileDetail: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<VideoCaptureV2ResponseDto> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const blame = await this.assertV3InPersonClaim(claimCase);
const skipMetalPlate = !!(blame as any).isMadeByFileMaker;
if (!fileDetail) {
throw new BadRequestException('Video file is required.');
}
if (claimCase.media?.videoCaptureId) {
// FILE_REVIEWER re-reviewing after a FileMaker rejection: allow replacing
// the previous walk-around video by clearing the stale id first so that
// setVideoCaptureV2's own conflict check doesn't block the upload.
if (actor?.role === RoleEnum.FILE_REVIEWER) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$unset: { 'media.videoCaptureId': '' },
});
claimCase.media = {
...(claimCase.media ?? {}),
videoCaptureId: undefined,
} as any;
} else {
throw new ConflictException(
'A walk-around video has already been uploaded for this claim.',
);
}
}
if (
claimCase.workflow?.currentStep !==
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS
) {
throw new BadRequestException(
`Complete capture-phase documents (chassis/engine) first. Expected ${ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS}, but current step is ${claimCase.workflow?.currentStep}`,
);
}
const captureProgress = getClaimCaptureProgress(claimCase, {
skipMetalPlate,
});
if (!captureProgress.partsComplete) {
throw new BadRequestException(
'Upload photos for all selected damaged parts before the walk-around video.',
);
}
if (!captureProgress.anglesComplete) {
throw new BadRequestException(
'Capture all four car angles before the walk-around video.',
);
}
if (!isClaimCaptureStepComplete(claimCase, { skipMetalPlate })) {
throw new BadRequestException(
skipMetalPlate
? 'Upload capture-phase vehicle documents (chassis and engine) before the walk-around video.'
: 'Upload capture-phase vehicle documents (chassis, engine, metal plate) before the walk-around video.',
);
}
// Store the walk-around video (shared V2 logic).
const result = await this.setVideoCaptureV2(
claimRequestId,
fileDetail,
currentUserId,
actor,
);
// V4/V5 only (isMadeByFileMaker): car-capture is the FINAL FileReviewer step.
// For the v3 mirror (FIELD_EXPERT IN_PERSON), car-capture is penultimate —
// expertUploadBlameVideoV3 finalises the blame with the accident video next.
// Advance the workflow step so that if the expert exits and reopens the claim
// the system correctly resumes at upload-video rather than replaying car-capture.
if (!(blame as any).isMadeByFileMaker) {
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
'workflow.currentStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
'workflow.nextStep': undefined,
},
$push: {
'workflow.completedSteps':
ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType: 'field_expert',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS,
description:
'V3 walk-around video uploaded. Upload blame accident video to finalise.',
v3InPersonFlow: true,
},
},
},
});
} else if ((blame as any).isMadeByFileMaker) {
// Both V4 and V5 land at WAITING_FOR_DAMAGE_EXPERT here.
// For V5 (requiresFileMakerApproval=true), autoSubmitToFanavaranV2OnClaimCompleted
// intercepts COMPLETED → WAITING_FOR_FILE_MAKER_APPROVAL after expert review.
await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, {
$set: {
status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT,
claimStatus: ClaimStatus.PENDING,
'workflow.currentStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
'workflow.nextStep': ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT,
},
$push: {
'workflow.completedSteps': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
history: {
type: 'STEP_COMPLETED',
actor: {
actorId: new Types.ObjectId(currentUserId),
actorName: claimCase.owner?.fullName || 'User',
actorType:
actor?.role === RoleEnum.FILE_REVIEWER
? 'file_reviewer'
: 'user',
},
timestamp: new Date(),
metadata: {
stepKey: ClaimWorkflowStep.USER_SUBMISSION_COMPLETE,
description:
'V4/V5 walk-around video uploaded. Claim ready for damage expert review.',
v3InPersonFlow: true,
},
},
},
});
// Mark the linked blame file as COMPLETED.
if (claimCase.blameRequestId) {
await this.blameRequestDbService.findByIdAndUpdate(
String(claimCase.blameRequestId),
{ $set: { status: BlameCaseStatus.COMPLETED } },
);
}
}
return result;
}
async capturePartV3(
claimRequestId: string,
body: CapturePartV2Dto,
file: Express.Multer.File,
currentUserId: string,
actor?: { sub: string; role?: string },
): Promise<CapturePartV2ResponseDto> {
const claimCase = await this.claimCaseDbService.findById(claimRequestId);
if (!claimCase) {
throw new NotFoundException(
`Claim case with ID ${claimRequestId} not found`,
);
}
const blame = await this.assertV3InPersonClaim(claimCase);
this.assertV3ClaimPartsPhase(blame);
this.assertV3ClaimWorkflowStep(
claimCase,
ClaimWorkflowStep.CAPTURE_PART_DAMAGES,
'Select other parts before capturing damaged parts and angles.',
);
if (
!this.claimV3StepCompleted(
claimCase,
ClaimWorkflowStep.SELECT_OTHER_PARTS,
)
) {
throw new BadRequestException(
'Complete other part selection before capture.',
);
}
return this.capturePartV2(claimRequestId, body, file, currentUserId, actor);
}
}