Files
CatoandClaude 0474c3a887 paykit 0.7.0: prepaid credit, top-ups, auto top-up and per-key limits (#31)
Pay as you go beside the subscriptions, the way OpenRouter charges:

- ./credits: append-only CreditLedger with idempotency keys and an
  in-memory ledger; balance, FIFO lots and debt; charge refused with 402
  below the app's floor or over a spending key's daily/weekly/monthly
  limit; hold then settle or release; top-up quotes with a fee per rail
  in integer arithmetic; refund eligibility (window, fee kept, rails that
  never refund); expiry of old lots; auto top-up decision with backoff
  and a failure cap; credit events applied idempotently; top-ups through
  any PaymentProvider (OrangeCat: sats, never refundable).
- ./stripe: stripeCredits — top-up Checkout Session (saves the method
  off-session when auto top-up is on), off-session PaymentIntent with an
  Idempotency-Key, refunds, and webhook mapping for
  checkout.session.completed, payment_intent.succeeded/payment_failed
  and charge.refunded. The pass provider ignores top-up sessions.
- ./react: CreditBalance, TopUp, AutoTopUp, CreditActivity; PickerTier
  gains optional rates for a pay-as-you-go tier.

No price, fee or threshold is built in; all are the app's config.


Claude-Session: https://claude.ai/code/session_019MDtmtfseicWGK2CMC2U5r

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-03 13:07:29 +01:00

142 lines
15 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use client";
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
/**
* Prepaid credit on screen: the balance, buying more, buying more
* automatically, and what it was spent on.
*
* WHY IT IS HERE. Every product that charges by use needs these four, and
* the shape people know from pay-as-you-go services (a balance with one
* button to add to it, a few amounts to pick from, the fee written out before
* paying, a threshold and an amount for automatic top-up, a list of what was
* spent that can be narrowed to one key) is the same for all of them. The
* app passes words and its own handlers; the layout, focus order and 320 px
* behaviour are here, once, styled by `@bitbaum/paykit/styles.css`.
*
* WHAT IS COMPUTED, NOT TYPED. Amounts are `Money` in the smallest unit and
* are written with `formatMoney`; the fee and the total are `topUpQuote` from
* `@bitbaum/paykit/credits`, from the fee rule the app passes per way of
* paying. A page cannot show a fee the rule does not charge.
*/
import { useId, useMemo, useState } from "react";
import { activityOf, effectOf } from "../credits/ledger.js";
import { parseAmount, topUpQuote } from "../credits/quote.js";
import { formatMoney } from "../plans/index.js";
const formatter = (locale, format) => format ?? ((money) => formatMoney(money, locale));
function ActionButton({ action, primary = true }) {
const [busy, setBusy] = useState(false);
const className = primary ? "pk-button" : "pk-button pk-quiet";
if (action.href) {
return (_jsx("a", { className: className, href: action.href, "data-pk": "action", children: action.label }));
}
return (_jsx("button", { type: "button", className: className, "data-pk": "action", disabled: busy, "aria-busy": busy || undefined, onClick: async () => {
if (busy)
return;
setBusy(true);
try {
await action.onSelect?.();
}
finally {
setBusy(false);
}
}, children: action.label }));
}
/** The balance, what is reserved, a word when it is low or below zero, and the way to add to it. */
export function CreditBalance({ label, balance, held, heldLabel, low, negative, action, locale, format, className, }) {
const write = formatter(locale, format);
const state = balance.amount < 0 ? "negative" : low && balance.amount < low.below ? "low" : "ok";
const note = state === "negative" ? negative : state === "low" ? low?.message : null;
return (_jsxs("section", { className: ["pk-credits", "pk-balance", className].filter(Boolean).join(" "), "data-pk": "balance", "data-state": state, children: [_jsx("p", { className: "pk-balance-label", children: label }), _jsx("p", { className: "pk-balance-amount", "data-pk": "balance-amount", children: write(balance) }), held && held.amount > 0 && (_jsxs("p", { className: "pk-balance-held", "data-pk": "held", children: [write(held), " ", heldLabel] })), note && (_jsx("p", { className: "pk-balance-note", role: "status", "data-pk": "balance-note", children: note })), action && (_jsx("div", { className: "pk-action", children: _jsx(ActionButton, { action: action }) }))] }));
}
function Chips({ legend, name, options, value, onChange, render, }) {
return (_jsxs("fieldset", { className: "pk-chips", "data-count": options.length, children: [_jsx("legend", { className: "pk-field-label", children: legend }), options.map((option) => {
const checked = option === value;
return (_jsxs("label", { className: "pk-chip", "data-checked": checked || undefined, "data-value": String(option), children: [_jsx("input", { className: "pk-visually-hidden", type: "radio", name: name, value: String(option), checked: checked, onChange: () => onChange(option) }), _jsx("span", { children: render(option) })] }, String(option)));
})] }));
}
/** Buying credit: an amount (a few choices and, optionally, one typed), a way to pay, the fee and total, one button. */
export function TopUp({ title, currency, amounts, defaultAmount, amountLabel, custom, rails, railLabel, defaultRail, mode, minimum, maximum, words, save, onPay, fine, error, locale, format, className, }) {
const id = useId();
const write = formatter(locale, format);
const [amount, setAmount] = useState(() => (defaultAmount !== undefined && amounts.includes(defaultAmount) ? defaultAmount : (amounts[0] ?? null)));
const [typed, setTyped] = useState("");
const [rail, setRail] = useState(() => rails.find((r) => r.id === defaultRail)?.id ?? rails[0]?.id ?? "");
const [saveIt, setSaveIt] = useState(save?.defaultChecked ?? false);
const [busy, setBusy] = useState(false);
const chosenRail = rails.find((r) => r.id === rail) ?? rails[0];
const typedAmount = typed.trim() ? parseAmount(typed, currency) : null;
const wanted = typed.trim() ? typedAmount : amount;
const quote = useMemo(() => {
if (!wanted || !chosenRail)
return null;
return topUpQuote({ amount: wanted, currency, rail: chosenRail.id, fee: chosenRail.fee ?? null, mode, minimum, maximum });
}, [wanted, chosenRail, currency, mode, minimum, maximum]);
const problem = typed.trim() && typedAmount === null
? words.invalid
: quote && !quote.ok
? quote.reason === "below_minimum"
? words.belowMinimum?.replace("{limit}", write(quote.limit))
: quote.reason === "above_maximum"
? words.aboveMaximum?.replace("{limit}", write(quote.limit))
: words.invalid
: null;
const ready = quote?.ok ? quote : null;
return (_jsxs("section", { className: ["pk-credits", "pk-topup", className].filter(Boolean).join(" "), "data-pk": "topup", children: [title && _jsx("h2", { className: "pk-name", children: title }), _jsx(Chips, { legend: amountLabel, name: `${id}-amount`, options: amounts, value: typed.trim() ? null : amount, onChange: (value) => {
setAmount(value);
setTyped("");
}, render: (value) => write({ amount: value, currency }) }), custom && (_jsxs("label", { className: "pk-field", children: [_jsx("span", { className: "pk-field-label", children: custom.label }), _jsx("input", { className: "pk-input", type: "text", inputMode: "decimal", autoComplete: "off", placeholder: custom.placeholder, value: typed, "aria-invalid": problem ? true : undefined, onChange: (event) => setTyped(event.target.value) })] })), rails.length > 1 ? (_jsxs("fieldset", { className: "pk-rails", children: [_jsx("legend", { className: "pk-field-label", children: railLabel }), rails.map((r) => (_jsxs("label", { className: "pk-rail", "data-rail": r.id, "data-checked": r.id === chosenRail?.id || undefined, children: [_jsx("input", { type: "radio", className: "pk-checkbox", name: `${id}-rail`, value: r.id, checked: r.id === chosenRail?.id, onChange: () => setRail(r.id) }), _jsxs("span", { className: "pk-rail-text", children: [_jsx("span", { className: "pk-rail-label", children: r.label }), r.note && _jsx("span", { className: "pk-rail-note", children: r.note })] })] }, r.id)))] })) : null, ready && (_jsxs("dl", { className: "pk-quote", "data-pk": "quote", children: [_jsxs("div", { className: "pk-quote-row", children: [_jsx("dt", { children: words.credit }), _jsx("dd", { "data-pk": "quote-credit", children: write(ready.credit) })] }), _jsxs("div", { className: "pk-quote-row", children: [_jsx("dt", { children: words.fee }), _jsx("dd", { "data-pk": "quote-fee", children: write(ready.fee) })] }), _jsxs("div", { className: "pk-quote-row pk-quote-total", children: [_jsx("dt", { children: words.total }), _jsx("dd", { "data-pk": "quote-total", children: write(ready.total) })] })] })), problem && (_jsx("p", { className: "pk-hint", role: "status", children: problem })), save && (_jsxs("label", { className: "pk-term", children: [_jsx("input", { type: "checkbox", className: "pk-checkbox", checked: saveIt, onChange: (event) => setSaveIt(event.target.checked) }), _jsx("span", { className: "pk-term-label", children: save.label })] })), error && (_jsx("p", { className: "pk-error", role: "alert", children: error })), _jsx("div", { className: "pk-action", children: _jsx("button", { type: "button", className: "pk-button", "data-pk": "pay", disabled: !ready || busy, "aria-busy": busy || undefined, onClick: async () => {
if (!ready || busy || !wanted)
return;
setBusy(true);
try {
await onPay({ amount: wanted, rail: ready.rail, quote: { rail: ready.rail, credit: ready.credit, fee: ready.fee, total: ready.total }, saveForAutoTopUp: saveIt });
}
finally {
setBusy(false);
}
}, children: busy && words.busy ? words.busy : words.pay.replace("{total}", ready ? write(ready.total) : "") }) }), fine && _jsx("div", { className: "pk-fine", children: fine })] }));
}
/** Automatic top-up: on or off, below which balance, how much, with which saved method. */
export function AutoTopUp({ title, currency, enabled, threshold, amount, thresholds, amounts, words, method, fee, status, onSave, locale, format, className, }) {
const id = useId();
const write = formatter(locale, format);
const [on, setOn] = useState(enabled);
const [below, setBelow] = useState(threshold);
const [add, setAdd] = useState(amount);
const [busy, setBusy] = useState(false);
const quote = add > 0 ? topUpQuote({ amount: add, currency, rail: "saved", fee: fee ?? null }) : null;
const summary = words.summary && quote?.ok
? words.summary
.replace("{threshold}", write({ amount: below, currency }))
.replace("{amount}", write(quote.credit))
.replace("{total}", write(quote.total))
: null;
return (_jsxs("section", { className: ["pk-credits", "pk-auto", className].filter(Boolean).join(" "), "data-pk": "auto-topup", "data-enabled": on || undefined, children: [title && _jsx("h2", { className: "pk-name", children: title }), status && (_jsx("p", { className: status.tone === "warning" ? "pk-error" : "pk-hint", role: "status", "data-pk": "auto-status", children: status.text })), !method ? (_jsx("p", { className: "pk-hint", "data-pk": "no-method", children: words.noMethod })) : (_jsxs(_Fragment, { children: [_jsxs("label", { className: "pk-term", children: [_jsx("input", { type: "checkbox", role: "switch", className: "pk-checkbox", checked: on, onChange: (event) => setOn(event.target.checked) }), _jsx("span", { className: "pk-term-label", children: words.enable })] }), on && (_jsxs(_Fragment, { children: [_jsx(Chips, { legend: words.threshold, name: `${id}-threshold`, options: thresholds, value: below, onChange: setBelow, render: (v) => write({ amount: v, currency }) }), _jsx(Chips, { legend: words.amount, name: `${id}-amount`, options: amounts, value: add, onChange: setAdd, render: (v) => write({ amount: v, currency }) }), summary && (_jsx("p", { className: "pk-auto-summary", "data-pk": "auto-summary", children: summary }))] })), _jsxs("div", { className: "pk-account", children: [_jsx("span", { className: "pk-account-value", children: method.label }), method.change && _jsx(ActionButton, { action: method.change, primary: false })] }), _jsx("div", { className: "pk-action", children: _jsx("button", { type: "button", className: "pk-button", "data-pk": "save", disabled: busy, "aria-busy": busy || undefined, onClick: async () => {
if (busy)
return;
setBusy(true);
try {
await onSave({ enabled: on, threshold: below, amount: add });
}
finally {
setBusy(false);
}
}, children: busy && words.busy ? words.busy : words.save }) })] }))] }));
}
/** What credit was bought and spent on, newest first, narrowed to one key or one kind. */
export function CreditActivity({ title, entries, kinds, keys, words, describe, locale, format, dateFormat, limit, className, }) {
const id = useId();
const write = formatter(locale, format);
const [kind, setKind] = useState("");
const [key, setKey] = useState("");
const offered = Object.keys(kinds).filter((k) => kinds[k]);
const rows = activityOf(entries, { kinds: kind ? [kind] : offered, ...(key ? { key } : {}), ...(limit !== undefined ? { limit } : {}) });
const when = new Intl.DateTimeFormat(locale, dateFormat ?? { dateStyle: "medium", timeStyle: "short" });
const keyName = (k) => (k ? (keys?.find((x) => x.id === k)?.label ?? k) : null);
return (_jsxs("section", { className: ["pk-credits", "pk-activity", className].filter(Boolean).join(" "), "data-pk": "activity", children: [title && _jsx("h2", { className: "pk-name", children: title }), _jsxs("div", { className: "pk-filters", children: [_jsxs("label", { className: "pk-field", children: [_jsx("span", { className: "pk-field-label", children: words.kind }), _jsxs("select", { className: "pk-input", id: `${id}-kind`, value: kind, onChange: (event) => setKind(event.target.value), children: [_jsx("option", { value: "", children: words.all }), offered.map((k) => (_jsx("option", { value: k, children: kinds[k] }, k)))] })] }), keys && keys.length > 0 && words.key && (_jsxs("label", { className: "pk-field", children: [_jsx("span", { className: "pk-field-label", children: words.key }), _jsxs("select", { className: "pk-input", id: `${id}-key`, value: key, onChange: (event) => setKey(event.target.value), children: [_jsx("option", { value: "", children: words.all }), keys.map((k) => (_jsx("option", { value: k.id, children: k.label }, k.id)))] })] }))] }), rows.length === 0 ? (_jsx("p", { className: "pk-hint", "data-pk": "empty", children: words.empty })) : (_jsx("ul", { className: "pk-rows", children: rows.map((entry) => {
const effect = effectOf(entry);
const detail = describe?.(entry);
const by = keyName(entry.key);
return (_jsxs("li", { className: "pk-row", "data-kind": entry.kind, children: [_jsxs("span", { className: "pk-row-main", children: [_jsx("span", { className: "pk-row-kind", children: kinds[entry.kind] ?? entry.kind }), detail && _jsx("span", { className: "pk-row-detail", children: detail }), _jsxs("span", { className: "pk-row-meta", children: [_jsx("time", { dateTime: entry.at, children: when.format(new Date(entry.at)) }), by && _jsxs(_Fragment, { children: [" \u00B7 ", by] })] })] }), _jsxs("span", { className: "pk-row-amount", "data-sign": effect > 0 ? "plus" : effect < 0 ? "minus" : "zero", children: [effect > 0 ? "+" : effect < 0 ? "−" : "", write({ amount: Math.abs(effect || entry.amount), currency: entry.currency })] })] }, entry.idempotencyKey));
}) }))] }));
}