Compare commits

...
4 Commits
Author SHA1 Message Date
s.hajizadeh f33eabeb4f fanavaran expert codes 2026-11-09 18:05:20 +03:30
s.hajizadeh c81002da7d updated the experts context 2026-11-09 18:00:46 +03:30
s.hajizadeh f49e6b704b expert codes 2026-11-09 17:29:35 +03:30
s.hajizadeh 6775635a81 read the expert Ids from the db not hardcoded from every flow 2026-11-09 16:31:25 +03:30
13 changed files with 1057 additions and 163 deletions
+26 -1
View File
@@ -1,5 +1,5 @@
--- ---
last_updated: 2026-08-08 last_updated: 2026-11-09
tags: [fanavaran, yara, integration] tags: [fanavaran, yara, integration]
source: fanavaran-module-docs source: fanavaran-module-docs
--- ---
@@ -51,6 +51,31 @@ source: fanavaran-module-docs
| Store | `claimId`, `claimNo`, `fanavaranSync.baseClaim.*`, history | | Store | `claimId`, `claimNo`, `fanavaranSync.baseClaim.*`, history |
| Consumers | Damage/expertise soft-ensure; UI claim detail | | Consumers | Damage/expertise soft-ensure; UI claim detail |
#### Staff source for ClaimExpertId across request flows
The flows in `docs/Yara724 flows.pdf` share the same base-claim resolver.
Base claims use `ThirdPartyClaimExpertId` / `CarBodyClaimExpertId`; expertise
uses `ThirdPartyExpertiseClaim` / `CarBodyExpertiseClaim` from staff profiles.
| Local flow | Base-claim staff source | Expertise staff source |
|------------|------------------------|------------------------|
| V1/V2 user, including expert-panel review | Blame expert when present; otherwise claim damage-review actor or persistent reviewer assignment | Claim damage-review actor |
| V2 expert-initiated / V3 | Initiating field expert, then blame expert; claim damage reviewer is a fallback | Claim damage-review actor |
| V4 / V5 | Initiating FileMaker | Assigned FileReviewer |
Outside V4/V5, base resolution checks blame initiator, blame assigned expert,
blame deciding expert, claim initiator, claim reply actor, then
`workflow.assignedForReviewBy.actorId`, in that order. Reply actor selection
matches expertise: the active submitted reply, then final/initial reply actor.
Temporary workflow locks are not reviewer assignments.
An unassigned user-created claim can still have no expert early in its lifecycle:
preview returns a missing-expert warning, and submit requires a resolvable code.
Tenant defaults and unrelated staff profiles do not supply expert ids.
For example, a claim review actor with `ThirdPartyClaimExpertId="5507"` and
`ThirdPartyExpertiseClaim="5510"` supplies base `ClaimExpertId=5507` and
expertise `ClaimExpertId=5510`.
### C. Damage case ### C. Damage case
| | | | | |
@@ -3,7 +3,6 @@ import {
isTejaratNotifierLookup, isTejaratNotifierLookup,
} from "src/fanavaran/tejarat-notifier"; } from "src/fanavaran/tejarat-notifier";
import { import {
BadGatewayException,
BadRequestException, BadRequestException,
ConflictException, ConflictException,
ForbiddenException, ForbiddenException,
@@ -33,11 +32,15 @@ import { BranchDbService } from "src/client/entities/db-service/branch.db.servic
import { InquiryParticipantRole } from "src/common/dto/inquiry-participants.dto"; import { InquiryParticipantRole } from "src/common/dto/inquiry-participants.dto";
import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto"; import { ListQueryV2Dto } from "src/common/dto/list-query-v2.dto";
import { import {
assertFileMakerCanCreateBlameType,
assertFileReviewerCanReviewBlameType,
resolveFileMakerStageOneExpertId, resolveFileMakerStageOneExpertId,
resolveFileReviewerExpertiseExpertId, 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"; import { FanavaranLocationService } from "src/fanavaran/fanavaran-location.service";
import { import {
canUserCreateClaim, canUserCreateClaim,
@@ -119,6 +122,9 @@ import {
OuterPartCatalogItem, 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 { FileMakerDbService } from "src/users/entities/db-service/file-maker.db.service";
import { FileReviewerDbService } from "src/users/entities/db-service/file-reviewer.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 { UserDbService } from "src/users/entities/db-service/user.db.service";
@@ -349,6 +355,12 @@ interface FanavaranAttachmentCandidate {
submittedFileId?: unknown; submittedFileId?: unknown;
} }
interface FanavaranClaimExpertContext {
initiatedByFieldExpertId?: unknown;
evaluation?: object;
workflow?: { assignedForReviewBy?: { actorId?: unknown } };
}
/** /**
* Returns today's Jalali date as a packed integer YYYYMMDD for cheap comparison. * Returns today's Jalali date as a packed integer YYYYMMDD for cheap comparison.
* Uses the browser/Node `fa-IR` locale which is available everywhere Node runs. * Uses the browser/Node `fa-IR` locale which is available everywhere Node runs.
@@ -445,12 +457,11 @@ export class ClaimRequestManagementService {
location: "210050", location: "210050",
} as const; } 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 = { private readonly TEJARATNO_FANAVARAN_DEFAULTS = {
AccidentCityId: 701, AccidentCityId: 701,
AccidentReportTypeId: 155, AccidentReportTypeId: 155,
AccidentVehicleUsedId: 1, AccidentVehicleUsedId: 1,
ClaimExpertId: 4543092,
CompensationReferenceId: 167, CompensationReferenceId: 167,
CulpritLicenceTypeId: 2, CulpritLicenceTypeId: 2,
CulpritTypeId: 337, CulpritTypeId: 337,
@@ -483,6 +494,9 @@ export class ClaimRequestManagementService {
private readonly fanavaranLookupService: FanavaranLookupService, private readonly fanavaranLookupService: FanavaranLookupService,
private readonly fileMakerDbService: FileMakerDbService, private readonly fileMakerDbService: FileMakerDbService,
private readonly fileReviewerDbService: FileReviewerDbService, private readonly fileReviewerDbService: FileReviewerDbService,
private readonly fieldExpertDbService: FieldExpertDbService,
private readonly expertDbService: ExpertDbService,
private readonly damageExpertDbService: DamageExpertDbService,
private readonly plateNormalizer: PlateNormalizerService, private readonly plateNormalizer: PlateNormalizerService,
private readonly fanavaranLocationService: FanavaranLocationService, private readonly fanavaranLocationService: FanavaranLocationService,
@@ -1859,13 +1873,16 @@ export class ClaimRequestManagementService {
AccidentCityId: number; AccidentCityId: number;
AccidentReportTypeId: number; AccidentReportTypeId: number;
AccidentVehicleUsedId: number; AccidentVehicleUsedId: number;
ClaimExpertId: number;
CompensationReferenceId: number; CompensationReferenceId: number;
CulpritLicenceTypeId: number; CulpritLicenceTypeId: number;
CulpritTypeId: number; CulpritTypeId: number;
}; };
}): Promise<Record<string, unknown>> { }): 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> = { const result: Record<string, unknown> = {
...lookupDefaults, ...lookupDefaults,
AccidentCauseId: FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID, AccidentCauseId: FANAVARAN_DEFAULT_ACCIDENT_CAUSE_ID,
@@ -3370,53 +3387,395 @@ export class ClaimRequestManagementService {
} }
} }
private fanavaranPayloadDefaultsWithoutExpertIds(
defaults: Record<string, unknown>,
): Record<string, unknown> {
const {
ClaimExpertId: _claimExpertId,
ExpertiseClaimExpertId: _expertiseClaimExpertId,
...rest
} = defaults;
return rest;
}
private staffFanavaranCodesFromDoc(
doc: unknown,
): (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes) | null {
if (!doc || typeof doc !== "object") return null;
const plain =
typeof (doc as { toObject?: () => Record<string, unknown> }).toObject ===
"function"
? (doc as { toObject: () => Record<string, unknown> }).toObject()
: (doc as Record<string, unknown>);
return {
ThirdPartyClaimExpertId:
plain.ThirdPartyClaimExpertId != null
? String(plain.ThirdPartyClaimExpertId)
: undefined,
CarBodyClaimExpertId:
plain.CarBodyClaimExpertId != null
? String(plain.CarBodyClaimExpertId)
: undefined,
ThirdPartyExpertiseClaim:
plain.ThirdPartyExpertiseClaim != null
? String(plain.ThirdPartyExpertiseClaim)
: undefined,
CarBodyExpertiseClaim:
plain.CarBodyExpertiseClaim != null
? String(plain.CarBodyExpertiseClaim)
: undefined,
};
}
private async findStaffDocumentById(
staffId: string,
): Promise<
| (StaffFanavaranStageOneCodes & StaffFanavaranExpertiseCodes)
| null
> {
const loaders = [
() => this.expertDbService.findById(staffId),
() => this.damageExpertDbService.findById(staffId),
() => this.fieldExpertDbService.findById(staffId),
() => this.fileMakerDbService.findById(staffId),
() => this.fileReviewerDbService.findById(staffId),
];
for (const load of loaders) {
try {
const doc = await load();
const codes = this.staffFanavaranCodesFromDoc(doc);
if (codes) return codes;
} catch {
// invalid ObjectId / cast errors — try next collection
}
}
return null;
}
private async tryResolveFanavaranBaseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown;
expert?: {
assignedExpertId?: unknown;
decision?: { decidedByExpertId?: unknown };
};
},
claimCase?: FanavaranClaimExpertContext | null,
): Promise<{
claimExpertId: number | null;
code: string | null;
message: string | null;
candidatesTried: string[];
}> {
const fieldName =
blame?.type === BlameRequestType.CAR_BODY
? "CarBodyClaimExpertId"
: "ThirdPartyClaimExpertId";
if (blame?.type == null) {
return {
claimExpertId: null,
code: "FANAVARAN_CLAIM_EXPERT_ID_MISSING",
message:
"ClaimExpertId unresolved: blame.type is missing, so the product line expert code cannot be chosen.",
candidatesTried: [],
};
}
if (blame.isMadeByFileMaker && blame.initiatedByFieldExpertId) {
const fileMakerId = String(blame.initiatedByFieldExpertId);
const fileMaker = await this.fileMakerDbService.findById(fileMakerId);
if (!fileMaker) {
return {
claimExpertId: null,
code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING",
message: `ClaimExpertId unresolved: FileMaker ${fileMakerId} was not found.`,
candidatesTried: [fileMakerId],
};
}
const id = resolveFileMakerStageOneExpertId(fileMaker, blame.type);
if (id == null) {
return {
claimExpertId: null,
code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING",
message: `ClaimExpertId unresolved: FileMaker ${fileMakerId} has empty ${fieldName}.`,
candidatesTried: [fileMakerId],
};
}
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: [fileMakerId],
};
}
// User-created claims may have no blame expert. Their damage reviewer is
// still staff attached to this file and can supply the stage-1 product code.
const candidateIds = [
...new Set(
[
blame.initiatedByFieldExpertId,
blame.expert?.assignedExpertId,
blame.expert?.decision?.decidedByExpertId,
claimCase?.initiatedByFieldExpertId,
this.fanavaranDamageReplyActorId(claimCase),
claimCase?.workflow?.assignedForReviewBy?.actorId,
]
.filter((value) => value != null && String(value).trim() !== "")
.map((value) => String(value)),
),
];
const missingOnStaff: string[] = [];
for (const staffId of candidateIds) {
const staff = await this.findStaffDocumentById(staffId);
if (!staff) {
missingOnStaff.push(`${staffId} (staff not found in expert/damage/field/fileMaker/fileReviewer)`);
continue;
}
const rawValue = (staff as Record<string, unknown>)[fieldName];
const id = resolveFileMakerStageOneExpertId(staff, blame.type);
if (id != null) {
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: candidateIds,
};
}
missingOnStaff.push(
`${staffId} (${fieldName}=${rawValue == null || rawValue === "" ? "empty" : JSON.stringify(rawValue)})`,
);
}
return {
claimExpertId: null,
code: "FANAVARAN_CLAIM_EXPERT_ID_MISSING",
message:
candidateIds.length === 0
? `ClaimExpertId unresolved: this claim/blame has no assigned staff id (checked initiatedByFieldExpertId, expert.assignedExpertId, expert.decision.decidedByExpertId, evaluation.damageExpertReplyFinal/damageExpertReply.actorDetail.actorId, workflow.assignedForReviewBy.actorId). Assign staff with ${fieldName} to this file.`
: `ClaimExpertId unresolved: checked assigned staff [${missingOnStaff.join("; ")}]. Your ${fieldName} must be on THAT assigned staff document, not a different user.`,
candidatesTried: candidateIds,
};
}
/** /**
* V4/V5 FileMaker flows: GEN.03 ClaimExpertId from file-maker; GEN.06 from file-reviewer. * GEN.03 ClaimExpertId from the staff assigned to this file (never tenant defaults).
* Returns null for non–file-maker blames (tenant defaults apply). * Preview may pass `{ required: false }` to keep building the payload with null.
*/ */
private async resolveFanavaranBaseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown;
expert?: {
assignedExpertId?: unknown;
decision?: { decidedByExpertId?: unknown };
};
},
claimCase?: FanavaranClaimExpertContext | null,
options?: { required?: boolean },
): Promise<number | null> {
const resolved = await this.tryResolveFanavaranBaseClaimExpertId(
blame,
claimCase,
);
if (resolved.claimExpertId != null) return resolved.claimExpertId;
if (options?.required === false) return null;
throw new BadRequestException({
code: resolved.code ?? "FANAVARAN_CLAIM_EXPERT_ID_MISSING",
message:
resolved.message ??
"ClaimExpertId unresolved on the assigned expert profile.",
});
}
private fanavaranDamageReplyActorId(
claimCase?: { evaluation?: object } | null,
): unknown {
const evaluation = claimCase?.evaluation as
| {
damageExpertReplyFinal?: { actorDetail?: { actorId?: unknown } };
damageExpertReply?: { actorDetail?: { actorId?: unknown } };
}
| undefined;
const active = getActiveV2ExpertReply({
evaluation: claimCase?.evaluation as Record<string, unknown> | undefined,
});
return (
(active?.reply as { actorDetail?: { actorId?: unknown } } | undefined)
?.actorDetail?.actorId ??
evaluation?.damageExpertReplyFinal?.actorDetail?.actorId ??
evaluation?.damageExpertReply?.actorDetail?.actorId
);
}
private async tryResolveFanavaranExpertiseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
assignedFileReviewerId?: unknown;
},
claimCase: { evaluation?: Record<string, unknown> } | null | undefined,
): Promise<{
claimExpertId: number | null;
code: string | null;
message: string | null;
candidatesTried: string[];
}> {
const fieldName =
blame?.type === BlameRequestType.CAR_BODY
? "CarBodyExpertiseClaim"
: "ThirdPartyExpertiseClaim";
if (blame?.type == null) {
return {
claimExpertId: null,
code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message:
"Expertise ClaimExpertId unresolved: blame.type is missing.",
candidatesTried: [],
};
}
if (blame.isMadeByFileMaker) {
if (!blame.assignedFileReviewerId) {
return {
claimExpertId: null,
code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING",
message:
"Expertise ClaimExpertId unresolved: no assignedFileReviewerId on this FileMaker file.",
candidatesTried: [],
};
}
const fileReviewerId = String(blame.assignedFileReviewerId);
const fileReviewer =
await this.fileReviewerDbService.findById(fileReviewerId);
if (!fileReviewer) {
return {
claimExpertId: null,
code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING",
message: `Expertise ClaimExpertId unresolved: FileReviewer ${fileReviewerId} was not found.`,
candidatesTried: [fileReviewerId],
};
}
const id = resolveFileReviewerExpertiseExpertId(fileReviewer, blame.type);
if (id == null) {
return {
claimExpertId: null,
code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING",
message: `Expertise ClaimExpertId unresolved: FileReviewer ${fileReviewerId} has empty ${fieldName}.`,
candidatesTried: [fileReviewerId],
};
}
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: [fileReviewerId],
};
}
const actorId = this.fanavaranDamageReplyActorId(claimCase);
if (actorId == null || String(actorId).trim() === "") {
return {
claimExpertId: null,
code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message:
"Expertise ClaimExpertId unresolved: no damage-expert reply actorDetail.actorId on this claim.",
candidatesTried: [],
};
}
const staffId = String(actorId);
const staff = await this.findStaffDocumentById(staffId);
if (!staff) {
return {
claimExpertId: null,
code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message: `Expertise ClaimExpertId unresolved: staff ${staffId} was not found.`,
candidatesTried: [staffId],
};
}
const id = resolveFileReviewerExpertiseExpertId(staff, blame.type);
if (id == null) {
return {
claimExpertId: null,
code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message: `Expertise ClaimExpertId unresolved: staff ${staffId} has empty ${fieldName}.`,
candidatesTried: [staffId],
};
}
return {
claimExpertId: id,
code: null,
message: null,
candidatesTried: [staffId],
};
}
/**
* GEN.08 / GEN.06 ClaimExpertId from the assessor assigned to this file (never tenant defaults).
* Preview may pass `{ required: false }` to keep building the payload with null.
*/
private async resolveFanavaranExpertiseClaimExpertId(
blame: {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
assignedFileReviewerId?: unknown;
},
claimCase: { evaluation?: Record<string, unknown> } | null | undefined,
options?: { required?: boolean },
): Promise<number | null> {
const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId(
blame,
claimCase,
);
if (resolved.claimExpertId != null) return resolved.claimExpertId;
if (options?.required === false) return null;
throw new BadRequestException({
code: resolved.code ?? "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message:
resolved.message ??
"Expertise ClaimExpertId unresolved on the assigned assessor profile.",
});
}
/** @deprecated Use resolveFanavaranBaseClaimExpertId / resolveFanavaranExpertiseClaimExpertId */
private async resolveFanavaranFileRoleExpertIdsForBlame(blame: { private async resolveFanavaranFileRoleExpertIdsForBlame(blame: {
isMadeByFileMaker?: boolean; isMadeByFileMaker?: boolean;
type?: BlameRequestType; type?: BlameRequestType;
initiatedByFieldExpertId?: unknown; initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown; assignedFileReviewerId?: unknown;
expert?: {
assignedExpertId?: unknown;
decision?: { decidedByExpertId?: unknown };
};
}): Promise<{ }): Promise<{
baseClaimExpertId: number | null; baseClaimExpertId: number | null;
expertiseClaimExpertId: number | null; expertiseClaimExpertId: number | null;
} | 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; 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( private async getPolicyIdFromNationalCode(
@@ -4006,6 +4365,12 @@ export class ClaimRequestManagementService {
resolvePolicy?: boolean; resolvePolicy?: boolean;
/** When true (submit), missing PolicyId throws. Preview keeps payload even if inquiry fails. */ /** When true (submit), missing PolicyId throws. Preview keeps payload even if inquiry fails. */
requirePolicyId?: boolean; requirePolicyId?: boolean;
/**
* When false (HTTP preview), missing staff ClaimExpertId stays null and is
* reported in previewWarnings instead of throwing.
* Submit keeps the default (required).
*/
requireClaimExpertId?: boolean;
auditSession?: FanavaranAuditSession; auditSession?: FanavaranAuditSession;
/** Persist built payload onto fanavaranSync.baseClaim.lastPayload (default true). */ /** Persist built payload onto fanavaranSync.baseClaim.lastPayload (default true). */
persistPayload?: boolean; persistPayload?: boolean;
@@ -4018,11 +4383,21 @@ export class ClaimRequestManagementService {
}, },
): Promise<any> { ): Promise<any> {
const profile = getFanavaranClientProfile(clientKey); const profile = getFanavaranClientProfile(clientKey);
const payloadDefaults = this.fanavaranPayloadDefaultsWithoutExpertIds(
profile.defaults as unknown as Record<string, unknown>,
);
const logPrefix = `[Fanavaran ${clientKey} V2] claimCaseId=${claimCaseId}`; const logPrefix = `[Fanavaran ${clientKey} V2] claimCaseId=${claimCaseId}`;
const forceRefreshPolicy = options?.forceRefreshPolicy === true; const forceRefreshPolicy = options?.forceRefreshPolicy === true;
const forceRefreshUsedId = options?.forceRefreshUsedId === true; const forceRefreshUsedId = options?.forceRefreshUsedId === true;
const requirePolicyId = options?.requirePolicyId === true; const requirePolicyId = options?.requirePolicyId === true;
const requireClaimExpertId = options?.requireClaimExpertId !== false;
const persistPayload = options?.persistPayload !== false; const persistPayload = options?.persistPayload !== false;
const previewWarnings: Array<{
code: string;
message: string;
field: string;
candidatesTried?: string[];
}> = [];
const auditSession = const auditSession =
options?.auditSession ?? options?.auditSession ??
({ ({
@@ -4129,7 +4504,14 @@ export class ClaimRequestManagementService {
createdAt: accidentAt, createdAt: accidentAt,
location: firstParty?.location, location: firstParty?.location,
damageParts, damageParts,
defaults: profile.defaults, defaults: payloadDefaults as {
AccidentCityId: number;
AccidentReportTypeId: number;
AccidentVehicleUsedId: number;
CompensationReferenceId: number;
CulpritLicenceTypeId: number;
CulpritTypeId: number;
},
logPrefix, logPrefix,
requirePolicyId, requirePolicyId,
resolvePolicyId: async () => { resolvePolicyId: async () => {
@@ -4389,17 +4771,33 @@ export class ClaimRequestManagementService {
} }
} }
const fileRoleExpertIds = const claimExpertResolution =
await this.resolveFanavaranFileRoleExpertIdsForBlame(blameCase); await this.tryResolveFanavaranBaseClaimExpertId(blameCase, claimCase);
if (fileRoleExpertIds) { payload.ClaimExpertId = claimExpertResolution.claimExpertId;
if (fileRoleExpertIds.baseClaimExpertId == null) { (debug as any).steps.claimExpertIdResolved =
claimExpertResolution.claimExpertId != null;
(debug as any).values.claimExpertId =
claimExpertResolution.claimExpertId;
(debug as any).values.claimExpertIdCandidatesTried =
claimExpertResolution.candidatesTried;
if (claimExpertResolution.claimExpertId == null) {
const warning = {
code:
claimExpertResolution.code ?? "FANAVARAN_CLAIM_EXPERT_ID_MISSING",
message:
claimExpertResolution.message ??
"ClaimExpertId unresolved on the assigned expert profile.",
field: "ClaimExpertId",
candidatesTried: claimExpertResolution.candidatesTried,
};
previewWarnings.push(warning);
(debug as any).values.claimExpertIdWarning = warning.message;
if (requireClaimExpertId) {
throw new BadRequestException({ throw new BadRequestException({
code: "FILE_MAKER_FANAVARAN_EXPERT_CODE_MISSING", code: warning.code,
message: message: warning.message,
"This FileMaker file cannot be submitted to Fanavaran: stage-1 claim expert id is missing for this product line.",
}); });
} }
payload.ClaimExpertId = fileRoleExpertIds.baseClaimExpertId;
} }
if (persistPayload) { if (persistPayload) {
@@ -4431,6 +4829,14 @@ export class ClaimRequestManagementService {
clientKey, clientKey,
payload, payload,
debug, debug,
previewWarnings,
};
}
if (previewWarnings.length > 0) {
return {
payload,
previewWarnings,
}; };
} }
@@ -4465,7 +4871,9 @@ export class ClaimRequestManagementService {
`[Fanavaran ${clientKey} V2] Error submitting to Fanavaran`, `[Fanavaran ${clientKey} V2] Error submitting to Fanavaran`,
error, error,
); );
throw new BadGatewayException(this.extractFanavaranErrorMessage(error)); throw toFanavaranHttpException(error, {
fallback: "Failed to submit data to Fanavaran API",
});
} }
} }
@@ -4563,7 +4971,9 @@ export class ClaimRequestManagementService {
`[Fanavaran ${clientKey} V2] Error submitting damage case to Fanavaran`, `[Fanavaran ${clientKey} V2] Error submitting damage case to Fanavaran`,
error, error,
); );
throw new BadGatewayException(this.extractFanavaranErrorMessage(error)); throw toFanavaranHttpException(error, {
fallback: "Failed to submit data to Fanavaran API",
});
} }
} }
@@ -5367,6 +5777,8 @@ export class ClaimRequestManagementService {
private async buildFanavaranExpertisePayload(input: { private async buildFanavaranExpertisePayload(input: {
claimCase: any; claimCase: any;
clientKey: FanavaranClientKey; clientKey: FanavaranClientKey;
/** Preview keeps null ClaimExpertId; submit requires it. Default true. */
requireClaimExpertId?: boolean;
}): Promise<{ }): Promise<{
payload: Record<string, unknown>; payload: Record<string, unknown>;
warnings: string[]; warnings: string[];
@@ -5374,6 +5786,7 @@ export class ClaimRequestManagementService {
}> { }> {
const profile = getFanavaranClientProfile(input.clientKey); const profile = getFanavaranClientProfile(input.clientKey);
const active = getActiveV2ExpertReply(input.claimCase as any); const active = getActiveV2ExpertReply(input.claimCase as any);
const requireClaimExpertId = input.requireClaimExpertId !== false;
const blameForExpertIds = input.claimCase?.blameRequestId const blameForExpertIds = input.claimCase?.blameRequestId
? await this.blameRequestDbService.findById( ? await this.blameRequestDbService.findById(
@@ -5381,30 +5794,43 @@ export class ClaimRequestManagementService {
) )
: null; : null;
// GEN.06 ClaimExpertId = tenant ExpertiseClaimExpertId (assessor role), unless // GEN.08 / GEN.06 ClaimExpertId always from assigned assessor staff profile.
// V4/V5 FileMaker flow → file-reviewer expertise code for this product line. const warnings: string[] = [];
let claimExpertId = profile.defaults.ExpertiseClaimExpertId; let claimExpertId: number | null = null;
if (blameForExpertIds) { if (!blameForExpertIds) {
const roleExpertIds = const message =
await this.resolveFanavaranFileRoleExpertIdsForBlame( "Expertise ClaimExpertId unresolved: linked blame case was not found.";
blameForExpertIds as { if (requireClaimExpertId) {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
initiatedByFieldExpertId?: unknown;
assignedFileReviewerId?: unknown;
},
);
if (roleExpertIds?.expertiseClaimExpertId != null) {
claimExpertId = roleExpertIds.expertiseClaimExpertId;
} else if (roleExpertIds) {
throw new BadRequestException({ throw new BadRequestException({
code: "FILE_REVIEWER_FANAVARAN_EXPERT_CODE_MISSING", code: "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message: message,
"Fanavaran expertise cannot be submitted: assign a FileReviewer with an expertise claim expert id for this product line.",
}); });
} }
warnings.push(message);
} else {
const resolved = await this.tryResolveFanavaranExpertiseClaimExpertId(
blameForExpertIds as {
isMadeByFileMaker?: boolean;
type?: BlameRequestType;
assignedFileReviewerId?: unknown;
},
input.claimCase,
);
claimExpertId = resolved.claimExpertId;
if (resolved.claimExpertId == null) {
const message =
resolved.message ??
"Expertise ClaimExpertId unresolved on the assigned assessor profile.";
if (requireClaimExpertId) {
throw new BadRequestException({
code:
resolved.code ?? "FANAVARAN_EXPERTISE_CLAIM_EXPERT_ID_MISSING",
message,
});
}
warnings.push(message);
}
} }
const warnings: string[] = [];
if (!active?.parts?.length) { 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.");
@@ -5526,7 +5952,11 @@ export class ClaimRequestManagementService {
if (!claimCase) throw new NotFoundException("Claim case not found"); if (!claimCase) throw new NotFoundException("Claim case not found");
const { payload, warnings, replyKey } = const { payload, warnings, replyKey } =
await this.buildFanavaranExpertisePayload({ claimCase, clientKey }); await this.buildFanavaranExpertisePayload({
claimCase,
clientKey,
requireClaimExpertId: false,
});
await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, { await this.claimCaseDbService.findByIdAndUpdate(claimCaseId, {
$set: { $set: {
@@ -5545,7 +5975,7 @@ export class ClaimRequestManagementService {
submitUrl: claimCase.claimId submitUrl: claimCase.claimId
? `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/expertise` ? `${await this.fanavaranClaimsUrlForClaim(claimCaseId)}/${claimCase.claimId}/expertise`
: null, : null,
ready: warnings.length === 0, ready: warnings.length === 0 && payload.ClaimExpertId != null,
warnings: Array.from(new Set(warnings)), warnings: Array.from(new Set(warnings)),
payload, payload,
}; };
@@ -5589,7 +6019,9 @@ export class ClaimRequestManagementService {
`[Fanavaran ${clientKey} V2] Error submitting expertise to Fanavaran`, `[Fanavaran ${clientKey} V2] Error submitting expertise to Fanavaran`,
error, error,
); );
throw new BadGatewayException(this.extractFanavaranErrorMessage(error)); throw toFanavaranHttpException(error, {
fallback: "Failed to submit data to Fanavaran API",
});
} }
} }
@@ -6794,29 +7226,10 @@ export class ClaimRequestManagementService {
} }
private extractFanavaranErrorMessage(error: unknown): string { private extractFanavaranErrorMessage(error: unknown): string {
if (isAxiosError(error)) { return extractFanavaranOriginalMessage(
return ( error,
error.response?.data?.message || "Failed to submit data to Fanavaran API",
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";
} }
private static readonly FANAVARAN_RETRY_DELAY_MS = 5 * 60 * 1000; // 5 minutes private static readonly FANAVARAN_RETRY_DELAY_MS = 5 * 60 * 1000; // 5 minutes
@@ -0,0 +1,265 @@
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("resolves a user-created base claim from its damage-expert reply actor", async () => {
const management = serviceWithStaff({
damageExpert: {
ThirdPartyClaimExpertId: "5507",
ThirdPartyExpertiseClaim: "5510",
},
});
const resolved = await (
management as any
).tryResolveFanavaranBaseClaimExpertId(
{ type: BlameRequestType.THIRD_PARTY },
{
evaluation: {
damageExpertReply: {
actorDetail: { actorId: "6af036ab0222c1322767ce19" },
},
},
},
);
expect(resolved).toMatchObject({
claimExpertId: 5507,
code: null,
candidatesTried: ["6af036ab0222c1322767ce19"],
});
});
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.each(["blame", "claim"])(
"reads V2/V3 stage-1 codes from the %s field-expert initiator",
async (source) => {
const management = serviceWithStaff({
fieldExpert: { ThirdPartyClaimExpertId: "154" },
});
(management as any).damageExpertDbService.findById.mockImplementation(
async (id: string) =>
id === "dmg-1" ? { ThirdPartyClaimExpertId: "5507" } : null,
);
await expect(
(management as any).resolveFanavaranBaseClaimExpertId(
{
type: BlameRequestType.THIRD_PARTY,
...(source === "blame" && { initiatedByFieldExpertId: "field-1" }),
},
{
...(source === "claim" && { initiatedByFieldExpertId: "field-1" }),
evaluation: {
damageExpertReply: { actorDetail: { actorId: "dmg-1" } },
},
},
),
).resolves.toBe(154);
},
);
it("resolves the CAR_BODY stage-1 code from the final review actor", async () => {
const management = serviceWithStaff({
damageExpert: {
CarBodyClaimExpertId: "5508",
CarBodyExpertiseClaim: "5509",
},
});
const resolved = await (
management as any
).tryResolveFanavaranBaseClaimExpertId(
{ type: BlameRequestType.CAR_BODY },
{
evaluation: {
damageExpertReply: { actorDetail: { actorId: "initial-reviewer" } },
damageExpertReplyFinal: {
actorDetail: { actorId: "final-reviewer" },
},
},
},
);
expect(resolved.claimExpertId).toBe(5508);
expect(
(management as any).damageExpertDbService.findById,
).toHaveBeenCalledWith("final-reviewer");
});
it("resolves stage-1 from persistent claim assignment before a reply exists", async () => {
const management = serviceWithStaff({
damageExpert: { ThirdPartyClaimExpertId: "5507" },
});
await expect(
(management as any).resolveFanavaranBaseClaimExpertId(
{ type: BlameRequestType.THIRD_PARTY },
{ workflow: { assignedForReviewBy: { actorId: "dmg-1" } } },
),
).resolves.toBe(5507);
});
it("does not treat a temporary workflow lock as review assignment", async () => {
const management = serviceWithStaff({
damageExpert: { ThirdPartyClaimExpertId: "5507" },
});
const resolved = await (
management as any
).tryResolveFanavaranBaseClaimExpertId(
{ type: BlameRequestType.THIRD_PARTY },
{ workflow: { lockedBy: { actorId: "someone-else" } } },
);
expect(resolved.claimExpertId).toBeNull();
expect(
(management as any).damageExpertDbService.findById,
).not.toHaveBeenCalled();
});
it("reports an attached review actor whose stage-1 code is missing", async () => {
const management = serviceWithStaff({
damageExpert: { ThirdPartyExpertiseClaim: "5510" },
});
const resolved = await (
management as any
).tryResolveFanavaranBaseClaimExpertId(
{ type: BlameRequestType.THIRD_PARTY },
{
evaluation: {
damageExpertReply: { actorDetail: { actorId: "dmg-1" } },
},
},
);
expect(resolved.claimExpertId).toBeNull();
expect(resolved.candidatesTried).toEqual(["dmg-1"]);
expect(resolved.message).toContain("ThirdPartyClaimExpertId=empty");
});
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",
},
{
evaluation: {
damageExpertReply: { actorDetail: { actorId: "dmg-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);
});
it("preview soft-resolve returns null plus a concrete warning instead of throwing", async () => {
const management = serviceWithStaff({});
await expect(
(management as any).resolveFanavaranBaseClaimExpertId(
{
type: BlameRequestType.THIRD_PARTY,
expert: { assignedExpertId: "missing" },
},
null,
{ required: false },
),
).resolves.toBeNull();
const soft = await (management as any).tryResolveFanavaranBaseClaimExpertId(
{
type: BlameRequestType.THIRD_PARTY,
expert: { assignedExpertId: "missing" },
},
);
expect(soft.claimExpertId).toBeNull();
expect(soft.code).toBe("FANAVARAN_CLAIM_EXPERT_ID_MISSING");
expect(soft.message).toMatch(/ThirdPartyClaimExpertId/);
expect(soft.candidatesTried).toEqual(["missing"]);
});
});
+10
View File
@@ -561,6 +561,16 @@ export function localizeErrorMessage(
return "این عملیات در مرحله فعلی پرونده امکان‌پذیر نیست. پرونده را دوباره باز کنید و مرحله جاری را بررسی کنید."; return "این عملیات در مرحله فعلی پرونده امکان‌پذیر نیست. پرونده را دوباره باز کنید و مرحله جاری را بررسی کنید.";
if (/file.*required|video.*required|image.*required/i.test(message)) if (/file.*required|video.*required|image.*required/i.test(message))
return "فایل لازم برای این مرحله را بارگذاری کنید."; return "فایل لازم برای این مرحله را بارگذاری کنید.";
if (
/ClaimExpertId unresolved|ThirdPartyClaimExpertId|CarBodyClaimExpertId|ThirdPartyExpertiseClaim|CarBodyExpertiseClaim/i.test(
message,
)
) {
if (/Expertise ClaimExpertId|expertise claim expert|FileReviewer/i.test(message)) {
return "کد کارشناس ارزیاب فناوران (ClaimExpertId مرحله کارشناسی) روی پروفایل کارشناس اختصاص‌یافته تنظیم نشده است. ThirdPartyExpertiseClaim یا CarBodyExpertiseClaim را در مدیریت کارکنان تنظیم کنید.";
}
return "کد کارشناس مسئول پرونده فناوران (ClaimExpertId) روی پروفایل کارشناس اختصاص‌یافته تنظیم نشده است. ThirdPartyClaimExpertId یا CarBodyClaimExpertId را در مدیریت کارکنان تنظیم کنید.";
}
if ( if (
/fanavaran.*(?:missing|required|failed)|policyid.*required/i.test(message) /fanavaran.*(?:missing|required|failed)|policyid.*required/i.test(message)
) )
@@ -152,9 +152,14 @@ describe("Expert Fanavaran stage fields", () => {
management.resolveAccidentVehicleUsedFromApis = jest management.resolveAccidentVehicleUsedFromApis = jest
.fn() .fn()
.mockResolvedValue({ usedId: 1 }); .mockResolvedValue({ usedId: 1 });
management.resolveFanavaranFileRoleExpertIdsForBlame = jest management.tryResolveFanavaranBaseClaimExpertId = jest
.fn() .fn()
.mockResolvedValue(null); .mockResolvedValue({
claimExpertId: 154,
code: null,
message: null,
candidatesTried: ["expert-1"],
});
management.enrichCarBodyHullBaseClaimPayload = jest management.enrichCarBodyHullBaseClaimPayload = jest
.fn() .fn()
.mockImplementation(async ({ payload }) => { .mockImplementation(async ({ payload }) => {
@@ -164,7 +169,9 @@ describe("Expert Fanavaran stage fields", () => {
const payload = await management.previewFanavaranSubmitV2(id, clientKey, { const payload = await management.previewFanavaranSubmitV2(id, clientKey, {
persistPayload: false, persistPayload: false,
forceRefreshPolicy: false, forceRefreshPolicy: false,
requireClaimExpertId: false,
}); });
expect(payload.ClaimExpertId).toBe(154);
expect(payload).toMatchObject({ expect(payload).toMatchObject({
AccidentLocationAddress: "نشانی واقعی", AccidentLocationAddress: "نشانی واقعی",
AccidentCityId: 702, AccidentCityId: 702,
@@ -233,19 +240,26 @@ describe("Expert Fanavaran stage fields", () => {
management.blameRequestDbService = { management.blameRequestDbService = {
findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }), findById: jest.fn().mockResolvedValue({ type: "THIRD_PARTY" }),
}; };
management.resolveFanavaranFileRoleExpertIdsForBlame = jest management.tryResolveFanavaranExpertiseClaimExpertId = jest
.fn() .fn()
.mockResolvedValue(null); .mockResolvedValue({
claimExpertId: 29,
code: null,
message: null,
candidatesTried: ["dmg-1"],
});
management.resolveFanavaranClaimProduct = jest management.resolveFanavaranClaimProduct = jest
.fn() .fn()
.mockResolvedValue("third-party"); .mockResolvedValue("third-party");
const result = await management.buildFanavaranExpertisePayload({ const result = await management.buildFanavaranExpertisePayload({
claimCase: claim, claimCase: claim,
clientKey: "parsian", clientKey: "parsian",
requireClaimExpertId: false,
}); });
expect(result.payload).toMatchObject({ expect(result.payload).toMatchObject({
InspectionPlaceId: 283, InspectionPlaceId: 283,
DmgCaseId: 20, DmgCaseId: 20,
ClaimExpertId: 29,
}); });
}); });
+2 -19
View File
@@ -4,6 +4,7 @@ import { isAxiosError, type AxiosResponse } from "axios";
import { Model, Types } from "mongoose"; import { Model, Types } from "mongoose";
import { randomBytes } from "node:crypto"; import { randomBytes } from "node:crypto";
import type { FanavaranAuditSession } from "./fanavaran-audit.types"; import type { FanavaranAuditSession } from "./fanavaran-audit.types";
import { extractFanavaranOriginalMessage } from "./fanavaran-http-exception";
import { import {
FanavaranAuditLog, FanavaranAuditLog,
FanavaranAuditLogDocument, FanavaranAuditLogDocument,
@@ -236,25 +237,7 @@ export class FanavaranAuditService {
} }
extractErrorMessage(error: unknown): string { extractErrorMessage(error: unknown): string {
if (isAxiosError(error)) { return extractFanavaranOriginalMessage(error, "Fanavaran request failed");
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";
} }
formatErrorWithTrackingCode(message: string, trackingCode?: string): string { formatErrorWithTrackingCode(message: string, trackingCode?: string): string {
+5 -15
View File
@@ -18,6 +18,7 @@ import {
} from "src/core/config/fanavaran-client.config"; } from "src/core/config/fanavaran-client.config";
import { FanavaranAuditService } from "./fanavaran-audit.service"; import { FanavaranAuditService } from "./fanavaran-audit.service";
import type { FanavaranAuditSession } from "./fanavaran-audit.types"; import type { FanavaranAuditSession } from "./fanavaran-audit.types";
import { toFanavaranHttpException } from "./fanavaran-http-exception";
import { import {
FanavaranAuditStatus, FanavaranAuditStatus,
FanavaranAuditStep, FanavaranAuditStep,
@@ -634,20 +635,9 @@ export class FanavaranAuthService {
fallback: string, fallback: string,
auditSession?: FanavaranAuditSession, auditSession?: FanavaranAuditSession,
): HttpException { ): HttpException {
if (error instanceof HttpException) { return toFanavaranHttpException(error, {
return error; fallback,
} trackingCode: auditSession?.trackingCode,
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,
),
);
} }
} }
@@ -2,16 +2,24 @@ import { BadRequestException } from "@nestjs/common";
import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum"; import { BlameRequestType } from "src/Types&Enums/blame-request-management/blameRequestType.enum";
import { parseFanavaranId } from "src/lookups/fanavaran-last-car-policy"; 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; ThirdPartyClaimExpertId?: string;
CarBodyClaimExpertId?: string; CarBodyClaimExpertId?: string;
}; };
export type FileReviewerFanavaranExpertCodes = { /** Expertise / GEN.08–GEN.06 assessor Fanavaran codes. */
export type StaffFanavaranExpertiseCodes = {
ThirdPartyExpertiseClaim?: string; ThirdPartyExpertiseClaim?: string;
CarBodyExpertiseClaim?: 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 { export function parseFanavaranExpertId(raw?: string | null): number | null {
if (raw == null) return null; if (raw == null) return null;
const trimmed = String(raw).trim(); 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)",
);
});
});
+107
View File
@@ -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,
);
}
+19 -23
View File
@@ -1,16 +1,10 @@
import { mkdir, readFile, writeFile } from "node:fs/promises"; import { mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { HttpService } from "@nestjs/axios"; import { HttpService } from "@nestjs/axios";
import { import { Injectable, Logger, NotFoundException } from "@nestjs/common";
BadGatewayException,
Injectable,
Logger,
NotFoundException,
} from "@nestjs/common";
import { InjectModel } from "@nestjs/mongoose"; import { InjectModel } from "@nestjs/mongoose";
import { Model } from "mongoose"; import { Model } from "mongoose";
import { firstValueFrom } from "rxjs"; import { firstValueFrom } from "rxjs";
import { isAxiosError } from "axios";
import { import {
getFanavaranLookupBaseUrl, getFanavaranLookupBaseUrl,
type FanavaranClientKey, type FanavaranClientKey,
@@ -25,6 +19,10 @@ import {
tejaratStaticAccidentFilePath, tejaratStaticAccidentFilePath,
} from "./fanavaran-lookup.config"; } from "./fanavaran-lookup.config";
import { FanavaranAuthService } from "./fanavaran-auth.service"; import { FanavaranAuthService } from "./fanavaran-auth.service";
import {
extractFanavaranOriginalMessage,
toFanavaranHttpException,
} from "./fanavaran-http-exception";
@Injectable() @Injectable()
export class FanavaranLookupService { export class FanavaranLookupService {
@@ -124,18 +122,17 @@ export class FanavaranLookupService {
return response.data; return response.data;
} catch (error) { } catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error); this.fanavaranAuthService.registerFailure(clientKey, error);
const message = isAxiosError(error) const message = extractFanavaranOriginalMessage(
? error.response?.data?.Message || error,
error.response?.data?.message || "Fanavaran lookup request failed",
error.message );
: error instanceof Error
? error.message
: "Fanavaran lookup request failed";
this.logger.error( this.logger.error(
`Fanavaran lookup fetch failed for ${clientKey} (${url}): ${message}`, `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; return response.data;
} catch (error) { } catch (error) {
this.fanavaranAuthService.registerFailure(clientKey, error); this.fanavaranAuthService.registerFailure(clientKey, error);
const message = isAxiosError(error) const message = extractFanavaranOriginalMessage(
? error.response?.data?.Message || error,
error.response?.data?.message || "Fanavaran POST request failed",
error.message );
: error instanceof Error
? error.message
: "Fanavaran POST request failed";
this.logger.error( this.logger.error(
`Fanavaran POST failed for ${clientKey} (${url}): ${message}`, `Fanavaran POST failed for ${clientKey} (${url}): ${message}`,
); );
throw new BadGatewayException(String(message)); throw toFanavaranHttpException(error, {
fallback: "Fanavaran POST request failed",
});
} }
} }
+2 -1
View File
@@ -58,7 +58,7 @@ export class FanavaranController {
@ApiOperation({ @ApiOperation({
summary: "Preview Fanavaran base claim create payload", summary: "Preview Fanavaran base claim create payload",
description: description:
"GET has no request body. Always rebuilds GEN.03 from live policy + VIN/vehicle inquiries. Does not reuse fanavaranSync lastPayload / PolicyId / UsedId cache. Auth token is still shared until Asia/Tehran midnight.", "GET has no request body. Always rebuilds GEN.03 from live policy + VIN/vehicle inquiries. Does not reuse fanavaranSync lastPayload / PolicyId / UsedId cache. Missing staff ClaimExpertId does not fail the preview — it returns ClaimExpertId=null plus previewWarnings with the exact missing field/staff. Auth token is still shared until Asia/Tehran midnight.",
}) })
@ApiParam({ @ApiParam({
name: "client", name: "client",
@@ -102,6 +102,7 @@ export class FanavaranController {
forceRefreshPolicy: true, forceRefreshPolicy: true,
forceRefreshUsedId: true, forceRefreshUsedId: true,
requirePolicyId: false, requirePolicyId: false,
requireClaimExpertId: false,
}, },
); );
} }
@@ -20,6 +20,12 @@ export class ExpertDbService {
return await this.expertModel.findOne(user).lean(); 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( async findOneAndUpdate(
user: FilterQuery<ExpertModel>, user: FilterQuery<ExpertModel>,
update: FilterQuery<ExpertModel>, update: FilterQuery<ExpertModel>,