fix(reports): localize Persian reports and resolve person display names

This commit is contained in:
SepehrYahyaee
2026-11-23 17:08:51 +03:30
parent 187a0ea3a9
commit 297664a9a6
8 changed files with 396 additions and 87 deletions
@@ -297,10 +297,10 @@ describe("buildInsurerFileReport", () => {
"سپر جلو",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
"۲٬۵۰۰٬۰۰۰ تومان",
"۲٬۵۰۰٬۰۰۰ ریال",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / مبلغ کل")).toBe(
"۳٬۰۰۰٬۰۰۰ تومان",
"۳٬۰۰۰٬۰۰۰ ریال",
);
});
@@ -352,7 +352,7 @@ describe("buildInsurerFileReport", () => {
"چراغ جلو",
);
expect(getFieldValue(report, "قیمت قطعات", "قطعه ۱ / قیمت قطعه")).toBe(
"۴٬۰۰۰٬۰۰۰ تومان",
"۴٬۰۰۰٬۰۰۰ ریال",
);
});
@@ -1,3 +1,4 @@
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
import {
resolveClaimOwnerParty,
resolveDamagedPartyRow,
@@ -96,11 +97,11 @@ function normalizeNumber(value: unknown): number | undefined {
return Number.isFinite(parsed) ? parsed : undefined;
}
function formatToman(value: unknown): string | undefined {
function formatRial(value: unknown): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
const amount = normalizeNumber(value);
if (amount === undefined) return asString(value);
return `${PERSIAN_NUMBER_FORMATTER.format(amount)} تومان`;
if (amount === undefined) return /factor|invoice/i.test(String(value)) ? "طبق فاکتور" : /[a-z]/i.test(String(value)) ? undefined : asString(value);
return `${PERSIAN_NUMBER_FORMATTER.format(amount)} ریال`;
}
function firstDefined(...values: unknown[]): string | undefined {
@@ -188,7 +189,7 @@ function dedupeFields(
for (const field of fields) {
const value = asString(field.value);
if (!value) continue;
if (!value || !field.label) continue;
const key = `${field.label}::${value}`;
if (seen.has(key)) continue;
seen.add(key);
@@ -227,9 +228,7 @@ function expertNameFromSnapshot(snapshot?: {
lastName?: string;
}): string | undefined {
if (!snapshot) return undefined;
const name = [snapshot.firstName, snapshot.lastName]
.filter(Boolean)
.join(" ");
const name = personDisplayName(snapshot);
return name || undefined;
}
@@ -254,7 +253,7 @@ function collectExpertNames(
if (!reply) continue;
const actor = (reply.actorDetail as { actorName?: string } | undefined)
?.actorName;
if (actor) names.add(actor);
if (meaningfulPersonName(actor)) names.add(meaningfulPersonName(actor));
const snap = expertNameFromSnapshot(
reply.expertProfileSnapshot as
| { firstName?: string; lastName?: string }
@@ -263,7 +262,7 @@ function collectExpertNames(
if (snap) names.add(snap);
}
return names.size ? [...names].join(", ") : undefined;
return names.size ? [...names].join("، ") : undefined;
}
function inquiryRoleData(
@@ -598,8 +597,8 @@ function buildPartyOwnerSection(
{
label: PR.name,
value: options?.useClaimOwnerFallback
? firstDefined(person?.fullName, claimOwner?.fullName)
: firstDefined(person?.fullName),
? personDisplayName(person, claimOwner)
: personDisplayName(person),
},
{ label: PR.phone, value: asString(person?.phoneNumber) },
{
@@ -644,7 +643,7 @@ function buildParticipantRolesSection(
(candidate) => String(candidate.participantId) === String(participantId),
);
const value = [
asString(participant?.fullName),
personDisplayName(participant),
participant?.nationalCode
? `${PR.nationalCode}: ${asString(participant.nationalCode)}`
: undefined,
@@ -696,8 +695,6 @@ function licenseFieldsFromInquiry(inquiry?: Record<string, unknown>): {
inquiry.issueDate,
inquiry.LicenseIssueDate,
inquiry.licenseIssueDate,
inquiry.ExpireDate,
inquiry.expireDate,
),
};
}
@@ -716,9 +713,11 @@ function buildDriverSection(
String(role),
);
const { licenseType, licenseDate } = licenseFieldsFromInquiry(licenseInquiry);
const driverId = damagedParty?.participantRoles?.driver;
const driver = (sanitizeStoredInquiryParticipants(damagedParty?.participants) ?? []).find(participant => participant.participantId === driverId);
return buildSection(PR.driverSection, [
{ label: PR.name, value: asString(person.fullName) },
{ label: PR.name, value: personDisplayName(driver,{fullName:person.driverFullName,phoneNumber:person.driverPhoneNumber}) },
{
label: PR.licenseType,
value:
@@ -733,11 +732,9 @@ function buildDriverSection(
{
label: PR.licenseDate,
value:
asString(person.driverLicenseDate) ||
licenseDate ||
asString(person.driverLicense),
asString(person.driverLicenseDate) || licenseDate,
},
{ label: PR.phone, value: asString(person.phoneNumber) },
{ label: PR.phone, value: asString(person.driverPhoneNumber) },
{ label: PR.nationalCode, value: asString(person.nationalCodeOfDriver) },
{ label: PR.birthDate, value: formatBirthDate(person.driverBirthday) },
{ label: PR.licenseNumber, value: asString(person.driverLicense) },
@@ -774,7 +771,7 @@ function buildPartyStatementSection(
},
{
label: PR.name,
value: firstDefined(party.person?.fullName),
value: personDisplayName(party.person),
},
{
label: PR.admitsGuilt,
@@ -892,7 +889,7 @@ function buildEvaluationSection(
},
{
label: PR.evaluationExpert,
value: actorDetail?.actorName ?? snapshotName,
value: snapshotName || meaningfulPersonName(actorDetail?.actorName),
},
{
label: PR.evaluationSubmittedAt,
@@ -930,7 +927,7 @@ function evaluationDaghiValue(value: unknown): string | undefined {
}
const daghi = value as ReportRecord;
const option = asString(persianReportValue("daghi.option", daghi.option));
const price = formatToman(daghi.price);
const price = formatRial(daghi.price);
return [option, price].filter(Boolean).join(" - ") || undefined;
}
@@ -953,14 +950,14 @@ function buildEvaluationPartsSection(
persianReportValue("evaluation.part.typeOfDamage", part.typeOfDamage),
),
},
{ label: `${prefix} / ${PR.partPrice}`, value: formatToman(part.price) },
{ label: `${prefix} / ${PR.partPrice}`, value: formatRial(part.price) },
{
label: `${prefix} / ${PR.repairSalary}`,
value: formatToman(part.salary),
value: formatRial(part.salary),
},
{
label: `${prefix} / ${PR.totalPayment}`,
value: formatToman(part.totalPayment),
value: formatRial(part.totalPayment),
},
{
label: `${prefix} / ${PR.factorNeeded}`,
@@ -0,0 +1,101 @@
import {
PR,
persianFieldPath,
persianReportValue,
persianStatus,
} from "./persian-report-labels";
import { buildInsurerFileReport } from "./case-expert-report.builder";
import { ClaimCaseStatus } from "src/Types&Enums/claim-request-management/claim-case-status.enum";
import { CaseStatus } from "src/Types&Enums/blame-request-management/caseStatus.enum";
describe("Persian report presentation", () => {
it.each([...Object.values(ClaimCaseStatus), ...Object.values(CaseStatus)])(
"translates persisted status %s",
(status) => expect(persianStatus(status)).not.toMatch(/[a-z]/i),
);
it("uses meaningful Persian labels and suppresses unknown provider field keys", () => {
expect(persianFieldPath("party.vehicle.vin")).toBe(
"خودرو / شماره شناسایی خودرو",
);
expect(
persianFieldPath("party.vehicle.inquiry.unmappedProviderField"),
).toBe("");
expect(persianReportValue("vehicle.expedited", true)).toBe("فوری");
expect(persianReportValue("vehicle.carType", "sedan")).toBe("سواری");
expect(persianReportValue("vehicle.status", "NEW_UNKNOWN_STATUS")).toBe(
"وضعیت نامشخص",
);
});
it("keeps factual identifiers intact, uses phones for unnamed users and keeps driver/owner identities separate", () => {
const vin = "IR1ABC23456789012";
const report = buildInsurerFileReport({
overview: { publicId: "QA-1" },
blame: {
type: "CAR_BODY",
status: "COMPLETED",
parties: [
{
role: "FIRST",
person: {
userId: "650000000000000000000001",
fullName: "1234567890",
phoneNumber: "09120000000",
driverIsInsurer: false,
nationalCodeOfDriver: "1111111111",
driverLicense: "987654321",
},
participants: [
{
participantId: "driver",
fullName: "حسن احمدی",
nationalCode: "1111111111",
birthday: "1370/01/01",
},
],
participantRoles: { driver: "driver" },
vehicle: {
vin,
carType: "sedan",
unknownProviderField: "DO_NOT_SHOW",
},
},
],
},
claim: {
owner: { userId: "650000000000000000000001" },
evaluation: {
damageExpertReply: {
parts: [
{
carPartDamage: { label_fa: "گلگیر جلو" },
typeOfDamage: "تعویض",
price: "2000000",
totalPayment: "3000000",
factorNeeded: false,
},
],
},
},
},
});
const fields = report.sections.flatMap((section) => section.fields);
expect(fields.every((field) => !/[a-z]/i.test(field.label))).toBe(true);
expect(fields.some((field) => field.value === vin)).toBe(true);
expect(fields.some((field) => field.value === "DO_NOT_SHOW")).toBe(false);
expect(
report.sections
.find((section) => section.title === PR.ownerSection)
?.fields.find((field) => field.label === PR.name)?.value,
).toBe("09120000000");
const driver = report.sections.find(
(section) => section.title === PR.driverSection,
);
expect(driver?.fields.find((field) => field.label === PR.name)?.value).toBe(
"حسن احمدی",
);
expect(
driver?.fields.find((field) => field.label === PR.licenseDate),
).toBeUndefined();
expect(fields.some((field) => field.value === "۲٬۰۰۰٬۰۰۰ ریال")).toBe(true);
});
});
+57 -26
View File
@@ -1,5 +1,6 @@
import { UNIFIED_FILE_STATUS_CATALOG } from "src/helpers/unified-file-status";
export const PR = {
reportTitle: "گزارش پرونده بیمه گر",
reportTitle: "گزارش پرونده بیمه‌گر",
publicId: "شناسه عمومی",
requestNo: "شماره درخواست",
empty: "-",
@@ -21,17 +22,20 @@ export const PR = {
fanavaranSection: "کدهای فناوران",
evaluationSection: "نتیجه ارزیابی",
accidentSection: "گزارش حادثه",
name: "نام",
name: "نام و نام خانوادگی",
phone: "شماره تلفن",
nationalCode: "کد ملی",
birthDate: "تاریخ تولد",
sheba: "شماره شبا",
licenseType: "نوع گواهینامه",
licenseDate: "تاریخ گواهینامه",
licenseDate: "تاریخ صدور گواهینامه",
licenseNumber: "شماره گواهینامه",
hasDrivingLicense: "گواهینامه دارد",
driverLicense: "گواهینامه راننده",
insuranceCompany: "شرکت بیمه",
expedited: "رسیدگی فوری",
status: "وضعیت",
color: "رنگ",
policyNumber: "شماره بیمه‌نامه",
policyStartDate: "تاریخ شروع بیمه‌نامه",
policyEndDate: "تاریخ پایان بیمه‌نامه",
@@ -40,8 +44,8 @@ export const PR = {
fileRegisteredAt: "تاریخ و ساعت ثبت پرونده",
evaluationRegisteredAt: "تاریخ و ساعت ثبت نتیجه ارزیابی",
fanavaranClaimNo: "شماره پرونده فناوران",
fanavaranClaimId: "کد پرونده فناوران",
fanavaranDamageCaseId: "کد کیس خسارت فناوران",
fanavaranClaimId: "کد رایانه پرونده فناوران",
fanavaranDamageCaseId: "کد پرونده خسارت فناوران",
fanavaranExpertiseId: "کد کارشناسی فناوران",
fanavaranPolicyId: "کد بیمه‌نامه فناوران",
fanavaranDriverId: "کد راننده فناوران",
@@ -78,9 +82,9 @@ export const PR = {
weather: "وضعیت آب و هوا",
road: "وضعیت جاده",
light: "وضعیت نور",
blameStatus: "وضعیت مقصر",
blameStatus: "وضعیت پرونده تعیین مقصر",
claimStatus: "وضعیت خسارت",
expertDecision: "نظر کارشناس مقصر",
expertDecision: "نظر کارشناس تصادف",
accidentWay: "نحوه برخورد",
accidentReason: "علت حادثه",
accidentType: "نوع حادثه",
@@ -89,7 +93,11 @@ export const PR = {
partyDescription: "توضیحات طرف",
} as const;
const KEY_LABELS: Record<string, string> = {
export const KEY_LABELS: Record<string, string> = {
hasEndorsement: "دارای الحاقیه",
expedited: "رسیدگی فوری",
status: "وضعیت",
color: "رنگ",
policyNumber: "شماره بیمه‌نامه",
company: "شرکت بیمه",
insurerCompany: "شرکت بیمه‌گر",
@@ -140,8 +148,8 @@ const KEY_LABELS: Record<string, string> = {
MapTypNam: "نام نوع خودرو",
MtrNum: "شماره موتور",
ShsNum: "شماره شاسی",
vin: "VIN",
VinNumberField: "VIN",
vin: "شماره شناسایی خودرو",
VinNumberField: "شماره شناسایی خودرو",
DisFnYrPrcnt: "درصد تخفیف مالی",
DisLfYrPrcnt: "درصد تخفیف جانی",
DisPrsnYrPrcnt: "درصد تخفیف شخص ثالث",
@@ -209,7 +217,7 @@ const KEY_LABELS: Record<string, string> = {
previousPlate: "پلاک قبلی",
previousPlateId: "پلاک قبلی",
previousPolicyholderNationalCode: "کد ملی بیمه‌گذار پلاک قبلی",
vehicleVin: "شماره شاسی (VIN)",
vehicleVin: "شماره شناسایی خودرو",
driver: "راننده",
vehicleOwner: "مالک وسیله نقلیه",
thirdPartyPolicyholder: "بیمه‌گذار شخص ثالث",
@@ -222,7 +230,27 @@ const KEY_LABELS: Record<string, string> = {
error: "خطا",
};
const STATUS_LABELS: Record<string, string> = {
export const STATUS_LABELS: Record<string, string> = {
...Object.fromEntries(UNIFIED_FILE_STATUS_CATALOG.map(item => [item.key,item.labelFa])),
OPEN: "پرونده باز",
CREATED: "ثبت‌شده",
SELECTING_OUTER_PARTS: "در حال انتخاب قطعات آسیب‌دیده",
SELECTING_OTHER_PARTS: "در حال ثبت سایر قطعات",
UPLOADING_REQUIRED_DOCUMENTS: "در حال بارگذاری مدارک",
CAPTURING_PART_DAMAGES: "در حال ثبت تصاویر خسارت",
WAITING_FOR_EXPERT: "در انتظار کارشناس تصادف",
WAITING_FOR_USER_RESEND: "در انتظار تکمیل اطلاعات کاربر",
IN_PERSON_VISIT_PENDING: "در انتظار مراجعه حضوری",
WAITING_FOR_INSURER_APPROVAL: "در انتظار تأیید پرونده",
INSURER_REVIEW_AWAITING_OWNER_SIGN: "در انتظار امضای مالک",
INSURER_REVIEW_MIXED_FACTORS_PENDING: "در انتظار تأیید مبالغ و بارگذاری فاکتورها",
OWNER_REPAIR_FACTOR_UPLOAD_PENDING: "در انتظار بارگذاری فاکتورها",
EXPERT_VALIDATING_REPAIR_FACTORS: "در انتظار بررسی فاکتورها توسط کارشناس",
WAITING_FOR_FILE_REVIEWER: "در انتظار کارشناس ارزیاب",
WAITING_FOR_FILE_MAKER_APPROVAL: "در انتظار تأیید کارشناس مسئول پرونده",
FILE_MAKER_REJECTED: "نیازمند اصلاح توسط کارشناس ارزیاب",
AUTO_CLOSED: "بسته‌شده خودکار",
AGREED: "توافق",
DISAGREEMENT: "اختلاف نظر",
UNKNOWN: "نامشخص",
@@ -333,7 +361,9 @@ export function persianFieldPath(path: string): string {
if (!path) return PR.data;
const parts = path.split(".").filter(Boolean);
const last = parts[parts.length - 1] ?? path;
const translatedLast = KEY_LABELS[last] ?? last;
const translate = (key: string) => KEY_LABELS[key] ?? (/^\d+$/.test(key) ? Number(key).toLocaleString("fa-IR") : /[a-z]/i.test(key) ? "" : key);
const translatedLast = translate(last);
if (!translatedLast) return "";
const inquiryRoot = parts.find(
(p) => p === "thirdParty" || p === "carBody" || p === "mapped",
@@ -386,7 +416,7 @@ export function persianFieldPath(path: string): string {
if (parts.length === 1) return translatedLast;
const translated = parts.map((part) => KEY_LABELS[part] ?? part);
const translated = parts.map(translate).filter(Boolean);
return translated.join(" / ");
}
@@ -399,36 +429,37 @@ export function persianReportValue(
value: unknown,
): unknown {
if (value === undefined || value === null || value === "") return value;
if (typeof value === "boolean") return value ? "بله" : "خیر";
if (typeof value === "boolean") return path.endsWith("expedited") ? value ? "فوری" : "عادی" : value ? "بله" : "خیر";
if (typeof value !== "string" && typeof value !== "number") return value;
const raw = String(value).trim();
const key = raw.toUpperCase().replace(/[\s-]+/g, "_");
const field = path.split(".").filter(Boolean).pop() ?? "";
if (field === "expedited") return raw === "true" || raw === "1" ? "فوری" : "عادی";
if (field === "licenseType" || field === "LicenseType") {
return LICENSE_TYPE_LABELS[key] ?? raw;
return LICENSE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "عنوان گواهینامه ثبت نشده است" : raw);
}
if (field === "registrationState") {
return REGISTRATION_STATE_LABELS[key] ?? raw;
return REGISTRATION_STATE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
}
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? raw;
if (field === "plateKind") return PLATE_KIND_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نامشخص" : raw);
if (field === "role" || field.endsWith("Role")) {
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? raw;
return PARTICIPANT_ROLE_VALUE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نقش ثبت‌نشده" : raw);
}
if (field === "blameRequestType" || field === "fileType") {
return CASE_TYPE_LABELS[key] ?? raw;
return CASE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع پرونده ثبت نشده است" : raw);
}
if (
(field === "carType" || field === "type") &&
path.toLowerCase().includes("vehicle")
) {
return VEHICLE_TYPE_LABELS[key] ?? raw;
return VEHICLE_TYPE_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "نوع خودرو ثبت نشده است" : raw);
}
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? raw;
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? raw;
if (field === "typeOfDamage") return DAMAGE_TYPE_LABELS[key] ?? (/[a-z]/i.test(raw) ? "نوع خسارت ثبت نشده است" : raw);
if (field === "error") return INQUIRY_ERROR_LABELS[key] ?? (/^[a-z_ -]+$/i.test(raw) ? "استعلام ناموفق بود" : raw);
if (/status$/i.test(field)) {
return STATUS_LABELS[raw] ?? VALIDITY_LABELS[key] ?? raw;
return STATUS_LABELS[key] ?? VALIDITY_LABELS[key] ?? (/[a-z]/i.test(raw) ? "وضعیت نامشخص" : raw);
}
if (raw === "true" || raw === "false") return STATUS_LABELS[raw];
@@ -438,7 +469,7 @@ export function persianReportValue(
export function persianStatus(value: unknown): string | undefined {
if (value === undefined || value === null || value === "") return undefined;
const key = String(value);
return STATUS_LABELS[key] ?? key;
return STATUS_LABELS[key] ?? STATUS_LABELS[key.toLowerCase()] ?? (/[a-z]/i.test(key) ? "وضعیت نامشخص" : key);
}
export function persianAccidentCondition(
@@ -454,5 +485,5 @@ export function persianAccidentCondition(
: kind === "road"
? ROAD_LABELS
: LIGHT_LABELS;
return labels[normalized] ?? raw;
return labels[normalized] ?? (/[a-z]/i.test(raw) ? "ثبت نشده است" : raw);
}
+31 -33
View File
@@ -1,3 +1,4 @@
import { personDisplayName, meaningfulPersonName } from "src/helpers/person-display-name";
import {
BadRequestException,
ConflictException,
@@ -269,7 +270,7 @@ export class ExpertInsurerService {
if (!Array.isArray(parties) || !parties.length) return undefined;
return parties.map((p: any) => ({
role: p?.role,
fullName: p?.person?.fullName,
fullName: personDisplayName(p?.person),
vehicle: {
carName: p?.vehicle?.carName ?? p?.vehicle?.name,
carModel: p?.vehicle?.carModel ?? p?.vehicle?.model,
@@ -524,11 +525,24 @@ export class ExpertInsurerService {
}
}
private async personForDisplay(person: any, cache: Map<string, Promise<any>>) {
if (!person) return person;
const id = String(person.userId ?? "");
let profile: any;
if (Types.ObjectId.isValid(id) && this.userDbService?.findOne) {
if (!cache.has(id)) cache.set(id, this.userDbService.findOne({_id:new Types.ObjectId(id)}));
profile = await cache.get(id);
}
return {...person,fullName:personDisplayName(profile,person),phoneNumber:person.phoneNumber || profile?.mobile || ""};
}
private async buildInsurerBlameDetail(
blameLean: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const doc: Record<string, unknown> = { ...blameLean };
const parties = (Array.isArray(doc.parties) ? doc.parties : []) as any[];
const displayCache = new Map<string, Promise<any>>();
await Promise.all(parties.map(async party => { party.person = await this.personForDisplay(party.person,displayCache); }));
await this.enrichBlamePartyEvidenceUrls(parties);
doc.parties = enrichBlamePartiesForAgreementView(doc);
@@ -571,6 +585,11 @@ export class ExpertInsurerService {
claim: Record<string, unknown>,
blameForContext: Record<string, unknown> | null,
): Promise<Record<string, unknown>> {
const displayCache = new Map<string, Promise<any>>();
claim = {...claim,owner:await this.personForDisplay(claim.owner,displayCache)};
if (Array.isArray(blameForContext?.parties)) {
blameForContext = {...blameForContext,parties:await Promise.all(blameForContext.parties.map(async (party:any) => ({...party,person:await this.personForDisplay(party.person,displayCache)})))};
}
// Add at the top of buildInsurerClaimDetail, before the return:
const carType = (claim as any).vehicle?.carType as
| ClaimVehicleTypeV2
@@ -2511,25 +2530,14 @@ export class ExpertInsurerService {
]);
private static getDisplayNameFromRecord(record: any): string | null {
if (!record) return null;
const fullName =
typeof record.fullName === "string" ? record.fullName.trim() : "";
if (fullName) return fullName;
const firstName =
typeof record.firstName === "string" ? record.firstName.trim() : "";
const lastName =
typeof record.lastName === "string" ? record.lastName.trim() : "";
const combined = [firstName, lastName].filter(Boolean).join(" ").trim();
return combined || null;
return personDisplayName(record) || null;
}
private static isMeaningfulTimelineActorName(
name: string | undefined,
): boolean {
const trimmed = typeof name === "string" ? name.trim() : "";
if (!trimmed) return false;
if (!meaningfulPersonName(trimmed)) return false;
return !ExpertInsurerService.TIMELINE_PLACEHOLDER_ACTOR_NAMES.has(
trimmed.toLowerCase(),
);
@@ -2552,11 +2560,11 @@ export class ExpertInsurerService {
)
: null;
const matchedName = matchedParty?.person?.fullName?.trim?.();
const matchedName = personDisplayName(matchedParty?.person);
if (matchedName) return matchedName;
if (parties.length === 1) {
return parties[0]?.person?.fullName?.trim?.() || null;
return personDisplayName(parties[0]?.person) || null;
}
return null;
@@ -2711,7 +2719,7 @@ export class ExpertInsurerService {
): Promise<string | null> {
const explicitName =
typeof actor?.actorName === "string" ? actor.actorName.trim() : "";
if (ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) {
if (actorType !== "user" && ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) {
return explicitName;
}
@@ -2721,16 +2729,6 @@ export class ExpertInsurerService {
return ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
}
if (actorType === "user") {
const ownerName = sourceDoc?.owner?.fullName?.trim?.();
if (ownerName) return ownerName;
const blamePartyName = ExpertInsurerService.resolveBlamePartyName(
sourceDoc,
event?.metadata?.partyRole,
);
if (blamePartyName) return blamePartyName;
}
const actorId = actor?.actorId ? String(actor.actorId).trim() : "";
if (actorId) {
@@ -2745,14 +2743,13 @@ export class ExpertInsurerService {
);
if (!resolvedName && actorType === "user") {
resolvedName =
sourceDoc?.owner?.fullName?.trim?.() ??
ExpertInsurerService.resolveBlamePartyName(
sourceDoc,
event?.metadata?.partyRole,
);
const parties = Array.isArray(sourceDoc?.parties) ? sourceDoc.parties : [];
const party = parties.find((row:any) => String(row?.person?.userId ?? "") === actorId);
resolvedName = personDisplayName(party?.person,
String(sourceDoc?.owner?.userId ?? "") === actorId ? sourceDoc.owner : undefined) || null;
}
if (!resolvedName && ExpertInsurerService.isMeaningfulTimelineActorName(explicitName)) resolvedName = explicitName;
if (!resolvedName) {
resolvedName =
ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
@@ -2762,6 +2759,7 @@ export class ExpertInsurerService {
return resolvedName ?? null;
}
if (actorType === "user") return personDisplayName(sourceDoc?.owner) || ExpertInsurerService.resolveBlamePartyName(sourceDoc,event?.metadata?.partyRole);
return ExpertInsurerService.resolveTimelinePerformedByFaLabel(actorType);
}
+83
View File
@@ -0,0 +1,83 @@
import { meaningfulPersonName, personDisplayName } from "./person-display-name";
import { ExpertInsurerService } from "src/expert-insurer/expert-insurer.service";
describe("person labels in panels/reports", () => {
it.each([
"1234567890",
"۱۲۳۴۵۶۷۸۹۰",
"650000000000000000000001",
"Unknown User",
"User",
"user@example.com",
])("never uses an identifier or placeholder as a name: %s", (name) => {
expect(meaningfulPersonName(name)).toBe("");
expect(
personDisplayName({
fullName: name,
mobile: "09120000000",
nationalCode: "1234567890",
}),
).toBe("09120000000");
});
it("prefers saved names across records and combines first/last names", () => {
expect(
personDisplayName(
{ fullName: "1234567890", mobile: "09120000000" },
{ firstName: "علی", lastName: "رضایی" },
),
).toBe("علی رضایی");
expect(personDisplayName({ firstName: "علی" })).toBe("علی");
expect(
personDisplayName({ fullName: "9123456789", nationalCode: "9123456789" }),
).toBe("");
expect(personDisplayName({ fullName: "نامشخص" })).toBe("");
});
it("hydrates current profile names without changing stored case data and caches lookups", async () => {
const service = Object.create(ExpertInsurerService.prototype) as any;
service.userDbService = {
findOne: jest.fn(async () => ({
fullName: "علی رضایی",
mobile: "09120000000",
})),
};
const person = {
userId: "650000000000000000000001",
fullName: "1234567890",
};
const cache = new Map();
expect(await service.personForDisplay(person, cache)).toMatchObject({
fullName: "علی رضایی",
phoneNumber: "09120000000",
});
await service.personForDisplay(person, cache);
expect(service.userDbService.findOne).toHaveBeenCalledTimes(1);
expect(person.fullName).toBe("1234567890");
});
it("timeline identifies the actual user, rather than the other party or a legacy ID name", async () => {
const service = Object.create(ExpertInsurerService.prototype) as any;
service.userDbService = {
findOne: jest.fn(async () => ({
fullName: "علی رضایی",
mobile: "09120000000",
})),
};
const actor = {
actorId: "650000000000000000000001",
actorName: "1234567890",
};
const document = {
owner: { userId: "650000000000000000000002", fullName: "شخص دیگر" },
};
expect(
await service.resolveTimelineActorName(actor, "user", document),
).toBe("علی رضایی");
service.userDbService.findOne.mockResolvedValue({ mobile: "09120000000" });
expect(
await service.resolveTimelineActorName(actor, "user", document),
).toBe("09120000000");
service.userDbService.findOne.mockResolvedValue(null);
expect(
await service.resolveTimelineActorName(actor, "user", document),
).not.toBe("شخص دیگر");
});
});
+71
View File
@@ -0,0 +1,71 @@
type PersonRecord = object | null | undefined;
const placeholders = new Set([
"user",
"actor",
"expert",
"unknown",
"unknown user",
"unknown expert",
"system",
"null",
"undefined",
"نامشخص",
"کاربر",
"موجود نیست",
]);
const englishDigits = (value: string) =>
value.replace(/[۰-۹٠-٩]/g, (digit) =>
String("۰۱۲۳۴۵۶۷۸۹٠١٢٣٤٥٦٧٨٩".indexOf(digit) % 10),
);
export function meaningfulPersonName(value: unknown): string {
if (typeof value !== "string") return "";
const name = value.trim().replace(/\s+/g, " ");
const normalized = englishDigits(name);
if (
!name ||
placeholders.has(name.toLowerCase()) ||
/^\+?[\d\s()-]+$/.test(normalized) ||
/^[a-f\d]{24}$/i.test(normalized) ||
/^[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12}$/i.test(normalized) ||
/@/.test(name)
)
return "";
return name;
}
function phone(value: unknown): string {
if (typeof value !== "string" && typeof value !== "number") return "";
const text = String(value).trim();
return /^\+?[\d۰-۹٠-٩][\d۰-۹٠-٩ ()-]{6,17}$/.test(text) ? text : "";
}
/** Names first, then explicitly recorded phone numbers. IDs/national codes are never names. */
export function personDisplayName(...records: PersonRecord[]): string {
for (const source of records) {
if (!source) continue;
const record = source as Record<string, unknown>;
const joined = [
meaningfulPersonName(record.firstName),
meaningfulPersonName(record.lastName),
]
.filter(Boolean)
.join(" ");
const name =
meaningfulPersonName(record.fullName) ||
joined ||
meaningfulPersonName(record.name);
if (name) return name;
}
for (const source of records) {
if (!source) continue;
const record = source as Record<string, unknown>;
for (const key of ["phoneNumber", "mobile", "mobileNumber", "phone"]) {
const value = phone(record[key]);
if (value) return value;
}
const legacy = englishDigits(
String(record.fullName ?? record.username ?? ""),
).replace(/[\s()-]/g, "");
if (/^(?:\+98|0098|98|0)9\d{9}$/.test(legacy)) return legacy;
}
return "";
}