/** * Helpers behind the checkout "use my club balance" control (a CASHBACK club's money balance). * * The balance is spent as a DISCOUNT, so it is not a payment method and not a gift card: the server * lowers the checkout's discount, total and tax, and answers every change with a * `LoyaltyCreditQuote`. Render what the answer says (`applied`, `totalAmount`), never a number the * page worked out for itself. */ import type { LoyaltyCreditQuote } from 'brainerce'; /** A plain positive decimal such as "12", "12.5" or "12.50". No sign, no exponent, no separators. */ const DECIMAL = /^\d+(\.\d+)?$/; export type CreditAmountCheck = | { ok: true; amount: string } | { ok: false; reason: 'invalid' | 'tooMuch' }; /** * Checks a typed amount against what the quote says is spendable. Compared in whole minor units so * "0.10 + 0.20" style float drift can never let 1 cent too much through. */ export function checkCreditAmount(input: string, maxApplicable: string): CreditAmountCheck { const text = input.trim().replace(',', '.'); if (!DECIMAL.test(text)) return { ok: false, reason: 'invalid' }; const typed = Number(text); if (!Number.isFinite(typed) || typed <= 0) return { ok: false, reason: 'invalid' }; const max = Number(maxApplicable); if (Math.round(typed * 1000) > Math.round(max * 1000)) return { ok: false, reason: 'tooMuch' }; return { ok: true, amount: text }; } export type CreditControlState = | { kind: 'hidden' } | { kind: 'debt' } | { kind: 'applied'; applied: string } | { kind: 'offer'; available: string; maxApplicable: string }; /** * What the control shows for a quote. Fails closed: with no quote, no program, a guest or nothing to * spend it renders nothing at all, because an empty "0 balance" box reads as a broken feature. */ export function creditControlState(quote: LoyaltyCreditQuote | null): CreditControlState { if (!quote) return { kind: 'hidden' }; if (Number(quote.applied) > 0) return { kind: 'applied', applied: quote.applied }; if (quote.reason === 'has_debt') return { kind: 'debt' }; if (!quote.usable) return { kind: 'hidden' }; return { kind: 'offer', available: quote.available, maxApplicable: quote.maxApplicable }; }