forked from Yara724/api
fix: harden profile updates and localize public errors in Persian
Preserve actor and user profile fields during partial updates and validate supported personal data. Add Persian HTTP error handling, validation translations, regression tests, and audit documentation.
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
import {
|
||||
ArgumentsHost,
|
||||
Catch,
|
||||
ExceptionFilter,
|
||||
HttpException,
|
||||
Logger,
|
||||
} from "@nestjs/common";
|
||||
import { HttpAdapterHost } from "@nestjs/core";
|
||||
import { localizeErrorPayload } from "./persian-errors";
|
||||
|
||||
@Catch()
|
||||
export class PersianErrorFilter implements ExceptionFilter {
|
||||
private readonly logger = new Logger(PersianErrorFilter.name);
|
||||
constructor(private readonly adapterHost: HttpAdapterHost) {}
|
||||
|
||||
catch(exception: unknown, host: ArgumentsHost) {
|
||||
const { httpAdapter } = this.adapterHost;
|
||||
const response = host.switchToHttp().getResponse();
|
||||
const error = exception as any;
|
||||
let status =
|
||||
exception instanceof HttpException ? exception.getStatus() : 500;
|
||||
let body: unknown =
|
||||
exception instanceof HttpException ? exception.getResponse() : undefined;
|
||||
if (!(exception instanceof HttpException)) {
|
||||
if (error?.name === "ValidationError") {
|
||||
status = 400;
|
||||
body = {
|
||||
statusCode: status,
|
||||
message: Object.values(error.errors ?? {}).map(
|
||||
(item: any) => item.message,
|
||||
),
|
||||
};
|
||||
} else if (error?.name === "CastError") {
|
||||
status = 400;
|
||||
body = {
|
||||
statusCode: status,
|
||||
message: `${error.path || "id"} is invalid`,
|
||||
};
|
||||
} else if (error?.code === 11000) {
|
||||
status = 409;
|
||||
body = {
|
||||
statusCode: status,
|
||||
message: "این اطلاعات قبلاً ثبت شده است. مورد ثبتشده را بررسی کنید.",
|
||||
};
|
||||
}
|
||||
}
|
||||
if (status >= 500)
|
||||
this.logger.error(
|
||||
error instanceof Error ? error.message : "Unhandled request failure",
|
||||
error instanceof Error ? error.stack : undefined,
|
||||
);
|
||||
if (httpAdapter.isHeadersSent(response)) return;
|
||||
const localized = localizeErrorPayload(body, status);
|
||||
httpAdapter.reply(response, localized, status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import {
|
||||
CallHandler,
|
||||
ExecutionContext,
|
||||
Injectable,
|
||||
NestInterceptor,
|
||||
} from "@nestjs/common";
|
||||
import { map } from "rxjs";
|
||||
import { localizeFailureEnvelopes } from "./persian-errors";
|
||||
|
||||
@Injectable()
|
||||
export class PersianErrorInterceptor implements NestInterceptor {
|
||||
intercept(_context: ExecutionContext, next: CallHandler) {
|
||||
return next.handle().pipe(map(localizeFailureEnvelopes));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
import {
|
||||
BadRequestException,
|
||||
ForbiddenException,
|
||||
HttpException,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { firstValueFrom, of } from "rxjs";
|
||||
import {
|
||||
getPersianErrorMessage,
|
||||
localizeErrorMessage,
|
||||
localizeErrorPayload,
|
||||
localizeFailureEnvelopes,
|
||||
} from "./persian-errors";
|
||||
import { PersianErrorFilter } from "./persian-error.filter";
|
||||
import { PersianErrorInterceptor } from "./persian-error.interceptor";
|
||||
|
||||
const persian = (value: string) => {
|
||||
expect(value).toMatch(/[\u0600-\u06ff]/);
|
||||
expect(value).not.toMatch(/[A-Za-z]{2,}/);
|
||||
};
|
||||
|
||||
describe("public Persian error wording", () => {
|
||||
it.each([
|
||||
["nationalCode must be a string", "کد ملی"],
|
||||
[
|
||||
"driverBirthday must be a valid ISO 8601 date string",
|
||||
"تاریخ تولد راننده",
|
||||
],
|
||||
[
|
||||
"licenseType must be one of the following values: 1, 2, 3",
|
||||
"نوع گواهینامه",
|
||||
],
|
||||
["description must be longer than or equal to 100 characters", "۱۰۰"],
|
||||
["CAR_BODY description must contain at least 100 characters", "۱۰۰"],
|
||||
["latitude must not be greater than 90", "حداکثر ۹۰"],
|
||||
["latitude must not be less than -90", "حداقل -۹۰"],
|
||||
[
|
||||
"price must be a number conforming to the specified constraints",
|
||||
"قیمت قطعه",
|
||||
],
|
||||
[
|
||||
"Guilty party OTP must be verified before running inquiries.",
|
||||
"کد تأیید طرف مقصر",
|
||||
],
|
||||
[
|
||||
"Damaged party OTP must be verified before running inquiries.",
|
||||
"کد تأیید زیاندیده",
|
||||
],
|
||||
["Complete damaged-party inquiries before signing.", "پیش از امضا"],
|
||||
["Request is locked by another expert", "کارشناس دیگری"],
|
||||
["Only the damaged party can create the claim", "زیاندیده"],
|
||||
[
|
||||
"Unknown provider exception with credentials and stack details",
|
||||
"دوباره تلاش کنید",
|
||||
],
|
||||
])(
|
||||
"localizes %s without exposing identifiers or internal prose",
|
||||
(input, expected) => {
|
||||
const result = localizeErrorMessage(input);
|
||||
persian(result);
|
||||
if (expected === "پیش از امضا") expect(result).toContain("سپس امضا");
|
||||
else expect(result).toContain(expected);
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves helpful Persian messages and translates technical field names", () => {
|
||||
expect(localizeErrorMessage("کد ملی راننده باید ۱۰ رقم باشد.")).toBe(
|
||||
"کد ملی راننده باید ۱۰ رقم باشد.",
|
||||
);
|
||||
expect(localizeErrorMessage("VIN واردشده معتبر نیست.")).toBe(
|
||||
"شماره شاسی واردشده معتبر نیست.",
|
||||
);
|
||||
persian(localizeErrorMessage("خطا: Internal server error"));
|
||||
});
|
||||
|
||||
it.each([401, 403, 404, 409, 413, 415, 429, 500, 502, 503, 504])(
|
||||
"has a readable fallback for HTTP %s",
|
||||
(status) => {
|
||||
persian(localizeErrorPayload(undefined, status).message);
|
||||
},
|
||||
);
|
||||
|
||||
it("retains machine codes, field paths, IDs, arrays and numeric constraints without mutating the original", () => {
|
||||
const original = {
|
||||
statusCode: 422,
|
||||
code: "VALIDATION_ERROR",
|
||||
error: "PART_NOT_ON_CLAIM",
|
||||
field: "parts[0].price",
|
||||
partId: 30,
|
||||
minAmount: 100000,
|
||||
message: ["price must be a number", "partId must be an integer number"],
|
||||
validationErrors: [
|
||||
{ field: "parts[0].price", message: "price must be a number" },
|
||||
],
|
||||
};
|
||||
const result = localizeErrorPayload(original, 422);
|
||||
expect(result).toMatchObject({
|
||||
code: "VALIDATION_ERROR",
|
||||
error: "PART_NOT_ON_CLAIM",
|
||||
field: "parts[0].price",
|
||||
partId: 30,
|
||||
minAmount: 100000,
|
||||
});
|
||||
expect(result.message).toHaveLength(2);
|
||||
result.message.forEach(persian);
|
||||
persian(result.validationErrors[0].message);
|
||||
expect(original.message[0]).toBe("price must be a number");
|
||||
});
|
||||
|
||||
it("reads nested responses and message arrays rather than generic transport messages", () => {
|
||||
expect(
|
||||
getPersianErrorMessage({
|
||||
message: "Request failed with status code 422",
|
||||
response: {
|
||||
status: 422,
|
||||
data: {
|
||||
message: [
|
||||
"nationalCode should not be empty",
|
||||
"birthday must be a valid ISO 8601 date string",
|
||||
],
|
||||
},
|
||||
},
|
||||
}),
|
||||
).toContain("کد ملی");
|
||||
expect(
|
||||
getPersianErrorMessage({
|
||||
response: { status: 400, data: "کد ملی صحیح نیست." },
|
||||
}),
|
||||
).toBe("کد ملی صحیح نیست.");
|
||||
expect(
|
||||
getPersianErrorMessage({
|
||||
errors: ["نام را وارد کنید.", "کد ملی را وارد کنید."],
|
||||
message: "2 errors occurred",
|
||||
}),
|
||||
).toBe("نام را وارد کنید.، کد ملی را وارد کنید.");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ code: "ECONNABORTED" },
|
||||
{ code: "ERR_NETWORK" },
|
||||
{ code: "CERT_HAS_EXPIRED" },
|
||||
{ name: "NotAllowedError", code: 0, message: "Permission denied" },
|
||||
{ name: "NotFoundError", code: 8, message: "No camera" },
|
||||
])("handles network, TLS and browser device errors: %j", (error) =>
|
||||
persian(getPersianErrorMessage(error)),
|
||||
);
|
||||
|
||||
it("changes only failure envelopes, retaining success data, reports and statuses", async () => {
|
||||
const value = {
|
||||
message: "Saved",
|
||||
report: "original English evidence",
|
||||
status: "COMPLETED",
|
||||
checks: [
|
||||
{
|
||||
success: false,
|
||||
code: "INQUIRY_NO_MATCH",
|
||||
message: "Policy not found",
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = await firstValueFrom(
|
||||
new PersianErrorInterceptor().intercept({} as any, {
|
||||
handle: () => of(value),
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
message: "Saved",
|
||||
report: value.report,
|
||||
status: "COMPLETED",
|
||||
checks: [{ code: "INQUIRY_NO_MATCH", success: false }],
|
||||
});
|
||||
persian(result.checks[0].message);
|
||||
expect(localizeFailureEnvelopes(Buffer.from("original bytes"))).toEqual(
|
||||
Buffer.from("original bytes"),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("global Persian HTTP error filter", () => {
|
||||
const reply = jest.fn();
|
||||
const response = {};
|
||||
const filter = new PersianErrorFilter({
|
||||
httpAdapter: { reply, isHeadersSent: () => false },
|
||||
} as any);
|
||||
const host = { switchToHttp: () => ({ getResponse: () => response }) } as any;
|
||||
beforeEach(() => reply.mockClear());
|
||||
it.each([
|
||||
new BadRequestException("nationalCode should not be empty"),
|
||||
new ForbiddenException("Forbidden"),
|
||||
new NotFoundException("Request not found"),
|
||||
new HttpException(
|
||||
{
|
||||
code: "PRICE_CAP_ERROR",
|
||||
partId: 30,
|
||||
message: "price must be a number",
|
||||
},
|
||||
422,
|
||||
),
|
||||
])("preserves exception status and localizes the HTTP body", (error) => {
|
||||
filter.catch(error, host);
|
||||
const [target, body, status] = reply.mock.calls[0];
|
||||
expect(target).toBe(response);
|
||||
expect(status).toBe(error.getStatus());
|
||||
persian(body.message);
|
||||
if (status === 422)
|
||||
expect(body).toMatchObject({ code: "PRICE_CAP_ERROR", partId: 30 });
|
||||
});
|
||||
it("does not expose unexpected exception details", () => {
|
||||
jest
|
||||
.spyOn((filter as any).logger, "error")
|
||||
.mockImplementation(() => undefined);
|
||||
filter.catch(new Error("DB credentials / stack trace"), host);
|
||||
expect(reply.mock.calls[0][2]).toBe(500);
|
||||
expect(JSON.stringify(reply.mock.calls[0][1])).not.toContain("credentials");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,732 @@
|
||||
/** Shared public-error wording. Keep the copies in both independent UI repositories in sync. */
|
||||
const fieldLabels: Record<string, string> = {
|
||||
insurerBirthday: "تاریخ تولد بیمهگذار",
|
||||
driverNationalCodeSecond: "کد ملی راننده طرف دوم",
|
||||
insurerNationalCode: "کد ملی بیمهگذار",
|
||||
driverCode: "کد ملی راننده",
|
||||
insurerCode: "کد ملی بیمهگذار",
|
||||
previousLeftDigits: "دو رقم پلاک قبلی",
|
||||
previousCenterAlphabet: "حرف پلاک قبلی",
|
||||
previousCenterDigits: "سه رقم پلاک قبلی",
|
||||
vinNumber: "شماره شاسی",
|
||||
nationalCode: "کد ملی",
|
||||
nationalcode: "کد ملی",
|
||||
nationalCodeOfInsurer: "کد ملی بیمهگذار",
|
||||
driverNationalCode: "کد ملی راننده",
|
||||
ownerNationalCode: "کد ملی مالک",
|
||||
policyNationalCode: "کد ملی بیمهگذار ثالث",
|
||||
bodyNationalCode: "کد ملی بیمهگذار بدنه",
|
||||
policyholderNationalCode: "کد ملی بیمهگذار",
|
||||
previousPolicyholderNationalCode: "کد ملی بیمهگذار پلاک قبلی",
|
||||
birthDay: "تاریخ تولد",
|
||||
birthday: "تاریخ تولد",
|
||||
birthDate: "تاریخ تولد",
|
||||
driverBirthday: "تاریخ تولد راننده",
|
||||
ownerBirthday: "تاریخ تولد مالک",
|
||||
policyBirthday: "تاریخ تولد بیمهگذار ثالث",
|
||||
bodyBirthday: "تاریخ تولد بیمهگذار بدنه",
|
||||
firstName: "نام",
|
||||
lastName: "نام خانوادگی",
|
||||
fullName: "نام و نام خانوادگی",
|
||||
username: "نام کاربری",
|
||||
email: "ایمیل",
|
||||
password: "رمز عبور",
|
||||
newPassword: "رمز عبور جدید",
|
||||
confirmPassword: "تکرار رمز عبور",
|
||||
mobile: "شماره همراه",
|
||||
phoneNumber: "شماره همراه",
|
||||
phone: "تلفن ثابت",
|
||||
otp: "کد تأیید",
|
||||
firstPartyOtp: "کد تأیید طرف اول",
|
||||
secondPartyOtp: "کد تأیید طرف دوم",
|
||||
captcha: "کد امنیتی",
|
||||
captchaId: "کد امنیتی",
|
||||
role: "نقش کاربری",
|
||||
userType: "نوع حساب",
|
||||
state: "استان",
|
||||
city: "شهر",
|
||||
cityId: "شهر",
|
||||
stateId: "استان",
|
||||
address: "نشانی",
|
||||
gender: "جنسیت",
|
||||
registrationState: "وضعیت پلاک",
|
||||
isNewCar: "وضعیت صفر بودن خودرو",
|
||||
hasDrivingLicense: "وضعیت گواهینامه",
|
||||
ownerRelation: "نسبت مالک با راننده",
|
||||
policyRelation: "نسبت بیمهگذار ثالث",
|
||||
bodyRelation: "نسبت بیمهگذار بدنه",
|
||||
licenseNumber: "شماره گواهینامه",
|
||||
drivingLicenseNumber: "شماره گواهینامه",
|
||||
licenseType: "نوع گواهینامه",
|
||||
drivingLicenseType: "نوع گواهینامه",
|
||||
CulpritLicenceTypeId: "نوع گواهینامه",
|
||||
driverLicenseDate: "تاریخ صدور گواهینامه",
|
||||
driverLicenceDate: "تاریخ صدور گواهینامه",
|
||||
vin: "شماره شاسی",
|
||||
VIN: "شماره شاسی",
|
||||
chassisNumber: "شماره شاسی",
|
||||
engineNumber: "شماره موتور",
|
||||
previousLeft: "دو رقم پلاک قبلی",
|
||||
previousCenter: "سه رقم پلاک قبلی",
|
||||
previousIr: "کد ایران پلاک قبلی",
|
||||
previousAlphabet: "حرف پلاک قبلی",
|
||||
left: "دو رقم پلاک",
|
||||
center: "سه رقم پلاک",
|
||||
ir: "کد ایران پلاک",
|
||||
alphabet: "حرف پلاک",
|
||||
plaque: "پلاک خودرو",
|
||||
plate: "پلاک خودرو",
|
||||
plaque1: "بخش اول پلاک",
|
||||
plaque2: "بخش دوم پلاک",
|
||||
plaque3: "بخش سوم پلاک",
|
||||
plaque4: "کد ایران پلاک",
|
||||
sheba: "شماره شبا",
|
||||
shebaNumber: "شماره شبا",
|
||||
iban: "شماره شبا",
|
||||
bankAccountNumber: "شماره حساب",
|
||||
accidentDate: "تاریخ حادثه",
|
||||
accidentTime: "ساعت حادثه",
|
||||
description: "شرح حادثه",
|
||||
desc: "شرح حادثه",
|
||||
location: "موقعیت حادثه",
|
||||
latitude: "عرض جغرافیایی",
|
||||
longitude: "طول جغرافیایی",
|
||||
lat: "عرض جغرافیایی",
|
||||
lon: "طول جغرافیایی",
|
||||
AccidentLocationAddress: "نشانی محل حادثه",
|
||||
AccidentCityId: "شهر محل حادثه",
|
||||
AccidentReportTypeId: "نوع گزارش حادثه",
|
||||
DmgHistoryStatus: "سابقه خسارت",
|
||||
InspectionPlaceId: "محل بازدید",
|
||||
AccidentTypeId: "نوع حادثه",
|
||||
CulpritTypeId: "نوع مقصر",
|
||||
AuthorityCulpritId: "مرجع تعیین مقصر",
|
||||
CustomerFaultPercent: "درصد تقصیر",
|
||||
RepairDuration: "مدت تعمیر",
|
||||
VehicleCurrentValue: "ارزش روز خودرو",
|
||||
NotifierTypeId: "نوع اعلامکننده",
|
||||
NotifierRelationId: "نسبت اعلامکننده",
|
||||
partId: "قطعه آسیبدیده",
|
||||
selectedPartIds: "قطعات آسیبدیده",
|
||||
carPartDamage: "قطعات آسیبدیده",
|
||||
typeOfDamage: "نوع عملیات روی قطعه",
|
||||
parts: "قطعات آسیبدیده",
|
||||
price: "قیمت قطعه",
|
||||
salary: "اجرت",
|
||||
totalPayment: "مبلغ خسارت",
|
||||
carPrice: "ارزش روز خودرو",
|
||||
currentCarPrice: "ارزش روز خودرو",
|
||||
carModelYear: "سال ساخت خودرو",
|
||||
carModel: "مدل خودرو",
|
||||
carName: "نام خودرو",
|
||||
carType: "نوع خودرو",
|
||||
manualPriceDrop: "مبلغ افت قیمت",
|
||||
partSeverities: "شدت آسیب قطعات",
|
||||
severity: "شدت آسیب",
|
||||
option: "وضعیت داغی",
|
||||
branchId: "شعبه",
|
||||
priceCap: "سقف مبلغ خسارت",
|
||||
file: "فایل",
|
||||
files: "فایلها",
|
||||
images: "تصاویر",
|
||||
image: "تصویر",
|
||||
signature: "امضا",
|
||||
voice: "صدای حادثه",
|
||||
video: "ویدیوی حادثه",
|
||||
requiredDocuments: "مدارک الزامی",
|
||||
requestedItems: "موارد نیازمند اصلاح",
|
||||
resendDocuments: "مدارک نیازمند ارسال مجدد",
|
||||
policyNumber: "شماره بیمهنامه",
|
||||
policyId: "بیمهنامه",
|
||||
policyUniqueCode: "کد یکتای بیمهنامه",
|
||||
policyCINumber: "کد یکتای بیمهنامه",
|
||||
requestId: "شناسه پرونده",
|
||||
claimRequestId: "شناسه پرونده خسارت",
|
||||
publicId: "شماره پرونده",
|
||||
claimId: "شناسه پرونده خسارت",
|
||||
clientKey: "شرکت بیمه",
|
||||
clientId: "شرکت بیمه",
|
||||
insuActivityCo: "شرکت بیمه",
|
||||
type: "نوع پرونده",
|
||||
partyRole: "طرف پرونده",
|
||||
from: "تاریخ شروع",
|
||||
to: "تاریخ پایان",
|
||||
page: "شماره صفحه",
|
||||
limit: "تعداد نتایج",
|
||||
isActive: "وضعیت فعالیت",
|
||||
ThirdPartyClaimExpertId: "کد کارشناس مسئول پرونده مالی",
|
||||
CarBodyClaimExpertId: "کد کارشناس مسئول پرونده بدنه",
|
||||
ThirdPartyExpertiseClaim: "کد کارشناس ارزیاب خسارت ثالث مالی",
|
||||
CarBodyExpertiseClaim: "کد کارشناس ارزیاب خسارت بدنه",
|
||||
};
|
||||
export const persianNumber = (value: unknown): string =>
|
||||
String(value ?? "").replace(/\d/g, (digit) => "۰۱۲۳۴۵۶۷۸۹"[Number(digit)]);
|
||||
export function errorFieldLabel(value?: string): string {
|
||||
if (!value) return "این فیلد";
|
||||
if (/[\u0600-\u06ff]/.test(value)) return value;
|
||||
if (fieldLabels[value]) return fieldLabels[value];
|
||||
const segments = value.replace(/\[\d+\]/g, "").split(".");
|
||||
return fieldLabels[segments[segments.length - 1]] || "این فیلد";
|
||||
}
|
||||
const wording: Record<string, string> = {
|
||||
error: "خطا",
|
||||
"bad request": "اطلاعات ارسالشده معتبر نیست. فیلدهای فرم را بررسی کنید.",
|
||||
unauthorized: "برای ادامه، دوباره وارد حساب کاربری شوید.",
|
||||
forbidden: "شما اجازه انجام این عملیات را ندارید.",
|
||||
"not found":
|
||||
"اطلاعات موردنظر یافت نشد. صفحه را تازه کنید و دوباره تلاش کنید.",
|
||||
"internal server error":
|
||||
"انجام عملیات در سرور با خطا مواجه شد. لطفاً کمی بعد دوباره تلاش کنید.",
|
||||
"something went wrong": "مشکلی پیش آمده است. لطفاً دوباره تلاش کنید.",
|
||||
"missing bearer token": "برای ادامه، دوباره وارد حساب کاربری شوید.",
|
||||
"token not found": "برای ادامه، دوباره وارد حساب کاربری شوید.",
|
||||
"invalid token": "نشست شما معتبر نیست. دوباره وارد حساب کاربری شوید.",
|
||||
"invalid or expired token":
|
||||
"نشست شما منقضی شده است. دوباره وارد حساب کاربری شوید.",
|
||||
"otp invalid": "کد تأیید صحیح نیست. کد پیامکشده را بررسی کنید.",
|
||||
"wait for expiry time to finish":
|
||||
"لطفاً تا پایان زمان انتظار، برای دریافت کد تأیید جدید صبر کنید.",
|
||||
"username, email, or nationalcode is required":
|
||||
"نام کاربری، ایمیل یا کد ملی خود را وارد کنید.",
|
||||
"a user with these details already exists.":
|
||||
"حسابی با این مشخصات قبلاً ثبت شده است.",
|
||||
"no changes supplied": "تغییری برای ذخیره ارسال نشده است.",
|
||||
"only personal profile fields can be updated":
|
||||
"فقط اطلاعات شخصی مجاز حساب قابل ویرایش است.",
|
||||
"invalid actor payload":
|
||||
"اطلاعات حساب معتبر نیست. دوباره وارد حساب کاربری شوید.",
|
||||
"select an insurance company": "ابتدا شرکت بیمه را انتخاب کنید.",
|
||||
"invalid management route":
|
||||
"این عملیات مدیریت در دسترس نیست. صفحه را تازه کنید.",
|
||||
"unsupported staff role": "نقش انتخابشده برای این کاربر پشتیبانی نمیشود.",
|
||||
"'from' must be before or equal to 'to'":
|
||||
"تاریخ شروع باید قبل از تاریخ پایان یا برابر با آن باشد.",
|
||||
"invalid 'from' date": "تاریخ شروع معتبر نیست.",
|
||||
"invalid 'to' date": "تاریخ پایان معتبر نیست.",
|
||||
"invalid step. expected first_voice or second_voice but got first_location":
|
||||
"ابتدا موقعیت حادثه را ثبت کنید، سپس صدا را ارسال کنید.",
|
||||
"provide sheba (24 digits) and nationalcodeofinsurer (10 digits) together to finish this step, or supply partial fields incrementally.":
|
||||
"برای تکمیل این مرحله، شماره شبای ۲۴ رقمی و کد ملی ۱۰ رقمی صاحب حساب را وارد کنید.",
|
||||
"shebanumber is required and must be valid (ir + 24 digits or only 24 digits)":
|
||||
"شماره شبا باید شامل ۲۴ رقم باشد؛ وارد کردن حروف ابتدایی شبا اختیاری است.",
|
||||
"a signature file is required": "امضای خود را ثبت کنید.",
|
||||
"signature file is required": "امضای خود را ثبت کنید.",
|
||||
"a factor file is required for upload.": "فایل فاکتور را بارگذاری کنید.",
|
||||
"this part does not require a factor upload.":
|
||||
"برای این قطعه نیازی به ارسال فاکتور نیست.",
|
||||
"a factor has already been uploaded for this part.":
|
||||
"فاکتور این قطعه قبلاً ارسال شده است. صفحه را تازه کنید.",
|
||||
"no expert reply found in this claim.":
|
||||
"هنوز نظر کارشناسی برای این پرونده ثبت نشده است.",
|
||||
"the specified part was not found in the expert's reply.":
|
||||
"قطعه انتخابشده در پاسخ کارشناس یافت نشد. پرونده را دوباره باز کنید.",
|
||||
"you must lock the request before submitting a reply.":
|
||||
"ابتدا بررسی پرونده را بر عهده بگیرید، سپس پاسخ کارشناسی را ثبت کنید.",
|
||||
"you must lock the request first before submitting a reply.":
|
||||
"ابتدا بررسی پرونده را بر عهده بگیرید، سپس پاسخ کارشناسی را ثبت کنید.",
|
||||
"you must lock the claim before entering price-drop data":
|
||||
"ابتدا بررسی پرونده را بر عهده بگیرید، سپس افت قیمت را ثبت کنید.",
|
||||
"your lock time has expired. please lock the request again before submitting.":
|
||||
"مهلت بررسی پرونده تمام شده است. دوباره بررسی پرونده را بر عهده بگیرید.",
|
||||
"you are not a party in this request":
|
||||
"این پرونده به حساب کاربری شما تعلق ندارد.",
|
||||
"this file does not belong to your organization.":
|
||||
"این پرونده متعلق به شرکت بیمه شما نیست.",
|
||||
"this file belongs to another branch.": "این پرونده متعلق به شعبه دیگری است.",
|
||||
"filemaker account is not assigned to a branch.":
|
||||
"برای حساب شما شعبهای تعیین نشده است. با مدیر سامانه تماس بگیرید.",
|
||||
"guilty party otp must be verified before running inquiries.":
|
||||
"ابتدا کد تأیید طرف مقصر را تأیید کنید، سپس استعلام بگیرید.",
|
||||
"damaged party otp must be verified before running inquiries.":
|
||||
"ابتدا کد تأیید زیاندیده را تأیید کنید، سپس استعلام بگیرید.",
|
||||
"party otp must be verified before the car-body form.":
|
||||
"ابتدا کد تأیید پیامکشده را تأیید کنید، سپس فرم بیمه بدنه را تکمیل کنید.",
|
||||
"guilty party must sign before running damaged-party inquiries.":
|
||||
"ابتدا امضای طرف مقصر را ثبت کنید، سپس اطلاعات زیاندیده را استعلام بگیرید.",
|
||||
"guilty party must sign before damaged-party inquiries.":
|
||||
"ابتدا امضای طرف مقصر را ثبت کنید، سپس اطلاعات زیاندیده را استعلام بگیرید.",
|
||||
"submit car-body-form before running inquiries (car_body).":
|
||||
"ابتدا فرم بیمه بدنه را تکمیل کنید، سپس استعلام بگیرید.",
|
||||
"car-body form must be submitted before running inquiries.":
|
||||
"ابتدا فرم بیمه بدنه را تکمیل کنید، سپس استعلام بگیرید.",
|
||||
"complete guilty-party inquiries before collecting details.":
|
||||
"ابتدا استعلامهای طرف مقصر را تکمیل کنید، سپس اطلاعات حادثه را ثبت کنید.",
|
||||
"complete damaged-party inquiries before collecting details.":
|
||||
"ابتدا استعلامهای زیاندیده را تکمیل کنید، سپس اطلاعات حادثه را ثبت کنید.",
|
||||
"complete guilty-party inquiries before signing.":
|
||||
"ابتدا استعلامهای طرف مقصر را تکمیل کنید، سپس امضا را ثبت کنید.",
|
||||
"complete damaged-party inquiries before signing.":
|
||||
"ابتدا استعلامهای زیاندیده را تکمیل کنید، سپس امضا را ثبت کنید.",
|
||||
"guilty party has already signed.":
|
||||
"طرف مقصر قبلاً امضا کرده است. صفحه را تازه کنید.",
|
||||
"damaged party has already signed.":
|
||||
"زیاندیده قبلاً امضا کرده است. صفحه را تازه کنید.",
|
||||
"all party inquiries are already complete.":
|
||||
"استعلامهای طرفین قبلاً تکمیل شده است. صفحه را تازه کنید.",
|
||||
"all required party signatures must be collected before accident fields.":
|
||||
"ابتدا امضای تمام طرفهای لازم را ثبت کنید، سپس اطلاعات حادثه را تکمیل کنید.",
|
||||
"all required party signatures must be collected before the blame accident video.":
|
||||
"ابتدا امضای تمام طرفهای لازم را ثبت کنید، سپس ویدیوی حادثه را ارسال کنید.",
|
||||
"submit accident fields before uploading the blame accident video.":
|
||||
"ابتدا اطلاعات حادثه را تکمیل کنید، سپس ویدیوی حادثه را ارسال کنید.",
|
||||
"upload the claim walk-around video (car-capture) before the blame accident video.":
|
||||
"ابتدا ویدیوی دور خودرو را ارسال کنید، سپس ویدیوی حادثه را بارگذاری کنید.",
|
||||
"complete capture-part (parts, angles, and capture-phase documents) before the blame accident video.":
|
||||
"ابتدا عکس قطعات، زوایای خودرو و مدارک لازم را کامل کنید، سپس ویدیوی حادثه را ارسال کنید.",
|
||||
"claim not found. complete guilty-party inquiries first.":
|
||||
"ابتدا استعلامهای طرف مقصر را تکمیل کنید تا پرونده خسارت ایجاد شود.",
|
||||
"no claim linked to this blame file yet. complete guilty-party run-inquiries first.":
|
||||
"ابتدا استعلامهای طرف مقصر را تکمیل کنید تا پرونده خسارت ایجاد شود.",
|
||||
"car_body has only one party.": "پرونده بیمه بدنه فقط یک طرف دارد.",
|
||||
"car_body has only first party; use partyrole first.":
|
||||
"پرونده بیمه بدنه فقط یک طرف دارد. اطلاعات طرف اول را ثبت کنید.",
|
||||
"the case changed during review. refresh before saving.":
|
||||
"اطلاعات پرونده هنگام بررسی تغییر کرده است. پیش از ذخیره، صفحه را تازه کنید.",
|
||||
"the fanavaran fields changed. refresh before saving.":
|
||||
"اطلاعات موردنیاز فناوران تغییر کرده است. پیش از ذخیره، صفحه را تازه کنید.",
|
||||
"the case changed or its stage was sent. refresh before saving.":
|
||||
"اطلاعات یا مرحله پرونده تغییر کرده است. پیش از ذخیره، صفحه را تازه کنید.",
|
||||
"provide at least one partseverities line, or use manualpricedrop for a direct override.":
|
||||
"شدت آسیب حداقل یک قطعه را انتخاب کنید یا مبلغ نهایی افت قیمت را بهصورت دستی وارد کنید.",
|
||||
"no valid severity coefficients could be derived from partseverities.":
|
||||
"برای قطعات انتخابشده ضریب معتبری پیدا نشد. قطعات و شدت آسیب را بررسی کنید.",
|
||||
"carmodelyear is required when it cannot be resolved from the linked blame plate inquiry.":
|
||||
"سال ساخت خودرو از استعلام مشخص نشد. سال ساخت را وارد کنید.",
|
||||
"file too large":
|
||||
"حجم فایل بیش از حد مجاز است. فایل کمحجمتری بارگذاری کنید.",
|
||||
"unexpected field":
|
||||
"فایل ارسالشده با مدارک لازم برای این مرحله مطابقت ندارد.",
|
||||
"canvas is not supported":
|
||||
"این مرورگر امکان آمادهسازی تصویر را ندارد. از مرورگر بهروز استفاده کنید.",
|
||||
};
|
||||
const defaultMessage = "انجام عملیات با خطا مواجه شد. لطفاً دوباره تلاش کنید.";
|
||||
export function statusErrorMessage(status?: number): string {
|
||||
if (status === 401)
|
||||
return "نشست شما معتبر نیست یا منقضی شده است. دوباره وارد حساب کاربری شوید.";
|
||||
if (status === 403) return "شما اجازه انجام این عملیات را ندارید.";
|
||||
if (status === 404)
|
||||
return "اطلاعات موردنظر یافت نشد. صفحه را تازه کنید و دوباره تلاش کنید.";
|
||||
if (status === 409)
|
||||
return "اطلاعات تغییر کرده یا قبلاً ثبت شده است. صفحه را تازه کنید و دوباره بررسی کنید.";
|
||||
if (status === 413) return wording["file too large"];
|
||||
if (status === 415)
|
||||
return "نوع فایل پشتیبانی نمیشود. فایل را با قالب مجاز بارگذاری کنید.";
|
||||
if (status === 429)
|
||||
return "تعداد درخواستها بیش از حد مجاز است. کمی صبر کنید و دوباره تلاش کنید.";
|
||||
if (status === 502 || status === 503)
|
||||
return "سرویس موردنیاز در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید.";
|
||||
if (status === 504 || status === 408)
|
||||
return "زمان پاسخگویی به پایان رسید. لطفاً دوباره تلاش کنید.";
|
||||
if (status === 400 || status === 422)
|
||||
return "اطلاعات فرم کامل یا معتبر نیست. فیلدهای مشخصشده را بررسی کنید.";
|
||||
return defaultMessage;
|
||||
}
|
||||
|
||||
/** Translate messages at the display boundary; never translate IDs, codes or enum values in data. */
|
||||
export function localizeErrorMessage(
|
||||
value: unknown,
|
||||
status?: number,
|
||||
fallback?: string,
|
||||
): string {
|
||||
const safeFallback =
|
||||
fallback && /[\u0600-\u06ff]/.test(fallback)
|
||||
? fallback
|
||||
: statusErrorMessage(status);
|
||||
if (Array.isArray(value))
|
||||
return (
|
||||
[
|
||||
...new Set(
|
||||
value.map((item) => localizeErrorMessage(item, status, safeFallback)),
|
||||
),
|
||||
].join("، ") || safeFallback
|
||||
);
|
||||
if (typeof value !== "string" || !value.trim()) return safeFallback;
|
||||
const message = value.trim();
|
||||
const lower = message.toLowerCase();
|
||||
if (wording[lower]) return wording[lower];
|
||||
if (
|
||||
/car_body.*description.*(?:100|۱۰۰)|description.*must.*(?:100|۱۰۰).*characters/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "شرح حادثه باید حداقل ۱۰۰ کاراکتر باشد.";
|
||||
const operation =
|
||||
/^failed to (fetch|get|load|send|upload|submit|add|create|update|verify|delete|remove) (.+)$/i.exec(
|
||||
message,
|
||||
);
|
||||
if (operation) {
|
||||
const subject = /profile/i.test(operation[2])
|
||||
? "اطلاعات حساب"
|
||||
: /licen[cs]e.*type/i.test(operation[2])
|
||||
? "انواع گواهینامه"
|
||||
: /state/i.test(operation[2])
|
||||
? "فهرست استانها"
|
||||
: /cit(?:y|ies)/i.test(operation[2])
|
||||
? "فهرست شهرها"
|
||||
: /otp/i.test(operation[2])
|
||||
? "کد تأیید"
|
||||
: /video/i.test(operation[2])
|
||||
? "ویدیو"
|
||||
: /voice|audio/i.test(operation[2])
|
||||
? "صدا"
|
||||
: /image|photo/i.test(operation[2])
|
||||
? "تصویر"
|
||||
: /link/i.test(operation[2])
|
||||
? "لینک پرونده"
|
||||
: /claim.*case|claim.*request/i.test(operation[2])
|
||||
? "پرونده خسارت"
|
||||
: /blame.*case|blame.*request/i.test(operation[2])
|
||||
? "پرونده تصادف"
|
||||
: /request.*id/i.test(operation[2])
|
||||
? "شناسه پرونده"
|
||||
: /request/i.test(operation[2])
|
||||
? "پرونده"
|
||||
: /accident/i.test(operation[2])
|
||||
? "اطلاعات حادثه"
|
||||
: /initial form/i.test(operation[2])
|
||||
? "اطلاعات اولیه"
|
||||
: "اطلاعات موردنیاز";
|
||||
const action = /^(fetch|get|load)$/i.test(operation[1])
|
||||
? "دریافت"
|
||||
: /^(send|upload)$/i.test(operation[1])
|
||||
? "ارسال"
|
||||
: /verify/i.test(operation[1])
|
||||
? "تأیید"
|
||||
: /^(delete|remove)$/i.test(operation[1])
|
||||
? "حذف"
|
||||
: "ثبت";
|
||||
return `${action} ${subject} انجام نشد. لطفاً دوباره تلاش کنید.`;
|
||||
}
|
||||
if (
|
||||
/timeout|timed out|time limit|econnaborted|etimedout|request aborted/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return statusErrorMessage(504);
|
||||
if (
|
||||
/network error|^failed to fetch$|err_network|econnrefused|enotfound|econnreset|fetch failed|socket hang up/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "ارتباط با سرور برقرار نشد. اتصال اینترنت را بررسی کنید و دوباره تلاش کنید.";
|
||||
if (/ssl|certificate|cert_has_expired|err_cert_/i.test(message))
|
||||
return "برقراری ارتباط امن با سرور ممکن نشد. با پشتیبانی تماس بگیرید.";
|
||||
if (/permission denied|notallowederror|permission dismissed/i.test(message))
|
||||
return "دسترسی لازم داده نشده است. مجوز دوربین یا میکروفون را در تنظیمات مرورگر فعال کنید.";
|
||||
if (/notfounderror|requested device not found/i.test(message))
|
||||
return "دوربین یا میکروفونی پیدا نشد. اتصال دستگاه و تنظیمات مرورگر را بررسی کنید.";
|
||||
if (
|
||||
/notreadableerror|could not start video source|device.*(?:busy|in use)/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "دوربین یا میکروفون در دسترس نیست. برنامههای دیگری را که از آن استفاده میکنند ببندید.";
|
||||
if (/overconstrainederror|constraintnotsatisfiederror/i.test(message))
|
||||
return "دوربین یا میکروفون با تنظیمات فعلی سازگار نیست. دستگاه دیگری انتخاب کنید.";
|
||||
|
||||
const validation =
|
||||
/^([\w.[\]-]+)\s+(?:must|should|is|has|cannot|can not)\s+(.+)$/i.exec(
|
||||
message,
|
||||
);
|
||||
if (
|
||||
validation &&
|
||||
(fieldLabels[validation[1]] ||
|
||||
/required|not be empty|be defined|be a[n]? (?:string|number|integer|boolean|array|object)|date string|ISO.?8601|one of|enum|characters|greater than|less than|must match/i.test(
|
||||
validation[2],
|
||||
))
|
||||
) {
|
||||
const label = errorFieldLabel(validation[1]);
|
||||
const rule = validation[2];
|
||||
const count = /(?:equal to|than|least|most|exactly|contain)\s+(\d+)/i.exec(
|
||||
rule,
|
||||
)?.[1];
|
||||
if (/not be empty|be defined|required|not be null/i.test(rule))
|
||||
return `${label} را وارد کنید.`;
|
||||
if (
|
||||
/longer than|at least|minimum/i.test(rule) &&
|
||||
/character/i.test(rule) &&
|
||||
count
|
||||
)
|
||||
return `${label} باید حداقل ${persianNumber(count)} کاراکتر باشد.`;
|
||||
if (
|
||||
/shorter than|at most|maximum/i.test(rule) &&
|
||||
/character/i.test(rule) &&
|
||||
count
|
||||
)
|
||||
return `${label} باید حداکثر ${persianNumber(count)} کاراکتر باشد.`;
|
||||
const exactLength = /(?:equal to|exactly)\s+(\d+)\s+characters/i.exec(rule);
|
||||
if (exactLength)
|
||||
return `${label} باید ${persianNumber(exactLength[1])} کاراکتر باشد.`;
|
||||
if (/one of|enum|not be one of/i.test(rule))
|
||||
return `${label} را از گزینههای موجود انتخاب کنید.`;
|
||||
if (/email/i.test(rule))
|
||||
return `${label} معتبر نیست. نشانی ایمیل را کامل وارد کنید.`;
|
||||
if (/phone|mobile/i.test(rule))
|
||||
return `${label} معتبر نیست. شماره را کامل وارد کنید.`;
|
||||
if (/date|iso ?8601/i.test(rule))
|
||||
return `${label} معتبر نیست. تاریخ را از تقویم انتخاب کنید.`;
|
||||
if (/integer|number|numeric|decimal/i.test(rule))
|
||||
return `برای ${label} یک عدد معتبر وارد کنید.`;
|
||||
if (/boolean/i.test(rule)) return `وضعیت ${label} را مشخص کنید.`;
|
||||
if (/array|list/i.test(rule))
|
||||
return `گزینههای ${label} را بهدرستی انتخاب کنید.`;
|
||||
const bound =
|
||||
/(?:not be greater than|not be less than|be greater than|be less than)\s+(-?\d+(?:\.\d+)?)/i.exec(
|
||||
rule,
|
||||
);
|
||||
if (bound) {
|
||||
const comparison = /not be greater/i.test(rule)
|
||||
? "حداکثر"
|
||||
: /not be less/i.test(rule)
|
||||
? "حداقل"
|
||||
: /be greater/i.test(rule)
|
||||
? "بیشتر از"
|
||||
: "کمتر از";
|
||||
return `${label} باید ${comparison} ${persianNumber(bound[1])} باشد.`;
|
||||
}
|
||||
return `${label} معتبر نیست. مقدار واردشده را بررسی کنید.`;
|
||||
}
|
||||
const required = /^([\w.[\]-]+)\s+(?:is required|required)(?:[. ]|$)/i.exec(
|
||||
message,
|
||||
);
|
||||
if (required) return `${errorFieldLabel(required[1])} را وارد کنید.`;
|
||||
if (/validation failed.*numeric string/i.test(message))
|
||||
return "شناسه واردشده باید عدد باشد.";
|
||||
if (
|
||||
/cast to objectid|invalid.*(?:objectid|request id|claim.*id|publicid)/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "شناسه پرونده معتبر نیست. پرونده را از فهرست پروندهها باز کنید.";
|
||||
if (
|
||||
/invalid outer part id|unknown partid|no price-drop mapping/i.test(message)
|
||||
)
|
||||
return "قطعه انتخابشده برای این عملیات معتبر نیست. فهرست قطعات را دوباره بررسی کنید.";
|
||||
if (/only.*damaged party|only.*beneficiary/i.test(message))
|
||||
return "ثبت درخواست خسارت فقط برای زیاندیده پرونده امکانپذیر است.";
|
||||
if (
|
||||
/(blame|accident).*not.*(?:completed|finished)|complete.*blame.*before/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "ابتدا مراحل پرونده تصادف را کامل کنید، سپس درخواست خسارت را ثبت کنید.";
|
||||
if (/locked by another|taken by another|currently locked/i.test(message))
|
||||
return "کارشناس دیگری در حال بررسی این پرونده است. پس از پایان بررسی دوباره تلاش کنید.";
|
||||
if (/must lock|lock.*before|lock time.*expired/i.test(message))
|
||||
return "ابتدا بررسی پرونده را بر عهده بگیرید، سپس این عملیات را انجام دهید.";
|
||||
if (/already exists|duplicate|e11000/i.test(message))
|
||||
return "این اطلاعات قبلاً ثبت شده است. مورد ثبتشده را بررسی کنید.";
|
||||
if (/already.*signed/i.test(message))
|
||||
return "امضای این طرف قبلاً ثبت شده است. صفحه را تازه کنید.";
|
||||
if (/already.*(?:uploaded|submitted|set|complete)/i.test(message))
|
||||
return "این مرحله قبلاً ثبت شده است. صفحه را تازه کنید و وضعیت پرونده را بررسی کنید.";
|
||||
if (/not found/i.test(message)) {
|
||||
if (/first party/i.test(message))
|
||||
return "اطلاعات طرف اول پرونده یافت نشد. پرونده را دوباره باز کنید.";
|
||||
if (/second party/i.test(message))
|
||||
return "اطلاعات طرف دوم پرونده یافت نشد. پرونده را دوباره باز کنید.";
|
||||
if (/user|actor|profile/i.test(message))
|
||||
return "حساب کاربری یافت نشد. دوباره وارد حساب کاربری شوید.";
|
||||
if (/client|insurer/i.test(message))
|
||||
return "شرکت بیمه انتخابشده یافت نشد. انتخاب شرکت را بررسی کنید.";
|
||||
if (/part/i.test(message))
|
||||
return "قطعه انتخابشده یافت نشد. فهرست قطعات را دوباره بررسی کنید.";
|
||||
if (/claim|blame|request|case|file/i.test(message))
|
||||
return "پرونده موردنظر یافت نشد. پرونده را از فهرست پروندهها باز کنید.";
|
||||
return statusErrorMessage(404);
|
||||
}
|
||||
if (/only.*(?:filemakers|filemaker)/i.test(message))
|
||||
return "این عملیات فقط برای کارشناس تشکیل پرونده مجاز است.";
|
||||
if (/only.*(?:filereviewers|filereviewer)/i.test(message))
|
||||
return "این عملیات فقط برای کارشناس بررسی پرونده مجاز است.";
|
||||
if (/only.*call.center/i.test(message))
|
||||
return "این عملیات فقط برای کارشناس مرکز تماس مجاز است.";
|
||||
if (
|
||||
/only.*initiating field expert|only.*filemaker who created|access.*(?:created|initiated)/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "این عملیات فقط برای کارشناس ایجادکننده پرونده مجاز است.";
|
||||
if (
|
||||
/unauthori[sz]ed|invalid.*role|access.*required|not allowed for.*role/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return statusErrorMessage(403);
|
||||
if (
|
||||
/invalid.*step|workflow.*step|current status|current:|not available for review|not waiting|must be.*status|must be.*state/i.test(
|
||||
message,
|
||||
)
|
||||
)
|
||||
return "این عملیات در مرحله فعلی پرونده امکانپذیر نیست. پرونده را دوباره باز کنید و مرحله جاری را بررسی کنید.";
|
||||
if (/file.*required|video.*required|image.*required/i.test(message))
|
||||
return "فایل لازم برای این مرحله را بارگذاری کنید.";
|
||||
if (
|
||||
/fanavaran.*(?:missing|required|failed)|policyid.*required/i.test(message)
|
||||
)
|
||||
return "اطلاعات لازم برای ارسال به فناوران کامل نیست. استعلام و اطلاعات پرونده را بررسی کنید؛ در صورت تداوم خطا با پشتیبانی تماس بگیرید.";
|
||||
if (/configuration|not configured|environment variable/i.test(message))
|
||||
return "تنظیمات لازم برای این عملیات کامل نیست. با مدیر سامانه تماس بگیرید.";
|
||||
|
||||
if (/[\u0600-\u06ff]/.test(message)) {
|
||||
let translated = message.replace(
|
||||
/\b(?:CAR_BODY|THIRD_PARTY|IN_PERSON|OTP|VIN|API|Fanavaran)\b/gi,
|
||||
(word) =>
|
||||
(
|
||||
({
|
||||
car_body: "بیمه بدنه",
|
||||
third_party: "بیمه شخص ثالث",
|
||||
in_person: "حضوری",
|
||||
otp: "کد تأیید",
|
||||
vin: "شماره شاسی",
|
||||
api: "سرویس",
|
||||
fanavaran: "فناوران",
|
||||
}) as Record<string, string>
|
||||
)[word.toLowerCase()]!,
|
||||
);
|
||||
translated = translated.replace(
|
||||
/\b[A-Za-z][A-Za-z0-9_]*\b/g,
|
||||
(word) => fieldLabels[word] || word,
|
||||
);
|
||||
// A Persian prefix must not allow an entire technical English sentence through.
|
||||
if (
|
||||
!/[A-Za-z]{2,}/.test(
|
||||
translated.replace(
|
||||
/\b(?:JPEG|JPG|PNG|PDF|HEIC|WEBP|MP4|WEBM|IR)\b/gi,
|
||||
"",
|
||||
),
|
||||
)
|
||||
)
|
||||
return translated;
|
||||
}
|
||||
return safeFallback;
|
||||
}
|
||||
|
||||
type ErrorRecord = Record<string, any>;
|
||||
const record = (value: unknown): ErrorRecord | undefined =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as ErrorRecord)
|
||||
: undefined;
|
||||
export function getPersianErrorMessage(
|
||||
error: unknown,
|
||||
fallback?: string,
|
||||
): string {
|
||||
const root = record(error);
|
||||
const data = record(root?.response?.data) ?? record(root?.data) ?? root;
|
||||
const status =
|
||||
Number(root?.response?.status ?? data?.statusCode ?? root?.status) ||
|
||||
undefined;
|
||||
const code = `${root?.code ?? ""} ${root?.name ?? ""}`;
|
||||
if (
|
||||
/ECONN|ETIMEDOUT|ERR_NETWORK|CERT_|NotAllowedError|NotFoundError|NotReadableError|OverconstrainedError/i.test(
|
||||
code,
|
||||
)
|
||||
)
|
||||
return localizeErrorMessage(code, status, fallback);
|
||||
if (
|
||||
typeof root?.response?.data === "string" ||
|
||||
Array.isArray(root?.response?.data)
|
||||
)
|
||||
return localizeErrorMessage(root.response.data, status, fallback);
|
||||
const validationMessages =
|
||||
Array.isArray(data?.errors) &&
|
||||
data.errors.every((item: unknown) => typeof item === "string")
|
||||
? data.errors
|
||||
: undefined;
|
||||
const source =
|
||||
data?.messageFa ??
|
||||
validationMessages ??
|
||||
data?.message ??
|
||||
data?.Message ??
|
||||
data?.error?.message ??
|
||||
data?.error ??
|
||||
root?.message ??
|
||||
error;
|
||||
return localizeErrorMessage(source, status, fallback);
|
||||
}
|
||||
|
||||
const isCode = (value: string) => /^[A-Z][A-Z0-9_.:-]*$/.test(value);
|
||||
/** Preserve structured validation metadata and message arrays for existing clients. */
|
||||
export function localizeErrorPayload(value: unknown, status?: number): any {
|
||||
if (typeof value === "string" || Array.isArray(value))
|
||||
return Array.isArray(value)
|
||||
? value.map((item) =>
|
||||
typeof item === "object"
|
||||
? localizeErrorPayload(item, status)
|
||||
: localizeErrorMessage(item, status),
|
||||
)
|
||||
: { statusCode: status, message: localizeErrorMessage(value, status) };
|
||||
const body = record(value);
|
||||
if (!body) return { statusCode: status, message: statusErrorMessage(status) };
|
||||
const result: ErrorRecord = { ...body };
|
||||
for (const key of [
|
||||
"message",
|
||||
"messageFa",
|
||||
"Message",
|
||||
"errorMessage",
|
||||
"detail",
|
||||
"reason",
|
||||
]) {
|
||||
if (body[key] != null)
|
||||
result[key] = Array.isArray(body[key])
|
||||
? body[key].map((item: unknown) => localizeErrorMessage(item, status))
|
||||
: localizeErrorMessage(body[key], status);
|
||||
}
|
||||
if (typeof body.error === "string" && !isCode(body.error))
|
||||
result.error = localizeErrorMessage(body.error, status);
|
||||
else if (record(body.error))
|
||||
result.error = localizeErrorPayload(body.error, status);
|
||||
for (const key of ["errors", "validationErrors", "details"]) {
|
||||
if (Array.isArray(body[key]))
|
||||
result[key] = body[key].map((item: unknown) =>
|
||||
typeof item === "object"
|
||||
? localizeErrorPayload(item, status)
|
||||
: localizeErrorMessage(item, status),
|
||||
);
|
||||
else if (record(body[key]))
|
||||
result[key] = Object.fromEntries(
|
||||
Object.entries(body[key]).map(([field, item]) => [
|
||||
field,
|
||||
Array.isArray(item)
|
||||
? item.map((message) => localizeErrorMessage(message, status))
|
||||
: localizeErrorMessage(item, status),
|
||||
]),
|
||||
);
|
||||
}
|
||||
if (record(body.constraints))
|
||||
result.constraints = Object.fromEntries(
|
||||
Object.entries(body.constraints).map(([key, message]) => [
|
||||
key,
|
||||
localizeErrorMessage(message, status),
|
||||
]),
|
||||
);
|
||||
if (body.children && Array.isArray(body.children))
|
||||
result.children = body.children.map((item: unknown) =>
|
||||
localizeErrorPayload(item, status),
|
||||
);
|
||||
if (!result.message && !result.messageFa)
|
||||
result.message = getPersianErrorMessage(body, statusErrorMessage(status));
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Only localize failure nodes in successful JSON; leave business data and success messages alone. */
|
||||
export function localizeFailureEnvelopes(value: any): any {
|
||||
if (Array.isArray(value)) return value.map(localizeFailureEnvelopes);
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== "object" ||
|
||||
Object.getPrototypeOf(value) !== Object.prototype
|
||||
)
|
||||
return value;
|
||||
if (
|
||||
value.success === false ||
|
||||
value.isSuccess === false ||
|
||||
value.type === "error" ||
|
||||
value.status === "failed"
|
||||
)
|
||||
return localizeErrorPayload(value, value.statusCode);
|
||||
const output: ErrorRecord = {};
|
||||
for (const [key, item] of Object.entries(value))
|
||||
output[key] = localizeFailureEnvelopes(item);
|
||||
return output;
|
||||
}
|
||||
Reference in New Issue
Block a user