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

231 lines
12 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.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import { createElement as h } from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { AutoTopUp, CreditActivity, CreditBalance, PlanPicker, PlanReview, TopUp } from '../dist/react/index.js';
const tiers = [
{ id: 'free', name: 'Free', price: 'CHF 0', benefits: ['100 questions a day'], action: { kind: 'link', href: '/join', label: 'Start free' } },
{
id: 'plus',
name: 'Plus',
badge: 'Recommended',
periodsLabel: 'Billing period',
defaultPeriod: 'month',
periods: [
{ id: 'month', label: 'Monthly', price: 'CHF 12', per: '/ month', highlight: 'First 3 months CHF 6' },
{ id: 'year', label: 'Yearly', price: 'CHF 99', per: '/ year', detail: 'CHF 8.25 / month', badge: 'Save 31%' },
],
benefits: ['Own daily allowance'],
action: { kind: 'button', label: 'Continue with Plus', onSelect: () => {} },
fine: 'Renews automatically until you cancel.',
},
{ id: 'key', name: 'Your own key', price: 'CHF 0', per: 'You pay your AI provider directly', benefits: ['No daily limit'], action: { kind: 'link', href: '/settings#model', label: 'Connect your key' } },
{ id: 'org', name: 'Organisations', price: 'Contact us', benefits: [], action: { kind: 'link', href: '/organisations', label: 'Get in touch' } },
];
test('PlanPicker draws the switch, the chosen tier, both period cards and one button', () => {
const html = renderToStaticMarkup(h(PlanPicker, { tiers, defaultTier: 'plus', label: 'Plan' }));
assert.equal((html.match(/role="tab"/g) ?? []).length, 4);
assert.match(html, /aria-selected="true"[^>]*data-tier="plus"/);
assert.match(html, /data-pk="badge">Recommended</);
assert.match(html, /data-period="month" data-checked="true"/);
assert.match(html, /data-pk="intro">First 3 months CHF 6</);
assert.match(html, /data-pk="save">Save 31%</);
assert.equal((html.match(/data-pk="action"/g) ?? []).length, 1);
assert.match(html, /Renews automatically until you cancel\./);
assert.match(html, /<legend class="pk-visually-hidden">Billing period<\/legend>/);
});
test('a tier without periods shows its price line and its link', () => {
const html = renderToStaticMarkup(h(PlanPicker, { tiers, defaultTier: 'key', label: 'Plan' }));
assert.match(html, /You pay your AI provider directly/);
assert.match(html, /href="\/settings#model"/);
assert.equal(html.includes('pk-periods'), false);
});
const review = {
title: 'Review your plan',
step: 'Step 2 of 2',
summary: { name: 'Plus, monthly', price: 'CHF 12', per: 'per month', detail: 'First 3 months CHF 6' },
notes: [{ id: 'cancel', title: 'Cancel anytime', line: 'In Settings', more: 'Access lasts to the end of the period.' }],
account: { label: 'Account', value: 'a@example.ch' },
terms: [
{ id: 'renew', label: 'It renews automatically', required: true },
{ id: 'terms', label: 'I accept the terms', required: true },
{ id: 'mail', label: 'Practice reminders', required: false },
],
requiredHint: 'Tick the {n} required boxes to continue',
confirm: { label: 'Continue to payment', onConfirm: () => {} },
};
test('PlanReview keeps the button off until the required terms are ticked, and says how many', () => {
const html = renderToStaticMarkup(h(PlanReview, review));
assert.match(html, /data-pk="confirm" disabled=""/);
assert.match(html, /Tick the 2 required boxes to continue/);
assert.match(html, /<details class="pk-note">/);
assert.match(html, /a@example\.ch/);
const ticked = renderToStaticMarkup(h(PlanReview, { ...review, terms: review.terms.map((t) => ({ ...t, defaultChecked: t.required })) }));
assert.doesNotMatch(ticked, /data-pk="confirm" disabled/);
assert.doesNotMatch(ticked, /required boxes/);
});
test('with an overlapping plan the buy button is replaced by the way to manage it', () => {
const html = renderToStaticMarkup(h(PlanReview, { ...review, overlap: { title: 'You already have Plus', body: 'Change it instead.', manage: { label: 'Manage', href: '/manage' } } }));
assert.match(html, /data-pk="overlap"/);
assert.match(html, /href="\/manage" data-pk="manage"/);
assert.equal(html.includes('data-pk="confirm"'), false);
});
test('the stylesheet styles every class the components use, through --pk-* variables', () => {
const css = readFileSync(new URL('../styles.css', import.meta.url), 'utf8');
const html = renderToStaticMarkup(
h(
'div',
null,
h(PlanPicker, { tiers, defaultTier: 'plus', label: 'Plan' }),
h(PlanPicker, { tiers: [payg], label: 'Plan' }),
h(PlanReview, review),
h(CreditBalance, { ...balanceProps, held: { amount: 300, currency: 'CHF' }, heldLabel: 'reserved' }),
h(TopUp, topUpProps),
h(AutoTopUp, autoProps),
h(CreditActivity, activityProps),
),
);
const used = new Set([...html.matchAll(/class="([^"]+)"/g)].flatMap((m) => m[1].split(/\s+/)));
for (const name of used) assert.ok(css.includes(`.${name}`), `.${name} is styled`);
// Colours are variables with system fallbacks; the only literal is the last fallback of the warning colour.
const literal = css.split('\n').filter((line) => /#[0-9a-f]{3,6}\b/i.test(line) && !line.trim().startsWith('*'));
assert.deepEqual(literal.map((line) => line.trim().split(':')[0]), ['--pk-warning-']);
});
const payg = {
id: 'payg',
name: 'Pay as you go',
price: 'From CHF 5',
per: 'Prepaid credit, no subscription',
ratesLabel: 'What it costs',
rates: [
{ label: 'A question', price: 'CHF 0.01', per: 'each' },
{ label: 'A minute of audio', price: 'CHF 0.02', per: 'per minute' },
],
benefits: ['Top up when you like'],
action: { kind: 'link', href: '/credits', label: 'Add credit' },
};
test('a pay-as-you-go tier lists its rates under the price; tiers without rates are unchanged', () => {
const html = renderToStaticMarkup(h(PlanPicker, { tiers: [...tiers, payg], defaultTier: 'payg', label: 'Plan' }));
assert.match(html, /data-pk="rates"/);
assert.match(html, /<dt>A question<\/dt><dd><span class="pk-rate-price">CHF 0.01<\/span><span class="pk-per"> each<\/span><\/dd>/);
assert.match(html, /From CHF 5/);
const plus = renderToStaticMarkup(h(PlanPicker, { tiers: [...tiers, payg], defaultTier: 'plus', label: 'Plan' }));
assert.equal(plus.includes('data-pk="rates"'), false);
});
const balanceProps = { label: 'Credits', balance: { amount: 1250, currency: 'CHF' }, locale: 'de-CH', low: { below: 500, message: 'Running low' }, negative: 'Top up to continue', action: { label: 'Add credit', href: '/credits/top-up' } };
test('CreditBalance writes the balance, marks it low or negative, and always leads to adding credit', () => {
const html = renderToStaticMarkup(h(CreditBalance, balanceProps));
assert.match(html, /data-state="ok"/);
assert.match(html, /data-pk="balance-amount">CHF.12\.50</);
assert.match(html, /href="\/credits\/top-up"/);
assert.equal(html.includes('balance-note'), false);
const low = renderToStaticMarkup(h(CreditBalance, { ...balanceProps, balance: { amount: 300, currency: 'CHF' } }));
assert.match(low, /data-state="low"/);
assert.match(low, /Running low/);
const negative = renderToStaticMarkup(h(CreditBalance, { ...balanceProps, balance: { amount: -40, currency: 'CHF' } }));
assert.match(negative, /data-state="negative"/);
assert.match(negative, /Top up to continue/);
});
const topUpProps = {
title: 'Add credit',
currency: 'CHF',
locale: 'de-CH',
amounts: [1000, 2000, 5000],
defaultAmount: 2000,
amountLabel: 'Amount',
custom: { label: 'Other amount' },
rails: [
{ id: 'card', label: 'Card or TWINT', fee: { percent: 5.5, min: 80 } },
{ id: 'bitcoin', label: 'Bitcoin', fee: { percent: 5 }, note: 'Not refundable' },
],
railLabel: 'Pay with',
words: { credit: 'Credit', fee: 'Purchase fee', total: 'Total', pay: 'Pay {total}', belowMinimum: 'At least {limit}' },
save: { label: 'Save this card for automatic top-up' },
onPay: () => {},
fine: 'Unused credit can be refunded within 24 hours; the fee is kept.',
};
test('TopUp shows the fee and the total from the rail\'s rule before paying, with the total on the button', () => {
const html = renderToStaticMarkup(h(TopUp, topUpProps));
assert.match(html, /data-value="2000"[^>]*>|data-checked="true" data-value="2000"/);
assert.match(html, /data-pk="quote-credit">CHF.20</);
assert.match(html, /data-pk="quote-fee">CHF.1\.10</);
assert.match(html, /data-pk="quote-total">CHF.21\.10</);
assert.match(html, /data-pk="pay">Pay CHF.21\.10</);
assert.match(html, /Not refundable/);
assert.match(html, /Save this card/);
const minimum = renderToStaticMarkup(h(TopUp, { ...topUpProps, minimum: 2500 }));
assert.match(minimum, /At least CHF.25/);
assert.match(minimum, /data-pk="pay" disabled=""/);
});
const autoProps = {
title: 'Automatic top-up',
currency: 'CHF',
locale: 'de-CH',
enabled: true,
threshold: 500,
amount: 2000,
thresholds: [200, 500, 1000],
amounts: [1000, 2000, 5000],
fee: { percent: 5.5, min: 80 },
method: { label: 'Visa ending 4242', change: { label: 'Change', href: '/billing' } },
words: { enable: 'Top up automatically', threshold: 'When the balance falls below', amount: 'Add', save: 'Save', summary: 'Below {threshold} we add {amount} and charge {total}.', noMethod: 'Top up once and save your card first.' },
onSave: () => {},
};
test('AutoTopUp states the rule with the fee included, and asks for a saved method first', () => {
const html = renderToStaticMarkup(h(AutoTopUp, autoProps));
assert.match(html, /role="switch"[^>]*checked=""/);
assert.match(html, /data-pk="auto-summary">Below CHF.5 we add CHF.20 and charge CHF.21\.10\.</);
assert.match(html, /Visa ending 4242/);
const none = renderToStaticMarkup(h(AutoTopUp, { ...autoProps, method: null }));
assert.match(none, /data-pk="no-method">Top up once/);
assert.equal(none.includes('data-pk="save"'), false);
const warned = renderToStaticMarkup(h(AutoTopUp, { ...autoProps, status: { tone: 'warning', text: 'The last top-up was declined' } }));
assert.match(warned, /class="pk-error" role="status" data-pk="auto-status">The last top-up was declined/);
});
const entry = (over) => ({ currency: 'CHF', key: null, ref: null, rail: null, fee: null, refundable: null, expiresAt: null, meta: {}, ...over });
const activityProps = {
title: 'Activity',
locale: 'en-GB',
dateFormat: { dateStyle: 'medium', timeZone: 'UTC' },
entries: [
entry({ idempotencyKey: 't1', kind: 'top_up', amount: 2000, at: '2026-12-01T10:00:00Z', rail: 'card', fee: 110 }),
entry({ idempotencyKey: 'c1', kind: 'charge', amount: 12, at: '2026-12-02T10:00:00Z', key: 'k1', meta: { model: 'fast' } }),
entry({ idempotencyKey: 'h1', kind: 'hold', amount: 50, at: '2026-12-03T10:00:00Z' }),
],
kinds: { top_up: 'Top-up', charge: 'Use', refund: 'Refund' },
keys: [{ id: 'k1', label: 'Phone' }],
words: { kind: 'Kind', key: 'Key', all: 'All', empty: 'Nothing yet' },
describe: (e) => (e.meta.model ? String(e.meta.model) : null),
};
test('CreditActivity lists newest first with signed amounts, hides holds, and offers kind and key filters', () => {
const html = renderToStaticMarkup(h(CreditActivity, activityProps));
const order = [...html.matchAll(/data-kind="([a-z_]+)"/g)].map((m) => m[1]);
assert.deepEqual(order, ['charge', 'top_up']);
assert.match(html, /data-sign="minus">−CHF\s?0\.12</);
assert.match(html, /data-sign="plus">\+CHF\s?20(\.00)?</);
assert.match(html, /Phone/);
assert.match(html, /class="pk-row-detail">fast</);
assert.match(html, /<option value="charge">Use<\/option>/);
assert.match(html, /<option value="k1">Phone<\/option>/);
const empty = renderToStaticMarkup(h(CreditActivity, { ...activityProps, entries: [] }));
assert.match(empty, /data-pk="empty">Nothing yet/);
});