Files
compras/resources/js/lib/requisition-estimate.ts
T
nala eb32c74c56
tests / ci (push) Waiting to run
commit compras1 2811
2026-11-28 07:11:35 +02:00

35 lines
1.3 KiB
TypeScript

type EstimateLine = { quantity: string; unit_price: string; tax_rate: string };
function units(value: string, scale: number, maximum: bigint): bigint | null {
if (!new RegExp(`^\\d+(?:\\.\\d{1,${scale}})?$`).test(value)) return null;
const [whole, fraction = ''] = value.split('.');
const digits =
`${whole}${fraction.padEnd(scale, '0')}`.replace(/^0+/, '') || '0';
if (digits.length > maximum.toString().length) return null;
const result = BigInt(digits);
return result <= maximum ? result : null;
}
/** Presentation only: the server remains authoritative when saving. */
export function requisitionEstimate(lines: EstimateLine[]): string | null {
if (lines.length === 0) return null;
let total = 0n;
for (const line of lines) {
const quantity = units(line.quantity, 3, 1000000000n);
const price = units(line.unit_price, 2, 10000000000n);
const rate = units(line.tax_rate, 2, 10000n);
if (
quantity === null ||
quantity === 0n ||
price === null ||
price === 0n ||
rate === null
)
return null;
const subtotal = (quantity * price + 500n) / 1000n;
const tax = (subtotal * rate + 5000n) / 10000n;
total += subtotal + tax;
}
return total.toString();
}