forked from Yara724/api
Merge pull request 'fix: harden profile updates and localize public errors in Persian' (#373) from s.yahyaee/yara724-api:main into main
Reviewed-on: Yara724/api#373
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
# پیامهای خطای فارسی
|
||||
|
||||
خطاهای قابل نمایش به کاربر در API و دو رابط `ui-user` و `ui-expert` در مرز پاسخ یا نمایش فارسی میشوند. پیامهای استعلام، اعتبارسنجی، ورود، امضا، دسترسی و مراحل پرونده، خطاهای شبکه و دسترسی دوربین/میکروفون پوشش داده شدهاند.
|
||||
|
||||
## رفتار و توسعه
|
||||
|
||||
- `PersianErrorFilter` خطاهای HTTP را فارسی میکند؛ وضعیت HTTP، کد خطا، شناسهها و مسیر فیلدها حفظ میشوند. پیامهای آرایهای اعتبارسنجی همچنان آرایه هستند.
|
||||
- `PersianErrorInterceptor` فقط گرههایی را که صریحاً شکست را مشخص میکنند، در پاسخهای موفق پردازش میکند. گزارشها، دادههای پرونده، پاسخهای موفق و فایلها ترجمه نمیشوند.
|
||||
- برای خطای انگلیسی ناشناخته، پیام فارسی متناسب با وضعیت HTTP نمایش داده میشود. پیامهای شناختهشده راهنمای عملی دقیقتری دارند. خطاهای غیرمنتظره سرور در لاگ ثبت میشوند.
|
||||
- رشتههای داخلی سرویسها که بعضی مسیرها برای تصمیمگیری بررسی میکنند تغییر نکردهاند. برای تصمیمگیری جدید از `code` یا وضعیت HTTP استفاده کنید، نه متن پیام.
|
||||
- `getPersianErrorMessage` در رابطها آرایه پیامها و پاسخهای تودرتو را میخواند. تنظیمات Yup پیش از تعریف schema بارگذاری میشوند و پیامهای پیشفرض فارسی هستند. محدودیتهای بومی مرورگر نیز با حفظ اعتبارسنجی فارسی نمایش داده میشوند و با ویرایش فیلد پاک میشوند.
|
||||
- جدول پیامها و عنوان فیلدها در `src/common/errors/persian-errors.ts` است؛ کپی یکسان آن در `src/utils/persianErrors.ts` دو مخزن رابط نگهداری میشود. تغییرات مشترک باید در هر سه کپی اعمال شوند.
|
||||
- برای خطای کسبوکاری جدید، پیام مشخص فارسی و `code` پایدار تعریف کنید؛ اطلاعات حساس یا پاسخ خام سرویس بیرونی را در پیام کاربر نگذارید.
|
||||
|
||||
## بررسیها
|
||||
|
||||
- تست API: `src/common/errors/persian-errors.spec.ts`، `src/common/utils/inquiry-error.spec.ts` و `src/core/api-route-contract.spec.ts`.
|
||||
- تست رابطها: `npm run test:ui`؛ شامل `scripts/test-error-localization.cjs` برای پیامهای استعلام، Yup، مرورگر، آرایه خطا و حفظ کدها.
|
||||
- بررسی نوعها در هر سه مخزن؛ بررسی واقعی Firefox برای پیامهای اجباری، ایمیل، حداقل عدد و رفع خطا پس از ویرایش.
|
||||
|
||||
API و هر دو رابط را برای پوشش کامل با هم منتشر کنید. این تغییر، اعتبارسنجی سراسری جدیدی فعال نمیکند و قرارداد مسیرها یا مجوز نقشها را تغییر نمیدهد.
|
||||
@@ -0,0 +1,44 @@
|
||||
# Profile panel review — 2026-11-04
|
||||
|
||||
Scope: the regular user account pages, the actor profiles reachable through user flows V2–V6, and the expert panel's account page/editor. This is a profile functionality and accessibility review, not an audit of every application workflow.
|
||||
|
||||
## Plate management
|
||||
|
||||
Profile plate management remains retired. Neither panel exposes saved-plate management. `POST /user/profile/plate` and `DELETE /user/profile/plate/:id` remain absent from the API. Existing historical data is retained; accident inquiry plate entry is a separate capability and remains available.
|
||||
|
||||
## Confirmed problems and fixes
|
||||
|
||||
| Problem | Fix |
|
||||
| --- | --- |
|
||||
| User GET responses omitted saved province/address. | Return `state` and `address` in the public user profile. |
|
||||
| User PATCH returned the pre-update document. | Read and return the saved public profile after updating. |
|
||||
| Birthday format differed between the picker, legacy stored data and documented API. | Read legacy Jalali and Gregorian dates in the UI; submit Gregorian date-only strings. The API accepts legacy packed/separated Jalali input and validates before saving. |
|
||||
| Gender labels were submitted in Persian despite the stored `male`/`female` contract. | Normalize gender while preserving Persian UI labels. |
|
||||
| User-panel experts were offered birthday/gender fields unsupported by their profile storage. | Show supported actor name/contact/location fields instead. |
|
||||
| File makers, file reviewers and call-center agents could read profiles but not save their personal details. Field experts could not save their location. | Support personal profile updates for all corresponding actor roles. |
|
||||
| Insurer profile lookup depended on the token username being an email. | Resolve the authenticated insurer account by JWT subject when available. |
|
||||
| Expert editor split names on spaces, discarded later surname words and initialized the landline as empty. | Return explicit first/last names and phone; preserve all existing values. |
|
||||
| Expert location selects did not initialize from the profile and could submit undefined location values. | Bind saved names to form state and load cities for the selected province. Submit only changed fields. |
|
||||
| Province/city lookup failures were silent; stale requests could replace a newer city's options. | Provide recoverable errors and associate requests with the selected province; keep saved values. |
|
||||
| Profile fetch failures looked like empty accounts, and save failures were only logged. | Add loading/error/retry states, retain failed edits, and expose logout even when user profile loading fails. |
|
||||
| The expert edit modal nested buttons around its form and lacked proper dialog focus behavior. | Use the existing Radix dialog, associated input labels and error messages; restore focus to the edit button on close. |
|
||||
| Updating the header name replaced other Redux login properties. | Preserve the existing login state when updating the displayed name. |
|
||||
| Actor PATCH returned the authentication document. | Return the same public profile representation as GET, excluding passwords, OTPs, tokens and internal assignment fields. |
|
||||
|
||||
## Profile API contract
|
||||
|
||||
- `GET/PATCH /user/profile`: authenticated user's personal details only; partial updates supported. Birth dates are Gregorian `YYYY-MM-DD` for new writes. User responses continue to omit saved plates.
|
||||
- `GET/PATCH /actor/profile`: public profile includes explicit `firstName`, `lastName`, `phone`, and `editableFields`. The UI uses `editableFields` to offer only supported controls.
|
||||
- Blame expert, damage expert, field expert, insurer, file maker, file reviewer and call center: name, mobile, landline, province, city and address.
|
||||
- Super admin: first and last names, matching its existing schema.
|
||||
- Legacy registrar: email, matching its existing schema.
|
||||
- Self-profile updates cannot alter role, tenant/branch assignments, national code, password or Fanavaran expert codes. Those management operations retain their separate existing APIs.
|
||||
- Validation is performed in profile services because the application does not enable a global validation pipe. Invalid types, invalid phone numbers/dates and unsupported fields are rejected before writing.
|
||||
|
||||
## Verification
|
||||
|
||||
- Backend regression checks cover each supported actor role, insurer lookup by subject, partial updates, missing accounts, malformed/privileged fields, public responses and user birthday/gender compatibility. Existing authentication-guard and API-route-contract tests are included.
|
||||
- User utility checks cover Gregorian/legacy Jalali dates, Persian digits, multiword names and distinct actor/user PATCH payloads. Existing user UI utility/workflow checks are retained.
|
||||
- Expert profile utility checks cover multiword names, landline preservation, partial changes and role-supported fields.
|
||||
- Local Firefox checks use mocked API data only: regular user save/reopen and failed-save recovery; V2/V3 field expert, V4 file maker, V5 file reviewer and V6 call center profile navigation/save; expert dialog save/reopen/error recovery, mobile overflow, Escape and focus restoration. Desktop and mobile viewport screenshots were inspected.
|
||||
- These checks do not modify production accounts and do not establish that every application page is free of bugs. Physical-device and screen-reader testing remain outside this review.
|
||||
+5
-1
@@ -1,6 +1,8 @@
|
||||
import { PersianErrorFilter } from "./common/errors/persian-error.filter";
|
||||
import { PersianErrorInterceptor } from "./common/errors/persian-error.interceptor";
|
||||
import { ManagementModule } from "./management/management.module";
|
||||
import { join } from "node:path";
|
||||
import { APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
|
||||
import { APP_FILTER, APP_INTERCEPTOR, APP_PIPE } from "@nestjs/core";
|
||||
import { Module } from "@nestjs/common";
|
||||
import { ConfigModule, ConfigService } from "@nestjs/config";
|
||||
import { HttpModule } from "@nestjs/axios";
|
||||
@@ -73,6 +75,8 @@ import { PriceEstimationModule } from "./price-estimation/price-estimation.modul
|
||||
],
|
||||
controllers: [],
|
||||
providers: [
|
||||
{ provide: APP_FILTER, useClass: PersianErrorFilter },
|
||||
{ provide: APP_INTERCEPTOR, useClass: PersianErrorInterceptor },
|
||||
{
|
||||
provide: APP_INTERCEPTOR,
|
||||
useClass: UnicodeDigitsNormalizeInterceptor,
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
import { ActorAuthService } from "./actor.auth.service";
|
||||
import { RoleEnum } from "src/Types&Enums/role.enum";
|
||||
import { Types } from "mongoose";
|
||||
|
||||
const id = "aaaaaaaaaaaaaaaaaaaaaaaa";
|
||||
const personalRoles = [
|
||||
RoleEnum.EXPERT,
|
||||
RoleEnum.DAMAGE_EXPERT,
|
||||
RoleEnum.FIELD_EXPERT,
|
||||
RoleEnum.COMPANY,
|
||||
RoleEnum.FILE_MAKER,
|
||||
RoleEnum.FILE_REVIEWER,
|
||||
RoleEnum.CALL_CENTER,
|
||||
];
|
||||
function setup(role: RoleEnum, saveDocument = true) {
|
||||
const document: any = {
|
||||
_id: new Types.ObjectId(id),
|
||||
role,
|
||||
firstName: "نام چند بخشی",
|
||||
lastName: "نام خانوادگی چند بخشی",
|
||||
mobile: "09120000000",
|
||||
phone: "02122222222",
|
||||
state: "تهران",
|
||||
city: "تهران",
|
||||
address: "نشانی قبلی",
|
||||
email: "account@example.test",
|
||||
password: "private-password-hash",
|
||||
otp: "private-otp",
|
||||
tokens: { token: "private-token" },
|
||||
ThirdPartyClaimExpertId: "123",
|
||||
clientKey: new Types.ObjectId("bbbbbbbbbbbbbbbbbbbbbbbb"),
|
||||
};
|
||||
if (saveDocument) document.save = jest.fn().mockResolvedValue(document);
|
||||
const database = {
|
||||
findOne: jest.fn().mockResolvedValue(document),
|
||||
updateOne: jest
|
||||
.fn()
|
||||
.mockImplementation(async (_filter, update) =>
|
||||
Object.assign(document, update.$set),
|
||||
),
|
||||
};
|
||||
const client = {
|
||||
findOne: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ clientName: { persian: "بیمه آزمایشی" } }),
|
||||
};
|
||||
const service = new ActorAuthService(
|
||||
{} as any,
|
||||
{} as any,
|
||||
database as any,
|
||||
database as any,
|
||||
database as any,
|
||||
database as any,
|
||||
database as any,
|
||||
client as any,
|
||||
{} as any,
|
||||
{} as any,
|
||||
database as any,
|
||||
database as any,
|
||||
database as any,
|
||||
database as any,
|
||||
);
|
||||
const actor = { sub: id, role, username: "stale-username@example.test" };
|
||||
return { service, document, database, actor };
|
||||
}
|
||||
|
||||
describe("self profile across actor roles", () => {
|
||||
it.each(personalRoles)(
|
||||
"saves supported personal fields for %s and returns only the public profile",
|
||||
async (role) => {
|
||||
const { service, document, actor } = setup(role);
|
||||
const result = await service.modifyProfile(actor, {
|
||||
firstName: " نام جدید چند بخشی ",
|
||||
mobile: "۰۹۱۲۳۴۵۶۷۸۹",
|
||||
state: "البرز",
|
||||
city: "کرج",
|
||||
address: "نشانی جدید",
|
||||
});
|
||||
expect(document.save).toHaveBeenCalledTimes(1);
|
||||
expect(document.mobile).toBe("09123456789");
|
||||
expect(document.lastName).toBe("نام خانوادگی چند بخشی");
|
||||
expect(result).toMatchObject({
|
||||
firstName: "نام جدید چند بخشی",
|
||||
lastName: "نام خانوادگی چند بخشی",
|
||||
fullName: "نام جدید چند بخشی نام خانوادگی چند بخشی",
|
||||
mobile: "09123456789",
|
||||
state: "البرز",
|
||||
city: "کرج",
|
||||
insuActivityCo: "بیمه آزمایشی",
|
||||
});
|
||||
expect(result.editableFields).toContain("address");
|
||||
for (const key of [
|
||||
"password",
|
||||
"otp",
|
||||
"tokens",
|
||||
"clientKey",
|
||||
"ThirdPartyClaimExpertId",
|
||||
])
|
||||
expect(result).not.toHaveProperty(key);
|
||||
},
|
||||
);
|
||||
|
||||
it("resolves insurers by their subject rather than a stale or non-email username", async () => {
|
||||
const { service, database, actor } = setup(RoleEnum.COMPANY);
|
||||
await service.getProfiles(actor);
|
||||
expect(database.findOne).toHaveBeenCalledWith({
|
||||
_id: new Types.ObjectId(id),
|
||||
});
|
||||
});
|
||||
|
||||
it("supports the super-admin's lean record without offering unsupported contact fields", async () => {
|
||||
const { service, database, actor } = setup(RoleEnum.SUPER_ADMIN, false);
|
||||
const result = await service.modifyProfile(actor, {
|
||||
firstName: "نام جدید",
|
||||
});
|
||||
expect(database.updateOne).toHaveBeenCalledWith(
|
||||
{ _id: new Types.ObjectId(id) },
|
||||
{ $set: { firstName: "نام جدید" } },
|
||||
);
|
||||
expect(result.editableFields).toEqual(["firstName", "lastName"]);
|
||||
await expect(
|
||||
service.modifyProfile(actor, { mobile: "09123456789" }),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ role: "super_admin" },
|
||||
{ clientKey: id },
|
||||
{ password: "replacement" },
|
||||
{ ThirdPartyClaimExpertId: "666" },
|
||||
{ $set: { firstName: "bad" } },
|
||||
{ city: { $gt: "" } },
|
||||
{ mobile: "invalid" },
|
||||
{ address: null },
|
||||
])("rejects invalid/privileged fields before saving: %j", async (body) => {
|
||||
const { service, document, actor } = setup(RoleEnum.FILE_MAKER);
|
||||
await expect(service.modifyProfile(actor, body)).rejects.toThrow();
|
||||
expect(document.save).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not render undefined names or return data for a missing account", async () => {
|
||||
const { service, database, document, actor } = setup(RoleEnum.SUPER_ADMIN);
|
||||
delete document.firstName;
|
||||
delete document.lastName;
|
||||
expect((await service.getProfiles(actor)).fullName).toBe(document.email);
|
||||
database.findOne.mockResolvedValue(null);
|
||||
await expect(service.getProfiles(actor)).rejects.toThrow(
|
||||
"حساب کاربری یافت نشد",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
ForbiddenException,
|
||||
Injectable,
|
||||
InternalServerErrorException,
|
||||
ConflictException,
|
||||
HttpException,
|
||||
NotFoundException,
|
||||
UnauthorizedException,
|
||||
} from "@nestjs/common";
|
||||
@@ -10,7 +12,13 @@ import { JwtService } from "@nestjs/jwt";
|
||||
import { Types } from "mongoose";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { ForgetPasswordVerifyCodeDtoRs } from "src/auth/dto/actor/forget-password.actor.dto";
|
||||
import { ProfileActor } from "src/auth/dto/actor/profile.actor.dto";
|
||||
import {
|
||||
ActorEditUserProfileDto,
|
||||
ACTOR_PROFILE_EDITABLE_FIELDS,
|
||||
ProfileActor,
|
||||
} from "src/auth/dto/actor/profile.actor.dto";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
import {
|
||||
InsurerRegisterDto,
|
||||
RegisterDto,
|
||||
@@ -103,7 +111,9 @@ export class ActorAuthService {
|
||||
else res = await this.registrarDbService.findOne({ email: username });
|
||||
break;
|
||||
case RoleEnum.COMPANY:
|
||||
res = await this.insurerExpertDbService.findOne({ email: username });
|
||||
res = await this.insurerExpertDbService.findOne(
|
||||
userId ? { _id: new Types.ObjectId(userId) } : { email: username },
|
||||
);
|
||||
break;
|
||||
case RoleEnum.FILE_MAKER:
|
||||
if (username == null && userId)
|
||||
@@ -440,9 +450,10 @@ export class ActorAuthService {
|
||||
currentUser.role === "company" ? currentUser.username : null,
|
||||
currentUser.sub,
|
||||
);
|
||||
const profile = new ProfileActor(userDetail);
|
||||
if (!userDetail) throw new NotFoundException("حساب کاربری یافت نشد.");
|
||||
const profile = new ProfileActor(userDetail, currentUser.role);
|
||||
|
||||
if (currentUser.role !== RoleEnum.COMPANY) {
|
||||
{
|
||||
const clientId = [userDetail?.clientKey, userDetail?.insuActivityCo]
|
||||
.map((value) => String(value ?? "").trim())
|
||||
.find((value) => Types.ObjectId.isValid(value));
|
||||
@@ -469,69 +480,33 @@ export class ActorAuthService {
|
||||
throw new BadRequestException("Invalid actor payload");
|
||||
}
|
||||
|
||||
const allowedFieldsByRole: Record<string, string[]> = {
|
||||
expert: [
|
||||
"fullName",
|
||||
"firstName",
|
||||
"lastName",
|
||||
"email",
|
||||
"phone",
|
||||
"city",
|
||||
"state",
|
||||
"bio",
|
||||
"nationalCode",
|
||||
"birthDate",
|
||||
"avatarUrl",
|
||||
"address",
|
||||
],
|
||||
damage_expert: [
|
||||
"fullName",
|
||||
"firstName",
|
||||
"lastName",
|
||||
"email",
|
||||
"phone",
|
||||
"companyName",
|
||||
"city",
|
||||
"state",
|
||||
"bio",
|
||||
"nationalCode",
|
||||
"birthDate",
|
||||
"avatarUrl",
|
||||
"address",
|
||||
],
|
||||
company: [
|
||||
"firstName",
|
||||
"lastName",
|
||||
"phone",
|
||||
"mobile",
|
||||
"city",
|
||||
"state",
|
||||
"address",
|
||||
],
|
||||
field_expert: ["firstName", "lastName", "email", "phone", "mobile"],
|
||||
registrar: ["email"],
|
||||
};
|
||||
|
||||
const allowedFields = allowedFieldsByRole[role];
|
||||
if (!allowedFields) {
|
||||
throw new ForbiddenException("Profile update not allowed for this role");
|
||||
const allowedFields = ACTOR_PROFILE_EDITABLE_FIELDS[role];
|
||||
if (!allowedFields)
|
||||
throw new ForbiddenException("ویرایش اطلاعات برای این نقش مجاز نیست.");
|
||||
if (
|
||||
!update ||
|
||||
typeof update !== "object" ||
|
||||
Array.isArray(update) ||
|
||||
Object.keys(update).some((key) => !allowedFields.includes(key))
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
"فقط اطلاعات شخصی مجاز حساب قابل ویرایش است.",
|
||||
);
|
||||
}
|
||||
|
||||
// Local validation is necessary: this application has no global ValidationPipe.
|
||||
const dto = plainToInstance(ActorEditUserProfileDto, update);
|
||||
const sanitized = Object.fromEntries(
|
||||
Object.entries(update).filter(([key]) => allowedFields.includes(key)),
|
||||
Object.keys(update).map((key) => [key, dto[key]]),
|
||||
);
|
||||
|
||||
if (Object.keys(sanitized).length === 0) {
|
||||
throw new BadRequestException("No valid fields to update");
|
||||
}
|
||||
|
||||
if (sanitized.birthDate && typeof sanitized.birthDate === "string") {
|
||||
const parsed = new Date(sanitized.birthDate);
|
||||
if (isNaN(parsed.getTime())) {
|
||||
throw new BadRequestException("birthDate must be a valid date");
|
||||
}
|
||||
sanitized.birthDate = parsed;
|
||||
}
|
||||
if (!Object.keys(sanitized).length)
|
||||
throw new BadRequestException("اطلاعاتی برای ویرایش ارسال نشده است.");
|
||||
if (Object.values(sanitized).some((value) => value == null))
|
||||
throw new BadRequestException("مقدار اطلاعات حساب معتبر نیست.");
|
||||
const errors = validateSync(dto);
|
||||
if (errors.length)
|
||||
throw new BadRequestException(
|
||||
errors.flatMap((error) => Object.values(error.constraints ?? {})),
|
||||
);
|
||||
|
||||
// fetch user detail (document or plain object)
|
||||
const document = await this.dynamicDbController(
|
||||
@@ -543,51 +518,43 @@ export class ActorAuthService {
|
||||
if (!document) throw new NotFoundException("Profile not found");
|
||||
|
||||
try {
|
||||
// if it’s a mongoose document (has .save)
|
||||
if (typeof document.save === "function") {
|
||||
Object.assign(document, sanitized);
|
||||
await document.save();
|
||||
return document;
|
||||
} else {
|
||||
const services: Record<string, any> = {
|
||||
expert: this.expertDbService,
|
||||
damage_expert: this.damageExpertDbService,
|
||||
company: this.insurerExpertDbService,
|
||||
field_expert: this.fieldExpertDbService,
|
||||
registrar: this.registrarDbService,
|
||||
file_maker: this.fileMakerDbService,
|
||||
file_reviewer: this.fileReviewerDbService,
|
||||
call_center: this.callCenterAgentDbService,
|
||||
super_admin: this.superAdminDbService,
|
||||
};
|
||||
const service = services[role];
|
||||
const write = service.updateOne ?? service.findOneAndUpdate;
|
||||
if (typeof write !== "function")
|
||||
throw new ForbiddenException(
|
||||
"ویرایش اطلاعات برای این نقش مجاز نیست.",
|
||||
);
|
||||
await write.call(
|
||||
service,
|
||||
{ _id: new Types.ObjectId(userId) },
|
||||
{ $set: sanitized },
|
||||
);
|
||||
}
|
||||
|
||||
// else, update directly via corresponding DB service
|
||||
switch (role) {
|
||||
case "expert":
|
||||
await this.expertDbService.updateOne(
|
||||
{ _id: new Types.ObjectId(userId) },
|
||||
{ $set: sanitized },
|
||||
);
|
||||
break;
|
||||
|
||||
case "damage_expert":
|
||||
await this.damageExpertDbService.updateOne(
|
||||
{ _id: new Types.ObjectId(userId) },
|
||||
{ $set: sanitized },
|
||||
);
|
||||
break;
|
||||
|
||||
case "company":
|
||||
await this.insurerExpertDbService.updateOne(
|
||||
{ _id: new Types.ObjectId(userId) },
|
||||
{ $set: sanitized },
|
||||
);
|
||||
break;
|
||||
|
||||
case "field_expert":
|
||||
await this.fieldExpertDbService.updateOne(
|
||||
{ _id: new Types.ObjectId(userId) },
|
||||
{ $set: sanitized },
|
||||
);
|
||||
break;
|
||||
|
||||
default:
|
||||
throw new ForbiddenException("Unsupported role for update");
|
||||
}
|
||||
|
||||
// return the fresh document
|
||||
return await this.dynamicDbController(role, null, userId);
|
||||
return await this.getProfiles(currentUser);
|
||||
} catch (err) {
|
||||
throw new InternalServerErrorException("Failed to update profile");
|
||||
if (err instanceof HttpException) throw err;
|
||||
if (err?.code === 11000)
|
||||
throw new ConflictException(
|
||||
"این مشخصات قبلاً برای حساب دیگری ثبت شده است.",
|
||||
);
|
||||
throw new InternalServerErrorException(
|
||||
"ذخیره اطلاعات حساب انجام نشد؛ دوباره تلاش کنید.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,96 +1,149 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsMobilePhone, IsString, Length } from "class-validator";
|
||||
import { DamageExpertModel } from "src/users/entities/schema/damage-expert.schema";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import { Transform } from "class-transformer";
|
||||
import {
|
||||
IsEmail,
|
||||
IsOptional,
|
||||
IsString,
|
||||
Matches,
|
||||
MaxLength,
|
||||
MinLength,
|
||||
} from "class-validator";
|
||||
import { normalizeIranMobile } from "src/helpers/iran-mobile";
|
||||
|
||||
export const ACTOR_PERSONAL_PROFILE_FIELDS = [
|
||||
"firstName",
|
||||
"lastName",
|
||||
"mobile",
|
||||
"phone",
|
||||
"city",
|
||||
"state",
|
||||
"address",
|
||||
] as const;
|
||||
export const ACTOR_PROFILE_EDITABLE_FIELDS: Record<string, readonly string[]> =
|
||||
{
|
||||
expert: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
damage_expert: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
company: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
field_expert: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
file_maker: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
file_reviewer: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
call_center: ACTOR_PERSONAL_PROFILE_FIELDS,
|
||||
super_admin: ["firstName", "lastName"],
|
||||
registrar: ["email"],
|
||||
};
|
||||
|
||||
export const profileDigits = (value: string): string =>
|
||||
value
|
||||
.replace(/[۰-۹]/g, (digit) => String(digit.charCodeAt(0) - 1776))
|
||||
.replace(/[٠-٩]/g, (digit) => String(digit.charCodeAt(0) - 1632));
|
||||
const trim = ({ value }: { value: unknown }) =>
|
||||
typeof value === "string" ? value.trim() : value;
|
||||
|
||||
/** Public self-profile only. Never serialize the underlying authentication document. */
|
||||
export class ProfileActor {
|
||||
public email: string;
|
||||
public fullName: string;
|
||||
public nationalCode: string;
|
||||
public insuActivityCo: string;
|
||||
public userType: string;
|
||||
public mobile: string;
|
||||
public address: string;
|
||||
public state: string;
|
||||
public city: string;
|
||||
public phone?: string;
|
||||
email?: string;
|
||||
firstName?: string;
|
||||
lastName?: string;
|
||||
fullName: string;
|
||||
nationalCode?: string;
|
||||
insuActivityCo?: string;
|
||||
userType?: string;
|
||||
mobile?: string;
|
||||
address?: string;
|
||||
state?: string;
|
||||
city?: string;
|
||||
phone?: string;
|
||||
editableFields: readonly string[];
|
||||
|
||||
constructor(Profile: DamageExpertModel) {
|
||||
this.email = Profile?.email;
|
||||
this.fullName = `${Profile?.firstName} ${Profile?.lastName}`;
|
||||
this.nationalCode = Profile?.nationalCode;
|
||||
this.insuActivityCo = Profile?.insuActivityCo;
|
||||
this.userType = Profile?.userType;
|
||||
this.mobile = Profile?.mobile;
|
||||
this.address = Profile?.address;
|
||||
this.state = Profile?.state;
|
||||
this.city = Profile?.city;
|
||||
this.phone = Profile?.phone;
|
||||
constructor(profile: any, role?: string) {
|
||||
this.email = profile?.email;
|
||||
this.firstName = profile?.firstName;
|
||||
this.lastName = profile?.lastName;
|
||||
this.fullName =
|
||||
[profile?.firstName, profile?.lastName].filter(Boolean).join(" ") ||
|
||||
profile?.fullName ||
|
||||
profile?.email ||
|
||||
"";
|
||||
this.nationalCode = profile?.nationalCode;
|
||||
this.insuActivityCo = profile?.insuActivityCo;
|
||||
this.userType = profile?.userType || profile?.role;
|
||||
this.mobile = profile?.mobile;
|
||||
this.address = profile?.address;
|
||||
this.state = profile?.state;
|
||||
this.city = profile?.city;
|
||||
this.phone = profile?.phone;
|
||||
this.editableFields =
|
||||
ACTOR_PROFILE_EDITABLE_FIELDS[role || profile?.role] ?? [];
|
||||
}
|
||||
}
|
||||
|
||||
export class ActorEditUserProfileDto {
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "First name of the actor",
|
||||
example: "heshmat",
|
||||
nullable: true,
|
||||
})
|
||||
@IsString()
|
||||
@Length(2, 40)
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(trim)
|
||||
@IsString({ message: "نام باید متن باشد." })
|
||||
@MinLength(1, { message: "نام را وارد کنید." })
|
||||
@MaxLength(80, { message: "نام باید حداکثر ۸۰ کاراکتر باشد." })
|
||||
firstName?: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "Last name of the actor",
|
||||
example: "Heshmati",
|
||||
nullable: true,
|
||||
})
|
||||
@IsString()
|
||||
@Length(1, 10)
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(trim)
|
||||
@IsString({ message: "نام خانوادگی باید متن باشد." })
|
||||
@MinLength(1, { message: "نام خانوادگی را وارد کنید." })
|
||||
@MaxLength(80, { message: "نام خانوادگی باید حداکثر ۸۰ کاراکتر باشد." })
|
||||
lastName?: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "Mobile phone of the actor",
|
||||
example: "09123456789",
|
||||
nullable: true,
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(({ value }) =>
|
||||
typeof value === "string" && /^[\d\s+()-]*$/.test(profileDigits(value))
|
||||
? (normalizeIranMobile(profileDigits(value)) ?? "")
|
||||
: value,
|
||||
)
|
||||
@IsString()
|
||||
@Matches(/^$|^09\d{9}$/, {
|
||||
message: "شماره همراه معتبر نیست؛ مانند 09123456789 وارد کنید.",
|
||||
})
|
||||
@IsMobilePhone("fa-IR")
|
||||
mobile?: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "تلفن خط ثابت",
|
||||
example: "02122222222",
|
||||
nullable: true,
|
||||
})
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(({ value }) =>
|
||||
typeof value === "string"
|
||||
? profileDigits(value).replace(/[\s()-]/g, "")
|
||||
: value,
|
||||
)
|
||||
@IsString()
|
||||
@Matches(/^$|^\+?\d{7,15}$/, { message: "شماره تلفن ثابت معتبر نیست." })
|
||||
phone?: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "City of the user",
|
||||
example: "استان",
|
||||
nullable: true,
|
||||
})
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(trim)
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
city?: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "State of the user",
|
||||
example: "شهر",
|
||||
nullable: true,
|
||||
})
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(trim)
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
state?: string;
|
||||
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "Address of the user",
|
||||
example: "آدرس",
|
||||
nullable: true,
|
||||
})
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@Transform(trim)
|
||||
@IsString()
|
||||
@MaxLength(1000, { message: "نشانی باید حداکثر ۱۰۰۰ کاراکتر باشد." })
|
||||
address?: string;
|
||||
|
||||
@ApiPropertyOptional({
|
||||
description: "Editable only for legacy registrar accounts",
|
||||
})
|
||||
@IsOptional()
|
||||
@Transform(trim)
|
||||
@IsEmail({}, { message: "ایمیل معتبر نیست." })
|
||||
email?: string;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
+1
-1
@@ -25,7 +25,7 @@ async function bootstrap() {
|
||||
|
||||
const challenge = () => {
|
||||
res.setHeader("WWW-Authenticate", 'Basic realm="Swagger"');
|
||||
res.status(401).send("Unauthorized");
|
||||
res.status(401).send("برای دسترسی، نام کاربری و رمز عبور را وارد کنید.");
|
||||
};
|
||||
|
||||
if (!authHeader?.startsWith("Basic ")) {
|
||||
|
||||
@@ -14,6 +14,8 @@ export class ProfileUserRs {
|
||||
birthDay: string;
|
||||
gender?: "male" | "female";
|
||||
city: string;
|
||||
state: string;
|
||||
address: string;
|
||||
constructor(profile: UserModel) {
|
||||
this.userId = profile["_id"];
|
||||
this.fullName = profile.fullName;
|
||||
@@ -22,5 +24,7 @@ export class ProfileUserRs {
|
||||
this.birthDay = profile.birthDay;
|
||||
this.gender = profile.gender;
|
||||
this.city = profile.city;
|
||||
this.state = profile.state;
|
||||
this.address = profile.address;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,27 +1,42 @@
|
||||
import { ApiProperty } from "@nestjs/swagger";
|
||||
import { IsDateString } from "class-validator";
|
||||
import { ApiPropertyOptional } from "@nestjs/swagger";
|
||||
import {
|
||||
IsDateString,
|
||||
IsIn,
|
||||
IsOptional,
|
||||
IsString,
|
||||
MaxLength,
|
||||
} from "class-validator";
|
||||
|
||||
export class UpdateUserProfileDtoRq {
|
||||
// @ApiProperty({})
|
||||
// mobile: string;
|
||||
@ApiProperty({
|
||||
type: "string",
|
||||
description: "Birth date of the user",
|
||||
@ApiPropertyOptional({
|
||||
description:
|
||||
"Gregorian birth date (YYYY-MM-DD). Legacy packed Jalali dates are also accepted.",
|
||||
example: "1999-03-05",
|
||||
nullable: true,
|
||||
})
|
||||
@IsDateString()
|
||||
birthDay: string;
|
||||
@IsOptional()
|
||||
@IsDateString({ strict: true }, { message: "تاریخ تولد معتبر نیست." })
|
||||
birthDay?: string;
|
||||
|
||||
@ApiProperty()
|
||||
@ApiPropertyOptional({ enum: ["male", "female"] })
|
||||
@IsOptional()
|
||||
@IsIn(["male", "female"], { message: "جنسیت معتبر نیست." })
|
||||
gender?: "male" | "female";
|
||||
|
||||
@ApiProperty()
|
||||
city: string;
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
city?: string;
|
||||
|
||||
@ApiProperty()
|
||||
state: string;
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(100)
|
||||
state?: string;
|
||||
|
||||
@ApiProperty()
|
||||
address: string;
|
||||
@ApiPropertyOptional()
|
||||
@IsOptional()
|
||||
@IsString()
|
||||
@MaxLength(1000, { message: "نشانی باید حداکثر ۱۰۰۰ کاراکتر باشد." })
|
||||
address?: string;
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export class ProfileController {
|
||||
@Get()
|
||||
@UseGuards(GlobalGuard)
|
||||
async getProfile(@CurrentUser() user) {
|
||||
return await this.profileService.getProfileDetail(user.username);
|
||||
return await this.profileService.getProfileDetail(user.username, user.sub);
|
||||
}
|
||||
|
||||
@Patch()
|
||||
@@ -26,6 +26,10 @@ export class ProfileController {
|
||||
@CurrentUser() user,
|
||||
@Body() body: UpdateUserProfileDtoRq,
|
||||
) {
|
||||
return await this.profileService.updateProfile(user.username, body);
|
||||
return await this.profileService.updateProfile(
|
||||
user.username,
|
||||
body as Record<string, unknown>,
|
||||
user.sub,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -60,11 +60,89 @@ describe("ProfileService", () => {
|
||||
state: "Tehran",
|
||||
address: "Test address",
|
||||
};
|
||||
users.findOne.mockResolvedValue({ _id: "user-id", ...update, plates: [] });
|
||||
const profile = await service.updateProfile("09120000000", update);
|
||||
expect(users.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ username: "09120000000" },
|
||||
{ $set: update },
|
||||
);
|
||||
expect(profile).not.toHaveProperty("plates");
|
||||
expect(profile).toMatchObject({
|
||||
city: "Tehran",
|
||||
state: "Tehran",
|
||||
address: "Test address",
|
||||
birthDay: "1999-03-05",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns saved province/address and reports deleted accounts without crashing", async () => {
|
||||
users.findOne
|
||||
.mockResolvedValueOnce({
|
||||
_id: "user-id",
|
||||
state: "تهران",
|
||||
city: "تهران",
|
||||
address: "نشانی",
|
||||
})
|
||||
.mockResolvedValueOnce(null);
|
||||
expect(await service.getProfileDetail("09120000000")).toMatchObject({
|
||||
state: "تهران",
|
||||
address: "نشانی",
|
||||
});
|
||||
await expect(service.getProfileDetail("09120000000")).rejects.toThrow(
|
||||
"حساب کاربری یافت نشد",
|
||||
);
|
||||
});
|
||||
|
||||
it("supports partial updates and identifies the current user by their JWT subject", async () => {
|
||||
users.findOneAndUpdate.mockResolvedValue({
|
||||
_id: "user-id",
|
||||
address: "old address",
|
||||
});
|
||||
users.findOne.mockResolvedValue({
|
||||
_id: "user-id",
|
||||
address: "نشانی جدید",
|
||||
state: "تهران",
|
||||
});
|
||||
expect(
|
||||
await service.updateProfile(
|
||||
"old-phone",
|
||||
{ address: "نشانی جدید" },
|
||||
"user-id",
|
||||
),
|
||||
).toMatchObject({ address: "نشانی جدید", state: "تهران" });
|
||||
expect(users.findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ _id: "user-id" },
|
||||
{ $set: { address: "نشانی جدید" } },
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts legacy Persian birth dates/gender and stores canonical ISO/enum values", async () => {
|
||||
users.findOneAndUpdate.mockResolvedValue({ _id: "user-id" });
|
||||
users.findOne.mockResolvedValue({
|
||||
_id: "user-id",
|
||||
birthDay: "1998-09-15",
|
||||
gender: "male",
|
||||
});
|
||||
await service.updateProfile("09120000000", {
|
||||
birthDay: 13770624,
|
||||
gender: "مرد",
|
||||
});
|
||||
expect(users.findOneAndUpdate).toHaveBeenCalledWith(expect.anything(), {
|
||||
$set: { birthDay: "1998-09-15", gender: "male" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ birthDay: "1999-02-30" },
|
||||
{ birthDay: 13771301 },
|
||||
{ birthDay: "2999-01-01" },
|
||||
{ gender: "unknown" },
|
||||
{ address: { $gt: "" } },
|
||||
{ city: null },
|
||||
])("rejects invalid personal data before writing: %j", async (update) => {
|
||||
await expect(
|
||||
service.updateProfile("09120000000", update),
|
||||
).rejects.toThrow();
|
||||
expect(users.findOneAndUpdate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,25 +1,87 @@
|
||||
import { BadRequestException, Injectable } from "@nestjs/common";
|
||||
import {
|
||||
BadRequestException,
|
||||
Injectable,
|
||||
NotFoundException,
|
||||
} from "@nestjs/common";
|
||||
import { plainToInstance } from "class-transformer";
|
||||
import { validateSync } from "class-validator";
|
||||
import { UserDbService } from "src/users/entities/db-service/user.db.service";
|
||||
import { ProfileUserRs } from "./dto/user/profile.dto";
|
||||
import { UpdateUserProfileDtoRq } from "./dto/user/update-profile.dto";
|
||||
import { jalaliToGregorianDate, toJalaliDate } from "src/helpers/date-jalali";
|
||||
import { profileDigits } from "src/auth/dto/actor/profile.actor.dto";
|
||||
|
||||
@Injectable()
|
||||
export class ProfileService {
|
||||
constructor(private readonly userDbService: UserDbService) {}
|
||||
|
||||
async getProfileDetail(username: string) {
|
||||
const userDetail = await this.userDbService.findOne({ username });
|
||||
async getProfileDetail(username: string, userId?: string) {
|
||||
const userDetail = await this.userDbService.findOne(
|
||||
userId ? { _id: userId } : { username },
|
||||
);
|
||||
if (!userDetail) throw new NotFoundException("حساب کاربری یافت نشد.");
|
||||
return new ProfileUserRs(userDetail);
|
||||
}
|
||||
|
||||
async updateProfile(username: string, update) {
|
||||
async updateProfile(
|
||||
username: string,
|
||||
update: Record<string, unknown>,
|
||||
userId?: string,
|
||||
) {
|
||||
const allowedFields = ["birthDay", "gender", "city", "state", "address"];
|
||||
if (Object.keys(update).some((field) => !allowedFields.includes(field))) {
|
||||
throw new BadRequestException("Only personal profile fields can be updated");
|
||||
if (
|
||||
!update ||
|
||||
typeof update !== "object" ||
|
||||
Array.isArray(update) ||
|
||||
Object.keys(update).some((field) => !allowedFields.includes(field))
|
||||
) {
|
||||
throw new BadRequestException(
|
||||
"Only personal profile fields can be updated",
|
||||
);
|
||||
}
|
||||
const userDetail = await this.userDbService.findOneAndUpdate(
|
||||
{ username },
|
||||
{ $set: update },
|
||||
const values: Record<string, unknown> = Object.fromEntries(
|
||||
Object.entries(update).map(([key, value]) => [
|
||||
key,
|
||||
typeof value === "string" ? value.trim() : value,
|
||||
]),
|
||||
);
|
||||
return new ProfileUserRs(userDetail);
|
||||
if (
|
||||
!Object.keys(values).length ||
|
||||
Object.values(values).some((value) => value == null)
|
||||
)
|
||||
throw new BadRequestException("اطلاعات حساب معتبر نیست.");
|
||||
if (values.birthDay !== undefined) {
|
||||
const raw = profileDigits(String(values.birthDay));
|
||||
if (!/^(?:\d{8}|\d{4}[-/]\d{1,2}[-/]\d{1,2})$/.test(raw))
|
||||
throw new BadRequestException("تاریخ تولد معتبر نیست.");
|
||||
const date = jalaliToGregorianDate(raw);
|
||||
const packed = raw.replace(/[/-]/g, "");
|
||||
const isJalali = /^1[2345]\d{6}$/.test(packed);
|
||||
if (
|
||||
!date ||
|
||||
(isJalali &&
|
||||
toJalaliDate(new Date(`${date}T12:00:00Z`)).replace(/\//g, "") !==
|
||||
packed)
|
||||
)
|
||||
throw new BadRequestException("تاریخ تولد معتبر نیست.");
|
||||
values.birthDay = date;
|
||||
if (date > new Date().toISOString().slice(0, 10))
|
||||
throw new BadRequestException("تاریخ تولد نمیتواند در آینده باشد.");
|
||||
}
|
||||
if (values.gender === "مرد") values.gender = "male";
|
||||
if (values.gender === "زن") values.gender = "female";
|
||||
const dto = plainToInstance(UpdateUserProfileDtoRq, values);
|
||||
const errors = validateSync(dto);
|
||||
if (errors.length)
|
||||
throw new BadRequestException(
|
||||
errors.flatMap((error) => Object.values(error.constraints ?? {})),
|
||||
);
|
||||
const filter = userId ? { _id: userId } : { username };
|
||||
const existing = await this.userDbService.findOneAndUpdate(filter, {
|
||||
$set: values,
|
||||
});
|
||||
if (!existing) throw new NotFoundException("حساب کاربری یافت نشد.");
|
||||
// The shared DB helper returns the pre-update document. Read the saved values.
|
||||
return this.getProfileDetail(username, userId);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user