From 5d84b9697f7ed4cf62979cc923281933ba730b49 Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Wed, 11 Nov 2026 14:39:55 +0330 Subject: [PATCH] location default changed --- .../claim-request-management.service.ts | 2316 +++++++++-------- src/core/config/fanavaran-client.config.ts | 74 +- .../dto/create-insurer-expert.dto.ts | 54 +- 3 files changed, 1224 insertions(+), 1220 deletions(-) diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 3c718a3..c347587 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -1,7 +1,7 @@ import { hasReviewedTejaratNotifier, isTejaratNotifierLookup, -} from "src/fanavaran/tejarat-notifier"; +} from 'src/fanavaran/tejarat-notifier'; import { BadRequestException, ConflictException, @@ -12,46 +12,46 @@ import { InternalServerErrorException, Logger, NotFoundException, -} from "@nestjs/common"; -import { isAxiosError } from "axios"; -import { Types } from "mongoose"; -import { createReadStream, existsSync } 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"; +} from '@nestjs/common'; +import { isAxiosError } from 'axios'; +import { Types } from 'mongoose'; +import { createReadStream, existsSync } 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"; +} 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"; +} from 'src/fanavaran/fanavaran-http-exception'; +import { FanavaranLocationService } from 'src/fanavaran/fanavaran-location.service'; import { canUserCreateClaim, resolveClaimBeneficiary, -} from "src/helpers/blame-claim-eligibility"; +} from 'src/helpers/blame-claim-eligibility'; import { resolveClaimOwnerFieldsFromBlame, resolveClaimOwnerParty, resolveDamagedPartyRow, resolveDamagedPartyUserId, -} from "src/helpers/blame-damaged-party"; +} from 'src/helpers/blame-damaged-party'; import { canonicalizeClaimCarAngleKey, getClaimCarAngleCaptureBlob, @@ -60,9 +60,9 @@ import { 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"; +} 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, @@ -70,20 +70,20 @@ import { normalizeResendDocumentKeys, normalizeResendPartKeys, partKeyAllowedForExpertResend, -} from "src/helpers/claim-expert-resend"; +} 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"; +} 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"; +} from 'src/helpers/list-query-v2'; import { carPartDamageLabelForFactorRecord, catalogItemToSelectedPart, @@ -95,81 +95,81 @@ import { partLookupKey, resolvePartCaptureIndex, type DamageSelectedPartV2, -} from "src/helpers/outer-damage-parts"; +} 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 } from "src/helpers/tenant-scope"; -import { resolveUnifiedFileStatus } from "src/helpers/unified-file-status"; -import { buildFileLink, resolveStoredFileUrl } from "src/helpers/urlCreator"; +} from 'src/helpers/party-access-queries'; +import { toPublicListItems } from 'src/helpers/public-list-response'; +import { claimCaseInitiatedByFieldExpert } 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"; +} 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 { 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"; +} 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 { 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 { 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"; +} 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"; +} 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"; +} 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"; +} 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"; +} 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 { 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 { 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, @@ -182,8 +182,8 @@ import { pickCarBodyPolicyNationalCode, pickStoredCarBodyPolicyId, type FanavaranClaimProduct, -} from "./fanavaran-claim-product"; -import { fanavaranClaimReferences } from "./fanavaran-claim-references"; +} from './fanavaran-claim-product'; +import { fanavaranClaimReferences } from './fanavaran-claim-references'; import { actualPremiumFromHullPolicyRecord, authorityCulpritIdFromDetectionRows, @@ -192,8 +192,8 @@ import { FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, fanavaranHullNestedClaimId, toFanavaranHullBaseClaimPayload, -} from "./fanavaran-hull-base-claim"; -import { toTejaratV15ThirdPartyBasePayload } from "./fanavaran-v15-third-party-base"; +} from './fanavaran-hull-base-claim'; +import { toTejaratV15ThirdPartyBasePayload } from './fanavaran-v15-third-party-base'; import { collectFanavaranExpertiseReadinessWarnings, FANAVARAN_DEFAULT_HULL_REPAIR_DURATION, @@ -203,7 +203,7 @@ import { toFanavaranHullExpertiseDmgSection, toFanavaranHullExpertisePayload, vehicleCurrentValueFromHullPolicyRecord, -} from "./fanavaran-hull-expertise"; +} from './fanavaran-hull-expertise'; import { FANAVARAN_DEFAULT_HULL_DMG_COST_KIND_ID, FANAVARAN_DEFAULT_HULL_DMG_KIND_ID, @@ -211,18 +211,18 @@ import { FANAVARAN_HULL_DMG_COST_KIND_CAPTION, FANAVARAN_HULL_DMG_KIND_CAPTION, findLookupIdByCaption, -} from "./fanavaran-hull-expertise-lookups"; +} from './fanavaran-hull-expertise-lookups'; import { activeStageLookupRows, applyFanavaranStageFieldReview, fanavaranFieldStageSent, fanavaranStageFields, type FanavaranFieldValues, -} from "./fanavaran-stage-fields"; -import FormData = require("form-data"); +} from './fanavaran-stage-fields'; +import FormData = require('form-data'); -import { HttpService } from "@nestjs/axios"; -import { firstValueFrom } from "rxjs"; +import { HttpService } from '@nestjs/axios'; +import { firstValueFrom } from 'rxjs'; import { fanavaranSubmitPath, getFanavaranLookupBaseUrl, @@ -230,18 +230,18 @@ import { 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"; +} 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"; +} from 'src/fanavaran/schema/fanavaran-audit-log.schema'; import { CAPTURE_PHASE_DAMAGED_PARTY_DOC_KEYS, capturePhaseSequenceMessage, @@ -250,7 +250,7 @@ import { isCapturePhaseDamagedPartyDocKey, isClaimCaptureStepComplete, OPTIONAL_CAPTURE_PHASE_DOC_KEYS_V4V5, -} from "src/helpers/claim-capture-phase"; +} from 'src/helpers/claim-capture-phase'; import { applyFanavaranManualPayloadOverrides, asObjectRecord, @@ -270,11 +270,11 @@ import { resolveDamageCasePlaqueLookupIds, selectFanavaranVehicleForDamageCase, type FanavaranDamagedVehicleIdentity, -} from "src/lookups/fanavaran-last-car-policy"; +} from 'src/lookups/fanavaran-last-car-policy'; import { selectAccidentVehicleUsedId, vehicleGroupIdForKind, -} from "./fanavaran-accident-vehicle-used"; +} from './fanavaran-accident-vehicle-used'; import { asPartyInquiryRows, collectPersonBirthdays, @@ -284,11 +284,11 @@ import { pickPersonNationalCode, selectFanavaranDriverId, selectFanavaranOwnerId, -} from "./fanavaran-driver-inquiry"; +} from './fanavaran-driver-inquiry'; import { buildFanavaranOtherPeoplePayload, pickFanavaranRecordId, -} from "./fanavaran-other-people"; +} from './fanavaran-other-people'; import { resolveDriverFromParty, resolveDriverIsOwner, @@ -297,8 +297,8 @@ import { resolveOwnerFromParty, resolvePolicyholderFromParty, resolveThirdPartyCulpritTypeId, -} from "./fanavaran-party-roles"; -import { selectLatestActiveFanavaranPolicy } from "./fanavaran-policy-selection"; +} from './fanavaran-party-roles'; +import { selectLatestActiveFanavaranPolicy } from './fanavaran-policy-selection'; export interface FanavaranAutoSubmitResult { attempted: boolean; @@ -367,12 +367,12 @@ interface FanavaranClaimExpertContext { */ function jalaliDateToInt(d: Date): number { const parts = d - .toLocaleDateString("fa-IR", { - year: "numeric", - month: "2-digit", - day: "2-digit", + .toLocaleDateString('fa-IR', { + year: 'numeric', + month: '2-digit', + day: '2-digit', }) - .split("/") + .split('/') .map((p) => parseInt( p.replace(/[۰-۹]/g, (c) => String(c.charCodeAt(0) - 0x06f0)), @@ -396,7 +396,7 @@ function jalaliStringToInt(raw: string): number | null { return y * 10000 + mo * 100 + d; } -const FANAVARAN_ACCIDENT_LOCATION_ADDRESS = "استان تهران شهر تهران"; +const FANAVARAN_ACCIDENT_LOCATION_ADDRESS = 'استان تهران شهر تهران'; const FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID = 6; const FANAVARAN_DEFAULT_ACCIDENT_LEVEL = 5456; const FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT = 1000; @@ -405,15 +405,15 @@ const FANAVARAN_PROVISIONAL_ESTIMATE_AMOUNT = 1000; * 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"; + process.env.FANAVARAN_DUMMY_LICENCE_NO?.trim() || '9705463515'; /** Local carType → Fanavaran vehicle-kind Caption keywords for matching. */ const VEHICLE_KIND_KEYWORDS: Record = { - [ClaimVehicleTypeV2.SEDAN]: ["سواری", "سواري", "sedan"], - [ClaimVehicleTypeV2.SUV]: ["شاسی", "شاسي", "suv", "بلند"], - [ClaimVehicleTypeV2.HATCHBACK]: ["هاچبک", "هاچ بک", "hatchback"], - [ClaimVehicleTypeV2.PICKUP]: ["وانت", "پیکاپ", "pick", "pickup"], - [ClaimVehicleTypeV2.VAN]: ["ون", "van"], + [ClaimVehicleTypeV2.SEDAN]: ['سواری', 'سواري', 'sedan'], + [ClaimVehicleTypeV2.SUV]: ['شاسی', 'شاسي', 'suv', 'بلند'], + [ClaimVehicleTypeV2.HATCHBACK]: ['هاچبک', 'هاچ بک', 'hatchback'], + [ClaimVehicleTypeV2.PICKUP]: ['وانت', 'پیکاپ', 'pick', 'pickup'], + [ClaimVehicleTypeV2.VAN]: ['ون', 'van'], }; const FANAVARAN_PLATE_LETTER_CODE: Record = { @@ -448,13 +448,13 @@ 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: "210050", + 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). */ @@ -504,22 +504,22 @@ export class ClaimRequestManagementService { 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", + '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", + 'guilty_driving_license_front', + 'guilty_driving_license_back', + 'guilty_car_card_front', + 'guilty_car_card_back', + 'guilty_metal_plate', ]; } @@ -653,14 +653,14 @@ export class ClaimRequestManagementService { ir: number; } | null { if (!plateId) return null; - const parts = String(plateId).split("-"); + 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 || ""), + String(alphaRaw || ''), ); if ( !Number.isFinite(ir) || @@ -688,7 +688,7 @@ export class ClaimRequestManagementService { Number.isFinite(Number(p.leftDigits)) && Number.isFinite(Number(p.centerDigits)) && Number.isFinite(Number(p.ir)) && - this.plateNormalizer.normalizePlateText(String(p.centerAlphabet || "")) + this.plateNormalizer.normalizePlateText(String(p.centerAlphabet || '')) ) { return { leftDigits: Number(p.leftDigits), @@ -705,7 +705,7 @@ export class ClaimRequestManagementService { const matchedParty = blameRequest.parties.find( (party: any) => - String(party?.person?.userId || "") === String(ownerUserId || ""), + String(party?.person?.userId || '') === String(ownerUserId || ''), ) || blameRequest.parties.find( (party: any) => party?.role === PartyRole.FIRST, @@ -724,7 +724,7 @@ export class ClaimRequestManagementService { InquiryParticipantRole.VEHICLE_OWNER, ) : undefined; - const nationalCode = String(owner?.nationalCode ?? "").trim(); + const nationalCode = String(owner?.nationalCode ?? '').trim(); return nationalCode || undefined; } @@ -738,7 +738,7 @@ export class ClaimRequestManagementService { */ async getOuterPartsCatalogV2(): Promise { const clientKey = resolveFanavaranClientKey(); - const rows = await this.getFanavaranLookupRows(clientKey, "car-components"); + 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()); @@ -746,9 +746,9 @@ export class ClaimRequestManagementService { .filter( (r): r is { Id: number; Caption: string } => !!r && - typeof r === "object" && - typeof (r as any).Id === "number" && - typeof (r as any).Caption === "string", + typeof r === 'object' && + typeof (r as any).Id === 'number' && + typeof (r as any).Caption === 'string', ) .filter((r) => { const toDate = (r as any).ToDate; @@ -769,10 +769,10 @@ export class ClaimRequestManagementService { OuterPartCatalogItem[] > { const clientKey = resolveFanavaranClientKey(); - const rows = await this.getFanavaranLookupRows(clientKey, "car-components"); + const rows = await this.getFanavaranLookupRows(clientKey, 'car-components'); if (!rows.length) { this.logger.warn( - "getLiveFanavaranCatalogItems: remote lookup returned empty, falling back to snapshot", + 'getLiveFanavaranCatalogItems: remote lookup returned empty, falling back to snapshot', ); return FANAVARAN_CAR_PARTS_CATALOG; } @@ -780,16 +780,16 @@ export class ClaimRequestManagementService { .filter( (r): r is { Id: number; Caption: string } => !!r && - typeof r === "object" && - typeof (r as any).Id === "number" && - typeof (r as any).Caption === "string", + 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: "", + side: '', }), ); } @@ -814,10 +814,10 @@ export class ClaimRequestManagementService { if (Array.isArray(section)) { return section.filter( (row): row is Record => - !!row && typeof row === "object", + !!row && typeof row === 'object', ); } - if (typeof section === "object") { + if (typeof section === 'object') { return [section as Record]; } return []; @@ -839,10 +839,10 @@ export class ClaimRequestManagementService { private assertCarPartDamageAtMostTwoOfFourSides(dto: CarDamagePartDto): void { const d = dto as unknown as Record; const quadrants = [ - { key: "left", section: d.left }, - { key: "right", section: d.right }, - { key: "front", section: d.front }, - { key: "back", section: d.back }, + { 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), @@ -850,7 +850,7 @@ export class ClaimRequestManagementService { 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(", ")}.`, + `Sides with selections: ${used.map((u) => u.key).join(', ')}.`, ); } } @@ -864,7 +864,7 @@ export class ClaimRequestManagementService { if (slug) out.add(slug); }; const walkMainOnSide = ( - side: "left" | "right", + side: 'left' | 'right', items: unknown, map: Record, ) => { @@ -877,25 +877,25 @@ export class ClaimRequestManagementService { } }; // 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('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", + 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) => { for (const row of this.carPartDamageSectionToRows(items)) { @@ -905,15 +905,15 @@ export class ClaimRequestManagementService { } }; walkSimple((dto as any).front, { - frontBumper: "front_bumper", - carHood: "hood", + frontBumper: 'front_bumper', + carHood: 'hood', }); walkSimple((dto as any).back, { - backBumper: "rear_bumper", - carTrunk: "trunk", + backBumper: 'rear_bumper', + carTrunk: 'trunk', }); walkSimple((dto as any).top, { - roof: "roof", + roof: 'roof', }); return Array.from(out); } @@ -923,11 +923,11 @@ export class ClaimRequestManagementService { if (!raw || !Array.isArray(raw)) return []; const out: string[] = []; for (const item of raw) { - if (typeof item === "string" && item.trim()) { + if (typeof item === 'string' && item.trim()) { out.push(item.trim()); continue; } - if (item && typeof item === "object") { + if (item && typeof item === 'object') { for (const [k, v] of Object.entries(item)) { if (v === true && k) out.push(k); } @@ -942,29 +942,29 @@ export class ClaimRequestManagementService { ): Promise { const blameRequestId = claimCase?.blameRequestId?.toString?.(); if (!blameRequestId) { - throw new BadRequestException("Claim case has no linked blame request."); + 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."); + 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.", + 'This endpoint is only for expert-initiated IN_PERSON claim files.', ); } if (!blameRequest.initiatedByFieldExpertId) { throw new BadRequestException( - "Blame request is missing initiating field expert.", + '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.", + 'Only the initiating field expert can complete claim data for this file.', ); } } @@ -1006,27 +1006,27 @@ export class ClaimRequestManagementService { const claim = await this.claimDbService.findOne(claimRequestId); if (!claim) { - throw new NotFoundException("Claim file not found"); + throw new NotFoundException('Claim file not found'); } const blameFile = claim.blameFile as any; if ( !blameFile?.expertInitiated || - blameFile?.creationMethod !== "IN_PERSON" + blameFile?.creationMethod !== 'IN_PERSON' ) { throw new BadRequestException( - "This endpoint is only for expert-initiated IN_PERSON claim files.", + '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.", + '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."); + throw new BadRequestException('Car part damage is already set.'); } let trueItems: Array>; if (dto.selectedPartIds?.length) { @@ -1042,7 +1042,7 @@ export class ClaimRequestManagementService { ); } return { - side: item.side || "carDamage", + side: item.side || 'carDamage', part: item.titleFa, id: item.id, label_fa: item.titleFa, @@ -1110,7 +1110,7 @@ export class ClaimRequestManagementService { working.damage?.selectedParts && working.damage.selectedParts.length > 0 ) { - throw new BadRequestException("Car part damage is already set."); + throw new BadRequestException('Car part damage is already set.'); } let selectedPartObjs: DamageSelectedPartV2[]; if (dto.selectedPartIds?.length) { @@ -1138,7 +1138,7 @@ export class ClaimRequestManagementService { ); if (!selectedSlugStrings.length) { throw new BadRequestException( - "No outer damaged parts could be derived from carPartDamage. Check part selections.", + 'No outer damaged parts could be derived from carPartDamage. Check part selections.', ); } selectedPartObjs = normalizeDamageSelectedParts( @@ -1158,34 +1158,34 @@ export class ClaimRequestManagementService { const updated = await this.claimCaseDbService.findByIdAndUpdate( claimRequestId, { - "damage.selectedParts": selectedPartObjs, - "media.damagedParts": damagedPartsStubs, + 'damage.selectedParts': selectedPartObjs, + 'media.damagedParts': damagedPartsStubs, status: ClaimCaseStatus.SELECTING_OTHER_PARTS, - "workflow.currentStep": ClaimWorkflowStep.SELECT_OTHER_PARTS, - "workflow.nextStep": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, + 'workflow.currentStep': ClaimWorkflowStep.SELECT_OTHER_PARTS, + 'workflow.nextStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES, $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OUTER_PARTS, + 'workflow.completedSteps': ClaimWorkflowStep.SELECT_OUTER_PARTS, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(expert.sub), actorName: - `${expert.firstName || ""} ${expert.lastName || ""}`.trim() || - "field_expert", - actorType: "field_expert", + `${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", + description: 'Field expert submitted outer damage parts', }, }, }, }, ); if (!updated) { - throw new InternalServerErrorException("Failed to update claim case"); + throw new InternalServerErrorException('Failed to update claim case'); } working = updated; } @@ -1196,7 +1196,7 @@ export class ClaimRequestManagementService { dto.otherParts != null; if (hasBankOrOther) { const fresh = await this.claimCaseDbService.findById(claimRequestId); - if (!fresh) throw new NotFoundException("Claim case not found"); + if (!fresh) throw new NotFoundException('Claim case not found'); if ( fresh.workflow?.currentStep !== ClaimWorkflowStep.SELECT_OTHER_PARTS ) { @@ -1216,7 +1216,7 @@ export class ClaimRequestManagementService { dto.sheba != null && dto.sheba !== fresh.money.sheba ) { - throw new ConflictException("Sheba is already set for this claim."); + throw new ConflictException('Sheba is already set for this claim.'); } if ( fresh.money?.nationalCodeOfInsurer && @@ -1224,58 +1224,58 @@ export class ClaimRequestManagementService { dto.nationalCodeOfInsurer !== fresh.money.nationalCodeOfInsurer ) { throw new ConflictException( - "National code of insurer is already set for this claim.", + 'National code of insurer is already set for this claim.', ); } const otherPartsArr = this.normalizeExpertOtherPartsInput(dto.otherParts); const setPatch: Record = {}; - if (dto.sheba != null) setPatch["money.sheba"] = dto.sheba; + if (dto.sheba != null) setPatch['money.sheba'] = dto.sheba; if (dto.nationalCodeOfInsurer != null) { - setPatch["money.nationalCodeOfInsurer"] = dto.nationalCodeOfInsurer; + setPatch['money.nationalCodeOfInsurer'] = dto.nationalCodeOfInsurer; } if (dto.otherParts != null) { - setPatch["damage.otherParts"] = + 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, "")); + /^[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, ""); + 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, + 'money.sheba': shebaNorm, + 'money.nationalCodeOfInsurer': nationalNorm, ...(dto.otherParts != null ? { - "damage.otherParts": + 'damage.otherParts': otherPartsArr.length > 0 ? otherPartsArr : [], } : {}), status: ClaimCaseStatus.CAPTURING_PART_DAMAGES, - "workflow.currentStep": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "workflow.nextStep": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, + 'workflow.currentStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES, + 'workflow.nextStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OTHER_PARTS, + 'workflow.completedSteps': ClaimWorkflowStep.SELECT_OTHER_PARTS, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(expert.sub), actorName: - `${expert.firstName || ""} ${expert.lastName || ""}`.trim() || - "field_expert", - actorType: "field_expert", + `${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", + 'Field expert submitted bank info and optional other parts', }, }, }, @@ -1283,7 +1283,7 @@ export class ClaimRequestManagementService { } 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.", + 'Provide sheba (24 digits) and nationalCodeOfInsurer (10 digits) together to finish this step, or supply partial fields incrementally.', ); } await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { @@ -1319,7 +1319,7 @@ export class ClaimRequestManagementService { if (!reply) return reply; const mapped = { - ...(typeof reply?.toObject === "function" ? reply.toObject() : reply), + ...(typeof reply?.toObject === 'function' ? reply.toObject() : reply), }; const parts = Array.isArray(mapped.parts) ? mapped.parts : []; @@ -1331,7 +1331,7 @@ export class ClaimRequestManagementService { } const daghi = p?.daghi; const rawBranchId = - daghi && typeof daghi === "object" + daghi && typeof daghi === 'object' ? (daghi as any).branchId : undefined; if (rawBranchId && Types.ObjectId.isValid(String(rawBranchId))) { @@ -1371,7 +1371,7 @@ export class ClaimRequestManagementService { } const daghi = nextPart.daghi; - if (daghi && typeof daghi === "object" && !Array.isArray(daghi)) { + if (daghi && typeof daghi === 'object' && !Array.isArray(daghi)) { const branchId = (daghi as any).branchId; const branchName = branchId && Types.ObjectId.isValid(String(branchId)) @@ -1399,7 +1399,7 @@ export class ClaimRequestManagementService { // Resolve objection invoice paths to downloadable URLs (user-side view). const objectionRaw = evaluation.objection; let objection: any = objectionRaw - ? typeof objectionRaw?.toObject === "function" + ? typeof objectionRaw?.toObject === 'function' ? objectionRaw.toObject() : { ...objectionRaw } : undefined; @@ -1438,12 +1438,12 @@ export class ClaimRequestManagementService { ) { try { if (!file) { - throw new BadRequestException("A factor file is required for upload."); + 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"); + throw new NotFoundException('Claim not found'); } const effectiveUserId = await this.resolveClaimEffectiveUserId( @@ -1455,19 +1455,19 @@ export class ClaimRequestManagementService { claim, effectiveUserId, actor as { username?: string }, - "You do not have access to this claim file", + 'You do not have access to this claim file', ); const replyKey = claim.evaluation?.damageExpertReplyFinal - ? "damageExpertReplyFinal" - : "damageExpertReply"; + ? 'damageExpertReplyFinal' + : 'damageExpertReply'; const finalReply = - replyKey === "damageExpertReplyFinal" + replyKey === 'damageExpertReplyFinal' ? claim.evaluation?.damageExpertReplyFinal : claim.evaluation?.damageExpertReply; if (!finalReply?.parts?.length) { - throw new BadRequestException("No expert reply found in this claim."); + throw new BadRequestException('No expert reply found in this claim.'); } const part = finalReply.parts.find( @@ -1481,24 +1481,24 @@ export class ClaimRequestManagementService { if (!part.factorNeeded) { throw new BadRequestException( - "This part does not require a factor upload.", + 'This part does not require a factor upload.', ); } if (part.factorLink) { throw new ConflictException( - "A factor has already been uploaded for this part.", + '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).", + '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).", + 'Factors can only be uploaded while the claim needs owner action (claimStatus NEEDS_REVISION).', ); } if ( @@ -1506,7 +1506,7 @@ export class ClaimRequestManagementService { 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 ?? "")}.`, + `Repair factors are uploaded at workflow step ${ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS} (after accepting priced lines when applicable). Current: ${String(claim.workflow?.currentStep ?? '')}.`, ); } @@ -1517,13 +1517,13 @@ export class ClaimRequestManagementService { !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.", + '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 ?? ""); + String(part.partId ?? ''); const factorRecord = await this.claimFactorsImageDbService.create({ claimId: new Types.ObjectId(claimRequestId), @@ -1551,14 +1551,14 @@ export class ClaimRequestManagementService { if (!updatedClaim) { throw new NotFoundException( - "Could not find the specific part to update in the database.", + 'Could not find the specific part to update in the database.', ); } await this.checkAndTransitionStatusAfterFactorUploadV2(claimRequestId); return { - message: "Factor uploaded successfully. Awaiting expert validation.", + message: 'Factor uploaded successfully. Awaiting expert validation.', factorId: factorRecord._id, url: buildFileLink(file.path), }; @@ -1573,7 +1573,7 @@ export class ClaimRequestManagementService { } throw new HttpException( - "An internal server error occurred during factor upload.", + 'An internal server error occurred during factor upload.', HttpStatus.INTERNAL_SERVER_ERROR, ); } @@ -1620,12 +1620,12 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.EXPERT_VALIDATING_REPAIR_FACTORS, claimStatus: ClaimStatus.UNDER_REVIEW, - "workflow.currentStep": ClaimWorkflowStep.EXPERT_COST_EVALUATION, - "workflow.nextStep": ClaimWorkflowStep.INSURER_REVIEW, + 'workflow.currentStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION, + 'workflow.nextStep': ClaimWorkflowStep.INSURER_REVIEW, }, $push: { history: { - type: "ALL_FACTORS_UPLOADED_PENDING_VALIDATION", + type: 'ALL_FACTORS_UPLOADED_PENDING_VALIDATION', timestamp: new Date(), metadata: { claimRequestId }, }, @@ -1634,16 +1634,16 @@ export class ClaimRequestManagementService { } private async resendCarParts(claimFile, query, file) { - if (!Object.keys(query).includes("partId")) { + if (!Object.keys(query).includes('partId')) { throw new HttpException( - "use resendCarParts query string", + 'use resendCarParts query string', HttpStatus.BAD_REQUEST, ); } - if (!Object.keys(query).includes("side")) { + if (!Object.keys(query).includes('side')) { throw new HttpException( - "side is required for car parts", + 'side is required for car parts', HttpStatus.BAD_REQUEST, ); } @@ -1652,7 +1652,7 @@ export class ClaimRequestManagementService { (r) => r.partId, ); if (!fileRequired.includes(query.partId)) { - throw new HttpException("wrong required file", HttpStatus.BAD_REQUEST); + throw new HttpException('wrong required file', HttpStatus.BAD_REQUEST); } try { @@ -1665,7 +1665,7 @@ export class ClaimRequestManagementService { const updated = await this.claimRequestManagementDbService.findAndUpdate( String(claimFile._id), - { $push: { "userResendDocuments.carParts": fileEntry } }, + { $push: { 'userResendDocuments.carParts': fileEntry } }, { new: true }, ); @@ -1706,33 +1706,33 @@ export class ClaimRequestManagementService { */ 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", + 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", + '۰': '0', + '۱': '1', + '۲': '2', + '۳': '3', + '۴': '4', + '۵': '5', + '۶': '6', + '۷': '7', + '۸': '8', + '۹': '9', }; return persianDate - .split("/") + .split('/') .map((part) => part - .split("") + .split('') .map((char) => persianToEnglish[char] || char) - .join(""), + .join(''), ) - .join("/"); + .join('/'); } /** @@ -1740,8 +1740,8 @@ export class ClaimRequestManagementService { */ 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"); + const hours = d.getHours().toString().padStart(2, '0'); + const minutes = d.getMinutes().toString().padStart(2, '0'); return `${hours}:${minutes}`; } @@ -1770,12 +1770,12 @@ export class ClaimRequestManagementService { */ private extractNonEmptyLicenceDigits(value: unknown): string | null { if (value === null || value === undefined) return null; - const asString = typeof value === "number" ? String(value) : String(value); + 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, ""); + if (lowered === 'null' || lowered === 'undefined') return null; + const digits = trimmed.replace(/[^\d]/g, ''); return digits ? digits : null; } @@ -1826,7 +1826,7 @@ export class ClaimRequestManagementService { result.CulpritLicenceCityId = null; result.CulpritLicenceCountryId = null; result.CulpritLicenceForeignCityName = null; - result.CulpritLicenceIssuDate = "1394/10/13"; + result.CulpritLicenceIssuDate = '1394/10/13'; // Must never be empty/null. result.CulpritLicenceNo = FANAVARAN_DUMMY_LICENCE_NO; result.DamagedCount = 1; @@ -1849,11 +1849,11 @@ export class ClaimRequestManagementService { result.PlaqueSampleId = null; result.PlaqueSerial = null; result.PoliceOfficerId = 1; - result.PoliceReportDesc = "شرح گزارش"; + result.PoliceReportDesc = 'شرح گزارش'; result.PoliceReportSeri = null; result.PoliceReportSerial = null; result.PolicyId = null; - result.PreviousPolicyEndDate = ""; + result.PreviousPolicyEndDate = ''; result.StatusChangeDate = null; result.TrackingCode = null; result.IsLicenseReplacement = 0; @@ -1926,8 +1926,8 @@ export class ClaimRequestManagementService { private formatFanavaranSelectedPartsDesc(selectedParts: unknown[]): string { const labels = selectedParts .map((part) => { - if (typeof part === "string") return part; - if (part && typeof part === "object") { + if (typeof part === 'string') return part; + if (part && typeof part === 'object') { const p = part as { label_fa?: unknown; titleFa?: unknown; @@ -1939,11 +1939,11 @@ export class ClaimRequestManagementService { return null; }) .filter( - (label): label is string => typeof label === "string" && !!label.trim(), + (label): label is string => typeof label === 'string' && !!label.trim(), ) .map((label) => label.trim()); - return labels.length ? labels.join("/") : "موارد آسیب دیده خودرو"; + return labels.length ? labels.join('/') : 'موارد آسیب دیده خودرو'; } private getFanavaranPlateMiddleCode( @@ -1997,12 +1997,12 @@ export class ClaimRequestManagementService { 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 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", + 'plksrl', + 'PlkSrl', ]); if (!left || !middle || !right || !serial) return null; const leftDigits = Number(left); @@ -2033,7 +2033,7 @@ export class ClaimRequestManagementService { try { const lookup = this.fanavaranLookupService; const definition = FANAVARAN_REMOTE_LOOKUPS.find( - (l) => l.name === "vehicle-kinds", + (l) => l.name === 'vehicle-kinds', ); if (!definition) return null; @@ -2069,8 +2069,8 @@ export class ClaimRequestManagementService { if (vehicleKindId == null) return preferredId; try { const [kinds, useTypes] = await Promise.all([ - this.getFanavaranLookupRows(clientKey, "vehicle-kinds"), - this.getFanavaranLookupRows(clientKey, "vehicle-use-types"), + this.getFanavaranLookupRows(clientKey, 'vehicle-kinds'), + this.getFanavaranLookupRows(clientKey, 'vehicle-use-types'), ]); const groupId = vehicleGroupIdForKind(kinds, vehicleKindId); const usedId = selectAccidentVehicleUsedId( @@ -2079,7 +2079,7 @@ export class ClaimRequestManagementService { preferredId, ); this.logger.log( - `Resolved AccidentVehicleUsedId=${usedId} from VehicleKindId=${vehicleKindId} VehicleGroupId=${groupId ?? "none"} (UsedId=${preferredId ?? "none"})`, + `Resolved AccidentVehicleUsedId=${usedId} from VehicleKindId=${vehicleKindId} VehicleGroupId=${groupId ?? 'none'} (UsedId=${preferredId ?? 'none'})`, ); return usedId; } catch (error) { @@ -2126,7 +2126,7 @@ export class ClaimRequestManagementService { 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"}`, + `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, @@ -2163,7 +2163,7 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, vins: string[], identity: FanavaranDamagedVehicleIdentity, - product: FanavaranClaimProduct = "third-party", + product: FanavaranClaimProduct = 'third-party', ): Promise | null> { const requestOptions = { contractIdOverride: resolveFanavaranProductContractId(clientKey, product), @@ -2192,7 +2192,7 @@ export class ClaimRequestManagementService { } 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"}`, + `[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; @@ -2224,7 +2224,7 @@ export class ClaimRequestManagementService { fanavaranVehicleMatchesDamagedIdentity(fetched, identity) ) { this.logger.log( - `[buildFanavaranDamageCasePayload] vehicle GET ${vehicleId} confirmed identity PlaqueKindId=${pickFanavaranPlaqueLookupFields(fetched).kindId ?? "none"} VehicleKindId=${parseFanavaranId(fetched.VehicleKindId) ?? "none"}`, + `[buildFanavaranDamageCasePayload] vehicle GET ${vehicleId} confirmed identity PlaqueKindId=${pickFanavaranPlaqueLookupFields(fetched).kindId ?? 'none'} VehicleKindId=${parseFanavaranId(fetched.VehicleKindId) ?? 'none'}`, ); return fetched; } @@ -2249,7 +2249,7 @@ export class ClaimRequestManagementService { private async resolveAccidentVehicleUsedFromPolicy( clientKey: FanavaranClientKey, policyId: number, - product: FanavaranClaimProduct = "third-party", + product: FanavaranClaimProduct = 'third-party', ): Promise<{ usedId: number | null; vehicleKindId: number | null }> { try { const requestOptions = { @@ -2259,7 +2259,7 @@ export class ClaimRequestManagementService { ), }; const policy = asObjectRecord( - product === "car-body" + product === 'car-body' ? await this.fanavaranLookupService.bodyPolicyById( clientKey, policyId, @@ -2287,9 +2287,9 @@ export class ClaimRequestManagementService { ), ); this.logger.log( - `Policy ${policyId} VehicleId=${vehicleId} version=${versionNo ?? "latest"} VehicleKindId=${parseFanavaranId(vehicle?.VehicleKindId) ?? "none"} UsedId=${parseFanavaranId(vehicle?.UsedId) ?? "none"}`, + `Policy ${policyId} VehicleId=${vehicleId} version=${versionNo ?? 'latest'} VehicleKindId=${parseFanavaranId(vehicle?.VehicleKindId) ?? 'none'} UsedId=${parseFanavaranId(vehicle?.UsedId) ?? 'none'}`, ); - if (product === "car-body") { + 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 { @@ -2320,26 +2320,26 @@ export class ClaimRequestManagementService { }): Promise<{ usedId: number | null; vehicleKindId: number | null; - source: "vin-inquiry" | "policy-vehicle" | null; + source: 'vin-inquiry' | 'policy-vehicle' | null; }> { - if (input.product === "car-body") { - if (typeof input.policyId !== "number") { + 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", + 'car-body', ); return { ...resolved, - source: resolved.usedId == null ? null : "policy-vehicle", + source: resolved.usedId == null ? null : 'policy-vehicle', }; } const guiltyParty = (input.parties ?? []).find( (party: any) => - String(party?.person?.userId ?? "") === - String(input.guiltyPartyId ?? ""), + String(party?.person?.userId ?? '') === + String(input.guiltyPartyId ?? ''), ); const vin = pickVinFromPartyVehicle(guiltyParty); @@ -2349,18 +2349,18 @@ export class ClaimRequestManagementService { vin, ); if (fromVin.usedId != null) { - return { ...fromVin, source: "vin-inquiry" }; + return { ...fromVin, source: 'vin-inquiry' }; } } - if (typeof input.policyId === "number") { + if (typeof input.policyId === 'number') { const fromPolicy = await this.resolveAccidentVehicleUsedFromPolicy( input.clientKey, input.policyId, - input.product ?? "third-party", + input.product ?? 'third-party', ); if (fromPolicy.usedId != null) { - return { ...fromPolicy, source: "policy-vehicle" }; + return { ...fromPolicy, source: 'policy-vehicle' }; } } @@ -2377,8 +2377,8 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, ): Promise<{ types: number[]; relations: number[] }> { const [types, relations] = await Promise.all([ - this.getFanavaranLookupRows(clientKey, "notifier-type"), - this.getFanavaranLookupRows(clientKey, "notifier-relation"), + this.getFanavaranLookupRows(clientKey, 'notifier-type'), + this.getFanavaranLookupRows(clientKey, 'notifier-relation'), ]); const ids = (rows: unknown[]) => rows @@ -2406,7 +2406,7 @@ export class ClaimRequestManagementService { ); const guilty = parties.find( (party) => - String(party?.person?.userId ?? "") === String(guiltyPartyId ?? ""), + String(party?.person?.userId ?? '') === String(guiltyPartyId ?? ''), ); const person = guilty?.person; const nationalCode = @@ -2475,7 +2475,7 @@ export class ClaimRequestManagementService { 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}`, + `[resolveDriverFanavaranId] MATCH: Id=${driverId} RoleId=${match?.RoleId ?? 'none'} name=${match?.Name ?? ''} ${match?.LastName ?? ''} for nationalCode=${nationalCode}`, ); return driverId; } @@ -2487,7 +2487,7 @@ export class ClaimRequestManagementService { (e) => `{Id=${e.Id}, RoleId=${e.RoleId}, Name=${e.Name} ${e.LastName}}`, ) - .join("; ")} — submit will register GEN.44 other-people`, + .join('; ')} — submit will register GEN.44 other-people`, ); return null; } catch (error) { @@ -2526,7 +2526,7 @@ export class ClaimRequestManagementService { `[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`, + .join('; ')} — submit will register GEN.44 other-people`, ); return null; } catch (error) { @@ -2561,7 +2561,7 @@ export class ClaimRequestManagementService { { contractIdOverride: resolveFanavaranProductContractId( input.clientKey, - "car-body", + 'car-body', ), }, ), @@ -2582,7 +2582,7 @@ export class ClaimRequestManagementService { const vehicleValue = vehicleCurrentValueFromHullPolicyRecord(policyRecord); if (vehicleValue != null && input.claimCaseId) { await this.claimCaseDbService.findByIdAndUpdate(input.claimCaseId, { - $set: { "vehicle.carPrice": vehicleValue }, + $set: { 'vehicle.carPrice': vehicleValue }, }); } @@ -2640,7 +2640,7 @@ export class ClaimRequestManagementService { try { const authorityRows = await this.getFanavaranLookupRows( input.clientKey, - "detection-accident-culprits", + 'detection-accident-culprits', ); input.payload.AuthorityCulpritId = authorityCulpritIdFromDetectionRows(authorityRows); @@ -2677,7 +2677,7 @@ export class ClaimRequestManagementService { await this.fanavaranLookupService.bodyPolicyById(clientKey, policyId, { contractIdOverride: resolveFanavaranProductContractId( clientKey, - "car-body", + 'car-body', ), }), ); @@ -2724,15 +2724,15 @@ export class ClaimRequestManagementService { const contractOptions = { contractIdOverride: resolveFanavaranProductContractId( input.clientKey, - "car-body", + 'car-body', ), }; const [dmgKindRows, dmgCostKindRows, policyRecord] = await Promise.all([ - this.getFanavaranLookupRows(input.clientKey, "vehicle-hull-dmg-kind"), + this.getFanavaranLookupRows(input.clientKey, 'vehicle-hull-dmg-kind'), this.getFanavaranLookupRows( input.clientKey, - "vehicle-hull-dmg-cost-kinds", + 'vehicle-hull-dmg-cost-kinds', ), policyId != null ? this.fanavaranLookupService.bodyPolicyById( @@ -2882,59 +2882,59 @@ export class ClaimRequestManagementService { 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"}, ` + + `[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"}`, + `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"}`, + `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", + 'PrntCmpDocNo', + 'PrntPlcyCmpDocNo', + 'printNumber', + 'insuranceNumber', ]) ?? insurance.policyNumber ?? null; const policyCINumber = this.pickPartyInquiryField( inquiryMapped, inquiryRaw, - ["PlcyUnqCod", "ThirdPolicyCode"], + ['PlcyUnqCod', 'ThirdPolicyCode'], ); const beginDate = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "HBgnDte", - "StartDate", - "persianStartDate", - "SatrtDate", + 'HBgnDte', + 'StartDate', + 'persianStartDate', + 'SatrtDate', ]) ?? insurance.startDate ?? null; const endDate = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "HEndDte", - "EndDate", - "persianEndDate", + 'HEndDte', + 'EndDate', + 'persianEndDate', ]) ?? insurance.endDate ?? null; const builtYearRaw = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "PrdDte", - "ModelField", - "ModelCii", + 'PrdDte', + 'ModelField', + 'ModelCii', ]); const builtYearFromInquiry = builtYearRaw ? Number(builtYearRaw) || null @@ -2942,16 +2942,16 @@ export class ClaimRequestManagementService { const damagedVin = this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "VIN", - "vin", - "VinNumberField", + 'VIN', + 'vin', + 'VinNumberField', ]) ?? collectPartyVinCandidates(damagedParty)[0] ?? null; const damagedChassis = this.pickPartyInquiryField( inquiryMapped, inquiryRaw, - ["ShsNum", "ChassisNumberField", "shsNam"], + ['ShsNum', 'ChassisNumberField', 'shsNam'], ); const damagedIdentity: FanavaranDamagedVehicleIdentity = { vin: damagedVin, @@ -2983,7 +2983,7 @@ export class ClaimRequestManagementService { (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"}`, + `[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, @@ -2997,7 +2997,7 @@ export class ClaimRequestManagementService { const plaqueSampleId = plaqueLookup.sampleId; const plaqueKindSource = plaqueLookup.source; const plaqueSampleSource = plaqueLookup.source; - if (plaqueLookup.source !== "vehicle-inquiry") { + if (plaqueLookup.source !== 'vehicle-inquiry') { this.logger.log( `[buildFanavaranDamageCasePayload] PlaqueKindId not on a matched Fanavaran vehicle; using national-plate default ${plaqueKindId}/${plaqueSampleId}`, ); @@ -3013,18 +3013,18 @@ export class ClaimRequestManagementService { approvedVehicleKindId ?? this.firstPositiveFanavaranId(apiVehicle?.VehicleKindId); let vehicleKindSource: - | "expert-review" - | "vehicle-inquiry" - | "car-type-lookup" + | 'expert-review' + | 'vehicle-inquiry' + | 'car-type-lookup' | null = approvedVehicleKindId != null - ? "expert-review" + ? 'expert-review' : parseFanavaranId(apiVehicle?.VehicleKindId) != null - ? "vehicle-inquiry" + ? 'vehicle-inquiry' : null; if (vehicleKindId == null) { vehicleKindId = await this.resolveVehicleKindId(input.clientKey, carType); - if (vehicleKindId != null) vehicleKindSource = "car-type-lookup"; + if (vehicleKindId != null) vehicleKindSource = 'car-type-lookup'; } let driverFanavaranId: number | null = null; @@ -3127,8 +3127,8 @@ export class ClaimRequestManagementService { const partyIndex = (input.blameCase.parties ?? []).findIndex( (p: any) => p === damagedParty || - String(p?.person?.userId ?? "") === - String(damagedParty?.person?.userId ?? ""), + String(p?.person?.userId ?? '') === + String(damagedParty?.person?.userId ?? ''), ); if (partyIndex >= 0) { await this.blameRequestDbService.findByIdAndUpdate( @@ -3154,11 +3154,11 @@ export class ClaimRequestManagementService { ); let accidentVehicleUsedId: number | null = approvedVehicleUseTypeId; let usedSource: - | "expert-review" - | "vin-inquiry" - | "policy-vehicle" - | "vehicle-inquiry" - | null = approvedVehicleUseTypeId != null ? "expert-review" : null; + | 'expert-review' + | 'vin-inquiry' + | 'policy-vehicle' + | 'vehicle-inquiry' + | null = approvedVehicleUseTypeId != null ? 'expert-review' : null; if (accidentVehicleUsedId == null && apiVehicle) { const fromDamagedVehicle = await this.resolveAccidentVehicleUsedFromVehicleRecord( @@ -3166,7 +3166,7 @@ export class ClaimRequestManagementService { apiVehicle, ); accidentVehicleUsedId = fromDamagedVehicle.usedId; - if (accidentVehicleUsedId != null) usedSource = "vehicle-inquiry"; + if (accidentVehicleUsedId != null) usedSource = 'vehicle-inquiry'; } if (accidentVehicleUsedId == null) { accidentVehicleUsedId = @@ -3176,7 +3176,7 @@ export class ClaimRequestManagementService { parseFanavaranId(apiVehicle?.UsedId), ); if (accidentVehicleUsedId != null && usedSource == null) { - usedSource = apiVehicle ? "vehicle-inquiry" : null; + usedSource = apiVehicle ? 'vehicle-inquiry' : null; } } if (accidentVehicleUsedId == null) { @@ -3187,8 +3187,8 @@ export class ClaimRequestManagementService { } this.logger.log( - `[buildFanavaranDamageCasePayload] Final DriverId=${driverFanavaranId ?? "NULL"} OwnerId=${ownerFanavaranId ?? "NULL"} for driverNationalCode=${driverIdentity.nationalCode ?? "MISSING"}, ` + - `PolicyNo=${policyNo ?? "NULL"}, PolicyCINumber=${policyCINumber ?? "NULL"}`, + `[buildFanavaranDamageCasePayload] Final DriverId=${driverFanavaranId ?? 'NULL'} OwnerId=${ownerFanavaranId ?? 'NULL'} for driverNationalCode=${driverIdentity.nationalCode ?? 'MISSING'}, ` + + `PolicyNo=${policyNo ?? 'NULL'}, PolicyCINumber=${policyCINumber ?? 'NULL'}`, ); const payload = { @@ -3196,11 +3196,11 @@ export class ClaimRequestManagementService { BuiltYear: builtYear, ChassisNo: this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "ShsNum", - "ChassisNumberField", - "shsNam", + 'ShsNum', + 'ChassisNumberField', + 'shsNam', ]) ?? - (typeof apiVehicle?.ChassisNo === "string" + (typeof apiVehicle?.ChassisNo === 'string' ? apiVehicle.ChassisNo : null), DmgHistoryStatus: @@ -3228,11 +3228,11 @@ export class ClaimRequestManagementService { LicenceTypeId: input.defaults.CulpritLicenceTypeId, MotorNo: this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "MtrNum", - "EngineNumberField", - "mtrnum", + 'MtrNum', + 'EngineNumberField', + 'mtrnum', ]) ?? - (typeof apiVehicle?.MotorNo === "string" ? apiVehicle.MotorNo : null), + (typeof apiVehicle?.MotorNo === 'string' ? apiVehicle.MotorNo : null), OwnerId: ownerFanavaranId, PlaqueCityId: apiPlaque.cityId, PlaqueKindId: plaqueKindId, @@ -3243,21 +3243,21 @@ export class ClaimRequestManagementService { this.getFanavaranPlateMiddleCode(plate?.centerAlphabet), PlaqueNo: apiPlaque.plaqueNo ?? - this.pickPartyInquiryField(inquiryMapped, inquiryRaw, ["Plk"]) ?? + 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 ?? "", + PreviousPolicyEndDate: endDate ?? '', VehicleKindId: vehicleKindId, VIN: this.pickPartyInquiryField(inquiryMapped, inquiryRaw, [ - "VIN", - "vin", - "VinNumberField", - ]) ?? (typeof apiVehicle?.VIN === "string" ? apiVehicle.VIN : null), + 'VIN', + 'vin', + 'VinNumberField', + ]) ?? (typeof apiVehicle?.VIN === 'string' ? apiVehicle.VIN : null), AccidentVehicleUsedId: accidentVehicleUsedId, PolicyCINumber: policyCINumber, }; @@ -3270,39 +3270,39 @@ export class ClaimRequestManagementService { String(input.claimCase._id), { $set: { - "fanavaranSync.damageCase.lastPayload": persistedPayload, - "fanavaranSync.damageCase.lastPayloadBuiltAt": new Date(), + 'fanavaranSync.damageCase.lastPayload': persistedPayload, + 'fanavaranSync.damageCase.lastPayloadBuiltAt': new Date(), ...(driverFanavaranId != null - ? { "fanavaranSync.damageCase.driverId": driverFanavaranId } + ? { 'fanavaranSync.damageCase.driverId': driverFanavaranId } : {}), ...(otherPersonId != null - ? { "fanavaranSync.damageCase.otherPersonId": otherPersonId } + ? { 'fanavaranSync.damageCase.otherPersonId': otherPersonId } : {}), ...(vehicleKindId != null ? { - "fanavaranSync.damageCase.vehicleKindId": vehicleKindId, - "fanavaranSync.damageCase.vehicleKindSource": - vehicleKindSource ?? "car-type-lookup", + '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, + 'fanavaranSync.damageCase.plaqueKindId': plaqueKindId, + 'fanavaranSync.damageCase.plaqueKindSource': plaqueKindSource, + 'fanavaranSync.damageCase.plaqueSampleId': plaqueSampleId, + 'fanavaranSync.damageCase.plaqueSampleSource': plaqueSampleSource, ...(accidentVehicleUsedId != null ? { - "fanavaranSync.damageCase.accidentVehicleUsedId": + 'fanavaranSync.damageCase.accidentVehicleUsedId': accidentVehicleUsedId, ...(usedSource ? { - "fanavaranSync.damageCase.accidentVehicleUsedSource": + 'fanavaranSync.damageCase.accidentVehicleUsedSource': usedSource, } : {}), } : {}), ...(insuranceCorpId != null - ? { "fanavaranSync.damageCase.insuranceCorpId": insuranceCorpId } + ? { 'fanavaranSync.damageCase.insuranceCorpId': insuranceCorpId } : {}), }, }, @@ -3316,7 +3316,7 @@ export class ClaimRequestManagementService { appName: string; }): FanavaranClientKey { if (config.appName === this.PARSIAN_FANAVARAN_CONFIG.appName) { - return "parsian"; + return 'parsian'; } return resolveFanavaranClientKey(); } @@ -3328,9 +3328,9 @@ export class ClaimRequestManagementService { if (blameCase?.type) { return fanavaranClaimProductFromBlameType(blameCase.type); } - if (!claimCaseId) return "third-party"; + if (!claimCaseId) return 'third-party'; const claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase?.blameRequestId) return "third-party"; + if (!claimCase?.blameRequestId) return 'third-party'; const blame = await this.blameRequestDbService.findById( String(claimCase.blameRequestId), ); @@ -3423,10 +3423,10 @@ export class ClaimRequestManagementService { private staffFanavaranCodesFromDoc( doc: unknown, ): (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) | null { - if (!doc || typeof doc !== "object") return null; + if (!doc || typeof doc !== 'object') return null; const plain = typeof (doc as { toObject?: () => Record }).toObject === - "function" + 'function' ? (doc as { toObject: () => Record }).toObject() : (doc as Record); return { @@ -3452,8 +3452,7 @@ export class ClaimRequestManagementService { private async findStaffDocumentById( staffId: string, ): Promise< - | (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) - | null + (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) | null > { const loaders = [ () => this.expertDbService.findById(staffId), @@ -3494,15 +3493,15 @@ export class ClaimRequestManagementService { }> { const fieldName = blame?.type === BlameRequestType.CAR_BODY - ? "CarBodyClaimExpertId" - : "ThirdPartyClaimExpertId"; + ? 'CarBodyClaimExpertId' + : 'ThirdPartyClaimExpertId'; if (blame?.type == null) { return { claimExpertId: null, - code: "FANAVARAN_CLAIM_EXPERT_ID_MISSING", + code: 'FANAVARAN_CLAIM_EXPERT_ID_MISSING', message: - "ClaimExpertId unresolved: blame.type is missing, so the product line expert code cannot be chosen.", + 'ClaimExpertId unresolved: blame.type is missing, so the product line expert code cannot be chosen.', candidatesTried: [], }; } @@ -3513,7 +3512,7 @@ export class ClaimRequestManagementService { if (!fileMaker) { return { claimExpertId: null, - code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING", + code: 'FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING', message: `ClaimExpertId unresolved: FileMaker ${fileMakerId} was not found.`, candidatesTried: [fileMakerId], }; @@ -3522,7 +3521,7 @@ export class ClaimRequestManagementService { if (id == null) { return { claimExpertId: null, - code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING", + code: 'FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING', message: `ClaimExpertId unresolved: FileMaker ${fileMakerId} has empty ${fieldName}.`, candidatesTried: [fileMakerId], }; @@ -3547,7 +3546,7 @@ export class ClaimRequestManagementService { this.fanavaranDamageReplyActorId(claimCase), claimCase?.workflow?.assignedForReviewBy?.actorId, ] - .filter((value) => value != null && String(value).trim() !== "") + .filter((value) => value != null && String(value).trim() !== '') .map((value) => String(value)), ), ]; @@ -3556,7 +3555,9 @@ export class ClaimRequestManagementService { 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)`); + missingOnStaff.push( + `${staffId} (staff not found in expert/damage/field/fileMaker/fileReviewer)`, + ); continue; } const rawValue = (staff as Record)[fieldName]; @@ -3570,17 +3571,17 @@ export class ClaimRequestManagementService { }; } missingOnStaff.push( - `${staffId} (${fieldName}=${rawValue == null || rawValue === "" ? "empty" : JSON.stringify(rawValue)})`, + `${staffId} (${fieldName}=${rawValue == null || rawValue === '' ? 'empty' : JSON.stringify(rawValue)})`, ); } return { claimExpertId: null, - code: "FANAVARAN_CLAIM_EXPERT_ID_MISSING", + 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.`, + : `ClaimExpertId unresolved: checked assigned staff [${missingOnStaff.join('; ')}]. Your ${fieldName} must be on THAT assigned staff document, not a different user.`, candidatesTried: candidateIds, }; } @@ -3610,10 +3611,10 @@ export class ClaimRequestManagementService { if (resolved.claimExpertId != null) return resolved.claimExpertId; if (options?.required === false) return null; throw new BadRequestException({ - code: resolved.code ?? "FANAVARAN_CLAIM_EXPERT_ID_MISSING", + code: resolved.code ?? 'FANAVARAN_CLAIM_EXPERT_ID_MISSING', message: resolved.message ?? - "ClaimExpertId unresolved on the assigned expert profile.", + 'ClaimExpertId unresolved on the assigned expert profile.', }); } @@ -3652,15 +3653,14 @@ export class ClaimRequestManagementService { }> { const fieldName = blame?.type === BlameRequestType.CAR_BODY - ? "CarBodyExpertiseClaim" - : "ThirdPartyExpertiseClaim"; + ? 'CarBodyExpertiseClaim' + : 'ThirdPartyExpertiseClaim'; if (blame?.type == null) { return { claimExpertId: null, - code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", - message: - "Expertise ClaimExpertId unresolved: blame.type is missing.", + code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', + message: 'Expertise ClaimExpertId unresolved: blame.type is missing.', candidatesTried: [], }; } @@ -3669,9 +3669,9 @@ export class ClaimRequestManagementService { if (!blame.assignedFileReviewerId) { return { claimExpertId: null, - code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", + code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING', message: - "Expertise ClaimExpertId unresolved: no assignedFileReviewerId on this FileMaker file.", + 'Expertise ClaimExpertId unresolved: no assignedFileReviewerId on this FileMaker file.', candidatesTried: [], }; } @@ -3681,7 +3681,7 @@ export class ClaimRequestManagementService { if (!fileReviewer) { return { claimExpertId: null, - code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", + code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING', message: `Expertise ClaimExpertId unresolved: FileReviewer ${fileReviewerId} was not found.`, candidatesTried: [fileReviewerId], }; @@ -3690,7 +3690,7 @@ export class ClaimRequestManagementService { if (id == null) { return { claimExpertId: null, - code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", + code: 'FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING', message: `Expertise ClaimExpertId unresolved: FileReviewer ${fileReviewerId} has empty ${fieldName}.`, candidatesTried: [fileReviewerId], }; @@ -3704,12 +3704,12 @@ export class ClaimRequestManagementService { } const actorId = this.fanavaranDamageReplyActorId(claimCase); - if (actorId == null || String(actorId).trim() === "") { + if (actorId == null || String(actorId).trim() === '') { return { claimExpertId: null, - code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', message: - "Expertise ClaimExpertId unresolved: no damage-expert reply actorDetail.actorId on this claim.", + 'Expertise ClaimExpertId unresolved: no damage-expert reply actorDetail.actorId on this claim.', candidatesTried: [], }; } @@ -3719,7 +3719,7 @@ export class ClaimRequestManagementService { if (!staff) { return { claimExpertId: null, - code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', message: `Expertise ClaimExpertId unresolved: staff ${staffId} was not found.`, candidatesTried: [staffId], }; @@ -3728,7 +3728,7 @@ export class ClaimRequestManagementService { if (id == null) { return { claimExpertId: null, - code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', message: `Expertise ClaimExpertId unresolved: staff ${staffId} has empty ${fieldName}.`, candidatesTried: [staffId], }; @@ -3761,10 +3761,10 @@ export class ClaimRequestManagementService { 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", + code: resolved.code ?? 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', message: resolved.message ?? - "Expertise ClaimExpertId unresolved on the assigned assessor profile.", + 'Expertise ClaimExpertId unresolved on the assigned assessor profile.', }); } @@ -3784,9 +3784,8 @@ export class ClaimRequestManagementService { } | null> { if (blame?.type == null) return null; try { - const baseClaimExpertId = await this.resolveFanavaranBaseClaimExpertId( - blame, - ); + const baseClaimExpertId = + await this.resolveFanavaranBaseClaimExpertId(blame); let expertiseClaimExpertId: number | null = null; try { expertiseClaimExpertId = @@ -3846,7 +3845,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.POLICY_INQUIRY, status: FanavaranAuditStatus.STARTED, requestUrl: policyInquiryUrl, - requestMethod: "GET", + requestMethod: 'GET', requestMeta, }); } @@ -3860,7 +3859,7 @@ export class ClaimRequestManagementService { ); const requestHeaders = { ...headers, - "Content-Type": "application/json", + 'Content-Type': 'application/json', }; this.logger.log( @@ -3889,7 +3888,7 @@ export class ClaimRequestManagementService { if (options?.claimCaseId && selectedPolicy.policyId != null) { await this.claimCaseDbService.findByIdAndUpdate(options.claimCaseId, { $set: { - "fanavaranSync.baseClaim.policyId": selectedPolicy.policyId, + 'fanavaranSync.baseClaim.policyId': selectedPolicy.policyId, }, }); } @@ -3906,7 +3905,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.POLICY_INQUIRY, status: FanavaranAuditStatus.SUCCESS, requestUrl: policyInquiryUrl, - requestMethod: "GET", + requestMethod: 'GET', httpStatus: response.status, requestHeaders: exchange.requestHeaders, requestMeta, @@ -3926,7 +3925,7 @@ export class ClaimRequestManagementService { } catch (error) { this.fanavaranAuthService.registerFailure(clientKey, error); const errorMessage = - error instanceof Error ? error.message : "unknown policy inquiry error"; + error instanceof Error ? error.message : 'unknown policy inquiry error'; if (auditSession) { const exchange = this.fanavaranAuditService.captureAxiosExchange(error); await this.fanavaranAuditService.recordStep({ @@ -3934,7 +3933,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.POLICY_INQUIRY, status: FanavaranAuditStatus.FAILURE, requestUrl: policyInquiryUrl, - requestMethod: "GET", + requestMethod: 'GET', httpStatus: exchange.httpStatus, requestHeaders: exchange.requestHeaders, requestMeta, @@ -4038,7 +4037,7 @@ export class ClaimRequestManagementService { } this.logger.log( - `[resolveDriverFanavaranIdFromBlameCase] leftover codes=${leftoverCodes.join(",") || "none"} birthdays=${leftoverBirthdays.join(",") || "none"}`, + `[resolveDriverFanavaranIdFromBlameCase] leftover codes=${leftoverCodes.join(',') || 'none'} birthdays=${leftoverBirthdays.join(',') || 'none'}`, ); for (const nationalCode of leftoverCodes) { @@ -4067,12 +4066,12 @@ export class ClaimRequestManagementService { }> { 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"), + 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 }; } @@ -4142,8 +4141,8 @@ export class ClaimRequestManagementService { const seedRow = parties.find( (row) => - (typeof row.Name === "string" && row.Name.trim()) || - (typeof row.LastName === "string" && row.LastName.trim()), + (typeof row.Name === 'string' && row.Name.trim()) || + (typeof row.LastName === 'string' && row.LastName.trim()), ) ?? parties[0]; if (seedRow) { const roleId = Number(seedRow.RoleId); @@ -4151,11 +4150,11 @@ export class ClaimRequestManagementService { `[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, + name: typeof seedRow.Name === 'string' ? seedRow.Name : undefined, lastName: - typeof seedRow.LastName === "string" ? seedRow.LastName : undefined, + typeof seedRow.LastName === 'string' ? seedRow.LastName : undefined, fatherName: - typeof seedRow.FatherName === "string" + typeof seedRow.FatherName === 'string' ? seedRow.FatherName : undefined, genderId: (() => { @@ -4163,7 +4162,7 @@ export class ClaimRequestManagementService { return Number.isFinite(g) && g > 0 ? g : undefined; })(), identityNo: - typeof seedRow.IdentityNo === "string" + typeof seedRow.IdentityNo === 'string' ? seedRow.IdentityNo : undefined, }; @@ -4215,7 +4214,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.CREATE_OTHER_PERSON, status: FanavaranAuditStatus.STARTED, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', requestBody: payload, requestMeta: { nationalCode }, }); @@ -4231,7 +4230,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.CREATE_OTHER_PERSON, status: FanavaranAuditStatus.SUCCESS, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', requestBody: payload, responseBody: created, responseMeta: { otherPersonId: personId, nationalCode }, @@ -4253,7 +4252,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.CREATE_OTHER_PERSON, status: FanavaranAuditStatus.FAILURE, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', requestBody: payload, errorMessage: message, durationMs: Date.now() - startedAt, @@ -4286,7 +4285,7 @@ export class ClaimRequestManagementService { if ( blameCase?.type === BlameRequestType.CAR_BODY || - blameCase?.type === "CAR_BODY" + blameCase?.type === 'CAR_BODY' ) { return resolveDamagedPartyRow(blameCase) ?? parties[0] ?? null; } @@ -4294,7 +4293,7 @@ export class ClaimRequestManagementService { const ownerId = claimCase?.owner?.userId; if (ownerId) { const byOwner = parties.find( - (party) => String(party?.person?.userId ?? "") === String(ownerId), + (party) => String(party?.person?.userId ?? '') === String(ownerId), ); if (byOwner) return byOwner; } @@ -4306,7 +4305,7 @@ export class ClaimRequestManagementService { if (guiltyPartyId) { const injured = parties.find( (party) => - String(party?.person?.userId ?? "") !== String(guiltyPartyId), + String(party?.person?.userId ?? '') !== String(guiltyPartyId), ); if (injured) return injured; } @@ -4336,7 +4335,7 @@ export class ClaimRequestManagementService { if (!guiltyParty) return null; return ( - resolvePolicyholderFromParty(guiltyParty, "third-party").nationalCode ?? + resolvePolicyholderFromParty(guiltyParty, 'third-party').nationalCode ?? guiltyParty.person?.nationalCodeOfInsurer ?? null ); @@ -4459,18 +4458,18 @@ export class ClaimRequestManagementService { 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.", + 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"); + 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.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(); @@ -4479,7 +4478,7 @@ export class ClaimRequestManagementService { claimCase.blameRequestId, ); if (!blameCase) { - throw new NotFoundException("Blame case not found"); + throw new NotFoundException('Blame case not found'); } debug.steps.blameCaseFound = true; @@ -4545,7 +4544,7 @@ export class ClaimRequestManagementService { return Number(cachedPolicyId); } - if (product === "car-body") { + if (product === 'car-body') { const storedPolicyId = pickStoredCarBodyPolicyId(blameCase); if (storedPolicyId != null) { debug.values.policyId = storedPolicyId; @@ -4562,7 +4561,7 @@ export class ClaimRequestManagementService { `${logPrefix} car-body policyholder national code is missing`, ); debug.failureReason = - "car-body policyholder national code is missing"; + 'car-body policyholder national code is missing'; return null; } @@ -4572,14 +4571,14 @@ export class ClaimRequestManagementService { profile.auth, logPrefix, auditSession, - { clientKey, claimCaseId, product: "car-body" }, + { clientKey, claimCaseId, product: 'car-body' }, ); 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)"; + 'car-body policy inquiry returned no PolicyId (timeout, network error, empty response, or backoff)'; } return policyId; } @@ -4607,7 +4606,7 @@ export class ClaimRequestManagementService { this.logger.warn( `${logPrefix} guiltyPartyId not found in expert.decision`, ); - debug.failureReason = "expert.decision.guiltyPartyId is missing"; + debug.failureReason = 'expert.decision.guiltyPartyId is missing'; return null; } @@ -4616,7 +4615,7 @@ export class ClaimRequestManagementService { `${logPrefix} nationalCodeOfInsurer not found for guiltyPartyId: ${guiltyPartyId}`, ); debug.failureReason = - "nationalCodeOfInsurer not found for guilty party in blameCase.parties"; + 'nationalCodeOfInsurer not found for guilty party in blameCase.parties'; return null; } @@ -4626,14 +4625,14 @@ export class ClaimRequestManagementService { profile.auth, logPrefix, auditSession, - { clientKey, claimCaseId, product: "third-party" }, + { 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)"; + 'policy inquiry returned no PolicyId (timeout, network error, empty response, or backoff)'; } return policyId; }, @@ -4653,8 +4652,8 @@ export class ClaimRequestManagementService { ); return (blameCase.parties ?? []).find( (party: any) => - String(party?.person?.userId ?? "") === - String(guiltyPartyId ?? ""), + String(party?.person?.userId ?? '') === + String(guiltyPartyId ?? ''), ); })(); const culpritDriver = resolveDriverFromParty(culpritParty as any); @@ -4676,7 +4675,7 @@ export class ClaimRequestManagementService { )?.statement?.accidentTime; if ( blameCase.type === BlameRequestType.CAR_BODY && - typeof carBodyAccidentTime === "string" && + typeof carBodyAccidentTime === 'string' && carBodyAccidentTime.trim() ) { payload.AccidentTime = carBodyAccidentTime.trim(); @@ -4695,14 +4694,14 @@ export class ClaimRequestManagementService { !forceRefreshPolicy && cachedUsedId != null && Number(cachedUsedId) > 0 && - (cachedUsedSource === "vin-inquiry" || - cachedUsedSource === "policy-vehicle"); + (cachedUsedSource === 'vin-inquiry' || + cachedUsedSource === 'policy-vehicle'); delete payload.AccidentVehicleUsedId; let usedSource: - | "expert-review" - | "vin-inquiry" - | "policy-vehicle" + | 'expert-review' + | 'vin-inquiry' + | 'policy-vehicle' | null = null; if (canReuseApiUsedId) { payload.AccidentVehicleUsedId = Number(cachedUsedId); @@ -4717,7 +4716,7 @@ export class ClaimRequestManagementService { parties: blameCase.parties ?? [], guiltyPartyId: guiltyPartyIdForVin, policyId: - typeof payload.PolicyId === "number" ? payload.PolicyId : null, + typeof payload.PolicyId === 'number' ? payload.PolicyId : null, product: fanavaranClaimProductFromBlameType(blameCase.type), }); if (resolved.usedId != null) { @@ -4729,23 +4728,28 @@ export class ClaimRequestManagementService { const approvedUseTypeId = Number( (claimCase as any)?.fanavaranVehicleReview?.vehicleUseType?.id, ); - if (!isHull && Number.isInteger(approvedUseTypeId) && approvedUseTypeId > 0) { + if ( + !isHull && + Number.isInteger(approvedUseTypeId) && + approvedUseTypeId > 0 + ) { payload.AccidentVehicleUsedId = approvedUseTypeId; - usedSource = "expert-review"; + 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", + 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; + payload.AccidentVehicleUsedId = + profile.defaults.AccidentVehicleUsedId; this.logger.log( `${logPrefix} AccidentVehicleUsedId API miss; using config default ${payload.AccidentVehicleUsedId}`, ); @@ -4756,7 +4760,7 @@ export class ClaimRequestManagementService { accidentVehicleUsedSource: usedSource, }); - if (fanavaranClaimProductFromBlameType(blameCase.type) === "car-body") { + if (fanavaranClaimProductFromBlameType(blameCase.type) === 'car-body') { await this.enrichCarBodyHullBaseClaimPayload({ clientKey, payload, @@ -4768,8 +4772,8 @@ export class ClaimRequestManagementService { applyFanavaranStageFieldReview( payload, claimCase, - "car-body", - "baseClaim", + 'car-body', + 'baseClaim', clientKey, ); delete payload.IsLicenseReplacement; @@ -4779,16 +4783,16 @@ export class ClaimRequestManagementService { } if ( - fanavaranClaimProductFromBlameType(blameCase.type) === "third-party" + fanavaranClaimProductFromBlameType(blameCase.type) === 'third-party' ) { applyFanavaranStageFieldReview( payload, claimCase, - "third-party", - "baseClaim", + 'third-party', + 'baseClaim', clientKey, ); - if (clientKey === "tejaratno") { + if (clientKey === 'tejaratno') { const notifierPartyId = await this.resolveTejaratNotifierPartyId({ clientKey, blameCase, @@ -4796,9 +4800,9 @@ export class ClaimRequestManagementService { }); if (requirePolicyId && notifierPartyId == null) { throw new ConflictException({ - code: "FANAVARAN_NOTIFIER_PARTY_REQUIRED", + code: 'FANAVARAN_NOTIFIER_PARTY_REQUIRED', message: - "اعلام‌کننده خسارت در فناوران پیدا نشد. کد ملی، تاریخ تولد و موبایل بیمه‌گذار مقصر برای ثبت شخص لازم است.", + 'اعلام‌کننده خسارت در فناوران پیدا نشد. کد ملی، تاریخ تولد و موبایل بیمه‌گذار مقصر برای ثبت شخص لازم است.', }); } const v15 = toTejaratV15ThirdPartyBasePayload( @@ -4815,18 +4819,17 @@ export class ClaimRequestManagementService { payload.ClaimExpertId = claimExpertResolution.claimExpertId; (debug as any).steps.claimExpertIdResolved = claimExpertResolution.claimExpertId != null; - (debug as any).values.claimExpertId = - claimExpertResolution.claimExpertId; + (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", + claimExpertResolution.code ?? 'FANAVARAN_CLAIM_EXPERT_ID_MISSING', message: claimExpertResolution.message ?? - "ClaimExpertId unresolved on the assigned expert profile.", - field: "ClaimExpertId", + 'ClaimExpertId unresolved on the assigned expert profile.', + field: 'ClaimExpertId', candidatesTried: claimExpertResolution.candidatesTried, }; previewWarnings.push(warning); @@ -4842,29 +4845,30 @@ export class ClaimRequestManagementService { if (persistPayload) { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.baseClaim.lastPayload": payload, - "fanavaranSync.baseClaim.lastPayloadBuiltAt": new Date(), + 'fanavaranSync.baseClaim.lastPayload': payload, + 'fanavaranSync.baseClaim.lastPayloadBuiltAt': new Date(), ...(payload.PolicyId != null - ? { "fanavaranSync.baseClaim.policyId": payload.PolicyId } + ? { 'fanavaranSync.baseClaim.policyId': payload.PolicyId } : {}), ...(isHull ? { - "fanavaranSync.baseClaim.accidentVehicleUsedId": + 'fanavaranSync.baseClaim.accidentVehicleUsedId': payload.AccidentVehicleUsedId, - "fanavaranSync.baseClaim.accidentVehicleUsedSource": usedSource, + 'fanavaranSync.baseClaim.accidentVehicleUsedSource': + usedSource, } - : typeof payload.AccidentVehicleUsedId === "number" - ? { - "fanavaranSync.baseClaim.accidentVehicleUsedId": - payload.AccidentVehicleUsedId, - ...(usedSource - ? { - "fanavaranSync.baseClaim.accidentVehicleUsedSource": - usedSource, - } - : {}), - } - : {}), + : typeof payload.AccidentVehicleUsedId === 'number' + ? { + 'fanavaranSync.baseClaim.accidentVehicleUsedId': + payload.AccidentVehicleUsedId, + ...(usedSource + ? { + 'fanavaranSync.baseClaim.accidentVehicleUsedSource': + usedSource, + } + : {}), + } + : {}), }, }); } @@ -4917,7 +4921,7 @@ export class ClaimRequestManagementService { error, ); throw toFanavaranHttpException(error, { - fallback: "Failed to submit data to Fanavaran API", + fallback: 'Failed to submit data to Fanavaran API', }); } } @@ -4929,20 +4933,20 @@ export class ClaimRequestManagementService { const profile = getFanavaranClientProfile(clientKey); const claimCase = await this.claimCaseDbService.findById(claimCaseId); if (!claimCase) { - throw new NotFoundException("Claim case not found"); + throw new NotFoundException('Claim case not found'); } if (!claimCase.blameRequestId) { - throw new BadRequestException("Blame case not linked to claim case"); + 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"); + 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", + 'Fanavaran damage-case submit only applies to THIRD_PARTY and CAR_BODY claims', ); } @@ -4971,11 +4975,11 @@ export class ClaimRequestManagementService { const warnings: string[] = []; if (!claimCase.claimId) { - warnings.push("Fanavaran base claimId is required before submit."); + 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).", + 'Damaged party has no Fanavaran RoleId 161/166 yet; submit will register them via other-people (GEN.44).', ); } @@ -4987,12 +4991,12 @@ export class ClaimRequestManagementService { submitUrl: claimCase.claimId ? fanavaranClaimStageUrl( product, - "damage-case", + 'damage-case', claimCase.claimId, clientKey, ) : null, - warning: warnings.length ? warnings.join(" ") : undefined, + warning: warnings.length ? warnings.join(' ') : undefined, payload, }; } @@ -5017,7 +5021,7 @@ export class ClaimRequestManagementService { error, ); throw toFanavaranHttpException(error, { - fallback: "Failed to submit data to Fanavaran API", + fallback: 'Failed to submit data to Fanavaran API', }); } } @@ -5031,7 +5035,7 @@ export class ClaimRequestManagementService { for (const file of files) { const fileName = (file as { fileName?: unknown })?.fileName; - if (typeof fileName === "string" && fileName.trim()) { + if (typeof fileName === 'string' && fileName.trim()) { submitted.set(fileName, (file as { fileId?: unknown })?.fileId); } } @@ -5046,13 +5050,13 @@ export class ClaimRequestManagementService { input: { path?: unknown; fileName?: unknown; source: string }, fileTypeId: number, ): void { - const path = typeof input.path === "string" ? input.path : ""; + const path = typeof input.path === 'string' ? input.path : ''; const fileName = - typeof input.fileName === "string" && input.fileName.trim() + typeof input.fileName === 'string' && input.fileName.trim() ? input.fileName : path ? basename(path) - : ""; + : ''; if (!path || !fileName || seen.has(fileName)) return; seen.add(fileName); @@ -5080,7 +5084,7 @@ export class ClaimRequestManagementService { const profile = getFanavaranClientProfile(clientKey); const claimCase = await this.claimCaseDbService.findById(claimCaseId); if (!claimCase) { - throw new NotFoundException("Claim case not found"); + throw new NotFoundException('Claim case not found'); } const candidates: FanavaranAttachmentCandidate[] = []; @@ -5099,7 +5103,7 @@ export class ClaimRequestManagementService { { path: (document as { path?: unknown }).path, fileName: (document as { fileName?: unknown }).fileName, - source: `document:${String((document as { documentType?: unknown }).documentType ?? "unknown")}`, + source: `document:${String((document as { documentType?: unknown }).documentType ?? 'unknown')}`, }, fileTypeId, ); @@ -5109,7 +5113,7 @@ export class ClaimRequestManagementService { const angleEntries = carAngles instanceof Map ? Array.from(carAngles.entries()) - : carAngles && typeof carAngles === "object" + : carAngles && typeof carAngles === 'object' ? Object.entries(carAngles) : []; for (const [angleKey, image] of angleEntries) { @@ -5130,7 +5134,7 @@ export class ClaimRequestManagementService { const damagedParts = claimCase.media?.damagedParts; const partEntries = Array.isArray(damagedParts) ? damagedParts.map((part, index) => [String(index), part] as const) - : damagedParts && typeof damagedParts === "object" + : damagedParts && typeof damagedParts === 'object' ? Object.entries(damagedParts) : []; for (const [partKey, image] of partEntries) { @@ -5170,7 +5174,7 @@ export class ClaimRequestManagementService { : null, warning: claimCase.claimId ? undefined - : "Fanavaran base claimId is required before attachment submit.", + : 'Fanavaran base claimId is required before attachment submit.', totalLocalImages: candidates.length, alreadySubmitted: candidates.filter( (candidate) => candidate.alreadySubmitted, @@ -5251,12 +5255,12 @@ export class ClaimRequestManagementService { submitted: 0, failed: 0, skipped: pending.length, - warning: "Fanavaran base claimId is missing", + warning: 'Fanavaran base claimId is missing', results: pending.map((c) => ({ attempted: false, submitted: false, skipped: true, - skipReason: "Fanavaran base claimId is missing", + skipReason: 'Fanavaran base claimId is missing', fileName: c.fileName, })), }; @@ -5278,12 +5282,12 @@ export class ClaimRequestManagementService { submitted: 0, failed: 0, skipped: pending.length, - warning: "Fanavaran base claimId is missing", + warning: 'Fanavaran base claimId is missing', results: pending.map((c) => ({ attempted: false, submitted: false, skipped: true, - skipReason: "Fanavaran base claimId is missing", + skipReason: 'Fanavaran base claimId is missing', fileName: c.fileName, })), }; @@ -5302,7 +5306,7 @@ export class ClaimRequestManagementService { const content = { FileName: candidate.fileName, FileTypeId: fileTypeId, - ...(product === "car-body" ? { ClaimId: nestedClaimId } : {}), + ...(product === 'car-body' ? { ClaimId: nestedClaimId } : {}), }; this.logger.log( @@ -5348,7 +5352,7 @@ export class ClaimRequestManagementService { // and has its own inner retry/back-off via scheduleFanavaranRetry. await this.scheduleFanavaranRetry( claimCaseId, - "attachments", + 'attachments', () => this.autoSubmitFanavaranAttachment( claimCaseId, @@ -5384,15 +5388,15 @@ export class ClaimRequestManagementService { const auditSource = options?.auditSource ?? FanavaranAuditSource.AUTO_SUBMIT; const logPrefix = `[Fanavaran ${clientKey} V2 Attachment Auto] claimCaseId=${claimCaseId}`; - const filePath = file.path ? String(file.path) : ""; + const filePath = file.path ? String(file.path) : ''; const fileName = file.fileName ? String(file.fileName) : filePath ? basename(filePath) - : ""; + : ''; const profile = getFanavaranClientProfile(clientKey); - let url = ""; + let url = ''; let content: Record = {}; try { @@ -5401,7 +5405,7 @@ export class ClaimRequestManagementService { attempted: false, submitted: false, skipped: true, - skipReason: "Attachment file path or filename is missing", + skipReason: 'Attachment file path or filename is missing', }; } if (!existsSync(filePath)) { @@ -5419,7 +5423,7 @@ export class ClaimRequestManagementService { return { attempted: false, submitted: false, - warning: "Claim case not found for Fanavaran attachment submit.", + warning: 'Claim case not found for Fanavaran attachment submit.', fileName, }; } @@ -5435,12 +5439,12 @@ export class ClaimRequestManagementService { if (!claimCase?.claimId) { const warning = - "Fanavaran base claim is missing, so attachment was not submitted."; + 'Fanavaran base claim is missing, so attachment was not submitted.'; await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.attachments.status": "skipped", - "fanavaranSync.attachments.lastTriedAt": new Date(), - "fanavaranSync.attachments.lastError": warning, + 'fanavaranSync.attachments.status': 'skipped', + 'fanavaranSync.attachments.lastTriedAt': new Date(), + 'fanavaranSync.attachments.lastError': warning, }, }); return { @@ -5461,7 +5465,7 @@ export class ClaimRequestManagementService { { FileName: fileName, FileTypeId: profile.defaults.ClaimFileTypeId }, ], ...((await this.resolveFanavaranClaimProduct(claimCaseId)) === - "car-body" + 'car-body' ? { ClaimId: claimCase.claimId } : {}), }; @@ -5479,7 +5483,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_ATTACHMENT, status: FanavaranAuditStatus.STARTED, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', requestBody: content, requestMeta: { claimId: claimCase.claimId, @@ -5511,7 +5515,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_ATTACHMENT, status: FanavaranAuditStatus.SUCCESS, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: response.status, requestBody: content, responseHeaders: exchange.responseHeaders, @@ -5522,13 +5526,13 @@ export class ClaimRequestManagementService { 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.status': 'success', + 'fanavaranSync.attachments.lastTriedAt': new Date(), + 'fanavaranSync.attachments.claimId': claimCase.claimId, + 'fanavaranSync.attachments.response': response.data, }, $push: { - "fanavaranSync.attachments.files": { + 'fanavaranSync.attachments.files': { fileId, fileName, source: file.source, @@ -5536,8 +5540,8 @@ export class ClaimRequestManagementService { submittedAt: new Date(), }, history: { - type: "FANAVARAN_ATTACHMENT_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, + type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_SUCCEEDED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, @@ -5565,14 +5569,14 @@ export class ClaimRequestManagementService { try { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.attachments.status": "failed", - "fanavaranSync.attachments.lastTriedAt": new Date(), - "fanavaranSync.attachments.lastError": warning, + 'fanavaranSync.attachments.status': 'failed', + 'fanavaranSync.attachments.lastTriedAt': new Date(), + 'fanavaranSync.attachments.lastError': warning, }, $push: { history: { - type: "FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, + type: 'FANAVARAN_ATTACHMENT_AUTO_SUBMIT_FAILED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, @@ -5595,7 +5599,7 @@ export class ClaimRequestManagementService { try { await this.scheduleFanavaranRetry( claimCaseId, - "attachments", + 'attachments', () => this.autoSubmitFanavaranAttachment(claimCaseId, file, options), logPrefix, { error, clientKey }, @@ -5630,7 +5634,7 @@ export class ClaimRequestManagementService { 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.", + 'Fanavaran field review only applies to third-party and car-body claims.', ); } const product = fanavaranClaimProductFromBlameType(blame.type); @@ -5659,12 +5663,12 @@ export class ClaimRequestManagementService { AccidentTypeId: 2, CulpritTypeId: 300, AuthorityCulpritId: authorityCulpritIdFromDetectionRows( - options.get("detection-accident-culprits") ?? [], + options.get('detection-accident-culprits') ?? [], ), CustomerFaultPercent: FANAVARAN_DEFAULT_HULL_CUSTOMER_FAULT_PERCENT, RepairDuration: FANAVARAN_DEFAULT_HULL_REPAIR_DURATION, }; - if (product === "car-body") { + if (product === 'car-body') { const price = this.parseFanavaranMoney(claim?.vehicle?.carPrice) || this.parseFanavaranMoney(claim?.vehicle?.price) || @@ -5695,10 +5699,10 @@ export class ClaimRequestManagementService { value, source: sentValue != null - ? "submitted" + ? 'submitted' : reviewedValue != null - ? "reviewed" - : "default", + ? 'reviewed' + : 'default', editable: !sent, ...(field.lookup ? { @@ -5720,12 +5724,12 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, name: string, ): Promise { - if (clientKey === "tejaratno" && isTejaratNotifierLookup(name)) { + if (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 < 3 && rows && !Array.isArray(rows) && typeof rows === 'object'; level++ ) { rows = (rows as { data?: unknown }).data; @@ -5742,7 +5746,7 @@ export class ClaimRequestManagementService { let rows: unknown = data; for ( let level = 0; - level < 3 && rows && !Array.isArray(rows) && typeof rows === "object"; + level < 3 && rows && !Array.isArray(rows) && typeof rows === 'object'; level++ ) { rows = (rows as { data?: unknown }).data; @@ -5757,12 +5761,12 @@ export class ClaimRequestManagementService { } private parseFanavaranMoney(value: unknown): number { - if (value == null || value === "") return 0; - if (typeof value === "number" && Number.isFinite(value)) return value; + 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, "") + .replace(/,/g, '') .trim(); const parsed = Number(normalized); return Number.isFinite(parsed) ? parsed : 0; @@ -5770,7 +5774,7 @@ export class ClaimRequestManagementService { private fanavaranPartLabel(part: any): string { const damage = part?.carPartDamage; - if (damage && typeof damage === "object") { + if (damage && typeof damage === 'object') { const d = damage as { label_fa?: unknown; part?: unknown; @@ -5778,14 +5782,14 @@ export class ClaimRequestManagementService { catalogKey?: unknown; }; return String( - d.label_fa ?? d.part ?? d.name ?? d.catalogKey ?? part?.partId ?? "", + d.label_fa ?? d.part ?? d.name ?? d.catalogKey ?? part?.partId ?? '', ); } - return String(damage ?? part?.partId ?? ""); + return String(damage ?? part?.partId ?? ''); } private fanavaranDaghiWasteValue(daghi: unknown): number { - if (!daghi || typeof daghi !== "object") + if (!daghi || typeof daghi !== 'object') return this.parseFanavaranMoney(daghi); const d = daghi as { price?: unknown }; return this.parseFanavaranMoney(d.price); @@ -5797,9 +5801,9 @@ export class ClaimRequestManagementService { }): Record { const partId = parseCatalogPartIdInput(input.part?.partId); const accidentLevel = - typeof input.part?.typeOfDamage === "number" + typeof input.part?.typeOfDamage === 'number' ? input.part.typeOfDamage - : typeof input.part?.typeOfDamage === "string" && + : typeof input.part?.typeOfDamage === 'string' && /^\d+$/.test(input.part.typeOfDamage) ? Number(input.part.typeOfDamage) : FANAVARAN_DEFAULT_ACCIDENT_LEVEL; @@ -5844,10 +5848,10 @@ export class ClaimRequestManagementService { let claimExpertId: number | null = null; if (!blameForExpertIds) { const message = - "Expertise ClaimExpertId unresolved: linked blame case was not found."; + 'Expertise ClaimExpertId unresolved: linked blame case was not found.'; if (requireClaimExpertId) { throw new BadRequestException({ - code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + code: 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', message, }); } @@ -5865,11 +5869,11 @@ export class ClaimRequestManagementService { if (resolved.claimExpertId == null) { const message = resolved.message ?? - "Expertise ClaimExpertId unresolved on the assigned assessor profile."; + 'Expertise ClaimExpertId unresolved on the assigned assessor profile.'; if (requireClaimExpertId) { throw new BadRequestException({ code: - resolved.code ?? "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + resolved.code ?? 'FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING', message, }); } @@ -5878,7 +5882,7 @@ export class ClaimRequestManagementService { } if (!active?.parts?.length) { - warnings.push("No active damage expert reply with priced parts exists."); + warnings.push('No active damage expert reply with priced parts exists.'); } const reply = active?.reply as any; @@ -5888,12 +5892,12 @@ export class ClaimRequestManagementService { }) as any[]; if (!parts.length) { - warnings.push("No submit-ready expert pricing lines exist yet."); + warnings.push('No submit-ready expert pricing lines exist yet.'); } const [inspectionPlaces, dropAmountStatuses] = await Promise.all([ - this.getFanavaranLookupRows(input.clientKey, "inspection-place"), - this.getFanavaranLookupRows(input.clientKey, "drop-amount-status"), + this.getFanavaranLookupRows(input.clientKey, 'inspection-place'), + this.getFanavaranLookupRows(input.clientKey, 'drop-amount-status'), ]); const priceDrop = input.claimCase.evaluation?.priceDrop ?? {}; @@ -5926,7 +5930,7 @@ export class ClaimRequestManagementService { input.claimCase?._id ? String(input.claimCase._id) : undefined, ); - if (product === "car-body") { + if (product === 'car-body') { const blame = blameForExpertIds; return this.buildCarBodyFanavaranExpertisePayload({ clientKey: input.clientKey, @@ -5983,7 +5987,7 @@ export class ClaimRequestManagementService { const allWarnings = Array.from(new Set([...warnings, ...readyWarnings])); if (allWarnings.length) { throw new BadRequestException({ - message: "Fanavaran expertise payload is not ready.", + message: 'Fanavaran expertise payload is not ready.', warnings: allWarnings, }); } @@ -5994,7 +5998,7 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, ): Promise { const claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) throw new NotFoundException("Claim case not found"); + if (!claimCase) throw new NotFoundException('Claim case not found'); const { payload, warnings, replyKey } = await this.buildFanavaranExpertisePayload({ @@ -6005,8 +6009,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.expertise.lastPayload": payload, - "fanavaranSync.expertise.lastPayloadBuiltAt": new Date(), + 'fanavaranSync.expertise.lastPayload': payload, + 'fanavaranSync.expertise.lastPayloadBuiltAt': new Date(), }, }); @@ -6038,7 +6042,7 @@ export class ClaimRequestManagementService { FanavaranAuditSource.SUBMIT, ); const claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) throw new NotFoundException("Claim case not found"); + if (!claimCase) throw new NotFoundException('Claim case not found'); const product = await this.resolveFanavaranClaimProduct(claimCaseId); const built = await this.buildFanavaranExpertisePayload({ claimCase, @@ -6065,7 +6069,7 @@ export class ClaimRequestManagementService { error, ); throw toFanavaranHttpException(error, { - fallback: "Failed to submit data to Fanavaran API", + fallback: 'Failed to submit data to Fanavaran API', }); } } @@ -6077,7 +6081,7 @@ export class ClaimRequestManagementService { auditSource: FanavaranAuditSource, ): Promise { let claimCase = await this.claimCaseDbService.findById(claimCaseId); - if (!claimCase) throw new NotFoundException("Claim case not found"); + if (!claimCase) throw new NotFoundException('Claim case not found'); this.assertFanavaranVehicleReviewApproved(claimCase); const product = await this.resolveFanavaranClaimProduct(claimCaseId); if ( @@ -6089,7 +6093,7 @@ export class ClaimRequestManagementService { } if (!claimCase?.claimId) { throw new BadRequestException( - "Fanavaran claimId is required before submitting expertise", + 'Fanavaran claimId is required before submitting expertise', ); } if (claimCase.expertiseId != null) { @@ -6111,7 +6115,7 @@ export class ClaimRequestManagementService { }); if (nestedClaimId == null) { throw new BadRequestException( - "Fanavaran claimId is required before submitting expertise", + 'Fanavaran claimId is required before submitting expertise', ); } const url = `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${nestedClaimId}/expertise`; @@ -6128,7 +6132,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_EXPERTISE, status: FanavaranAuditStatus.STARTED, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', requestBody: payload, requestMeta: { claimId: claimCase.claimId }, }); @@ -6149,7 +6153,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_EXPERTISE, status: FanavaranAuditStatus.SUCCESS, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: response.status, requestBody: payload, responseHeaders: exchange.responseHeaders, @@ -6161,8 +6165,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { ...(expertiseId !== undefined ? { expertiseId } : {}), - "fanavaranSync.expertise": { - status: "success", + 'fanavaranSync.expertise': { + status: 'success', lastTriedAt: new Date(), claimId: claimCase.claimId, dmgCaseId: payload.DmgCaseId, @@ -6182,7 +6186,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_EXPERTISE, status: FanavaranAuditStatus.FAILURE, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: exchange.httpStatus, requestBody: payload, responseHeaders: exchange.responseHeaders, @@ -6206,7 +6210,7 @@ export class ClaimRequestManagementService { return { attempted: false, submitted: false, - warning: "Claim case not found for Fanavaran expertise submit.", + warning: 'Claim case not found for Fanavaran expertise submit.', }; } if (claimCase.expertiseId != null) { @@ -6215,7 +6219,7 @@ export class ClaimRequestManagementService { attempted: false, submitted: false, skipped: true, - skipReason: "Expertise already submitted to Fanavaran", + skipReason: 'Expertise already submitted to Fanavaran', claimId: claimCase.claimId, dmgCaseId: claimCase.dmgCaseId, expertiseId: claimCase.expertiseId, @@ -6254,8 +6258,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $push: { history: { - type: "FANAVARAN_EXPERTISE_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, + type: 'FANAVARAN_EXPERTISE_AUTO_SUBMIT_SUCCEEDED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, @@ -6281,14 +6285,14 @@ export class ClaimRequestManagementService { try { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.expertise.status": "failed", - "fanavaranSync.expertise.lastTriedAt": new Date(), - "fanavaranSync.expertise.lastError": warning, + 'fanavaranSync.expertise.status': 'failed', + 'fanavaranSync.expertise.lastTriedAt': new Date(), + 'fanavaranSync.expertise.lastError': warning, }, $push: { history: { - type: "FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, + type: 'FANAVARAN_EXPERTISE_AUTO_SUBMIT_FAILED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, error: warning }, }, @@ -6304,7 +6308,7 @@ export class ClaimRequestManagementService { // Schedule retry for expertise await this.scheduleFanavaranRetry( claimCaseId, - "expertise", + 'expertise', () => this.autoSubmitFanavaranExpertiseOnExpertReply(claimCaseId), logPrefix, { error, clientKey }, @@ -6344,9 +6348,9 @@ export class ClaimRequestManagementService { ids.some((id) => !Number.isInteger(Number(id)) || Number(id) <= 0) ) { throw new ConflictException({ - code: "FANAVARAN_VEHICLE_REVIEW_REQUIRED", + 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.", + 'An expert must review and approve the vehicle group, use type, system, and kind before any data can be sent to Fanavaran.', }); } } @@ -6355,16 +6359,16 @@ export class ClaimRequestManagementService { claimCase: any, ): Promise { if (claimCase.claimId != null || claimCase.claimNo != null) { - return "Already submitted to Fanavaran"; + return 'Already submitted to Fanavaran'; } if (!claimCase.fanavaranVehicleReview?.approved) { - return "Expert vehicle review is required before Fanavaran submission"; + return 'Expert vehicle review is required before Fanavaran submission'; } const clientKey = resolveFanavaranClientKey(); const notifierAllowed = - clientKey === "tejaratno" + clientKey === 'tejaratno' ? await this.tejaratNotifierAllowedIds(clientKey) : undefined; if ( @@ -6374,22 +6378,22 @@ export class ClaimRequestManagementService { notifierAllowed, ) ) { - return "نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران انتخاب شوند."; + return 'نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران انتخاب شوند.'; } if (!claimCase.blameRequestId) { - return "Blame case not linked to claim case"; + return 'Blame case not linked to claim case'; } const blameCase = await this.blameRequestDbService.findById( claimCase.blameRequestId, ); if (!blameCase) { - return "Blame case not found"; + return 'Blame case not found'; } if (!isFanavaranSubmitSupportedBlameType(blameCase.type)) { - return "Fanavaran submit only applies to THIRD_PARTY and CAR_BODY claims"; + return 'Fanavaran submit only applies to THIRD_PARTY and CAR_BODY claims'; } return null; @@ -6407,7 +6411,7 @@ export class ClaimRequestManagementService { ): Promise<{ claimId: number; claimNo?: string; created: boolean }> { const existing = await this.claimCaseDbService.findById(claimCaseId); if (!existing) { - throw new NotFoundException("Claim case not found"); + throw new NotFoundException('Claim case not found'); } if (existing.claimId != null) { return { @@ -6431,7 +6435,7 @@ export class ClaimRequestManagementService { 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.", + 'Fanavaran base claim is missing and could not be created before the next stage. Fix base claim first.', ); } return { @@ -6470,7 +6474,7 @@ export class ClaimRequestManagementService { if (!fanavaranHasDamageCaseStage(product)) { if (existing?.claimId == null) { throw new BadRequestException( - "Fanavaran claimId is required before the next hull stage.", + 'Fanavaran claimId is required before the next hull stage.', ); } return { @@ -6493,7 +6497,7 @@ export class ClaimRequestManagementService { 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.", + 'Fanavaran damage case is missing and could not be created before the next stage.', ); } return { @@ -6522,7 +6526,7 @@ export class ClaimRequestManagementService { this.httpService.post(url, payload, { headers: { ...headers, - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, }), ); @@ -6553,7 +6557,7 @@ export class ClaimRequestManagementService { this.httpService.put(url, payload, { headers: { ...headers, - "Content-Type": "application/json", + 'Content-Type': 'application/json', }, }), ); @@ -6574,7 +6578,7 @@ export class ClaimRequestManagementService { clientKey: FanavaranClientKey, ): Promise { const product = await this.resolveFanavaranClaimProduct(claimCaseId); - if (product !== "car-body") return; + if (product !== 'car-body') return; const claimCase = await this.claimCaseDbService.findById(claimCaseId); const nestedId = fanavaranHullNestedClaimId({ claimId: claimCase?.claimId, @@ -6587,14 +6591,14 @@ export class ClaimRequestManagementService { persistPayload: true, }); const hull = toFanavaranHullBaseClaimPayload( - built && typeof built === "object" && "payload" in built + built && typeof built === 'object' && 'payload' in built ? (built as { payload: Record }).payload : built, clientKey, ); - const url = `${fanavaranClaimsBaseUrl("car-body", clientKey)}/${nestedId}`; + const url = `${fanavaranClaimsBaseUrl('car-body', clientKey)}/${nestedId}`; this.logger.log( - `[Fanavaran hull sync] PUT ${url} keys=${Object.keys(hull).join(",")}`, + `[Fanavaran hull sync] PUT ${url} keys=${Object.keys(hull).join(',')}`, ); try { await this.putFanavaranJson(url, hull, clientKey, undefined, claimCaseId); @@ -6626,11 +6630,11 @@ export class ClaimRequestManagementService { ); const form = new FormData(); - form.append("Param", JSON.stringify(content), { - contentType: "application/json", + form.append('Param', JSON.stringify(content), { + contentType: 'application/json', }); for (const file of files) { - form.append("Param1", createReadStream(resolve(file.path)), { + form.append('Param1', createReadStream(resolve(file.path)), { filename: file.fileName, }); } @@ -6645,12 +6649,12 @@ export class ClaimRequestManagementService { ...files.map((f) => `-F 'Param1=@${f.path};filename=${f.fileName}'`), ]; this.logger.log( - `\n====== COPY THIS CURL ======\n${curlParts.join(" \\\n ")}\n====== END CURL ======\n`, + `\n====== COPY THIS CURL ======\n${curlParts.join(' \\\n ')}\n====== END CURL ======\n`, ); 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}`, + `${logPrefix} REQUEST: url=${url} | Param=${JSON.stringify(content)} | files=[${files.map((f) => f.fileName).join(', ')}] | fileCount=${files.length}`, ); try { @@ -6686,7 +6690,7 @@ export class ClaimRequestManagementService { const profile = getFanavaranClientProfile(clientKey); let claimCase = await this.claimCaseDbService.findById(claimCaseId); if (!claimCase) { - throw new NotFoundException("Claim case not found"); + throw new NotFoundException('Claim case not found'); } this.assertFanavaranVehicleReviewApproved(claimCase); if (!claimCase.claimId) { @@ -6694,7 +6698,7 @@ export class ClaimRequestManagementService { claimCase = await this.claimCaseDbService.findById(claimCaseId); if (!claimCase?.claimId) { throw new BadRequestException( - "Fanavaran claimId is required before submitting damage case", + 'Fanavaran claimId is required before submitting damage case', ); } } @@ -6709,25 +6713,25 @@ export class ClaimRequestManagementService { ); } if (!claimCase.blameRequestId) { - throw new BadRequestException("Blame case not linked to claim case"); + 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"); + 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", + 'Fanavaran damage-case submit only applies to THIRD_PARTY and CAR_BODY claims', ); } const product = fanavaranClaimProductFromBlameType(blameCase.type); const url = fanavaranClaimStageUrl( product, - "damage-case", + 'damage-case', claimCase.claimId, clientKey, ); @@ -6737,8 +6741,8 @@ export class ClaimRequestManagementService { ); await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.damageCase": { - status: "skipped", + 'fanavaranSync.damageCase': { + status: 'skipped', lastTriedAt: new Date(), lastError: FANAVARAN_HULL_NO_DAMAGE_CASE_REASON, claimId: claimCase.claimId, @@ -6772,7 +6776,7 @@ export class ClaimRequestManagementService { ); this.logger.log( - `[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? "NULL"} payload keys=${Object.keys(payload).join(", ")}`, + `[executeFanavaranDamageCaseSubmit] claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? 'NULL'} payload keys=${Object.keys(payload).join(', ')}`, ); const startedAt = Date.now(); const auditSession: FanavaranAuditSession = { @@ -6787,7 +6791,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE, status: FanavaranAuditStatus.STARTED, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', requestBody: payload, requestMeta: { claimId: claimCase.claimId }, }); @@ -6808,7 +6812,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE, status: FanavaranAuditStatus.SUCCESS, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: response.status, requestBody: payload, responseHeaders: exchange.responseHeaders, @@ -6821,8 +6825,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { dmgCaseId, - "fanavaranSync.damageCase": { - status: "success", + 'fanavaranSync.damageCase': { + status: 'success', lastTriedAt: new Date(), claimId: claimCase.claimId, dmgCaseId, @@ -6840,7 +6844,7 @@ export class ClaimRequestManagementService { ? error.message : String(error); this.logger.error( - `[executeFanavaranDamageCaseSubmit] FAILED claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? "NULL"} error: ${errDetail}`, + `[executeFanavaranDamageCaseSubmit] FAILED claimCaseId=${claimCaseId} claimId=${claimCase.claimId} payload.DriverId=${payload.DriverId ?? 'NULL'} error: ${errDetail}`, ); const exchange = this.fanavaranAuditService.captureAxiosExchange(error); await this.fanavaranAuditService.recordStep({ @@ -6848,7 +6852,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_DAMAGE_CASE, status: FanavaranAuditStatus.FAILURE, requestUrl: url, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: exchange.httpStatus, requestBody: payload, responseHeaders: exchange.responseHeaders, @@ -6874,7 +6878,7 @@ export class ClaimRequestManagementService { return { attempted: false, submitted: false, - warning: "Claim case not found for Fanavaran damage-case submit.", + warning: 'Claim case not found for Fanavaran damage-case submit.', }; } if (claimCase.dmgCaseId != null) { @@ -6882,7 +6886,7 @@ export class ClaimRequestManagementService { attempted: false, submitted: false, skipped: true, - skipReason: "Damage case already submitted to Fanavaran", + skipReason: 'Damage case already submitted to Fanavaran', claimId: claimCase.claimId, dmgCaseId: claimCase.dmgCaseId, }; @@ -6895,11 +6899,11 @@ export class ClaimRequestManagementService { if (!claimCase?.claimId) { const warning = - "Fanavaran base claim is missing, so damage case was not submitted."; + 'Fanavaran base claim is missing, so damage case was not submitted.'; await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.damageCase": { - status: "skipped", + 'fanavaranSync.damageCase': { + status: 'skipped', lastTriedAt: new Date(), lastError: warning, }, @@ -6935,8 +6939,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $push: { history: { - type: "FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, + type: 'FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_SUCCEEDED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, @@ -6963,14 +6967,14 @@ export class ClaimRequestManagementService { try { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.damageCase.status": "failed", - "fanavaranSync.damageCase.lastTriedAt": new Date(), - "fanavaranSync.damageCase.lastError": warning, + '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" }, + type: 'FANAVARAN_DAMAGE_CASE_AUTO_SUBMIT_FAILED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, error: warning }, }, @@ -6986,7 +6990,7 @@ export class ClaimRequestManagementService { // Schedule retry for damage case await this.scheduleFanavaranRetry( claimCaseId, - "damageCase", + 'damageCase', () => this.autoSubmitFanavaranDamageCaseOnOuterPartsSelected( claimCaseId, @@ -7017,7 +7021,7 @@ export class ClaimRequestManagementService { const locked = await this.withFanavaranStageLock( claimCaseId, - "baseClaim", + 'baseClaim', async () => { try { const claimCase = await this.claimCaseDbService.findById(claimCaseId); @@ -7026,7 +7030,7 @@ export class ClaimRequestManagementService { attempted: false, submitted: false, warning: - "Claim case not found for Fanavaran early submit. Retry manually when available.", + 'Claim case not found for Fanavaran early submit. Retry manually when available.', }; } @@ -7053,8 +7057,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $push: { history: { - type: "FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, + type: 'FANAVARAN_EARLY_AUTO_SUBMIT_SUCCEEDED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, @@ -7079,14 +7083,14 @@ export class ClaimRequestManagementService { try { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $set: { - "fanavaranSync.baseClaim.status": "failed", - "fanavaranSync.baseClaim.lastTriedAt": new Date(), - "fanavaranSync.baseClaim.lastError": warning, + 'fanavaranSync.baseClaim.status': 'failed', + 'fanavaranSync.baseClaim.lastTriedAt': new Date(), + 'fanavaranSync.baseClaim.lastError': warning, }, $push: { history: { - type: "FANAVARAN_EARLY_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, + type: 'FANAVARAN_EARLY_AUTO_SUBMIT_FAILED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, error: warning }, }, @@ -7101,7 +7105,7 @@ export class ClaimRequestManagementService { await this.scheduleFanavaranRetry( claimCaseId, - "baseClaim", + 'baseClaim', () => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId), logPrefix, { error, clientKey }, @@ -7118,8 +7122,8 @@ export class ClaimRequestManagementService { if ( locked && - typeof locked === "object" && - "skipped" in locked && + typeof locked === 'object' && + 'skipped' in locked && locked.skipped ) { return { @@ -7150,7 +7154,7 @@ export class ClaimRequestManagementService { attempted: false, submitted: false, warning: - "Claim case not found for Fanavaran auto-submit. Retry manually when available.", + 'Claim case not found for Fanavaran auto-submit. Retry manually when available.', }; } @@ -7170,8 +7174,8 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.WAITING_FOR_FILE_MAKER_APPROVAL }, $push: { history: { - type: "V5_HELD_FOR_FILE_MAKER_APPROVAL", - actor: { actorType: "system" }, + type: 'V5_HELD_FOR_FILE_MAKER_APPROVAL', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { claimCaseId }, }, @@ -7182,13 +7186,13 @@ export class ClaimRequestManagementService { submitted: false, skipped: true, skipReason: - "V5 flow: FileMaker approval required before Fanavaran submission. " + - "Claim is now in WAITING_FOR_FILE_MAKER_APPROVAL.", + '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: "" }, + $unset: { requiresFileMakerApproval: '' }, }); } @@ -7212,8 +7216,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $push: { history: { - type: "FANAVARAN_AUTO_SUBMIT_SUCCEEDED", - actor: { actorType: "system" }, + type: 'FANAVARAN_AUTO_SUBMIT_SUCCEEDED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, @@ -7239,8 +7243,8 @@ export class ClaimRequestManagementService { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { $push: { history: { - type: "FANAVARAN_AUTO_SUBMIT_FAILED", - actor: { actorType: "system" }, + type: 'FANAVARAN_AUTO_SUBMIT_FAILED', + actor: { actorType: 'system' }, timestamp: new Date(), metadata: { clientKey, error: warning }, }, @@ -7256,7 +7260,7 @@ export class ClaimRequestManagementService { // Schedule retry for base claim await this.scheduleFanavaranRetry( claimCaseId, - "baseClaim", + 'baseClaim', () => this.autoSubmitToFanavaranV2OnClaimCreated(claimCaseId), logPrefix, { error, clientKey }, @@ -7273,7 +7277,7 @@ export class ClaimRequestManagementService { private extractFanavaranErrorMessage(error: unknown): string { return extractFanavaranOriginalMessage( error, - "Failed to submit data to Fanavaran API", + 'Failed to submit data to Fanavaran API', ); } @@ -7283,7 +7287,7 @@ export class ClaimRequestManagementService { private fanavaranRetryKey( claimCaseId: string, - stage: "baseClaim" | "damageCase" | "attachments" | "expertise", + stage: 'baseClaim' | 'damageCase' | 'attachments' | 'expertise', ): string { return `${claimCaseId}:${stage}`; } @@ -7318,7 +7322,7 @@ export class ClaimRequestManagementService { */ private async scheduleFanavaranRetry( claimCaseId: string, - stage: "baseClaim" | "damageCase" | "attachments" | "expertise", + stage: 'baseClaim' | 'damageCase' | 'attachments' | 'expertise', retryFn: () => Promise, logPrefix: string, options?: { error?: unknown; clientKey?: FanavaranClientKey }, @@ -7342,7 +7346,7 @@ export class ClaimRequestManagementService { const existingNext = syncStage?.nextRetryAt ? new Date(syncStage.nextRetryAt).getTime() : 0; - if (syncStage?.status === "pending" && existingNext > Date.now() + 5_000) { + 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.`, ); @@ -7379,7 +7383,7 @@ export class ClaimRequestManagementService { [`fanavaranSync.${stage}.retryCount`]: nextRetryCount, [`fanavaranSync.${stage}.maxRetries`]: maxRetries, [`fanavaranSync.${stage}.nextRetryAt`]: nextRetryAt, - [`fanavaranSync.${stage}.status`]: "pending", + [`fanavaranSync.${stage}.status`]: 'pending', [`fanavaranSync.${stage}.lastTriedAt`]: new Date(), ...(options?.error ? { @@ -7391,7 +7395,7 @@ export class ClaimRequestManagementService { }); this.logger.log( - `${logPrefix} Scheduling retry ${nextRetryCount}/${maxRetries} for ${stage} at ${nextRetryAt.toISOString()} (delay=${delayMs}ms${transient ? ", transient backoff" : ""})`, + `${logPrefix} Scheduling retry ${nextRetryCount}/${maxRetries} for ${stage} at ${nextRetryAt.toISOString()} (delay=${delayMs}ms${transient ? ', transient backoff' : ''})`, ); const timer = setTimeout(async () => { @@ -7399,7 +7403,7 @@ export class ClaimRequestManagementService { try { const fresh = await this.claimCaseDbService.findById(claimCaseId); const freshStage = (fresh as any)?.fanavaranSync?.[stage]; - if (freshStage?.status === "pending") { + if (freshStage?.status === 'pending') { await retryFn(); } } catch (retryError) { @@ -7438,10 +7442,10 @@ export class ClaimRequestManagementService { } ); } - if (!existing) throw new NotFoundException("Claim case not found"); + if (!existing) throw new NotFoundException('Claim case not found'); this.assertFanavaranVehicleReviewApproved(existing); const notifierAllowed = - clientKey === "tejaratno" + clientKey === 'tejaratno' ? await this.tejaratNotifierAllowedIds(clientKey) : undefined; if ( @@ -7452,9 +7456,9 @@ export class ClaimRequestManagementService { ) ) { throw new ConflictException({ - code: "FANAVARAN_NOTIFIER_REVIEW_REQUIRED", + code: 'FANAVARAN_NOTIFIER_REVIEW_REQUIRED', message: - "نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران بررسی و انتخاب شوند.", + 'نوع و نسبت اعلام‌کننده باید پیش از ارسال اولیه پرونده به فناوران بررسی و انتخاب شوند.', }); } @@ -7511,14 +7515,14 @@ export class ClaimRequestManagementService { const requestHeaders = { ...headers, - "Content-Type": "application/json", + 'Content-Type': 'application/json', }; await this.fanavaranAuditService.recordStep({ session: auditSession, step: FanavaranAuditStep.SUBMIT_CLAIM, status: FanavaranAuditStatus.STARTED, requestUrl: submitUrl, - requestMethod: "POST", + requestMethod: 'POST', requestHeaders, requestBody: fanavaranData, requestMeta: { policyId: fanavaranData?.PolicyId ?? null }, @@ -7549,7 +7553,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_CLAIM, status: FanavaranAuditStatus.SUCCESS, requestUrl: submitUrl, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: response.status, requestHeaders: exchange.requestHeaders, requestBody: fanavaranData, @@ -7573,13 +7577,13 @@ export class ClaimRequestManagementService { 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; + 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"] = + updateData.$set['fanavaranSync.baseClaim.policyId'] = fanavaranData.PolicyId; } @@ -7601,7 +7605,7 @@ export class ClaimRequestManagementService { step: FanavaranAuditStep.SUBMIT_CLAIM, status: FanavaranAuditStatus.FAILURE, requestUrl: submitUrl, - requestMethod: "POST", + requestMethod: 'POST', httpStatus: exchange.httpStatus, requestHeaders: exchange.requestHeaders, requestBody: fanavaranData, @@ -7628,29 +7632,29 @@ export class ClaimRequestManagementService { const blameRequest = await this.blameRequestDbService.findById(blameRequestId); if (!blameRequest) { - throw new NotFoundException("Blame request not found"); + throw new NotFoundException('Blame request not found'); } if (blameRequest.status !== BlameCaseStatus.COMPLETED) { throw new BadRequestException( - "Blame request must be completed before creating a claim", + '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", + '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", + '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", + 'Both parties must sign and accept the decision before creating a claim', ); } @@ -7663,7 +7667,7 @@ export class ClaimRequestManagementService { if (existingClaim) { throw new ConflictException( - "A claim request for this blame case already exists", + 'A claim request for this blame case already exists', ); } @@ -7674,7 +7678,7 @@ export class ClaimRequestManagementService { const ownerParty = resolveClaimOwnerParty(blameRequest); if (!ownerParty?.person?.userId) { throw new BadRequestException( - "Could not resolve claim owner from blame parties", + 'Could not resolve claim owner from blame parties', ); } const damagedUserId = String(beneficiary.person!.userId); @@ -7707,11 +7711,11 @@ export class ClaimRequestManagementService { })(), history: [ { - type: "CLAIM_CREATED", + type: 'CLAIM_CREATED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: currentUserParty.person?.fullName || "User", - actorType: "user", + actorName: currentUserParty.person?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -7730,7 +7734,7 @@ export class ClaimRequestManagementService { String(newClaim._id), ); const message = this.withFanavaranAutoSubmitMessage( - "Claim request created successfully", + 'Claim request created successfully', fanavaran, ); @@ -7744,14 +7748,14 @@ export class ClaimRequestManagementService { } catch (error) { if (error instanceof HttpException) throw error; this.logger.error( - "createClaimFromBlameV2 failed", + 'createClaimFromBlameV2 failed', blameRequestId, error instanceof Error ? error.stack : String(error), ); throw new InternalServerErrorException( error instanceof Error ? error.message - : "Failed to create claim request", + : 'Failed to create claim request', ); } } @@ -7767,7 +7771,7 @@ export class ClaimRequestManagementService { const blameRequest = await this.blameRequestDbService.findById(blameRequestId); if (!blameRequest) { - throw new NotFoundException("Blame request not found"); + throw new NotFoundException('Blame request not found'); } // if (blameRequest.status !== BlameCaseStatus.COMPLETED) { // throw new BadRequestException( @@ -7776,29 +7780,29 @@ export class ClaimRequestManagementService { // } if ( !blameRequest.expertInitiated || - blameRequest.creationMethod !== "IN_PERSON" || + blameRequest.creationMethod !== 'IN_PERSON' || !blameRequest.initiatedByFieldExpertId ) { throw new BadRequestException( - "This endpoint is only for expert-initiated IN_PERSON blame files.", + '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.", + '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", + '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"); + throw new ConflictException('A claim for this blame case already exists'); } const claimNo = await this.generateUniqueClaimNumber(); const newClaim = await this.claimCaseDbService.create({ @@ -7836,12 +7840,12 @@ export class ClaimRequestManagementService { }, history: [ { - type: "CLAIM_CREATED", + type: 'CLAIM_CREATED', actor: { actorId: new Types.ObjectId(expert.sub), actorName: - `${expert.firstName || ""} ${expert.lastName || ""}`.trim(), - actorType: "field_expert", + `${expert.firstName || ''} ${expert.lastName || ''}`.trim(), + actorType: 'field_expert', }, timestamp: new Date(), metadata: { @@ -7859,7 +7863,7 @@ export class ClaimRequestManagementService { String(newClaim._id), ); const message = this.withFanavaranAutoSubmitMessage( - "Claim created successfully. You can now fill claim data on behalf of the damaged party.", + 'Claim created successfully. You can now fill claim data on behalf of the damaged party.', fanavaran, ); return { @@ -7910,7 +7914,7 @@ export class ClaimRequestManagementService { claimCase: any, effectiveUserId: string, actor?: { username?: string }, - message = "Only the damaged party can perform this action on the claim", + message = 'Only the damaged party can perform this action on the claim', ): Promise { const linkedUserIds = await resolveLinkedUserIdStrings(this.userDbService, { sub: effectiveUserId, @@ -8023,7 +8027,7 @@ export class ClaimRequestManagementService { const isV4OrV5File = !!(blame as any)?.isMadeByFileMaker && blame?.expertInitiated && - blame?.creationMethod === "IN_PERSON"; + blame?.creationMethod === 'IN_PERSON'; if ( actor.role === RoleEnum.FILE_MAKER && @@ -8036,7 +8040,7 @@ export class ClaimRequestManagementService { if ( actor.role === RoleEnum.FILE_REVIEWER && isV4OrV5File && - String((blame as any)?.assignedFileReviewerId ?? "") === + String((blame as any)?.assignedFileReviewerId ?? '') === String(currentUserId) ) { return; @@ -8056,7 +8060,7 @@ export class ClaimRequestManagementService { } } - throw new ForbiddenException("You do not have access to this claim"); + throw new ForbiddenException('You do not have access to this claim'); } /** @@ -8081,7 +8085,7 @@ export class ClaimRequestManagementService { const blameRequest = await this.blameRequestDbService.findById( claimCase.blameRequestId.toString(), ); - if (!blameRequest || blameRequest.creationMethod !== "IN_PERSON") + if (!blameRequest || blameRequest.creationMethod !== 'IN_PERSON') return currentUserId; if ( actorRole === RoleEnum.FIELD_EXPERT || @@ -8117,7 +8121,7 @@ export class ClaimRequestManagementService { ): Promise { const blameRequest = await this.blameRequestDbService.findById(blameRequestId); - if (!blameRequest) throw new NotFoundException("Blame request not found"); + 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}`, @@ -8125,29 +8129,29 @@ export class ClaimRequestManagementService { } if ( !blameRequest.registrarInitiated || - blameRequest.creationMethod !== "IN_PERSON" || + blameRequest.creationMethod !== 'IN_PERSON' || !blameRequest.initiatedByRegistrarId ) { throw new BadRequestException( - "This endpoint is only for registrar-initiated IN_PERSON blame files.", + '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.", + '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", + '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"); + throw new ConflictException('A claim for this blame case already exists'); const claimNo = await this.generateUniqueClaimNumber(); const newClaim = await this.claimCaseDbService.create({ requestNo: claimNo, @@ -8177,12 +8181,12 @@ export class ClaimRequestManagementService { createdByRegistrarId: new Types.ObjectId(registrar.sub), history: [ { - type: "CLAIM_CREATED", + type: 'CLAIM_CREATED', actor: { actorId: new Types.ObjectId(registrar.sub), actorName: - `${registrar.firstName || ""} ${registrar.lastName || ""}`.trim(), - actorType: "registrar", + `${registrar.firstName || ''} ${registrar.lastName || ''}`.trim(), + actorType: 'registrar', }, timestamp: new Date(), metadata: { @@ -8197,7 +8201,7 @@ export class ClaimRequestManagementService { String(newClaim._id), ); const message = this.withFanavaranAutoSubmitMessage( - "Claim created successfully. Registrar can now fill claim data.", + 'Claim created successfully. Registrar can now fill claim data.', fanavaran, ); return { @@ -8249,7 +8253,7 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner (damaged party) can select damaged parts", + 'Only the claim owner (damaged party) can select damaged parts', ); // 3. Validate workflow step is correct (should be at SELECT_OUTER_PARTS) @@ -8272,7 +8276,7 @@ export class ClaimRequestManagementService { claimCase.damage.selectedParts.length > 0 ) { throw new ConflictException( - "Outer parts have already been selected for this claim", + 'Outer parts have already been selected for this claim', ); } @@ -8304,7 +8308,7 @@ export class ClaimRequestManagementService { if (selectedFromIds.length === 0) { throw new BadRequestException( - "selectedPartIds is required and must contain at least one valid Fanavaran part ID", + 'selectedPartIds is required and must contain at least one valid Fanavaran part ID', ); } @@ -8338,21 +8342,21 @@ export class ClaimRequestManagementService { const updatedClaim = await this.claimCaseDbService.findByIdAndUpdate( claimRequestId, { - "damage.selectedParts": selectedPartDocs, - "media.damagedParts": damagedPartsInitial, - "vehicle.carType": selectedCarType, + '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": "" }, + 'workflow.currentStep': ClaimWorkflowStep.SELECT_OTHER_PARTS, + 'workflow.nextStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES, + $unset: { 'damage.selectedOuterParts': '' }, $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OUTER_PARTS, + 'workflow.completedSteps': ClaimWorkflowStep.SELECT_OUTER_PARTS, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -8369,7 +8373,7 @@ export class ClaimRequestManagementService { ); if (!updatedClaim) { - throw new InternalServerErrorException("Failed to update claim case"); + throw new InternalServerErrorException('Failed to update claim case'); } this.logger.log( @@ -8383,9 +8387,9 @@ export class ClaimRequestManagementService { ); let message = - "Outer parts selected successfully. Please proceed to select other parts and provide bank information."; + '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."; + message += ' The damage case was sent to Fanavaran successfully.'; } else if (fanavaranDamageCase.warning) { message += ` ${fanavaranDamageCase.warning}`; } @@ -8404,12 +8408,12 @@ export class ClaimRequestManagementService { } catch (error) { if (error instanceof HttpException) throw error; this.logger.error( - "selectOuterPartsV2 failed", + 'selectOuterPartsV2 failed', claimRequestId, error instanceof Error ? error.stack : String(error), ); throw new InternalServerErrorException( - error instanceof Error ? error.message : "Failed to select outer parts", + error instanceof Error ? error.message : 'Failed to select outer parts', ); } } @@ -8455,7 +8459,7 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner (damaged party) can submit other parts and bank information", + '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) @@ -8476,7 +8480,7 @@ export class ClaimRequestManagementService { claimCase.workflow?.currentStep !== ClaimWorkflowStep.USER_EXPERT_RESEND ) { throw new ConflictException( - "Bank information has already been submitted for this claim", + 'Bank information has already been submitted for this claim', ); } @@ -8490,7 +8494,7 @@ export class ClaimRequestManagementService { // Multipart clients may send otherParts as JSON string if ( !Array.isArray((body as any)?.otherParts) && - typeof (body as any)?.otherParts === "string" + typeof (body as any)?.otherParts === 'string' ) { try { const parsed = JSON.parse((body as any).otherParts); @@ -8500,19 +8504,19 @@ export class ClaimRequestManagementService { } } const shebaInput = String( - ((body as any).shebaNumber ?? (body as any).sheba ?? "") as string, - ).replace(/\s/g, ""); + ((body as any).shebaNumber ?? (body as any).sheba ?? '') as string, + ).replace(/\s/g, ''); - const shebaDigits = shebaInput.replace(/^IR/i, ""); + 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, ""); + '') 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)", + 'shebaNumber is required and must be valid (IR + 24 digits or only 24 digits)', ); } const blameRequest = claimCase.blameRequestId @@ -8528,13 +8532,13 @@ export class ClaimRequestManagementService { submittedNationalCode !== storedOwnerNationalCode ) { throw new BadRequestException( - "Submitted national code does not match the vehicle owner saved on the blame case.", + '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.", + 'Vehicle owner national code is unavailable; a 10-digit nationalCodeOfOwner is required only for legacy claims.', ); } const ownershipPlate = this.resolveOwnershipPlateForClaim( @@ -8543,7 +8547,7 @@ export class ClaimRequestManagementService { ); if (!ownershipPlate) { throw new BadRequestException( - "Could not resolve vehicle plate for ownership validation.", + 'Could not resolve vehicle plate for ownership validation.', ); } @@ -8556,22 +8560,22 @@ export class ClaimRequestManagementService { await this.sandHubService.getShebaValidation(nationalCode, shebaNumber); const updatePayload: any = { - "damage.otherParts": otherParts.length > 0 ? otherParts : undefined, - "money.sheba": shebaNumber, - "money.nationalCodeOfInsurer": nationalCode, + '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, + 'workflow.currentStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES, + 'workflow.nextStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OTHER_PARTS, + 'workflow.completedSteps': ClaimWorkflowStep.SELECT_OTHER_PARTS, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -8596,7 +8600,7 @@ export class ClaimRequestManagementService { ]; if (existingGreen?.uploaded) { throw new ConflictException( - "car_green_card has already been uploaded for this claim", + 'car_green_card has already been uploaded for this claim', ); } const docRef = await this.claimRequiredDocumentDbService.create({ @@ -8624,7 +8628,7 @@ export class ClaimRequestManagementService { ); if (!updatedClaim) { - throw new InternalServerErrorException("Failed to update claim case"); + throw new InternalServerErrorException('Failed to update claim case'); } this.logger.log( @@ -8645,17 +8649,17 @@ export class ClaimRequestManagementService { 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.", + '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", + 'selectOtherPartsV2 failed', claimRequestId, error instanceof Error ? error.stack : String(error), ); throw new InternalServerErrorException( - error instanceof Error ? error.message : "Failed to select other parts", + error instanceof Error ? error.message : 'Failed to select other parts', ); } } @@ -8686,7 +8690,7 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can view capture requirements", + 'Only the claim owner can view capture requirements', ); // Build outer-parts lookup for resolving stored DB parts. @@ -8709,103 +8713,103 @@ export class ClaimRequestManagementService { const requiredDocsDefinition = [ { key: ClaimRequiredDocumentType.ACCIDENT_SKETCH, - label_fa: "کروکی", - label_en: "Accident Sketch", - category: "general", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + 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", + key: 'guilty_metal_plate', + label_fa: 'پلاک فلزی مقصر', + label_en: 'Guilty Metal Plate', + category: 'guilty_party', required: true, }, ]), @@ -8829,10 +8833,10 @@ export class ClaimRequestManagementService { // 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" }, + { 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, @@ -8860,8 +8864,8 @@ export class ClaimRequestManagementService { ? catalogByKey.get(catalogLikeKeyFromPart(sp)) : undefined; const labelEnName = sp.name - .replace(/([a-z])([A-Z])/g, "$1 $2") - .replace(/_/g, " ") + .replace(/([a-z])([A-Z])/g, '$1 $2') + .replace(/_/g, ' ') .trim() .replace(/\b\w/g, (c) => c.toUpperCase()); const ck = sp.catalogKey ?? catalogLikeKeyFromPart(sp); @@ -8909,7 +8913,7 @@ export class ClaimRequestManagementService { return { claimRequestId: claimCase._id.toString(), publicId: claimCase.publicId, - currentStep: claimCase.workflow?.currentStep || "", + currentStep: claimCase.workflow?.currentStep || '', captureSequencePhase: captureProgress.sequencePhase, captureSequenceHint: capturePhaseSequenceMessage( captureProgress.sequencePhase, @@ -8931,9 +8935,9 @@ export class ClaimRequestManagementService { }; } catch (error) { if (error instanceof HttpException) throw error; - this.logger.error("getCaptureRequirementsV2 failed", error); + this.logger.error('getCaptureRequirementsV2 failed', error); throw new InternalServerErrorException( - "Failed to get capture requirements", + 'Failed to get capture requirements', ); } } @@ -8955,17 +8959,17 @@ export class ClaimRequestManagementService { $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(), + 'workflow.currentStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, + 'workflow.nextStep': ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, + 'evaluation.damageExpertResend.fulfilledAt': new Date(), }, $push: { history: { - type: "EXPERT_RESEND_FULFILLED", + type: 'EXPERT_RESEND_FULFILLED', actor: { actorId: new Types.ObjectId(actorUserId), actorName: ownerDisplayName, - actorType: "user", + actorType: 'user', }, timestamp: new Date(), metadata: {}, @@ -9003,13 +9007,13 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can complete this step", + '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"}`, + `No expert resend step is active. Current step: ${claimCase.workflow?.currentStep ?? 'none'}`, ); } if (claimCase.status !== ClaimCaseStatus.WAITING_FOR_USER_RESEND) { @@ -9020,7 +9024,7 @@ export class ClaimRequestManagementService { const r = claimCase.evaluation?.damageExpertResend; if (!r || r.fulfilledAt) { throw new BadRequestException( - "There is no active expert resend request to acknowledge.", + 'There is no active expert resend request to acknowledge.', ); } if ( @@ -9032,21 +9036,21 @@ export class ClaimRequestManagementService { ).length > 0 ) { throw new BadRequestException( - "Upload all requested documents and part photos before completing the resend step.", + 'Upload all requested documents and part photos before completing the resend step.', ); } await this.tryFinalizeExpertResendAfterUserAction( claimRequestId, effectiveUserId, - claimCase.owner?.fullName || "User", + 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.", + status: String(updated?.status ?? ''), + claimStatus: String(updated?.claimStatus ?? ''), + currentStep: String(updated?.workflow?.currentStep ?? ''), + message: 'Claim returned to the damage expert queue.', }; } @@ -9083,7 +9087,7 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can upload documents", + 'Only the claim owner can upload documents', ); const step = claimCase.workflow?.currentStep; @@ -9102,19 +9106,19 @@ export class ClaimRequestManagementService { !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.`, + `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.", + '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.", + 'Capture all four car angles (front, back, left, right) before uploading chassis, engine, or metal plate photos.', ); } } @@ -9138,7 +9142,7 @@ export class ClaimRequestManagementService { ).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(", ")}).`, + `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( @@ -9170,11 +9174,11 @@ export class ClaimRequestManagementService { 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", + '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( @@ -9206,11 +9210,11 @@ export class ClaimRequestManagementService { // Base history entry for this upload const uploadHistoryEntry = { - type: "DOCUMENT_UPLOADED", + type: 'DOCUMENT_UPLOADED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -9279,28 +9283,28 @@ export class ClaimRequestManagementService { // 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"] = + $set['status'] = ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS; + $set['workflow.currentStep'] = ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS; - $set["workflow.nextStep"] = + $set['workflow.nextStep'] = ClaimWorkflowStep.USER_SUBMISSION_COMPLETE; completedStepsEntries.push( ClaimWorkflowStep.CAPTURE_PART_DAMAGES, ); historyEntries.push({ - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + 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.", + ? 'V4/V5 capture docs complete. Upload walk-around video to finalise.' + : 'Angles, damaged parts, and capture-phase vehicle evidence are complete.', }, }); } @@ -9343,11 +9347,11 @@ export class ClaimRequestManagementService { // 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"] = + $set['status'] = ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT; + $set['claimStatus'] = ClaimStatus.PENDING; + $set['workflow.currentStep'] = ClaimWorkflowStep.USER_SUBMISSION_COMPLETE; - $set["workflow.nextStep"] = + $set['workflow.nextStep'] = ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT; completedStepsEntries.push( @@ -9355,30 +9359,30 @@ export class ClaimRequestManagementService { ); historyEntries.push( { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - description: "All required documents uploaded", + description: 'All required documents uploaded', }, }, { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + 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.", + 'User submission complete. Claim ready for damage expert review.', }, }, ); @@ -9416,9 +9420,9 @@ export class ClaimRequestManagementService { : { $each: historyEntries }, }; if (completedStepsEntries.length === 1) { - $push["workflow.completedSteps"] = completedStepsEntries[0]; + $push['workflow.completedSteps'] = completedStepsEntries[0]; } else if (completedStepsEntries.length > 1) { - $push["workflow.completedSteps"] = { $each: completedStepsEntries }; + $push['workflow.completedSteps'] = { $each: completedStepsEntries }; } updatePayload.$push = $push; @@ -9474,23 +9478,23 @@ export class ClaimRequestManagementService { { $set: { status: ClaimCaseStatus.WAITING_FOR_FILE_REVIEWER, - "workflow.nextStep": ClaimWorkflowStep.SELECT_OUTER_PARTS, + 'workflow.nextStep': ClaimWorkflowStep.SELECT_OUTER_PARTS, }, $push: { - "workflow.completedSteps": + 'workflow.completedSteps': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: afterWrite.owner?.fullName || "User", - actorType: "user", + actorName: afterWrite.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { stepKey: ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, description: - "FileMaker documents complete. File sealed — awaiting FileReviewer.", + 'FileMaker documents complete. File sealed — awaiting FileReviewer.', v3InPersonFlow: true, }, }, @@ -9547,7 +9551,7 @@ export class ClaimRequestManagementService { await this.tryFinalizeExpertResendAfterUserAction( claimRequestId, currentUserId, - claimCase.owner?.fullName || "User", + claimCase.owner?.fullName || 'User', ); const refreshed = await this.claimCaseDbService.findById(claimRequestId); @@ -9571,19 +9575,19 @@ export class ClaimRequestManagementService { 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.", + ? '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." + ? '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." + ? '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( @@ -9593,8 +9597,8 @@ export class ClaimRequestManagementService { ) : 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." + ? '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 { @@ -9625,8 +9629,8 @@ export class ClaimRequestManagementService { }; } catch (error) { if (error instanceof HttpException) throw error; - this.logger.error("uploadRequiredDocumentV2 failed", error); - throw new InternalServerErrorException("Failed to upload document"); + this.logger.error('uploadRequiredDocumentV2 failed', error); + throw new InternalServerErrorException('Failed to upload document'); } } @@ -9658,7 +9662,7 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can capture parts", + 'Only the claim owner can capture parts', ); const capStep = claimCase.workflow?.currentStep; @@ -9677,9 +9681,9 @@ export class ClaimRequestManagementService { `Claim is not waiting for expert resend uploads. Status: ${claimCase.status}`, ); } - if (body.captureType !== "part") { + if (body.captureType !== 'part') { throw new BadRequestException( - "During expert resend only damaged-part photos can be uploaded (not car angles).", + 'During expert resend only damaged-part photos can be uploaded (not car angles).', ); } if (!partKeyAllowedForExpertResend(claimCase, body.captureKey)) { @@ -9689,7 +9693,7 @@ export class ClaimRequestManagementService { } if (canonicalizeClaimCarAngleKey(body.captureKey)) { throw new BadRequestException( - "During expert resend only damaged-part photos are allowed, not car angles (front/back/left/right).", + 'During expert resend only damaged-part photos are allowed, not car angles (front/back/left/right).', ); } } @@ -9697,26 +9701,26 @@ export class ClaimRequestManagementService { if (!isResendCapture) { const captureProgressBefore = getClaimCaptureProgress(claimCase); const willBeAngle = - body.captureType === "angle" || - (body.captureType === "part" && + 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.", + 'Upload photos for all selected damaged parts before capturing car angles.', ); } } const angleCanon = canonicalizeClaimCarAngleKey(body.captureKey); - if (body.captureType === "angle" && !angleCanon) { + 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)); + (body.captureType === 'angle' || + (body.captureType === 'part' && angleCanon !== null)); const fileUrl = buildFileLink(file.path); const captureData = { @@ -9729,11 +9733,11 @@ export class ClaimRequestManagementService { const updateData: any = { $push: { history: { - type: treatAsAngle ? "ANGLE_CAPTURED" : "PART_CAPTURED", + type: treatAsAngle ? 'ANGLE_CAPTURED' : 'PART_CAPTURED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -9776,7 +9780,7 @@ export class ClaimRequestManagementService { if (unsetFieldKeys.length) { updateData.$unset = {}; for (const k of unsetFieldKeys) { - updateData.$unset[`media.damagedParts.${k}`] = ""; + updateData.$unset[`media.damagedParts.${k}`] = ''; } } } @@ -9786,7 +9790,7 @@ export class ClaimRequestManagementService { nextSelected, nextMedia, ); - if (isResendCapture && body.captureType === "part" && idx < 0) { + if (isResendCapture && body.captureType === 'part' && idx < 0) { const added = normalizeDamageSelectedParts( [body.captureKey], carType, @@ -9795,7 +9799,7 @@ export class ClaimRequestManagementService { const row = added[0] || { id: null, name: body.captureKey, - side: "", + side: '', label_fa: body.captureKey, catalogKey: body.captureKey, }; @@ -9814,7 +9818,7 @@ export class ClaimRequestManagementService { const base = nextSelected[idx] || { id: null, name: String(body.captureKey), - side: "", + side: '', label_fa: String(body.captureKey), }; nextMedia[idx] = { @@ -9830,7 +9834,7 @@ export class ClaimRequestManagementService { // 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; + updateData['media.damagedParts'] = nextMedia; } else { updateData[`media.damagedParts.${idx}`] = nextMedia[idx]; } @@ -9838,7 +9842,7 @@ export class ClaimRequestManagementService { isResendCapture && nextSelected.length !== selectedBeforeNorm.length ) { - updateData["damage.selectedParts"] = nextSelected; + updateData['damage.selectedParts'] = nextSelected; } } @@ -9857,7 +9861,7 @@ export class ClaimRequestManagementService { await this.tryFinalizeExpertResendAfterUserAction( claimRequestId, currentUserId, - claimCase.owner?.fullName || "User", + claimCase.owner?.fullName || 'User', ); const refreshed = await this.claimCaseDbService.findById(claimRequestId); @@ -9882,8 +9886,8 @@ export class ClaimRequestManagementService { 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.", + ? 'Expert resend requirements are complete. Your claim is back in the damage expert queue.' + : 'Part photo uploaded for expert resend.', fanavaranAttachment, }; } @@ -9894,22 +9898,22 @@ export class ClaimRequestManagementService { if (allCapturesComplete) { await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { status: ClaimCaseStatus.UPLOADING_REQUIRED_DOCUMENTS, - "workflow.currentStep": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, - "workflow.nextStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, + 'workflow.currentStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, + 'workflow.nextStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, $push: { - "workflow.completedSteps": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, + 'workflow.completedSteps': ClaimWorkflowStep.CAPTURE_PART_DAMAGES, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + 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.", + 'Angles, damaged parts, and capture-phase vehicle evidence (chassis, engine, metal plate) are complete. Please upload remaining required documents.', }, }, }, @@ -9929,8 +9933,8 @@ export class ClaimRequestManagementService { 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).`; + ? '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(), @@ -9953,8 +9957,8 @@ export class ClaimRequestManagementService { }; } catch (error) { if (error instanceof HttpException) throw error; - this.logger.error("capturePartV2 failed", error); - throw new InternalServerErrorException("Failed to capture part"); + this.logger.error('capturePartV2 failed', error); + throw new InternalServerErrorException('Failed to capture part'); } } @@ -9985,11 +9989,11 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can upload car capture video", + 'Only the claim owner can upload car capture video', ); if (!fileDetail) { - throw new BadRequestException("Video file is required."); + throw new BadRequestException('Video file is required.'); } if ( @@ -10004,18 +10008,18 @@ export class ClaimRequestManagementService { const captureProgress = getClaimCaptureProgress(claimCase); if (!captureProgress.partsComplete) { throw new BadRequestException( - "Upload photos for all selected damaged parts before uploading the walk-around video.", + '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.", + '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.", + 'A video has already been uploaded for this claim.', ); } @@ -10025,14 +10029,14 @@ export class ClaimRequestManagementService { ); await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $set: { "media.videoCaptureId": videoDoc._id }, + $set: { 'media.videoCaptureId': videoDoc._id }, $push: { history: { - type: "VIDEO_CAPTURE_UPLOADED", + type: 'VIDEO_CAPTURE_UPLOADED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -10046,12 +10050,12 @@ export class ClaimRequestManagementService { return { claimRequestId: claimCase._id.toString(), videoId: videoDoc._id.toString(), - message: "Video capture uploaded successfully.", + 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"); + this.logger.error('setVideoCaptureV2 failed', error); + throw new InternalServerErrorException('Failed to upload video capture'); } } @@ -10062,8 +10066,8 @@ export class ClaimRequestManagementService { const r = claimCase?.evaluation?.damageExpertResend; if (!r) return false; if ( - typeof r.resendDescription === "string" && - r.resendDescription.trim() !== "" + typeof r.resendDescription === 'string' && + r.resendDescription.trim() !== '' ) { return true; } @@ -10107,12 +10111,12 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can submit an objection", + '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.", + 'An objection has already been submitted for this claim.', ); } @@ -10125,7 +10129,7 @@ export class ClaimRequestManagementService { if (claimCase.evaluation?.damageExpertReplyFinal) { throw new ConflictException( - "The expert already submitted the final reply after objection; submit accept/reject via the owner signer.", + 'The expert already submitted the final reply after objection; submit accept/reject via the owner signer.', ); } @@ -10137,7 +10141,7 @@ export class ClaimRequestManagementService { const newPartsIn = body.newParts ?? []; if (partsIn.length === 0 && newPartsIn.length === 0) { throw new BadRequestException( - "Provide at least one entry in objectionParts and/or newParts.", + 'Provide at least one entry in objectionParts and/or newParts.', ); } @@ -10149,7 +10153,7 @@ export class ClaimRequestManagementService { ) { if (objectionDisallowedDueToOutstandingFactorWorkflow(claimCase)) { throw new BadRequestException( - "Objections are paused while factor files are uploading or the expert is validating repair factors.", + 'Objections are paused while factor files are uploading or the expert is validating repair factors.', ); } @@ -10165,8 +10169,8 @@ export class ClaimRequestManagementService { 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.", + 'No open objection window. Use this after a priced insurer-review step without a recorded final approval, ' + + 'or while completing an unpaid expert resend.', ); } @@ -10176,7 +10180,7 @@ export class ClaimRequestManagementService { !activeExpert?.parts?.length ) { throw new BadRequestException( - "A priced assessment is required before you can object.", + 'A priced assessment is required before you can object.', ); } @@ -10204,11 +10208,11 @@ export class ClaimRequestManagementService { partId: parseCatalogPartIdInput(p.partId)!, reason: p.reason?.trim() || undefined, partPrice: - p.partPrice != null && String(p.partPrice).trim() !== "" + p.partPrice != null && String(p.partPrice).trim() !== '' ? normalizeMoneyAmountString(String(p.partPrice)) : undefined, partSalary: - p.partSalary != null && String(p.partSalary).trim() !== "" + p.partSalary != null && String(p.partSalary).trim() !== '' ? normalizeMoneyAmountString(String(p.partSalary)) : undefined, typeOfDamage: @@ -10238,7 +10242,7 @@ export class ClaimRequestManagementService { for (const np of newParts) { const name = np.partName?.trim(); if (!name) continue; - const side = String(np.side ?? "").trim(); + const side = String(np.side ?? '').trim(); const row = { id: null as number | null, name, @@ -10270,26 +10274,26 @@ export class ClaimRequestManagementService { $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, + '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(), + 'evaluation.damageExpertResend.fulfilledAt': new Date(), }), }, $unset: { - "evaluation.ownerPricedPartsApproval": "", - "evaluation.ownerInsurerApproval": "", + 'evaluation.ownerPricedPartsApproval': '', + 'evaluation.ownerInsurerApproval': '', }, $push: { history: { - type: "USER_OBJECTION_SUBMITTED", + type: 'USER_OBJECTION_SUBMITTED', actor: { actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: { @@ -10304,8 +10308,8 @@ export class ClaimRequestManagementService { return objectionPayload; } catch (error) { if (error instanceof HttpException) throw error; - this.logger.error("handleUserObjectionV2 failed", error); - throw new InternalServerErrorException("Failed to submit objection"); + this.logger.error('handleUserObjectionV2 failed', error); + throw new InternalServerErrorException('Failed to submit objection'); } } @@ -10335,26 +10339,26 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner can submit a satisfaction rating.", + '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.", + '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.", + '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"], + [ratingDto.progressSpeed, 'progressSpeed'], + [ratingDto.registrationEase, 'registrationEase'], + [ratingDto.overallEvaluation, 'overallEvaluation'], ] as const) { const v = score(key); if (Number.isNaN(v) || v < 0 || v > 5) { @@ -10376,11 +10380,11 @@ export class ClaimRequestManagementService { $set: { userRating }, $push: { history: { - type: "USER_RATING_SUBMITTED", + type: 'USER_RATING_SUBMITTED', actor: { actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }, timestamp: new Date(), metadata: {}, @@ -10413,20 +10417,20 @@ export class ClaimRequestManagementService { claimStatus: ClaimStatus; currentStep?: ClaimWorkflowStep; accepted: boolean; - phase?: "PRICED_PARTS_FOR_FACTORS" | "FINAL_APPROVAL"; + phase?: 'PRICED_PARTS_FOR_FACTORS' | 'FINAL_APPROVAL'; fanavaran?: FanavaranAutoSubmitResult; fanavaranExpertise?: FanavaranExpertiseSubmitResult; }> { if (!Types.ObjectId.isValid(claimRequestId)) { - throw new BadRequestException("Invalid claim request id"); + throw new BadRequestException('Invalid claim request id'); } if (!signFile) { - throw new BadRequestException("A signature file is required"); + throw new BadRequestException('A signature file is required'); } const claimCase = await this.claimCaseDbService.findById(claimRequestId); if (!claimCase) { - throw new NotFoundException("Claim request not found"); + throw new NotFoundException('Claim request not found'); } const effectiveUserId = await this.resolveClaimEffectiveUserId( @@ -10438,7 +10442,7 @@ export class ClaimRequestManagementService { claimCase, effectiveUserId, actor as { username?: string }, - "Only the claim owner (damaged party) can sign at this step.", + 'Only the claim owner (damaged party) can sign at this step.', ); if (!claimCaseStatusAllowsOwnerInsurerSignStep(claimCase.status)) { @@ -10448,7 +10452,7 @@ export class ClaimRequestManagementService { } 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 ?? "")}`, + `Signing is only allowed at workflow step ${ClaimWorkflowStep.INSURER_REVIEW}. Current: ${String(claimCase.workflow?.currentStep ?? '')}`, ); } @@ -10457,7 +10461,7 @@ export class ClaimRequestManagementService { claimCase.evaluation?.damageExpertReply; if (!active?.submittedAt) { throw new BadRequestException( - "No expert reply is available to sign off on yet.", + 'No expert reply is available to sign off on yet.', ); } @@ -10473,9 +10477,9 @@ export class ClaimRequestManagementService { 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.", + '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.', ); } @@ -10484,7 +10488,7 @@ export class ClaimRequestManagementService { claimCase.evaluation?.ownerInsurerApproval?.signedAt ) { throw new ConflictException( - "Claim already has a final approval record; refresh the claim state.", + 'Claim already has a final approval record; refresh the claim state.', ); } if ( @@ -10492,7 +10496,7 @@ export class ClaimRequestManagementService { claimCase.evaluation?.ownerInsurerApproval?.signedAt ) { throw new ConflictException( - "You have already submitted a signature for this claim.", + 'You have already submitted a signature for this claim.', ); } @@ -10512,8 +10516,8 @@ export class ClaimRequestManagementService { const historyActor = { actorId: new Types.ObjectId(effectiveUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "user", + actorName: claimCase.owner?.fullName || 'User', + actorType: 'user', }; /** Mixed reply: priced lines acceptance before factor uploads */ @@ -10523,12 +10527,12 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.REJECTED, claimStatus: ClaimStatus.REJECTED, - "evaluation.ownerPricedPartsApproval": scopedApprovalPayload, - "workflow.nextStep": null, + 'evaluation.ownerPricedPartsApproval': scopedApprovalPayload, + 'workflow.nextStep': null, }, $push: { history: { - type: "OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS", + type: 'OWNER_REJECTED_PRICED_PARTS_BEFORE_FACTORS', actor: historyActor, timestamp: signedAt, metadata: {}, @@ -10537,27 +10541,27 @@ export class ClaimRequestManagementService { }); return { message: - "Your rejection has been recorded. This claim is marked rejected and will not proceed.", + '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", + phase: 'PRICED_PARTS_FOR_FACTORS', }; } await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { $set: { claimStatus: ClaimStatus.NEEDS_REVISION, - "evaluation.ownerPricedPartsApproval": scopedApprovalPayload, - "workflow.currentStep": + 'evaluation.ownerPricedPartsApproval': scopedApprovalPayload, + 'workflow.currentStep': ClaimWorkflowStep.OWNER_UPLOAD_FACTOR_DOCUMENTS, - "workflow.nextStep": ClaimWorkflowStep.EXPERT_COST_EVALUATION, + 'workflow.nextStep': ClaimWorkflowStep.EXPERT_COST_EVALUATION, }, $push: { history: { - type: "OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD", + type: 'OWNER_SIGNED_PRICED_PARTS_PENDING_FACTOR_UPLOAD', actor: historyActor, timestamp: signedAt, metadata: {}, @@ -10567,13 +10571,13 @@ export class ClaimRequestManagementService { 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.", + '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", + phase: 'PRICED_PARTS_FOR_FACTORS', }; } @@ -10583,12 +10587,12 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.REJECTED, claimStatus: ClaimStatus.REJECTED, - "evaluation.ownerInsurerApproval": scopedApprovalPayload, - "workflow.nextStep": null, + 'evaluation.ownerInsurerApproval': scopedApprovalPayload, + 'workflow.nextStep': null, }, $push: { history: { - type: "OWNER_REJECTED_INSURER_APPROVAL_PRICING", + type: 'OWNER_REJECTED_INSURER_APPROVAL_PRICING', actor: historyActor, timestamp: signedAt, metadata: {}, @@ -10597,13 +10601,13 @@ export class ClaimRequestManagementService { }); return { message: - "Your rejection has been recorded. This claim is marked rejected and will not proceed.", + '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", + phase: 'FINAL_APPROVAL', }; } @@ -10615,14 +10619,14 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.COMPLETED, claimStatus: ClaimStatus.APPROVED, - "evaluation.ownerInsurerApproval": scopedApprovalPayload, - "workflow.currentStep": ClaimWorkflowStep.CLAIM_COMPLETED, - "workflow.nextStep": ClaimWorkflowStep.CLAIM_COMPLETED, + 'evaluation.ownerInsurerApproval': scopedApprovalPayload, + 'workflow.currentStep': ClaimWorkflowStep.CLAIM_COMPLETED, + 'workflow.nextStep': ClaimWorkflowStep.CLAIM_COMPLETED, }, $push: { - "workflow.completedSteps": ClaimWorkflowStep.INSURER_REVIEW, + 'workflow.completedSteps': ClaimWorkflowStep.INSURER_REVIEW, history: { - type: "OWNER_SIGNED_INSURER_APPROVAL", + type: 'OWNER_SIGNED_INSURER_APPROVAL', actor: historyActor, timestamp: signedAt, metadata: {}, @@ -10633,9 +10637,9 @@ export class ClaimRequestManagementService { const fanavaran = await this.autoSubmitToFanavaranV2OnClaimCompleted(claimRequestId); - let message = "Your signature has been recorded. The claim is completed."; + let message = 'Your signature has been recorded. The claim is completed.'; if (fanavaran.submitted) { - message += " The claim was sent to Fanavaran successfully."; + message += ' The claim was sent to Fanavaran successfully.'; } else if (fanavaran.warning) { message += ` ${fanavaran.warning}`; } @@ -10647,7 +10651,7 @@ export class ClaimRequestManagementService { claimStatus: ClaimStatus.APPROVED, currentStep: ClaimWorkflowStep.CLAIM_COMPLETED, accepted: true, - phase: "FINAL_APPROVAL", + phase: 'FINAL_APPROVAL', fanavaran, fanavaranExpertise, }; @@ -10671,7 +10675,7 @@ export class ClaimRequestManagementService { expertInitiated: true, initiatedByFieldExpertId: expertOid, }, - { select: "_id", lean: true }, + { select: '_id', lean: true }, ) .then((docs) => docs.map((d) => (d as any)._id)); const claimOr: Record[] = [ @@ -10689,16 +10693,16 @@ export class ClaimRequestManagementService { .find( { registrarInitiated: true, - creationMethod: "IN_PERSON", + creationMethod: 'IN_PERSON', initiatedByRegistrarId: new Types.ObjectId(currentUserId), }, - { select: "_id", lean: true }, + { 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) }, + { 'owner.userId': new Types.ObjectId(currentUserId) }, ...(registrarBlameIds.length ? [{ blameRequestId: { $in: registrarBlameIds } }] : []), @@ -10740,9 +10744,9 @@ export class ClaimRequestManagementService { // at claim-creation time and always has the correct damaged-party userId. const snapshotPartyFilter = idVariants.length === 1 - ? { "snapshot.parties.person.userId": idVariants[0] } + ? { 'snapshot.parties.person.userId': idVariants[0] } : idVariants.length > 1 - ? { "snapshot.parties.person.userId": { $in: idVariants } } + ? { 'snapshot.parties.person.userId': { $in: idVariants } } : null; const [ @@ -10769,7 +10773,7 @@ export class ClaimRequestManagementService { : ({ $or: partyBlameOr } as any), { lean: true, - select: "type parties expert.decision blameStatus", + select: 'type parties expert.decision blameStatus', }, ) : Promise.resolve([]), @@ -10823,7 +10827,7 @@ export class ClaimRequestManagementService { $in: blameIdsForList.map((id) => new Types.ObjectId(id)), }, }, - { lean: true, select: "type creationMethod status" }, + { lean: true, select: 'type creationMethod status' }, )) as any[]) : []; const blameByIdForList = new Map( @@ -10839,8 +10843,8 @@ export class ClaimRequestManagementService { publicId: c.publicId, requestNo: c.requestNo, status: c.status, - claimStatus: c.claimStatus || "PENDING", - currentStep: c.workflow?.currentStep || "", + claimStatus: c.claimStatus || 'PENDING', + currentStep: c.workflow?.currentStep || '', createdAt: c.createdAt, blameRequestId: c.blameRequestId?.toString(), partyIdentities: c.parties ?? c.snapshot?.parties, @@ -10897,8 +10901,8 @@ export class ClaimRequestManagementService { }; } catch (error) { if (error instanceof HttpException) throw error; - this.logger.error("getMyClaimsV2 failed", error); - throw new InternalServerErrorException("Failed to get claims list"); + this.logger.error('getMyClaimsV2 failed', error); + throw new InternalServerErrorException('Failed to get claims list'); } } @@ -10914,7 +10918,7 @@ export class ClaimRequestManagementService { try { const claim = await this.claimCaseDbService.findById(claimRequestId); if (!claim) { - throw new NotFoundException("Claim request not found"); + throw new NotFoundException('Claim request not found'); } await this.assertActorCanViewClaimV2(claim, currentUserId, actor); @@ -10922,7 +10926,7 @@ export class ClaimRequestManagementService { ? (( await this.blameRequestDbService.find( { _id: new Types.ObjectId(claim.blameRequestId.toString()) }, - { lean: true, select: "type creationMethod" }, + { lean: true, select: 'type creationMethod' }, ) )[0] ?? null) : null; @@ -10953,7 +10957,7 @@ export class ClaimRequestManagementService { const carAnglesData = claim.media?.carAngles as any; const damagedPartsForAngles = claim.media?.damagedParts as any; const carAngles: Record = {}; - for (const k of ["front", "back", "left", "right"]) { + for (const k of ['front', 'back', 'left', 'right']) { const cap = getClaimCarAngleCaptureBlob( carAnglesData, damagedPartsForAngles, @@ -10991,7 +10995,7 @@ export class ClaimRequestManagementService { )[0] || { id: null, name: rk, - side: "", + side: '', label_fa: rk, catalogKey: rk, }; @@ -11040,9 +11044,9 @@ export class ClaimRequestManagementService { : undefined; const maskSheba = (s?: string) => - s ? s.replace(/^(.{4})(.*)(.{4})$/, "IR$1************$3") : undefined; + s ? s.replace(/^(.{4})(.*)(.{4})$/, 'IR$1************$3') : undefined; const maskNationalCode = (s?: string) => - s ? s.replace(/^(.{2})(.*)(.{2})$/, "$1******$3") : undefined; + s ? s.replace(/^(.{2})(.*)(.{2})$/, '$1******$3') : undefined; const isExpertViewer = actor?.role === RoleEnum.FIELD_EXPERT || actor?.role === RoleEnum.REGISTRAR; @@ -11098,8 +11102,8 @@ export class ClaimRequestManagementService { publicId: claim.publicId, requestNo: claim.requestNo, status: claim.status, - claimStatus: claim.claimStatus || "PENDING", - currentStep: claim.workflow?.currentStep || "", + claimStatus: claim.claimStatus || 'PENDING', + currentStep: claim.workflow?.currentStep || '', nextStep: claim.workflow?.nextStep, blameRequestId: claim.blameRequestId?.toString(), blameRequestNo: claim.blameRequestNo, @@ -11151,13 +11155,13 @@ export class ClaimRequestManagementService { }; } catch (error) { if (error instanceof HttpException) throw error; - this.logger.error("getClaimDetailsV2 failed", error); - throw new InternalServerErrorException("Failed to get claim details"); + this.logger.error('getClaimDetailsV2 failed', error); + throw new InternalServerErrorException('Failed to get claim details'); } } private async generateUniqueClaimNumber(): Promise { - const prefix = "CL"; + const prefix = 'CL'; const randomPart = Math.floor(10000 + Math.random() * 90000); // 5 digits return `${prefix}${randomPart}`; } @@ -11169,7 +11173,7 @@ export class ClaimRequestManagementService { ); } - private partyHasSignedOnBlame(blame: any, role: "FIRST" | "SECOND"): boolean { + private partyHasSignedOnBlame(blame: any, role: 'FIRST' | 'SECOND'): boolean { const party = (blame.parties ?? []).find((p: any) => p?.role === role); return !!party?.confirmation; } @@ -11183,25 +11187,25 @@ export class ClaimRequestManagementService { !(blame.expert?.decision as any)?.fields?.accidentWay ) { throw new BadRequestException( - "Submit accident fields before uploading required documents.", + 'Submit accident fields before uploading required documents.', ); } const isCarBody = - blame?.type === BlameRequestType.CAR_BODY || blame?.type === "CAR_BODY"; + blame?.type === BlameRequestType.CAR_BODY || blame?.type === 'CAR_BODY'; if (isCarBody) { - if (!this.partyHasSignedOnBlame(blame, "FIRST")) { + if (!this.partyHasSignedOnBlame(blame, 'FIRST')) { throw new BadRequestException( - "Upload documents after the party has signed.", + 'Upload documents after the party has signed.', ); } return; } if ( - !this.partyHasSignedOnBlame(blame, "FIRST") || - !this.partyHasSignedOnBlame(blame, "SECOND") + !this.partyHasSignedOnBlame(blame, 'FIRST') || + !this.partyHasSignedOnBlame(blame, 'SECOND') ) { throw new BadRequestException( - "Both parties must sign before uploading required documents.", + 'Both parties must sign before uploading required documents.', ); } } @@ -11209,25 +11213,25 @@ export class ClaimRequestManagementService { private assertV3ClaimPartsPhase(blame: any): void { if (!(blame.expert?.decision as any)?.fields?.accidentWay) { throw new BadRequestException( - "Submit accident fields before part selection.", + 'Submit accident fields before part selection.', ); } const isCarBody = - blame?.type === BlameRequestType.CAR_BODY || blame?.type === "CAR_BODY"; + blame?.type === BlameRequestType.CAR_BODY || blame?.type === 'CAR_BODY'; if (isCarBody) { - if (!this.partyHasSignedOnBlame(blame, "FIRST")) { + if (!this.partyHasSignedOnBlame(blame, 'FIRST')) { throw new BadRequestException( - "Part selection requires the party signature.", + 'Part selection requires the party signature.', ); } return; } if ( - !this.partyHasSignedOnBlame(blame, "FIRST") || - !this.partyHasSignedOnBlame(blame, "SECOND") + !this.partyHasSignedOnBlame(blame, 'FIRST') || + !this.partyHasSignedOnBlame(blame, 'SECOND') ) { throw new BadRequestException( - "Both parties must sign before part selection.", + 'Both parties must sign before part selection.', ); } } @@ -11249,7 +11253,7 @@ export class ClaimRequestManagementService { if (!allowed.includes(current)) { throw new BadRequestException( hint ?? - `Invalid workflow step. Expected ${allowed.join(" or ")}, but current step is ${current}`, + `Invalid workflow step. Expected ${allowed.join(' or ')}, but current step is ${current}`, ); } } @@ -11294,7 +11298,7 @@ export class ClaimRequestManagementService { } if (!(blame.expert?.decision as any)?.fields?.accidentWay) { throw new BadRequestException( - "Submit accident fields before selecting outer parts.", + 'Submit accident fields before selecting outer parts.', ); } @@ -11302,8 +11306,8 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.SELECTING_OUTER_PARTS, claimStatus: ClaimStatus.PENDING, - "workflow.currentStep": ClaimWorkflowStep.SELECT_OUTER_PARTS, - "workflow.nextStep": ClaimWorkflowStep.SELECT_OTHER_PARTS, + 'workflow.currentStep': ClaimWorkflowStep.SELECT_OUTER_PARTS, + 'workflow.nextStep': ClaimWorkflowStep.SELECT_OTHER_PARTS, }, }); } @@ -11312,17 +11316,17 @@ export class ClaimRequestManagementService { const blame = await this.loadBlameForV3Claim(claimCase); if (!blame) { throw new BadRequestException( - "V3 claim flow requires a linked blame file.", + '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.", + '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.", + 'V3 claim flow requires an expert-initiated blame file.', ); } return blame; @@ -11351,7 +11355,7 @@ export class ClaimRequestManagementService { !(claimCase as any)?.requiresFileMakerApproval; const isCarBody = blame?.type === BlameRequestType.CAR_BODY || - (blame as any)?.type === "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. @@ -11381,9 +11385,9 @@ export class ClaimRequestManagementService { return { ...base, requiredDocuments: preCaptureDocs, - captureSequencePhase: "parts", + 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.", + '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, @@ -11407,8 +11411,8 @@ export class ClaimRequestManagementService { requiredDocuments: base.requiredDocuments.filter( (d) => !d.preferUploadDuringCapture, ), - captureSequencePhase: "parts", - captureSequenceHint: "Select outer damaged parts before capture.", + captureSequencePhase: 'parts', + captureSequenceHint: 'Select outer damaged parts before capture.', totalRemaining: base.damagedParts.filter((p) => !p.captured).length, }; } @@ -11419,9 +11423,9 @@ export class ClaimRequestManagementService { requiredDocuments: base.requiredDocuments.filter( (d) => !d.preferUploadDuringCapture, ), - captureSequencePhase: "parts", + captureSequencePhase: 'parts', captureSequenceHint: - "Select other damaged parts (and car green card when required) before capture.", + 'Select other damaged parts (and car green card when required) before capture.', }; } @@ -11446,9 +11450,9 @@ export class ClaimRequestManagementService { ); const guiltyAreaDoc = { key: GUILTY_DAMAGE_AREA_DOC_KEY, - label_fa: "تصویر نقطه آسیب‌دیده مقصر", - label_en: "Guilty Car Damaged Area", - category: "guilty_party", + label_fa: 'تصویر نقطه آسیب‌دیده مقصر', + label_en: 'Guilty Car Damaged Area', + category: 'guilty_party', required: true, uploaded: guiltyAreaUploaded, preferUploadDuringCapture: true, @@ -11485,9 +11489,9 @@ export class ClaimRequestManagementService { return { ...base, requiredDocuments: [], - captureSequencePhase: "complete", + captureSequencePhase: 'complete', captureSequenceHint: - "Upload the walk-around car video (car-capture), then the blame accident video.", + 'Upload the walk-around car video (car-capture), then the blame accident video.', totalRemaining: claimCase.media?.videoCaptureId ? 0 : 1, }; } @@ -11501,9 +11505,9 @@ export class ClaimRequestManagementService { return { ...base, requiredDocuments: [], - captureSequencePhase: "complete", + captureSequencePhase: 'complete', captureSequenceHint: - "Walk-around video uploaded. Upload the blame accident video to finalise.", + 'Walk-around video uploaded. Upload the blame accident video to finalise.', totalRemaining: 0, }; } @@ -11531,7 +11535,7 @@ export class ClaimRequestManagementService { !(claimCase as any)?.requiresFileMakerApproval; const isCarBodyBlame = blame?.type === BlameRequestType.CAR_BODY || - (blame as any)?.type === "CAR_BODY"; + (blame as any)?.type === 'CAR_BODY'; // guilty_damage_area is an extra capture-phase doc key for V4 THIRD_PARTY const isGuiltyDamageAreaDoc = @@ -11548,7 +11552,7 @@ export class ClaimRequestManagementService { this.assertV3ClaimWorkflowStep( claimCase, ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "Upload chassis and engine photos during capture after damaged-part photos and car angles.", + 'Upload chassis and engine photos during capture after damaged-part photos and car angles.', ); if ( !this.claimV3StepCompleted( @@ -11557,7 +11561,7 @@ export class ClaimRequestManagementService { ) ) { throw new BadRequestException( - "Complete outer and other part selection before capture-phase vehicle documents.", + 'Complete outer and other part selection before capture-phase vehicle documents.', ); } const captureProgress = getClaimCaptureProgress(claimCase, { @@ -11566,17 +11570,17 @@ export class ClaimRequestManagementService { }); if (!captureProgress.partsComplete) { throw new BadRequestException( - "Upload photos for all selected damaged parts before chassis or engine photos.", + '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.", + 'Capture all four car angles before chassis or engine photos.', ); } } else { this.assertV3ClaimDocumentsPhase(blame, { - skipAccidentFieldsCheck: actor?.role === "file_maker", + skipAccidentFieldsCheck: actor?.role === 'file_maker', }); if (!this.isV3InitialDocumentsPhase(claimCase)) { throw new BadRequestException( @@ -11622,7 +11626,7 @@ export class ClaimRequestManagementService { if (this.isV3InitialDocumentsPhase(claimCase)) { this.assertV3ClaimDocumentsPhase(blame, { - skipAccidentFieldsCheck: actor?.role === "file_maker", + skipAccidentFieldsCheck: actor?.role === 'file_maker', }); } else if ( claimCase.workflow?.currentStep === ClaimWorkflowStep.CAPTURE_PART_DAMAGES @@ -11658,7 +11662,7 @@ export class ClaimRequestManagementService { this.assertV3ClaimWorkflowStep( refreshed, ClaimWorkflowStep.SELECT_OUTER_PARTS, - "Select outer parts after accident fields and required documents.", + 'Select outer parts after accident fields and required documents.', ); const result = await this.selectOuterPartsV2( @@ -11688,7 +11692,7 @@ export class ClaimRequestManagementService { this.assertV3ClaimWorkflowStep( claimCase, ClaimWorkflowStep.SELECT_OTHER_PARTS, - "Select outer parts before other parts.", + 'Select outer parts before other parts.', ); if ( !this.claimV3StepCompleted( @@ -11697,7 +11701,7 @@ export class ClaimRequestManagementService { ) ) { throw new BadRequestException( - "Complete outer part selection before selecting other parts.", + 'Complete outer part selection before selecting other parts.', ); } @@ -11706,7 +11710,7 @@ export class ClaimRequestManagementService { : []; if ( !Array.isArray((body as any)?.otherParts) && - typeof (body as any)?.otherParts === "string" + typeof (body as any)?.otherParts === 'string' ) { try { const parsed = JSON.parse((body as any).otherParts); @@ -11720,19 +11724,19 @@ export class ClaimRequestManagementService { const nationalCode = claimCase.money?.nationalCodeOfInsurer; const updatePayload: any = { - "damage.otherParts": otherParts.length > 0 ? otherParts : undefined, + 'damage.otherParts': otherParts.length > 0 ? otherParts : undefined, status: ClaimCaseStatus.CAPTURING_PART_DAMAGES, - "workflow.currentStep": ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "workflow.nextStep": ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, + 'workflow.currentStep': ClaimWorkflowStep.CAPTURE_PART_DAMAGES, + 'workflow.nextStep': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, $push: { - "workflow.completedSteps": ClaimWorkflowStep.SELECT_OTHER_PARTS, + 'workflow.completedSteps': ClaimWorkflowStep.SELECT_OTHER_PARTS, history: { - type: "V3_STEP_COMPLETED", + type: 'V3_STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "Actor", + actorName: claimCase.owner?.fullName || 'Actor', actorType: - actor?.role === RoleEnum.REGISTRAR ? "registrar" : "field_expert", + actor?.role === RoleEnum.REGISTRAR ? 'registrar' : 'field_expert', }, timestamp: new Date(), metadata: { @@ -11749,7 +11753,7 @@ export class ClaimRequestManagementService { updatePayload, ); if (!updatedClaim) { - throw new InternalServerErrorException("Failed to update claim case"); + throw new InternalServerErrorException('Failed to update claim case'); } return { @@ -11760,7 +11764,7 @@ export class ClaimRequestManagementService { ? { shebaNumber: String(shebaNumber).replace( /^(.{4})(.*)(.{4})$/, - "IR$1************$3", + 'IR$1************$3', ), } : {}), @@ -11768,14 +11772,14 @@ export class ClaimRequestManagementService { ? { nationalCodeOfOwner: String(nationalCode).replace( /^(.{2})(.*)(.{2})$/, - "$1******$3", + '$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).", + 'Other parts saved. Proceed to damaged-part photos and car angles (capture-part).', }; } @@ -11795,7 +11799,7 @@ export class ClaimRequestManagementService { const skipMetalPlate = !!(blame as any).isMadeByFileMaker; if (!fileDetail) { - throw new BadRequestException("Video file is required."); + throw new BadRequestException('Video file is required.'); } if (claimCase.media?.videoCaptureId) { // FILE_REVIEWER re-reviewing after a FileMaker rejection: allow replacing @@ -11803,7 +11807,7 @@ export class ClaimRequestManagementService { // setVideoCaptureV2's own conflict check doesn't block the upload. if (actor?.role === RoleEnum.FILE_REVIEWER) { await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { - $unset: { "media.videoCaptureId": "" }, + $unset: { 'media.videoCaptureId': '' }, }); claimCase.media = { ...(claimCase.media ?? {}), @@ -11811,7 +11815,7 @@ export class ClaimRequestManagementService { } as any; } else { throw new ConflictException( - "A walk-around video has already been uploaded for this claim.", + 'A walk-around video has already been uploaded for this claim.', ); } } @@ -11830,19 +11834,19 @@ export class ClaimRequestManagementService { }); if (!captureProgress.partsComplete) { throw new BadRequestException( - "Upload photos for all selected damaged parts before the walk-around video.", + '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.", + '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.", + ? '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.', ); } @@ -11862,24 +11866,24 @@ export class ClaimRequestManagementService { if (!(blame as any).isMadeByFileMaker) { await this.claimCaseDbService.findByIdAndUpdate(claimRequestId, { $set: { - "workflow.currentStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - "workflow.nextStep": undefined, + 'workflow.currentStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, + 'workflow.nextStep': undefined, }, $push: { - "workflow.completedSteps": + 'workflow.completedSteps': ClaimWorkflowStep.UPLOAD_REQUIRED_DOCUMENTS, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", - actorType: "field_expert", + 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.", + 'V3 walk-around video uploaded. Upload blame accident video to finalise.', v3InPersonFlow: true, }, }, @@ -11893,26 +11897,26 @@ export class ClaimRequestManagementService { $set: { status: ClaimCaseStatus.WAITING_FOR_DAMAGE_EXPERT, claimStatus: ClaimStatus.PENDING, - "workflow.currentStep": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, - "workflow.nextStep": ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, + 'workflow.currentStep': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, + 'workflow.nextStep': ClaimWorkflowStep.EXPERT_DAMAGE_ASSESSMENT, }, $push: { - "workflow.completedSteps": ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, + 'workflow.completedSteps': ClaimWorkflowStep.USER_SUBMISSION_COMPLETE, history: { - type: "STEP_COMPLETED", + type: 'STEP_COMPLETED', actor: { actorId: new Types.ObjectId(currentUserId), - actorName: claimCase.owner?.fullName || "User", + actorName: claimCase.owner?.fullName || 'User', actorType: actor?.role === RoleEnum.FILE_REVIEWER - ? "file_reviewer" - : "user", + ? '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.", + 'V4/V5 walk-around video uploaded. Claim ready for damage expert review.', v3InPersonFlow: true, }, }, @@ -11949,7 +11953,7 @@ export class ClaimRequestManagementService { this.assertV3ClaimWorkflowStep( claimCase, ClaimWorkflowStep.CAPTURE_PART_DAMAGES, - "Select other parts before capturing damaged parts and angles.", + 'Select other parts before capturing damaged parts and angles.', ); if ( !this.claimV3StepCompleted( @@ -11958,7 +11962,7 @@ export class ClaimRequestManagementService { ) ) { throw new BadRequestException( - "Complete other part selection before capture.", + 'Complete other part selection before capture.', ); } diff --git a/src/core/config/fanavaran-client.config.ts b/src/core/config/fanavaran-client.config.ts index b87af8a..e57c87e 100644 --- a/src/core/config/fanavaran-client.config.ts +++ b/src/core/config/fanavaran-client.config.ts @@ -1,9 +1,9 @@ -export type FanavaranClientKey = "parsian" | "tejaratno" | "moallem"; +export type FanavaranClientKey = 'parsian' | 'tejaratno' | 'moallem'; const FANAVARAN_API_ROOTS: Record = { - parsian: "https://apimanager.iraneit.com/BimeApiManager/api", - tejaratno: "https://apimanager.iraneit.com/BimeApiManager/api", - moallem: "https://apimanager.iraneit.com/BimeApiManager/api", + parsian: 'https://apimanager.iraneit.com/BimeApiManager/api', + tejaratno: 'https://apimanager.iraneit.com/BimeApiManager/api', + moallem: 'https://apimanager.iraneit.com/BimeApiManager/api', }; export function getFanavaranApiRoot(clientKey: FanavaranClientKey): string { @@ -17,9 +17,9 @@ export function getFanavaranLookupBaseUrl( } export const FANAVARAN_CLIENT_KEYS: readonly FanavaranClientKey[] = [ - "parsian", - "tejaratno", - "moallem", + 'parsian', + 'tejaratno', + 'moallem', ] as const; /** Swagger `@ApiParam({ enum })` value — keep in sync with {@link FANAVARAN_CLIENT_KEYS}. */ @@ -40,7 +40,7 @@ export function normalizeFanavaranClientKey(value: string): FanavaranClientKey { return normalized; } throw new Error( - `Invalid Fanavaran client "${value}". Expected one of: ${FANAVARAN_CLIENT_KEYS.join(", ")}`, + `Invalid Fanavaran client "${value}". Expected one of: ${FANAVARAN_CLIENT_KEYS.join(', ')}`, ); } @@ -126,15 +126,15 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record< FanavaranClientProfile > = { tejaratno: { - key: "tejaratno", + key: 'tejaratno', auth: { - appName: "fanhab", - secret: "5Fa@N#A2B", - username: "fanhabUser", - password: "Fan#@2U$3er", - corpId: "3539", - contractId: "263", - location: "100", + appName: 'fanhab', + secret: '5Fa@N#A2B', + username: 'fanhabUser', + password: 'Fan#@2U$3er', + corpId: '3539', + contractId: '263', + location: '100', }, defaults: { ...SHARED_FANAVARAN_DEFAULTS, @@ -146,15 +146,15 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record< }, }, parsian: { - key: "parsian", + key: 'parsian', auth: { - appName: "ParsianService", - secret: "P@r30@n$erv!ce", - username: "ParsianServiceUser", - password: "P@r30@n123", - corpId: "543", - contractId: "28", - location: "210050", + appName: 'ParsianService', + secret: 'P@r30@n$erv!ce', + username: 'ParsianServiceUser', + password: 'P@r30@n123', + corpId: '543', + contractId: '28', + location: '110011', }, defaults: { ...SHARED_FANAVARAN_DEFAULTS, @@ -168,15 +168,15 @@ export const SEED_FANAVARAN_CLIENT_PROFILES: Record< }, }, moallem: { - key: "moallem", + key: 'moallem', auth: { - appName: "ItTalie", - secret: "itT@l!3@api", - username: "itTalieUser", - password: "itT@l!3@user", - corpId: "5650", - contractId: "304", - location: "1", + appName: 'ItTalie', + secret: 'itT@l!3@api', + username: 'itTalieUser', + password: 'itT@l!3@user', + corpId: '5650', + contractId: '304', + location: '1', }, defaults: { ...SHARED_FANAVARAN_DEFAULTS, @@ -217,11 +217,11 @@ export function resolveFanavaranClientKey(): FanavaranClientKey { } // Optional deployment hint when FANAVARAN_CLIENT is not set. - if (String(process.env.CLIENT_ID ?? "") === "8") { - return "parsian"; + if (String(process.env.CLIENT_ID ?? '') === '8') { + return 'parsian'; } - return "tejaratno"; + return 'tejaratno'; } export function resolveFanavaranClientProfile(): FanavaranClientProfile { @@ -239,10 +239,10 @@ export function getFanavaranClientProfile( /** ثالث uses `contractId`. بدنه uses `hullContractId` when configured. */ export function resolveFanavaranProductContractId( clientKey: FanavaranClientKey, - product: "third-party" | "car-body", + product: 'third-party' | 'car-body', ): string { const profile = getFanavaranClientProfile(clientKey); - if (product === "car-body") { + if (product === 'car-body') { const hull = profile.auth.hullContractId?.trim(); if (hull) return hull; } diff --git a/src/expert-insurer/dto/create-insurer-expert.dto.ts b/src/expert-insurer/dto/create-insurer-expert.dto.ts index 87a8da1..2a142c2 100644 --- a/src/expert-insurer/dto/create-insurer-expert.dto.ts +++ b/src/expert-insurer/dto/create-insurer-expert.dto.ts @@ -1,5 +1,5 @@ -import { ApiProperty, ApiPropertyOptional, OmitType } from "@nestjs/swagger"; -import { Type } from "class-transformer"; +import { ApiProperty, ApiPropertyOptional, OmitType } from '@nestjs/swagger'; +import { Type } from 'class-transformer'; import { IsArray, IsEmail, @@ -10,20 +10,20 @@ import { IsOptional, IsString, ValidateNested, -} from "class-validator"; -import { RoleEnum } from "src/Types&Enums/role.enum"; -import { UserType } from "src/Types&Enums/userType.enum"; +} from 'class-validator'; +import { RoleEnum } from 'src/Types&Enums/role.enum'; +import { UserType } from 'src/Types&Enums/userType.enum'; export class ExpertLocationDto { @ApiProperty({ - example: "210050", - description: "Fanavaran Location / OpBUId", + example: '110011', + description: 'Fanavaran Location / OpBUId', }) @IsString() @IsNotEmpty() id: string; - @ApiProperty({ example: "شعبه غرب" }) + @ApiProperty({ example: 'شعبه غرب' }) @IsString() @IsNotEmpty() name: string; @@ -36,62 +36,62 @@ export class CreateInsurerExpertDto { @Matches(/^\d+$/) expertCode?: string; - @ApiPropertyOptional({ description: "کارشناس مسئول پرونده مالی" }) + @ApiPropertyOptional({ description: 'کارشناس مسئول پرونده مالی' }) @IsOptional() @IsString() @Matches(/^\d+$/) ThirdPartyClaimExpertId?: string; - @ApiPropertyOptional({ description: "کارشناس مسئول پرونده بدنه" }) + @ApiPropertyOptional({ description: 'کارشناس مسئول پرونده بدنه' }) @IsOptional() @IsString() @Matches(/^\d+$/) CarBodyClaimExpertId?: string; - @ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت ثالث مالی" }) + @ApiPropertyOptional({ description: 'کارشناس ارزیاب خسارت ثالث مالی' }) @IsOptional() @IsString() @Matches(/^\d+$/) ThirdPartyExpertiseClaim?: string; - @ApiPropertyOptional({ description: "کارشناس ارزیاب خسارت بدنه" }) + @ApiPropertyOptional({ description: 'کارشناس ارزیاب خسارت بدنه' }) @IsOptional() @IsString() @Matches(/^\d+$/) CarBodyExpertiseClaim?: string; - @ApiProperty({ example: "Ali" }) + @ApiProperty({ example: 'Ali' }) @IsString() @IsNotEmpty() firstName: string; - @ApiProperty({ example: "Ahmadi" }) + @ApiProperty({ example: 'Ahmadi' }) @IsString() @IsNotEmpty() lastName: string; - @ApiProperty({ example: "1234567890" }) + @ApiProperty({ example: '1234567890' }) @IsString() @IsNotEmpty() nationalCode: string; - @ApiProperty({ example: "expert@example.com" }) + @ApiProperty({ example: 'expert@example.com' }) @IsEmail() email: string; - @ApiProperty({ example: "StrongPass!123" }) + @ApiProperty({ example: 'StrongPass!123' }) @IsString() @IsNotEmpty() password: string; - @ApiProperty({ example: "09121234567" }) + @ApiProperty({ example: '09121234567' }) @IsString() @IsNotEmpty() mobile: string; @ApiProperty({ - example: "665f0e5ab74d670939b08920", - description: "Branch id this expert belongs to", + example: '665f0e5ab74d670939b08920', + description: 'Branch id this expert belongs to', }) @IsMongoId() branchId: string; @@ -101,22 +101,22 @@ export class CreateInsurerExpertDto { @IsEnum(UserType) userType?: UserType; - @ApiPropertyOptional({ example: "02112345678" }) + @ApiPropertyOptional({ example: '02112345678' }) @IsOptional() @IsString() phone?: string; - @ApiPropertyOptional({ example: "Tehran" }) + @ApiPropertyOptional({ example: 'Tehran' }) @IsOptional() @IsString() state?: string; - @ApiPropertyOptional({ example: "Tehran" }) + @ApiPropertyOptional({ example: 'Tehran' }) @IsOptional() @IsString() city?: string; - @ApiPropertyOptional({ example: "No. 12, Sample St." }) + @ApiPropertyOptional({ example: 'No. 12, Sample St.' }) @IsOptional() @IsString() address?: string; @@ -124,7 +124,7 @@ export class CreateInsurerExpertDto { @ApiPropertyOptional({ type: [ExpertLocationDto], description: - "Fanavaran Location entries (id = OpBUId). Sent as the HTTP Location header on Fanavaran business calls for this expert.", + 'Fanavaran Location entries (id = OpBUId). Sent as the HTTP Location header on Fanavaran business calls for this expert.', }) @IsOptional() @IsArray() @@ -151,7 +151,7 @@ export class CreateClaimExpertByInsurerDto extends CreateInsurerExpertDto { export class CreateFileMakerByInsurerDto extends OmitType( CreateInsurerExpertDto, - ["ThirdPartyExpertiseClaim", "CarBodyExpertiseClaim"] as const, + ['ThirdPartyExpertiseClaim', 'CarBodyExpertiseClaim'] as const, ) { @ApiPropertyOptional({ enum: [RoleEnum.FILE_MAKER], @@ -162,7 +162,7 @@ export class CreateFileMakerByInsurerDto extends OmitType( export class CreateFileReviewerByInsurerDto extends OmitType( CreateInsurerExpertDto, - ["ThirdPartyClaimExpertId", "CarBodyClaimExpertId"] as const, + ['ThirdPartyClaimExpertId', 'CarBodyClaimExpertId'] as const, ) { @ApiPropertyOptional({ enum: [RoleEnum.FILE_REVIEWER],