forked from Yara724/api
read the expert Ids from the db not hardcoded from every flow
This commit is contained in:
@@ -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<Record<string, unknown>> {
|
||||
const lookupDefaults = input.defaults ?? this.TEJARATNO_FANAVARAN_DEFAULTS;
|
||||
const lookupDefaults =
|
||||
input.defaults ??
|
||||
this.fanavaranPayloadDefaultsWithoutExpertIds(
|
||||
this.TEJARATNO_FANAVARAN_DEFAULTS as unknown as Record<string, unknown>,
|
||||
);
|
||||
const result: Record<string, unknown> = {
|
||||
...lookupDefaults,
|
||||
AccidentCauseId: FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID,
|
||||
@@ -3370,53 +3383,224 @@ export class ClaimRequestManagementService {
|
||||
}
|
||||
}
|
||||
|
||||
private fanavaranPayloadDefaultsWithoutExpertIds(
|
||||
defaults: Record<string, unknown>,
|
||||
): Record<string, unknown> {
|
||||
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<number> {
|
||||
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<string, unknown> } | null | undefined,
|
||||
): Promise<number> {
|
||||
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<string, unknown> },
|
||||
);
|
||||
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<any> {
|
||||
const profile = getFanavaranClientProfile(clientKey);
|
||||
const payloadDefaults = this.fanavaranPayloadDefaultsWithoutExpertIds(
|
||||
profile.defaults as unknown as Record<string, unknown>,
|
||||
);
|
||||
const logPrefix = `[Fanavaran ${clientKey} V2] claimCaseId=${claimCaseId}`;
|
||||
const forceRefreshPolicy = options?.forceRefreshPolicy === true;
|
||||
const forceRefreshUsedId = options?.forceRefreshUsedId === true;
|
||||
@@ -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(
|
||||
// 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;
|
||||
initiatedByFieldExpertId?: unknown;
|
||||
assignedFileReviewerId?: unknown;
|
||||
},
|
||||
input.claimCase,
|
||||
);
|
||||
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.",
|
||||
});
|
||||
}
|
||||
}
|
||||
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,30 +6979,11 @@ 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"
|
||||
return extractFanavaranOriginalMessage(
|
||||
error,
|
||||
"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";
|
||||
}
|
||||
|
||||
private static readonly FANAVARAN_RETRY_DELAY_MS = 5 * 60 * 1000; // 5 minutes
|
||||
private static readonly FANAVARAN_TRANSIENT_RETRY_DELAY_MS = 10 * 60 * 1000; // 10 minutes
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
}
|
||||
@@ -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",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,12 @@ export class ExpertDbService {
|
||||
return await this.expertModel.findOne(user).lean();
|
||||
}
|
||||
|
||||
async findById(userId: string): Promise<ExpertModel | null> {
|
||||
return await this.expertModel
|
||||
.findOne({ _id: new Types.ObjectId(userId) })
|
||||
.lean();
|
||||
}
|
||||
|
||||
async findOneAndUpdate(
|
||||
user: FilterQuery<ExpertModel>,
|
||||
update: FilterQuery<ExpertModel>,
|
||||
|
||||
Reference in New Issue
Block a user