manicanldes-backend/src/procurement/purchase-order-money.ts

22 lines
940 B
TypeScript

import { AppError } from '../common/errors/app-error';
export function scaled(value: string, scale: number): bigint {
const [whole, fraction] = value.split('.');
if (!whole || !fraction || fraction.length !== scale)
throw new AppError('DATA_CONSTRAINT');
return BigInt(whole) * 10n ** BigInt(scale) + BigInt(fraction);
}
export function lineTotal(quantity: string, unitPrice: string): string {
const total = (scaled(quantity, 3) * scaled(unitPrice, 2) + 500n) / 1000n;
if (total > 999999999999n) throw new AppError('DATA_CONSTRAINT');
return `${total / 100n}.${(total % 100n).toString().padStart(2, '0')}`;
}
export function totalOf(lines: readonly { lineTotal: string }[]): string {
const total = lines.reduce(
(sum, line) => sum + scaled(line.lineTotal, 2),
0n,
);
if (total > 999999999999n) throw new AppError('DATA_CONSTRAINT');
return `${total / 100n}.${(total % 100n).toString().padStart(2, '0')}`;
}