Files
CRM_Montzar/apps/web/src/lib/money.ts
T
Mahdi 33c95d72a8 feat: add invoice builder with line detail, address, and person picker.
Enrich invoice line items and previews, migrate several CRM surfaces to Ant, and wire shared money/picker helpers.
2026-11-30 14:34:47 +03:30

177 lines
6.2 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
export const CURRENCY_OPTIONS = [
{ code: 'IRR', labelFa: 'ریال ایران', suffix: 'ریال' },
{ code: 'USD', labelFa: 'دلار آمریکا', suffix: 'دلار' },
{ code: 'EUR', labelFa: 'یورو', suffix: 'یورو' },
{ code: 'AED', labelFa: 'درهم امارات', suffix: 'درهم' },
{ code: 'TRY', labelFa: 'لیر ترکیه', suffix: 'لیر' },
{ code: 'GBP', labelFa: 'پوند انگلیس', suffix: 'پوند' },
] as const;
export function currencySuffix(code: string): string {
if (code === 'IRT') return 'ریال';
return CURRENCY_OPTIONS.find((c) => c.code === code)?.suffix ?? code;
}
export function formatMoney(amount: number, currency = 'IRR'): string {
try {
return (
new Intl.NumberFormat('fa-IR').format(amount) +
' ' +
currencySuffix(currency)
);
} catch {
return `${amount} ${currency}`;
}
}
/** مثل ماکاپ: ۲۴۰ میلیون ریال */
export function formatCompactMoney(amount: number, currency = 'IRR'): string {
const suffix = currencySuffix(currency);
const abs = Math.abs(amount);
if (abs >= 1_000_000_000) {
const n = amount / 1_000_000_000;
const rounded = Math.abs(n - Math.round(n)) < 0.05 ? Math.round(n) : Math.round(n * 10) / 10;
return `${new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 1 }).format(rounded)} میلیارد ${suffix}`;
}
if (abs >= 1_000_000) {
const n = amount / 1_000_000;
const rounded = Math.abs(n - Math.round(n)) < 0.05 ? Math.round(n) : Math.round(n * 10) / 10;
return `${new Intl.NumberFormat('fa-IR', { maximumFractionDigits: 1 }).format(rounded)} میلیون ${suffix}`;
}
return formatMoney(amount, currency);
}
const PERSIAN_DIGITS = '۰۱۲۳۴۵۶۷۸۹';
const ARABIC_DIGITS = '٠١٢٣٤٥٦٧٨٩';
/** تبدیل ارقام فارسی/عربی به لاتین */
export function normalizeDigits(raw: string): string {
return raw.replace(/[۰-۹٠-٩]/g, (ch) => {
const p = PERSIAN_DIGITS.indexOf(ch);
if (p >= 0) return String(p);
return String(ARABIC_DIGITS.indexOf(ch));
});
}
/** نمایش عدد با جداکنندهٔ هزارگان (fa-IR) برای فیلدهای ورودی */
export function formatGroupedInput(value: number, maxFractionDigits = 2): string {
if (!Number.isFinite(value)) return '';
return new Intl.NumberFormat('fa-IR', {
maximumFractionDigits: maxFractionDigits,
minimumFractionDigits: 0,
}).format(value);
}
/** formatter برای a-input-number با جداکنندهٔ هزارگان فارسی */
export function groupedNumberFormatter(maxFractionDigits = 2) {
return (value: string | number) => {
if (value === '' || value == null) return '';
const n = typeof value === 'number' ? value : Number(value);
if (!Number.isFinite(n)) return String(value);
return formatGroupedInput(n, maxFractionDigits);
};
}
/** parser برای a-input-number؛ ارقام فارسی و جداکننده‌ها را می‌پذیرد */
export function groupedNumberParser(maxFractionDigits = 2) {
return (display?: string) => {
if (display == null || display === '') return '';
const n = parseMoneyNumber(display, maxFractionDigits);
return n == null ? '' : n;
};
}
/**
* فقط رقم (و در صورت نیاز اعشار/منفی) را هنگام تایپ می‌پذیرد.
* میانبرها (Ctrl/Meta) و کلیدهای کنترلی (Backspace، Enter، …) آزاد می‌مانند.
*/
export function blockNonNumericKeydown(
event: KeyboardEvent,
opts: { allowDecimal?: boolean; allowMinus?: boolean } = {},
) {
const { allowDecimal = true, allowMinus = false } = opts;
if (event.ctrlKey || event.metaKey || event.altKey) return;
if (event.isComposing) return;
if (event.key.length !== 1) return;
if (/[0-9۰-۹٠-٩]/.test(event.key)) return;
if (
allowDecimal &&
(event.key === '.' ||
event.key === ',' ||
event.key === '٫' ||
event.key === '،')
) {
return;
}
if (allowMinus && event.key === '-') return;
event.preventDefault();
}
/** متن پیست‌شده را به کاراکترهای مجاز عددی محدود می‌کند */
export function sanitizeNumericClipboard(
raw: string,
opts: { allowDecimal?: boolean; allowMinus?: boolean } = {},
): string {
const { allowDecimal = true, allowMinus = false } = opts;
let out = '';
for (const ch of raw) {
if (/[0-9۰-۹٠-٩]/.test(ch)) {
out += ch;
continue;
}
if (allowDecimal && (ch === '.' || ch === ',' || ch === '٫' || ch === '،')) {
out += ch;
continue;
}
if (allowMinus && ch === '-' && !out.includes('-')) {
out += ch;
}
}
return out;
}
/**
* پارس متن ورودی مبلغ/قیمت.
* جداکننده‌ها و ارقام فارسی را می‌پذیرد و مقدار عددی برمی‌گرداند.
*/
export function parseMoneyNumber(raw: string, maxFractionDigits = 2): number | null {
const cleaned = normalizeDigits(raw)
.replace(/[٬,،\s]/g, '')
.replace(/٫/g, '.')
.replace(/[^\d.-]/g, '');
if (!cleaned || cleaned === '-' || cleaned === '.' || cleaned === '-.') return null;
const n = Number(cleaned);
if (!Number.isFinite(n)) return null;
if (maxFractionDigits <= 0) return Math.round(n);
const factor = 10 ** maxFractionDigits;
return Math.round(n * factor) / factor;
}
/** رشتهٔ خام بدون جداکننده برای v-modelهای متنی فرم‌ها */
export function parseMoneyToRawString(raw: string, maxFractionDigits = 2): string {
const n = parseMoneyNumber(raw, maxFractionDigits);
return n == null ? '' : String(n);
}
export function countDigitChars(value: string): number {
return normalizeDigits(value).replace(/\D/g, '').length;
}
/** موقعیت کرسر را بر اساس تعداد ارقام قبل از کرسر حفظ می‌کند */
export function caretIndexForDigitCount(formatted: string, digitCount: number): number {
if (digitCount <= 0) return 0;
let seen = 0;
const normalized = normalizeDigits(formatted);
for (let i = 0; i < normalized.length; i++) {
if (/\d/.test(normalized[i]!)) {
seen += 1;
if (seen >= digitCount) return i + 1;
}
}
return formatted.length;
}