From 6775635a816eeb7d441eeec8c05d36b12023737b Mon Sep 17 00:00:00 2001 From: "s.hajizadeh" Date: Mon, 9 Nov 2026 16:31:25 +0330 Subject: [PATCH] read the expert Ids from the db not hardcoded from every flow --- .../claim-request-management.service.ts | 366 +++++++++++++----- .../fanavaran-assigned-expert-ids.spec.ts | 107 +++++ .../fanavaran-stage-fields.spec.ts | 10 +- src/fanavaran/fanavaran-audit.service.ts | 21 +- src/fanavaran/fanavaran-auth.service.ts | 20 +- .../fanavaran-file-role-expert-ids.ts | 12 +- .../fanavaran-http-exception.spec.ts | 76 ++++ src/fanavaran/fanavaran-http-exception.ts | 107 +++++ src/fanavaran/fanavaran-lookup.service.ts | 42 +- .../entities/db-service/expert.db.service.ts | 6 + 10 files changed, 604 insertions(+), 163 deletions(-) create mode 100644 src/claim-request-management/fanavaran-assigned-expert-ids.spec.ts create mode 100644 src/fanavaran/fanavaran-http-exception.spec.ts create mode 100644 src/fanavaran/fanavaran-http-exception.ts diff --git a/src/claim-request-management/claim-request-management.service.ts b/src/claim-request-management/claim-request-management.service.ts index 1c320b7..4d6a027 100644 --- a/src/claim-request-management/claim-request-management.service.ts +++ b/src/claim-request-management/claim-request-management.service.ts @@ -3,7 +3,6 @@ import { isTejaratNotifierLookup, } from "src/fanavaran/tejarat-notifier"; import { - BadGatewayException, BadRequestException, ConflictException, ForbiddenException, @@ -37,7 +36,13 @@ import { assertFileReviewerCanReviewBlameType, resolveFileMakerStageOneExpertId, resolveFileReviewerExpertiseExpertId, + type StaffFanavaranExpertiseCodes, + type StaffFanavaranStageOneCodes, } from "src/fanavaran/fanavaran-file-role-expert-ids"; +import { + extractFanavaranOriginalMessage, + toFanavaranHttpException, +} from "src/fanavaran/fanavaran-http-exception"; import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service"; import { canUserCreateClaim, @@ -119,6 +124,9 @@ import { OuterPartCatalogItem, } from "src/static/outer-car-parts-catalog"; +import { DamageExpertDbService } from "src/users/entities/db-service/damage-expert.db.service"; +import { ExpertDbService } from "src/users/entities/db-service/expert.db.service"; +import { FieldExpertDbService } from "src/users/entities/db-service/field-expert.db.service"; import { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service"; import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.db.service"; import { UserDbService } from "src/users/entities/db-service/user.db.service"; @@ -445,12 +453,11 @@ export class ClaimRequestManagementService { location: "210050", } as const; - /** Tejaratno hardcoded Fanavaran lookup defaults (legacy fallback only). */ + /** Tejaratno hardcoded Fanavaran lookup defaults (legacy fallback only; no expert ids). */ private readonly TEJARATNO_FANAVARAN_DEFAULTS = { AccidentCityId: 701, AccidentReportTypeId: 155, AccidentVehicleUsedId: 1, - ClaimExpertId: 4543092, CompensationReferenceId: 167, CulpritLicenceTypeId: 2, CulpritTypeId: 337, @@ -483,6 +490,9 @@ export class ClaimRequestManagementService { private readonly fanavaranLookupService: FanavaranLookupService, private readonly fileMakerDbService: FileMakerDbService, private readonly fileReviewerDbService: FileReviewerDbService, + private readonly fieldExpertDbService: FieldExpertDbService, + private readonly expertDbService: ExpertDbService, + private readonly damageExpertDbService: DamageExpertDbService, private readonly plateNormalizer: PlateNormalizerService, private readonly fanavaranLocationService: FanavaranLocationService, @@ -1859,13 +1869,16 @@ export class ClaimRequestManagementService { AccidentCityId: number; AccidentReportTypeId: number; AccidentVehicleUsedId: number; - ClaimExpertId: number; CompensationReferenceId: number; CulpritLicenceTypeId: number; CulpritTypeId: number; }; }): Promise> { - const lookupDefaults = input.defaults ?? this.TEJARATNO_FANAVARAN_DEFAULTS; + const lookupDefaults = + input.defaults ?? + this.fanavaranPayloadDefaultsWithoutExpertIds( + this.TEJARATNO_FANAVARAN_DEFAULTS as unknown as Record, + ); const result: Record = { ...lookupDefaults, AccidentCauseId: FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID, @@ -3370,53 +3383,224 @@ export class ClaimRequestManagementService { } } + private fanavaranPayloadDefaultsWithoutExpertIds( + defaults: Record, + ): Record { + const { + ClaimExpertId: _claimExpertId, + ExpertiseClaimExpertId: _expertiseClaimExpertId, + ...rest + } = defaults; + return rest; + } + + private async findStaffDocumentById( + staffId: string, + ): Promise< + | (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) + | null + > { + const loaders = [ + () => this.fileMakerDbService.findById(staffId), + () => this.fileReviewerDbService.findById(staffId), + () => this.fieldExpertDbService.findById(staffId), + () => this.expertDbService.findById(staffId), + () => this.damageExpertDbService.findById(staffId), + ]; + for (const load of loaders) { + const doc = await load(); + if (doc) return doc as StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes; + } + return null; + } + /** - * V4/V5 FileMaker flows: GEN.03 ClaimExpertId from file-maker; GEN.06 from file-reviewer. - * Returns null for non–file-maker blames (tenant defaults apply). + * GEN.03 ClaimExpertId from the staff assigned to this file (never tenant defaults). + * V4/V5 FileMaker → FileMaker codes; otherwise field/blame/claim expert assignment. */ + private async resolveFanavaranBaseClaimExpertId( + blame: { + isMadeByFileMaker?: boolean; + type?: BlameRequestType; + initiatedByFieldExpertId?: unknown; + assignedFileReviewerId?: unknown; + expert?: { + assignedExpertId?: unknown; + decision?: { decidedByExpertId?: unknown }; + }; + }, + claimCase?: { initiatedByFieldExpertId?: unknown } | null, + ): Promise { + if (blame?.type == null) { + throw new BadRequestException({ + code: "FANAVARAN_CLAIM_EXPERT_ID_MISSING", + message: + "Cannot resolve Fanavaran ClaimExpertId: blame product type is missing.", + }); + } + + if (blame.isMadeByFileMaker && blame.initiatedByFieldExpertId) { + const fileMaker = await this.fileMakerDbService.findById( + String(blame.initiatedByFieldExpertId), + ); + if (!fileMaker) { + throw new BadRequestException({ + code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING", + message: + "This FileMaker file cannot be submitted to Fanavaran: FileMaker profile was not found.", + }); + } + assertFileMakerCanCreateBlameType(fileMaker, blame.type); + const id = resolveFileMakerStageOneExpertId(fileMaker, blame.type); + if (id == null) { + throw new BadRequestException({ + code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING", + message: + "This FileMaker file cannot be submitted to Fanavaran: stage-1 claim expert id is missing for this product line.", + }); + } + return id; + } + + const candidateIds = [ + blame.initiatedByFieldExpertId, + blame.expert?.assignedExpertId, + blame.expert?.decision?.decidedByExpertId, + claimCase?.initiatedByFieldExpertId, + ] + .filter((value) => value != null && String(value).trim() !== "") + .map((value) => String(value)); + + for (const staffId of candidateIds) { + const staff = await this.findStaffDocumentById(staffId); + if (!staff) continue; + const id = resolveFileMakerStageOneExpertId(staff, blame.type); + if (id != null) return id; + } + + throw new BadRequestException({ + code: "FANAVARAN_CLAIM_EXPERT_ID_MISSING", + message: + "Fanavaran ClaimExpertId is missing on the assigned expert profile for this product line. Set ThirdPartyClaimExpertId or CarBodyClaimExpertId on the assigned staff.", + }); + } + + /** + * GEN.08 / GEN.06 ClaimExpertId from the assessor assigned to this file (never tenant defaults). + * V4/V5 FileMaker → FileReviewer; otherwise the damage-expert (or other staff) who priced the claim. + */ + private async resolveFanavaranExpertiseClaimExpertId( + blame: { + isMadeByFileMaker?: boolean; + type?: BlameRequestType; + assignedFileReviewerId?: unknown; + }, + claimCase: { evaluation?: Record } | null | undefined, + ): Promise { + if (blame?.type == null) { + throw new BadRequestException({ + code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + message: + "Cannot resolve Fanavaran expertise ClaimExpertId: blame product type is missing.", + }); + } + + if (blame.isMadeByFileMaker) { + if (!blame.assignedFileReviewerId) { + throw new BadRequestException({ + code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", + message: + "Fanavaran expertise cannot be submitted: assign a FileReviewer with an expertise claim expert id for this product line.", + }); + } + const fileReviewer = await this.fileReviewerDbService.findById( + String(blame.assignedFileReviewerId), + ); + if (!fileReviewer) { + throw new BadRequestException({ + code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", + message: + "Fanavaran expertise cannot be submitted: FileReviewer profile was not found.", + }); + } + assertFileReviewerCanReviewBlameType(fileReviewer, blame.type); + const id = resolveFileReviewerExpertiseExpertId(fileReviewer, blame.type); + if (id == null) { + throw new BadRequestException({ + code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", + message: + "Fanavaran expertise cannot be submitted: assign a FileReviewer with an expertise claim expert id for this product line.", + }); + } + return id; + } + + const evaluation = claimCase?.evaluation as + | { + damageExpertReplyFinal?: { actorDetail?: { actorId?: unknown } }; + damageExpertReply?: { actorDetail?: { actorId?: unknown } }; + } + | undefined; + const active = getActiveV2ExpertReply( + claimCase as unknown as { evaluation?: Record }, + ); + const actorId = + (active?.reply as { actorDetail?: { actorId?: unknown } } | undefined) + ?.actorDetail?.actorId ?? + evaluation?.damageExpertReplyFinal?.actorDetail?.actorId ?? + evaluation?.damageExpertReply?.actorDetail?.actorId; + if (actorId == null || String(actorId).trim() === "") { + throw new BadRequestException({ + code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + message: + "Fanavaran expertise ClaimExpertId cannot be resolved: no damage-expert reply actor is assigned on this claim.", + }); + } + + const staff = await this.findStaffDocumentById(String(actorId)); + const id = staff + ? resolveFileReviewerExpertiseExpertId(staff, blame.type) + : null; + if (id == null) { + throw new BadRequestException({ + code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + message: + "Fanavaran ClaimExpertId is missing on the assigned assessor profile for this product line. Set ThirdPartyExpertiseClaim or CarBodyExpertiseClaim on the assigned staff.", + }); + } + return id; + } + + /** @deprecated Use resolveFanavaranBaseClaimExpertId / resolveFanavaranExpertiseClaimExpertId */ private async resolveFanavaranFileRoleExpertIdsForBlame(blame: { isMadeByFileMaker?: boolean; type?: BlameRequestType; initiatedByFieldExpertId?: unknown; assignedFileReviewerId?: unknown; + expert?: { + assignedExpertId?: unknown; + decision?: { decidedByExpertId?: unknown }; + }; }): Promise<{ baseClaimExpertId: number | null; expertiseClaimExpertId: number | null; } | null> { - if (!blame?.isMadeByFileMaker || blame.type == null) { + if (blame?.type == null) return null; + try { + const baseClaimExpertId = await this.resolveFanavaranBaseClaimExpertId( + blame, + ); + let expertiseClaimExpertId: number | null = null; + try { + expertiseClaimExpertId = + await this.resolveFanavaranExpertiseClaimExpertId(blame, null); + } catch { + expertiseClaimExpertId = null; + } + return { baseClaimExpertId, expertiseClaimExpertId }; + } catch { return null; } - - let baseClaimExpertId: number | null = null; - let expertiseClaimExpertId: number | null = null; - - if (blame.initiatedByFieldExpertId) { - const fileMaker = await this.fileMakerDbService.findById( - String(blame.initiatedByFieldExpertId), - ); - if (fileMaker) { - assertFileMakerCanCreateBlameType(fileMaker, blame.type); - baseClaimExpertId = resolveFileMakerStageOneExpertId( - fileMaker, - blame.type, - ); - } - } - - if (blame.assignedFileReviewerId) { - const fileReviewer = await this.fileReviewerDbService.findById( - String(blame.assignedFileReviewerId), - ); - if (fileReviewer) { - assertFileReviewerCanReviewBlameType(fileReviewer, blame.type); - expertiseClaimExpertId = resolveFileReviewerExpertiseExpertId( - fileReviewer, - blame.type, - ); - } - } - - return { baseClaimExpertId, expertiseClaimExpertId }; } private async getPolicyIdFromNationalCode( @@ -4018,6 +4202,9 @@ export class ClaimRequestManagementService { }, ): Promise { const profile = getFanavaranClientProfile(clientKey); + const payloadDefaults = this.fanavaranPayloadDefaultsWithoutExpertIds( + profile.defaults as unknown as Record, + ); const logPrefix = `[Fanavaran ${clientKey} V2] claimCaseId=${claimCaseId}`; const forceRefreshPolicy = options?.forceRefreshPolicy === true; const forceRefreshUsedId = options?.forceRefreshUsedId === true; @@ -4129,7 +4316,14 @@ export class ClaimRequestManagementService { createdAt: accidentAt, location: firstParty?.location, damageParts, - defaults: profile.defaults, + defaults: payloadDefaults as { + AccidentCityId: number; + AccidentReportTypeId: number; + AccidentVehicleUsedId: number; + CompensationReferenceId: number; + CulpritLicenceTypeId: number; + CulpritTypeId: number; + }, logPrefix, requirePolicyId, resolvePolicyId: async () => { @@ -4389,18 +4583,10 @@ export class ClaimRequestManagementService { } } - const fileRoleExpertIds = - await this.resolveFanavaranFileRoleExpertIdsForBlame(blameCase); - if (fileRoleExpertIds) { - if (fileRoleExpertIds.baseClaimExpertId == null) { - throw new BadRequestException({ - code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING", - message: - "This FileMaker file cannot be submitted to Fanavaran: stage-1 claim expert id is missing for this product line.", - }); - } - payload.ClaimExpertId = fileRoleExpertIds.baseClaimExpertId; - } + payload.ClaimExpertId = await this.resolveFanavaranBaseClaimExpertId( + blameCase, + claimCase, + ); if (persistPayload) { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { @@ -4465,7 +4651,9 @@ export class ClaimRequestManagementService { `[Fanavaran ${clientKey} V2] Error submitting to Fanavaran`, error, ); - throw new BadGatewayException(this.extractFanavaranErrorMessage(error)); + throw toFanavaranHttpException(error, { + fallback: "Failed to submit data to Fanavaran API", + }); } } @@ -4563,7 +4751,9 @@ export class ClaimRequestManagementService { `[Fanavaran ${clientKey} V2] Error submitting damage case to Fanavaran`, error, ); - throw new BadGatewayException(this.extractFanavaranErrorMessage(error)); + throw toFanavaranHttpException(error, { + fallback: "Failed to submit data to Fanavaran API", + }); } } @@ -5381,29 +5571,22 @@ export class ClaimRequestManagementService { ) : null; - // GEN.06 ClaimExpertId = tenant ExpertiseClaimExpertId (assessor role), unless - // V4/V5 FileMaker flow → file-reviewer expertise code for this product line. - let claimExpertId = profile.defaults.ExpertiseClaimExpertId; - if (blameForExpertIds) { - const roleExpertIds = - await this.resolveFanavaranFileRoleExpertIdsForBlame( - blameForExpertIds as { - isMadeByFileMaker?: boolean; - type?: BlameRequestType; - initiatedByFieldExpertId?: unknown; - assignedFileReviewerId?: unknown; - }, - ); - if (roleExpertIds?.expertiseClaimExpertId != null) { - claimExpertId = roleExpertIds.expertiseClaimExpertId; - } else if (roleExpertIds) { - throw new BadRequestException({ - code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", - message: - "Fanavaran expertise cannot be submitted: assign a FileReviewer with an expertise claim expert id for this product line.", - }); - } + // GEN.08 / GEN.06 ClaimExpertId always from assigned assessor staff profile. + if (!blameForExpertIds) { + throw new BadRequestException({ + code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING", + message: + "Fanavaran expertise cannot be submitted: linked blame case was not found.", + }); } + const claimExpertId = await this.resolveFanavaranExpertiseClaimExpertId( + blameForExpertIds as { + isMadeByFileMaker?: boolean; + type?: BlameRequestType; + assignedFileReviewerId?: unknown; + }, + input.claimCase, + ); const warnings: string[] = []; if (!active?.parts?.length) { @@ -5589,7 +5772,9 @@ export class ClaimRequestManagementService { `[Fanavaran ${clientKey} V2] Error submitting expertise to Fanavaran`, error, ); - throw new BadGatewayException(this.extractFanavaranErrorMessage(error)); + throw toFanavaranHttpException(error, { + fallback: "Failed to submit data to Fanavaran API", + }); } } @@ -6794,29 +6979,10 @@ export class ClaimRequestManagementService { } private extractFanavaranErrorMessage(error: unknown): string { - if (isAxiosError(error)) { - return ( - error.response?.data?.message || - error.response?.data?.Message || - (typeof error.response?.data === "string" - ? error.response.data - : undefined) || - error.message || - "Failed to submit data to Fanavaran API" - ); - } - if (error instanceof HttpException) { - const response = error.getResponse(); - if (typeof response === "string") return response; - if (response && typeof response === "object" && "message" in response) { - const message = (response as { message?: string | string[] }).message; - return Array.isArray(message) ? message.join(", ") : String(message); - } - } - if (error instanceof Error) { - return error.message; - } - return "Failed to submit data to Fanavaran API"; + return extractFanavaranOriginalMessage( + error, + "Failed to submit data to Fanavaran API", + ); } private static readonly FANAVARAN_RETRY_DELAY_MS = 5 * 60 * 1000; // 5 minutes diff --git a/src/claim-request-management/fanavaran-assigned-expert-ids.spec.ts b/src/claim-request-management/fanavaran-assigned-expert-ids.spec.ts new file mode 100644 index 0000000..75dd6bd --- /dev/null +++ b/src/claim-request-management/fanavaran-assigned-expert-ids.spec.ts @@ -0,0 +1,107 @@ +import { BadRequestException } from "@nestjs/common"; +import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; +import { ClaimRequestManagementService } from "./claim-request-management.service"; + +function serviceWithStaff(stubs: { + fileMaker?: any; + fileReviewer?: any; + fieldExpert?: any; + expert?: any; + damageExpert?: any; +}) { + const management = Object.create( + ClaimRequestManagementService.prototype, + ) as any; + management.fileMakerDbService = { + findById: jest.fn().mockResolvedValue(stubs.fileMaker ?? null), + }; + management.fileReviewerDbService = { + findById: jest.fn().mockResolvedValue(stubs.fileReviewer ?? null), + }; + management.fieldExpertDbService = { + findById: jest.fn().mockResolvedValue(stubs.fieldExpert ?? null), + }; + management.expertDbService = { + findById: jest.fn().mockResolvedValue(stubs.expert ?? null), + }; + management.damageExpertDbService = { + findById: jest.fn().mockResolvedValue(stubs.damageExpert ?? null), + }; + return management as ClaimRequestManagementService; +} + +describe("Fanavaran assigned ClaimExpertId resolution", () => { + it("reads GEN.03 ClaimExpertId from assigned blame expert DB codes", async () => { + const management = serviceWithStaff({ + expert: { ThirdPartyClaimExpertId: "154" }, + }); + await expect( + (management as any).resolveFanavaranBaseClaimExpertId({ + type: BlameRequestType.THIRD_PARTY, + expert: { assignedExpertId: "expert-1" }, + }), + ).resolves.toBe(154); + }); + + it("reads GEN.03 ClaimExpertId from FileMaker on V4/V5", async () => { + const management = serviceWithStaff({ + fileMaker: { + ThirdPartyClaimExpertId: "5347", + CarBodyClaimExpertId: "100", + }, + }); + await expect( + (management as any).resolveFanavaranBaseClaimExpertId({ + type: BlameRequestType.THIRD_PARTY, + isMadeByFileMaker: true, + initiatedByFieldExpertId: "fm-1", + }), + ).resolves.toBe(5347); + }); + + it("reads expertise ClaimExpertId from damage-expert reply actor", async () => { + const management = serviceWithStaff({ + damageExpert: { ThirdPartyExpertiseClaim: "29" }, + }); + await expect( + (management as any).resolveFanavaranExpertiseClaimExpertId( + { type: BlameRequestType.THIRD_PARTY }, + { + evaluation: { + damageExpertReply: { + actorDetail: { actorId: "dmg-1" }, + submittedAt: new Date(), + parts: [{ price: 1 }], + }, + }, + }, + ), + ).resolves.toBe(29); + }); + + it("reads expertise ClaimExpertId from FileReviewer on V4/V5", async () => { + const management = serviceWithStaff({ + fileReviewer: { CarBodyExpertiseClaim: "15" }, + }); + await expect( + (management as any).resolveFanavaranExpertiseClaimExpertId( + { + type: BlameRequestType.CAR_BODY, + isMadeByFileMaker: true, + assignedFileReviewerId: "fr-1", + }, + null, + ), + ).resolves.toBe(15); + }); + + it("does not fall back to hardcoded tenant ClaimExpertId", async () => { + const management = serviceWithStaff({}); + await expect( + (management as any).resolveFanavaranBaseClaimExpertId({ + type: BlameRequestType.THIRD_PARTY, + expert: { assignedExpertId: "missing" }, + }), + ).rejects.toBeInstanceOf(BadRequestException); + }); +}); diff --git a/src/expert-claim/fanavaran-stage-fields.spec.ts b/src/expert-claim/fanavaran-stage-fields.spec.ts index 1892edd..1f0923d 100644 --- a/src/expert-claim/fanavaran-stage-fields.spec.ts +++ b/src/expert-claim/fanavaran-stage-fields.spec.ts @@ -152,9 +152,9 @@ describe("Expert Fanavaran stage fields", () => { management.resolveAccidentVehicleUsedFromApis = jest .fn() .mockResolvedValue({ usedId: 1 }); - management.resolveFanavaranFileRoleExpertIdsForBlame = jest + management.resolveFanavaranBaseClaimExpertId = jest .fn() - .mockResolvedValue(null); + .mockResolvedValue(154); management.enrichCarBodyHullBaseClaimPayload = jest .fn() .mockImplementation(async ({ payload }) => { @@ -165,6 +165,7 @@ describe("Expert Fanavaran stage fields", () => { persistPayload: false, forceRefreshPolicy: false, }); + expect(payload.ClaimExpertId).toBe(154); expect(payload).toMatchObject({ AccidentLocationAddress: "نشانی واقعی", AccidentCityId: 702, @@ -233,9 +234,9 @@ describe("Expert Fanavaran stage fields", () => { management.blameRequestDbService = { findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }), }; - management.resolveFanavaranFileRoleExpertIdsForBlame = jest + management.resolveFanavaranExpertiseClaimExpertId = jest .fn() - .mockResolvedValue(null); + .mockResolvedValue(29); management.resolveFanavaranClaimProduct = jest .fn() .mockResolvedValue("third-party"); @@ -246,6 +247,7 @@ describe("Expert Fanavaran stage fields", () => { expect(result.payload).toMatchObject({ InspectionPlaceId: 283, DmgCaseId: 20, + ClaimExpertId: 29, }); }); diff --git a/src/fanavaran/fanavaran-audit.service.ts b/src/fanavaran/fanavaran-audit.service.ts index 629b0e8..0e668cd 100644 --- a/src/fanavaran/fanavaran-audit.service.ts +++ b/src/fanavaran/fanavaran-audit.service.ts @@ -4,6 +4,7 @@ import { isAxiosError, type AxiosResponse } from "axios"; import { Model, Types } from "mongoose"; import { randomBytes } from "node:crypto"; import type { FanavaranAuditSession } from "./fanavaran-audit.types"; +import { extractFanavaranOriginalMessage } from "./fanavaran-http-exception"; import { FanavaranAuditLog, FanavaranAuditLogDocument, @@ -236,25 +237,7 @@ export class FanavaranAuditService { } extractErrorMessage(error: unknown): string { - if (isAxiosError(error)) { - const data = error.response?.data as - | { Message?: string; message?: string } - | string - | undefined; - if (typeof data === "string") { - return data; - } - return ( - data?.Message || - data?.message || - error.message || - "Fanavaran request failed" - ); - } - if (error instanceof Error) { - return error.message; - } - return "Fanavaran request failed"; + return extractFanavaranOriginalMessage(error, "Fanavaran request failed"); } formatErrorWithTrackingCode(message: string, trackingCode?: string): string { diff --git a/src/fanavaran/fanavaran-auth.service.ts b/src/fanavaran/fanavaran-auth.service.ts index 6072f74..d4fa038 100644 --- a/src/fanavaran/fanavaran-auth.service.ts +++ b/src/fanavaran/fanavaran-auth.service.ts @@ -18,6 +18,7 @@ import { } from "src/core/config/fanavaran-client.config"; import { FanavaranAuditService } from "./fanavaran-audit.service"; import type { FanavaranAuditSession } from "./fanavaran-audit.types"; +import { toFanavaranHttpException } from "./fanavaran-http-exception"; import { FanavaranAuditStatus, FanavaranAuditStep, @@ -634,20 +635,9 @@ export class FanavaranAuthService { fallback: string, auditSession?: FanavaranAuditSession, ): HttpException { - if (error instanceof HttpException) { - return error; - } - const message = isAxiosError(error) - ? error.response?.data?.Message || - error.response?.data?.message || - error.message || - fallback - : fallback; - return new BadGatewayException( - this.fanavaranAuditService.formatErrorWithTrackingCode( - String(message), - auditSession?.trackingCode, - ), - ); + return toFanavaranHttpException(error, { + fallback, + trackingCode: auditSession?.trackingCode, + }); } } diff --git a/src/fanavaran/fanavaran-file-role-expert-ids.ts b/src/fanavaran/fanavaran-file-role-expert-ids.ts index f085149..5a21e20 100644 --- a/src/fanavaran/fanavaran-file-role-expert-ids.ts +++ b/src/fanavaran/fanavaran-file-role-expert-ids.ts @@ -2,16 +2,24 @@ import { BadRequestException } from "@nestjs/common"; import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; import { parseFanavaranId } from "src/lookups/fanavaran-last-car-policy"; -export type FileMakerFanavaranExpertCodes = { +/** Stage-1 / GEN.03 case-owner Fanavaran codes (any staff role that may own the file). */ +export type StaffFanavaranStageOneCodes = { ThirdPartyClaimExpertId?: string; CarBodyClaimExpertId?: string; }; -export type FileReviewerFanavaranExpertCodes = { +/** Expertise / GEN.08–GEN.06 assessor Fanavaran codes. */ +export type StaffFanavaranExpertiseCodes = { ThirdPartyExpertiseClaim?: string; CarBodyExpertiseClaim?: string; }; +/** @deprecated Prefer StaffFanavaranStageOneCodes */ +export type FileMakerFanavaranExpertCodes = StaffFanavaranStageOneCodes; + +/** @deprecated Prefer StaffFanavaranExpertiseCodes */ +export type FileReviewerFanavaranExpertCodes = StaffFanavaranExpertiseCodes; + export function parseFanavaranExpertId(raw?: string | null): number | null { if (raw == null) return null; const trimmed = String(raw).trim(); diff --git a/src/fanavaran/fanavaran-http-exception.spec.ts b/src/fanavaran/fanavaran-http-exception.spec.ts new file mode 100644 index 0000000..d49d133 --- /dev/null +++ b/src/fanavaran/fanavaran-http-exception.spec.ts @@ -0,0 +1,76 @@ +import { HttpException, HttpStatus } from "@nestjs/common"; +import { AxiosError } from "axios"; +import { + extractFanavaranOriginalMessage, + toFanavaranHttpException, +} from "./fanavaran-http-exception"; + +function axiosFanavaranError(data: unknown, status = 400): AxiosError { + return new AxiosError( + "Request failed", + "ERR_BAD_REQUEST", + undefined, + undefined, + { + status, + statusText: "Bad Request", + headers: {}, + config: {} as any, + data, + }, + ); +} + +describe("toFanavaranHttpException", () => { + it("surfaces Fanavaran Message and RuleName in Nest response body", () => { + const fanavaranMessage = + "کد پیگیری خطا: 8817924\r\nمقدار انتخابی کارشناس پرونده صحیح نمیباشد ./"; + const exception = toFanavaranHttpException( + axiosFanavaranError({ + Message: fanavaranMessage, + RuleName: "BdCarPrvKarshenasLookupFilterRule", + }), + ); + + expect(exception.getStatus()).toBe(400); + expect(exception.getResponse()).toEqual({ + statusCode: 400, + message: fanavaranMessage, + Message: fanavaranMessage, + RuleName: "BdCarPrvKarshenasLookupFilterRule", + }); + }); + + it("prefers Message over message", () => { + expect( + extractFanavaranOriginalMessage( + axiosFanavaranError({ + Message: "original", + message: "nested lowercase", + }), + ), + ).toBe("original"); + }); + + it("uses 502 for non-4xx upstream status", () => { + const exception = toFanavaranHttpException( + axiosFanavaranError({ Message: "upstream down" }, 503), + ); + expect(exception.getStatus()).toBe(HttpStatus.BAD_GATEWAY); + }); + + it("passes through existing HttpException", () => { + const original = new HttpException("already mapped", HttpStatus.CONFLICT); + expect(toFanavaranHttpException(original)).toBe(original); + }); + + it("appends trackingCode when provided", () => { + const exception = toFanavaranHttpException( + axiosFanavaranError({ Message: "fail" }), + { trackingCode: "abc" }, + ); + expect((exception.getResponse() as { message: string }).message).toBe( + "fail (trackingCode: abc)", + ); + }); +}); diff --git a/src/fanavaran/fanavaran-http-exception.ts b/src/fanavaran/fanavaran-http-exception.ts new file mode 100644 index 0000000..0784cc3 --- /dev/null +++ b/src/fanavaran/fanavaran-http-exception.ts @@ -0,0 +1,107 @@ +import { HttpException, HttpStatus } from "@nestjs/common"; +import { isAxiosError } from "axios"; + +type FanavaranErrorData = { + Message?: unknown; + message?: unknown; + RuleName?: unknown; +}; + +function asNonEmptyString(value: unknown): string | undefined { + if (typeof value !== "string") return undefined; + const trimmed = value.trim(); + return trimmed ? trimmed : undefined; +} + +/** Prefer Fanavaran `Message`, then `message`, then raw string body. */ +export function extractFanavaranOriginalMessage( + error: unknown, + fallback = "Fanavaran request failed", +): string { + if (isAxiosError(error)) { + const data = error.response?.data as FanavaranErrorData | string | undefined; + if (typeof data === "string") { + return asNonEmptyString(data) ?? error.message ?? fallback; + } + return ( + asNonEmptyString(data?.Message) ?? + asNonEmptyString(data?.message) ?? + error.message ?? + fallback + ); + } + if (error instanceof HttpException) { + const response = error.getResponse(); + if (typeof response === "string") { + return asNonEmptyString(response) ?? fallback; + } + if (response && typeof response === "object") { + const body = response as FanavaranErrorData & { + message?: string | string[]; + }; + const nestMessage = body.message; + if (Array.isArray(nestMessage)) { + const joined = nestMessage.filter(Boolean).join(", "); + if (joined) return joined; + } + return ( + asNonEmptyString(body.Message) ?? + asNonEmptyString(nestMessage) ?? + fallback + ); + } + } + if (error instanceof Error) { + return asNonEmptyString(error.message) ?? fallback; + } + return fallback; +} + +export function extractFanavaranRuleName(error: unknown): string | undefined { + if (!isAxiosError(error)) return undefined; + const data = error.response?.data as FanavaranErrorData | undefined; + return asNonEmptyString(data?.RuleName); +} + +/** + * Map Fanavaran/axios failures to a Nest HttpException that keeps the original + * Fanavaran Message (and RuleName) in the response body. + */ +export function toFanavaranHttpException( + error: unknown, + options?: { + fallback?: string; + trackingCode?: string; + }, +): HttpException { + if (error instanceof HttpException) { + return error; + } + + const fallback = options?.fallback ?? "Fanavaran request failed"; + let message = extractFanavaranOriginalMessage(error, fallback); + if (options?.trackingCode) { + message = `${message} (trackingCode: ${options.trackingCode})`; + } + + const ruleName = extractFanavaranRuleName(error); + const upstreamStatus = isAxiosError(error) + ? error.response?.status + : undefined; + const status = + typeof upstreamStatus === "number" && + upstreamStatus >= 400 && + upstreamStatus < 500 + ? upstreamStatus + : HttpStatus.BAD_GATEWAY; + + return new HttpException( + { + statusCode: status, + message, + Message: message, + ...(ruleName ? { RuleName: ruleName } : {}), + }, + status, + ); +} diff --git a/src/fanavaran/fanavaran-lookup.service.ts b/src/fanavaran/fanavaran-lookup.service.ts index fd9383f..a6e4c74 100644 --- a/src/fanavaran/fanavaran-lookup.service.ts +++ b/src/fanavaran/fanavaran-lookup.service.ts @@ -1,16 +1,10 @@ import { mkdir, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { HttpService } from "@nestjs/axios"; -import { - BadGatewayException, - Injectable, - Logger, - NotFoundException, -} from "@nestjs/common"; +import { Injectable, Logger, NotFoundException } from "@nestjs/common"; import { InjectModel } from "@nestjs/mongoose"; import { Model } from "mongoose"; import { firstValueFrom } from "rxjs"; -import { isAxiosError } from "axios"; import { getFanavaranLookupBaseUrl, type FanavaranClientKey, @@ -25,6 +19,10 @@ import { tejaratStaticAccidentFilePath, } from "./fanavaran-lookup.config"; import { FanavaranAuthService } from "./fanavaran-auth.service"; +import { + extractFanavaranOriginalMessage, + toFanavaranHttpException, +} from "./fanavaran-http-exception"; @Injectable() export class FanavaranLookupService { @@ -124,18 +122,17 @@ export class FanavaranLookupService { return response.data; } catch (error) { this.fanavaranAuthService.registerFailure(clientKey, error); - const message = isAxiosError(error) - ? error.response?.data?.Message || - error.response?.data?.message || - error.message - : error instanceof Error - ? error.message - : "Fanavaran lookup request failed"; + const message = extractFanavaranOriginalMessage( + error, + "Fanavaran lookup request failed", + ); this.logger.error( `Fanavaran lookup fetch failed for ${clientKey} (${url}): ${message}`, ); - throw new BadGatewayException(String(message)); + throw toFanavaranHttpException(error, { + fallback: "Fanavaran lookup request failed", + }); } } @@ -381,18 +378,17 @@ export class FanavaranLookupService { return response.data; } catch (error) { this.fanavaranAuthService.registerFailure(clientKey, error); - const message = isAxiosError(error) - ? error.response?.data?.Message || - error.response?.data?.message || - error.message - : error instanceof Error - ? error.message - : "Fanavaran POST request failed"; + const message = extractFanavaranOriginalMessage( + error, + "Fanavaran POST request failed", + ); this.logger.error( `Fanavaran POST failed for ${clientKey} (${url}): ${message}`, ); - throw new BadGatewayException(String(message)); + throw toFanavaranHttpException(error, { + fallback: "Fanavaran POST request failed", + }); } } diff --git a/src/users/entities/db-service/expert.db.service.ts b/src/users/entities/db-service/expert.db.service.ts index bdc25a0..81a6d56 100644 --- a/src/users/entities/db-service/expert.db.service.ts +++ b/src/users/entities/db-service/expert.db.service.ts @@ -20,6 +20,12 @@ export class ExpertDbService { return await this.expertModel.findOne(user).lean(); } + async findById(userId: string): Promise { + return await this.expertModel + .findOne({ _id: new Types.ObjectId(userId) }) + .lean(); + } + async findOneAndUpdate( user: FilterQuery, update: FilterQuery,