// Wallet amount validation and cap helpers for the per-wallet checkout flow. // No next/* imports — used by routes and the page. import type { MemberCheckoutPreviewResult } from "@/app/lib/types"; export const WALLET_ORDER = ["GIFT", "ACORN", "PRODUCT", "APPLE"] as const; export const WALLET_REFUSAL_CODES = [ "WalletAmountOverBalance", "AcornsOverYellowLabel", "WalletAmountsOverDue", "WalletAmountInvalid", "WalletLegsDisabled", ] as const; /** Valid wallet type codes. */ const VALID_CODES = new Set(WALLET_ORDER); /** * Validate and parse a wallet amounts value from an untrusted source. * `undefined` → `{}` (absent means no wallet usage). * A plain object whose every key is one of GIFT/ACORN/PRODUCT/APPLE and every value * a finite number ≥ 0 with at most 2 decimals → that object. * Anything else (array, null, string, unknown code, NaN, Infinity) → `null`. */ export function parseWalletAmounts(raw: unknown): Record | null { if (raw === null) return null; if (raw === undefined) return {}; if (typeof raw !== "object") return null; if (Array.isArray(raw)) return null; const obj = raw as Record; const result: Record = {}; for (const [key, value] of Object.entries(obj)) { if (!VALID_CODES.has(key as typeof WALLET_ORDER[number])) return null; if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return null; // At most 2 decimal places: check in integer sense. if (Math.abs(value * 100 - Math.round(value * 100)) >= 1e-9) return null; result[key] = value; } return result; } /** * Compute the maximum amount this wallet may contribute right now. * = min(option.max, due − sum of OTHER wallets' amounts), floored at 0. * Computed in integer-sense (cents) and returned as an RM number with 2dp. */ export function walletCap( option: { walletTypeCode: string; max: number }, due: number, amounts: Record, ): number { // Sum of OTHER wallets' amounts (exclude the option's own code from the sum). const others = Object.entries(amounts) .filter(([key]) => key !== option.walletTypeCode) .reduce((sum, [, v]) => sum + v, 0); const cents = Math.round((Math.min(option.max, due - others) * 100)); return Math.max(0, Math.round(cents)) / 100; } /** Check if a parsed response body is a wallet refusal. */ export function isWalletRefusal(body: unknown): body is { code: string } { if (!body || typeof body !== "object") return false; const obj = body as Record; return typeof obj.code === "string" && WALLET_REFUSAL_CODES.includes(obj.code as typeof WALLET_REFUSAL_CODES[number]); } /** * Extract the wallet type code from a refusal body. * Tries `details.walletTypeCode` first, then `walletTypeCode` at the top level. */ export function refusalWallet(data: unknown): string | null { if (!data || typeof data !== "object") return null; const obj = data as Record; if (obj.details && typeof obj.details === "object") { const d = obj.details as Record; if (typeof d.walletTypeCode === "string") return d.walletTypeCode; } if (typeof obj.walletTypeCode === "string") return obj.walletTypeCode; return null; } // Keys the retired single-wallet flow sent; never forwarded. const RETIRED_KEYS = new Set(["election", "walletAmount", "splitWalletAmount"]); /** * The body to forward upstream: the retired single-wallet keys (`walletAmount`, `splitWalletAmount`, the Apple pick) removed and * `walletAmounts` replaced by the validated map. `null` when `walletAmounts` is invalid (answer 400 and do * not call upstream). */ export function withWalletAmounts(body: unknown): Record | null { const input = body && typeof body === "object" && !Array.isArray(body) ? (body as Record) : {}; const rest = Object.fromEntries(Object.entries(input).filter(([k]) => !RETIRED_KEYS.has(k))); const walletAmounts = parseWalletAmounts(rest.walletAmounts); return walletAmounts ? { ...rest, walletAmounts } : null; } /** Stable, order-independent key of the non-zero wallet amounts (`CODE=amount` 2dp, sorted) for client keys. */ export function walletAmountsKey(amounts: Record): string { return Object.entries(amounts) .filter(([, v]) => v > 0) .map(([k, v]) => `${k}=${v.toFixed(2)}`) .sort() .join(","); } /** Clamp entered amounts to the wallets' caps; drop wallets no longer offered. Same object back when nothing moved. */ export function clampWalletAmounts( prev: Record, options: { walletTypeCode: string; balance: number; max: number }[], ): Record { const kept: Record = {}; for (const [code, v] of Object.entries(prev)) { const o = options.find((x) => x.walletTypeCode === code && x.balance > 0); const clamped = o ? Math.min(v, o.max) : 0; if (clamped > 0) kept[code] = clamped; } const same = Object.keys(kept).length === Object.keys(prev).length && Object.entries(kept).every(([c, v]) => prev[c] === v); return same ? prev : kept; } /** The receipt's per-wallet breakdown: what the operator entered, not the pre-entry preview. */ export function receiptPreview(preview: MemberCheckoutPreviewResult, amounts: Record): MemberCheckoutPreviewResult { return { ...preview, giftWalletPaid: amounts.GIFT ?? 0, acornPaid: amounts.ACORN ?? 0, productPaid: amounts.PRODUCT ?? 0, applePaid: amounts.APPLE ?? 0, gatewayResidual: 0, }; }