read the expert Ids from the db not hardcoded from every flow

This commit is contained in:
2026-11-09 16:31:25 +03:30
parent 6cc59b1777
commit 6775635a81
10 changed files with 604 additions and 163 deletions
@@ -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(
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
@@ -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);
});
});