27 lines
865 B
TypeScript
27 lines
865 B
TypeScript
import { AppError } from '../common/errors/app-error';
|
|
|
|
export function minor(value: string): bigint {
|
|
if (!/^\d+(\.\d{1,2})?$/.test(value)) throw new AppError('MONEY_RANGE');
|
|
const [whole, fraction = ''] = value.split('.');
|
|
return BigInt(whole) * 100n + BigInt(fraction.padEnd(2, '0'));
|
|
}
|
|
export function decimal(value: bigint): string {
|
|
if (value < 0n || value > 9999999999999999n)
|
|
throw new AppError('MONEY_RANGE');
|
|
return `${value / 100n}.${(value % 100n).toString().padStart(2, '0')}`;
|
|
}
|
|
export function discountFor(
|
|
subtotal: bigint,
|
|
coupon: {
|
|
kind: 'FIXED' | 'PERCENT';
|
|
amount: string | null;
|
|
percentBps: number | null;
|
|
},
|
|
): bigint {
|
|
const amount =
|
|
coupon.kind === 'FIXED'
|
|
? minor(coupon.amount!)
|
|
: (subtotal * BigInt(coupon.percentBps!) + 5000n) / 10000n;
|
|
return amount > subtotal ? subtotal : amount;
|
|
}
|