commit
This commit is contained in:
47
src/features/crm/shared/formats.ts
Normal file
47
src/features/crm/shared/formats.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { format, isValid, parse, parseISO } from 'date-fns';
|
||||
|
||||
function coerceDate(value: string | Date | null | undefined) {
|
||||
if (!value) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (value instanceof Date) {
|
||||
return isValid(value) ? value : null;
|
||||
}
|
||||
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
const parsed = parse(value, 'yyyy-MM-dd', new Date());
|
||||
return isValid(parsed) ? parsed : null;
|
||||
}
|
||||
|
||||
const isoParsed = parseISO(value);
|
||||
return isValid(isoParsed) ? isoParsed : null;
|
||||
}
|
||||
|
||||
export function formatCrmDate(value: string | Date | null | undefined) {
|
||||
const date = coerceDate(value);
|
||||
return date ? format(date, 'dd/MM/yyyy') : '';
|
||||
}
|
||||
|
||||
export function formatCrmNumber(value: number | string | null | undefined, options?: Intl.NumberFormatOptions) {
|
||||
if (value === '' || value === null || value === undefined) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const parsed = typeof value === 'number' ? value : Number(String(value).replaceAll(',', ''));
|
||||
|
||||
if (Number.isNaN(parsed)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return new Intl.NumberFormat('en-US', options).format(parsed);
|
||||
}
|
||||
|
||||
export function sanitizeDecimalInput(value: string) {
|
||||
const normalized = value.replaceAll(',', '').replace(/[^\d.-]/g, '');
|
||||
const [head = '', ...tail] = normalized.split('.');
|
||||
const integerPart = head.replace(/(?!^)-/g, '');
|
||||
const decimalPart = tail.join('');
|
||||
|
||||
return decimalPart.length > 0 ? `${integerPart}.${decimalPart}` : integerPart;
|
||||
}
|
||||
Reference in New Issue
Block a user