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
+2 -19
View File
@@ -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 {
+5 -15
View File
@@ -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)",
);
});
});
+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 { 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",
});
}
}