@hjam91/billing 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -19,6 +19,15 @@ npm install @hjam91/billing
19
19
 
20
20
  `hono` and `react` are optional peer dependencies, needed only for `@hjam91/billing/hono` and `@hjam91/billing/react`.
21
21
 
22
+ ## 0.11.0: the pricing editor
23
+
24
+ ```ts
25
+ // server (a scoped key with read + config + pricing, from the service owner)
26
+ app.route('/super-admin/billing/pricing', billingPricingRoutes(createBillingAdmin({ baseUrl, appId, key }), { canManage: (c) => isSuperAdmin(c) }));
27
+ // browser
28
+ <PricingEditor basePath="/super-admin/billing/pricing" /> // edit ladders and prices, preview, save, move subscribers
29
+ ```
30
+
22
31
  ## 0.10.0: tiered plans (priced by a count your app reports)
23
32
 
24
33
  ```ts
package/dist/hono.d.ts CHANGED
@@ -7,6 +7,8 @@
7
7
  */
8
8
  import { Hono, type Context, type MiddlewareHandler } from 'hono';
9
9
  import type { Billing } from './index.js';
10
+ import type { BillingAdmin } from './admin.js';
11
+ import type { BillingConfig } from './config.js';
10
12
  import type { CheckResult, EntitlementChangedEvent, EntitlementResult, UsageEvent } from './types.js';
11
13
  /** Stable error codes the gate answers with. Clients branch on these. */
12
14
  export declare const BILLING_INACTIVE = "billing_inactive";
@@ -84,4 +86,38 @@ export interface BillingRoutesOptions {
84
86
  * The browser (sdk/react) calls these; the secret never leaves the server.
85
87
  */
86
88
  export declare function billingRoutes(billing: Billing, opts: BillingRoutesOptions): Hono<any>;
89
+ export interface BillingPricingRoutesOptions {
90
+ /** May this request's user edit the app's prices? THE APP DECIDES (e.g. "is a super admin"). Never `() => true`. */
91
+ canManage: (c: Context<any>) => boolean | Promise<boolean>;
92
+ }
93
+ export declare const BILLING_PRICING_FORBIDDEN = "billing_pricing_forbidden";
94
+ /** What GET {basePath} answers: the app's config document plus each plan's versions (when versioning is on). */
95
+ export interface PricingDocument {
96
+ config: BillingConfig;
97
+ versions: Record<string, {
98
+ current_version: number;
99
+ versioning: boolean;
100
+ versions: Array<{
101
+ version: number;
102
+ current: boolean;
103
+ subscribers: number;
104
+ price: string | null;
105
+ created_at: string | null;
106
+ }>;
107
+ }>;
108
+ }
109
+ /**
110
+ * The app's price-editing routes, ready to mount behind its own admin gate (e.g. at /super-admin/billing/pricing):
111
+ *
112
+ * GET / the config document (plans with their tiers, unit, prices) and plan versions
113
+ * POST /preview {config} → the diff a save would make (nothing changes)
114
+ * POST /save {config} → applies it: a changed ladder is a new price and, with plan_versioning, a new
115
+ * version — current subscribers stay on theirs until renewal / a migration
116
+ * POST /migrate {plan, when: 'now' | 'period_end'} → moves every subscriber of an older version to the current one
117
+ * GET /versions/:plan the versions of one plan
118
+ *
119
+ * Runs with the app's ADMIN key (a scoped key with read + config + pricing), which never reaches the browser; the
120
+ * service validates the document (ascending tiers, amounts, currency and interval rules) and answers in words.
121
+ */
122
+ export declare function billingPricingRoutes(admin: BillingAdmin, opts: BillingPricingRoutesOptions): Hono<any>;
87
123
  export {};
package/dist/hono.js CHANGED
@@ -316,3 +316,128 @@ export function billingRoutes(billing, opts) {
316
316
  });
317
317
  return r;
318
318
  }
319
+ export const BILLING_PRICING_FORBIDDEN = 'billing_pricing_forbidden';
320
+ /**
321
+ * The app's price-editing routes, ready to mount behind its own admin gate (e.g. at /super-admin/billing/pricing):
322
+ *
323
+ * GET / the config document (plans with their tiers, unit, prices) and plan versions
324
+ * POST /preview {config} → the diff a save would make (nothing changes)
325
+ * POST /save {config} → applies it: a changed ladder is a new price and, with plan_versioning, a new
326
+ * version — current subscribers stay on theirs until renewal / a migration
327
+ * POST /migrate {plan, when: 'now' | 'period_end'} → moves every subscriber of an older version to the current one
328
+ * GET /versions/:plan the versions of one plan
329
+ *
330
+ * Runs with the app's ADMIN key (a scoped key with read + config + pricing), which never reaches the browser; the
331
+ * service validates the document (ascending tiers, amounts, currency and interval rules) and answers in words.
332
+ */
333
+ export function billingPricingRoutes(admin, opts) {
334
+ const r = new Hono();
335
+ const asError = (c, err) => {
336
+ const e = err;
337
+ const status = e.status === 400 || e.status === 403 || e.status === 404 || e.status === 409 ? e.status : 502;
338
+ return c.json({ error: e.code ?? 'billing_error', message: e.message ?? 'Billing request failed' }, status);
339
+ };
340
+ const gate = async (c) => ((await opts.canManage(c)) ? null : c.json({ error: BILLING_PRICING_FORBIDDEN, message: 'You may not edit prices' }, 403));
341
+ const body = async (c) => {
342
+ try {
343
+ const raw = await c.req.text();
344
+ const value = raw.trim() ? JSON.parse(raw) : {};
345
+ if (!value || typeof value !== 'object' || Array.isArray(value))
346
+ throw new Error('object required');
347
+ return value;
348
+ }
349
+ catch {
350
+ return c.json({ error: 'invalid_json', message: 'A JSON object is required' }, 400);
351
+ }
352
+ };
353
+ const versionsOf = async (config) => {
354
+ const out = {};
355
+ if (!config.plan_versioning)
356
+ return out;
357
+ for (const [plan, spec] of Object.entries(config.plans ?? {})) {
358
+ if (spec.free)
359
+ continue;
360
+ try {
361
+ const v = (await admin.planVersions(plan));
362
+ out[plan] = { current_version: v.current_version, versioning: v.versioning, versions: (v.versions ?? []).map((x) => ({ version: x.version, current: x.current, subscribers: x.subscribers, price: x.price ?? null, created_at: x.created_at ?? null })) };
363
+ }
364
+ catch {
365
+ /* a plan without versions yet */
366
+ }
367
+ }
368
+ return out;
369
+ };
370
+ r.get('/', async (c) => {
371
+ const denied = await gate(c);
372
+ if (denied)
373
+ return denied;
374
+ try {
375
+ const config = await admin.pullConfig();
376
+ return c.json({ config, versions: await versionsOf(config) });
377
+ }
378
+ catch (err) {
379
+ return asError(c, err);
380
+ }
381
+ });
382
+ r.get('/versions/:plan', async (c) => {
383
+ const denied = await gate(c);
384
+ if (denied)
385
+ return denied;
386
+ try {
387
+ return c.json(await admin.planVersions(c.req.param('plan')));
388
+ }
389
+ catch (err) {
390
+ return asError(c, err);
391
+ }
392
+ });
393
+ for (const action of ['preview', 'save']) {
394
+ r.post(`/${action}`, async (c) => {
395
+ const denied = await gate(c);
396
+ if (denied)
397
+ return denied;
398
+ const b = await body(c);
399
+ if (b instanceof Response)
400
+ return b;
401
+ if (!b.config || typeof b.config !== 'object')
402
+ return c.json({ error: 'invalid_config', message: 'config must be a billing config document' }, 400);
403
+ try {
404
+ return c.json(await admin.pushConfig(b.config, { dryRun: action === 'preview' }));
405
+ }
406
+ catch (err) {
407
+ return asError(c, err);
408
+ }
409
+ });
410
+ }
411
+ /** Moves the subscribers of every older version of a plan to its current version, in batches, until none is left. */
412
+ r.post('/migrate', async (c) => {
413
+ const denied = await gate(c);
414
+ if (denied)
415
+ return denied;
416
+ const b = await body(c);
417
+ if (b instanceof Response)
418
+ return b;
419
+ const plan = typeof b.plan === 'string' ? b.plan : '';
420
+ const when = b.when === 'period_end' ? 'period_end' : b.when === 'now' || b.when === undefined ? 'now' : null;
421
+ if (!plan || !when)
422
+ return c.json({ error: 'invalid_field', message: 'plan is required; when must be now or period_end' }, 400);
423
+ try {
424
+ const v = (await admin.planVersions(plan));
425
+ let migrated = 0;
426
+ const errors = [];
427
+ for (const old of (v.versions ?? []).filter((x) => !x.current && x.subscribers > 0)) {
428
+ for (let round = 0; round < 50; round++) {
429
+ const r = (await admin.migratePlan(plan, { fromVersion: old.version, toVersion: v.current_version, when, limit: 100 }));
430
+ migrated += r.migrated ?? 0;
431
+ errors.push(...(r.errors ?? []));
432
+ if (!r.remaining || (r.errors?.length ?? 0) > 0)
433
+ break;
434
+ }
435
+ }
436
+ return c.json({ plan, when, to_version: v.current_version, migrated, errors });
437
+ }
438
+ catch (err) {
439
+ return asError(c, err);
440
+ }
441
+ });
442
+ return r;
443
+ }
package/dist/react.d.ts CHANGED
@@ -214,3 +214,41 @@ export interface BillingPanelProps extends BillingManagementOptions {
214
214
  }
215
215
  /** A complete, unstyled billing page. Its routes use the signed-in account and the app's canManage gate. */
216
216
  export declare function BillingPanel(props: BillingPanelProps): ReactElement;
217
+ import type { BillingConfig, ConfigChange } from './config.js';
218
+ export interface PricingEditorProps {
219
+ /** Where billingPricingRoutes() is mounted. Default "/api/billing/pricing". */
220
+ basePath?: string;
221
+ fetch?: typeof fetch;
222
+ locale?: string;
223
+ className?: string;
224
+ /** Called after a successful save with the service's answer. */
225
+ onSaved?: (result: {
226
+ changes: ConfigChange[];
227
+ }) => void;
228
+ /** window.confirm by default: "Move current subscribers now" asks first. */
229
+ confirm?: (message: string) => boolean;
230
+ }
231
+ type TierRow = {
232
+ up_to: string;
233
+ amount: string;
234
+ };
235
+ type Draft = Record<string, {
236
+ tiers?: TierRow[];
237
+ amount?: string;
238
+ unit: string;
239
+ hidden: boolean;
240
+ }>;
241
+ /** Validates a draft the way the service will (so the message appears before a round trip). Returns the problem in words, or null. */
242
+ export declare function pricingDraftProblem(plan: string, d: Draft[string]): string | null;
243
+ /** The config document a draft turns into (only prices, units and hidden flags change; everything else is carried over). */
244
+ export declare function pricingDraftToConfig(config: BillingConfig, draft: Draft): BillingConfig;
245
+ /**
246
+ * An unstyled editor for the app's plans: one card per plan; a tiered plan's rows (from, up to, price) can be
247
+ * edited, added and removed; a flat plan's price can be edited; free, id-based and lookup-key plans are shown as
248
+ * they are. "Preview changes" lists what a save would do; "Save" applies it (a changed ladder is a new price and,
249
+ * with plan versioning, a new version — current subscribers stay on theirs until renewal or a migration);
250
+ * "Move current subscribers" migrates them, now (prorated at once) or at renewal, after a confirmation.
251
+ * Every element has a `bk-` class name for the app to style. Talks only to the app's own billingPricingRoutes().
252
+ */
253
+ export declare function PricingEditor(props: PricingEditorProps): ReactElement;
254
+ export {};
package/dist/react.js CHANGED
@@ -410,3 +410,163 @@ export function BillingPanel(props) {
410
410
  : button('Subscribe', () => b.checkout(selectedPlan, discount?.valid ? { discount_code: discount.code } : {}), !selectedPlan || (!!code.trim() && !discount?.valid)))) : null, preview ? h('section', { className: 'bk-preview', 'aria-label': 'Change preview' }, h('h3', null, 'Review your change'), h('p', null, preview.kind === 'plan' ? `Plan: ${preview.request.plan}` : `Seats: ${preview.request.quantity}`), h('p', null, `Due now: ${money(preview.quote.amount_due_now, preview.quote.currency, props.locale)}`), h('p', null, `Next invoice: ${money(preview.quote.next_invoice_amount, preview.quote.currency, props.locale)}`), h('p', null, preview.quote.when === 'period_end' ? `Starts at renewal${preview.quote.effective_at ? ` (${fmtDate(preview.quote.effective_at, props.locale)})` : ''}` : 'Starts now'), ...preview.quote.lines.map((line, i) => h('p', { key: i }, `${line.description ?? 'Adjustment'}: ${money(line.amount, preview.quote.currency, props.locale)}`)), button('Confirm change', async () => { const result = await b.confirmChange(preview); if (result)
411
411
  setPreview(null); }), button('Dismiss preview', () => setPreview(null))) : null, ...subscriptions.filter((s) => s.scheduled_change).map((s) => h('section', { key: s.id, className: 'bk-scheduled' }, h('p', null, `Scheduled: ${s.scheduled_change.plan ?? s.plan ?? 'Subscription'}${s.scheduled_change.quantity != null ? ` × ${s.scheduled_change.quantity}` : ''}${s.scheduled_change.effective_at ? ` on ${fmtDate(s.scheduled_change.effective_at, props.locale)}` : ' at renewal'}`), canManage ? button('Cancel scheduled change', () => b.cancelScheduledChange({ subscription_id: s.id })) : null)), ...subscriptions.filter((s) => s.invoice).map((s) => h('p', { key: `invoice:${s.id}`, className: 'bk-invoice' }, s.invoice.due_at ? `Invoice due ${fmtDate(s.invoice.due_at, props.locale)}. ` : 'Invoice available. ', s.invoice.hosted_invoice_url ? h('a', { href: s.invoice.hosted_invoice_url, target: '_blank', rel: 'noopener noreferrer' }, 'View and pay invoice') : null)), canManage && b.offers.length ? h('section', { className: 'bk-offers' }, h('h3', null, 'Available offers'), ...b.offers.map((offer) => h('div', { key: offer.id }, h('p', null, offer.headline ?? offer.name), h('p', null, offer.discount.label), button(offer.audience === 'canceling' ? 'Keep subscription with this offer' : 'Choose this offer', () => offer.audience === 'canceling' ? b.acceptOffer(offer.id) : b.checkout(offer.plans.find((p) => p.plan === selectedPlan)?.plan ?? offer.plans[0].plan, { offer_id: offer.id }), !offer.plans.length)))) : null, b.balances && Object.keys(b.balances.features).length ? h('section', { className: 'bk-balances' }, h('h3', null, 'Usage and credits'), ...Object.entries(b.balances.features).map(([id, balance]) => h('p', { key: id }, `${id}: ${balance.unlimited ? 'Unlimited' : `${balance.balance ?? 0} remaining`}${balance.resets_at ? `; resets ${fmtDate(balance.resets_at, props.locale)}` : ''}`)), canManage && packs.length ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Buy credits'), h('label', null, 'Credit pack', h('select', { value: selectedProduct, onChange: (event) => setProduct(event.target.value) }, ...packs.map((p) => option(p.plan, `${p.plan}${p.price?.unit_amount != null ? ` — ${money(p.price.unit_amount, p.price.currency, props.locale)}` : ''}`)))), input('Number of packs', packQuantity, setPackQuantity, 'number', { min: 1, step: 1 }), button('Buy credits', () => b.purchaseCredits(selectedProduct, Number(packQuantity)), !validPack)) : null, canManage ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Overage spending limit'), input('Currency', capCurrency, setCapCurrency), input('Maximum per period (leave empty for no cap)', cap, setCap, 'number', { min: 0, step: 'any' }), button('Save spending limit', () => b.saveUsageSettings({ spend_cap: cap.trim() === '' ? null : { amount: capMinor, currency: selectedCurrency } }), cap.trim() !== '' && (!Number.isSafeInteger(capMinor) || capMinor < 0))) : null, canManage && creditFeatures.length ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Automatic credit top-ups'), h('label', null, 'Credit balance', h('select', { value: selectedFeature, onChange: (event) => setFeature(event.target.value) }, ...creditFeatures.map((id) => option(id)))), h('p', null, `Uses the ${selectedProduct} credit pack selected above.`), input('Top up below', threshold, setThreshold, 'number', { min: 0, step: 'any' }), input('Maximum purchases per month', monthlyMax, setMonthlyMax, 'number', { min: 1, step: 1 }), h('label', null, h('input', { type: 'checkbox', checked: auto, onChange: (event) => setAuto(event.target.checked) }), ' I authorize automatic charges to my saved payment method for this credit pack.'), button('Save automatic top-up', () => b.saveUsageSettings({ auto_topups: [...(b.balances?.auto_topups ?? []).filter((r) => r.feature_id !== selectedFeature).map(({ feature_id, threshold, product, auto, max_per_month }) => ({ feature_id, threshold, product, auto, max_per_month })), { feature_id: selectedFeature, product: selectedProduct, threshold: Number(threshold), auto, max_per_month: Number(monthlyMax) }] }), !Number.isFinite(Number(threshold)) || Number(threshold) < 0 || !Number.isSafeInteger(Number(monthlyMax)) || Number(monthlyMax) < 1 || !selectedPack?.grants?.some((g) => g.feature_id === selectedFeature))) : null) : null);
412
412
  }
413
+ import { formatChanges } from "./config.js";
414
+ const isSpec = (p) => !!p && typeof p === 'object' && ('tiers' in p || 'amount' in p);
415
+ const toMajor = (minor, currency) => (minor / 10 ** currencyDigits(currency)).toString();
416
+ const toMinor = (major, currency) => Math.round(Number(major) * 10 ** currencyDigits(currency));
417
+ /** Validates a draft the way the service will (so the message appears before a round trip). Returns the problem in words, or null. */
418
+ export function pricingDraftProblem(plan, d) {
419
+ if (d.tiers) {
420
+ if (!d.tiers.length)
421
+ return `${plan}: a ladder needs at least one tier.`;
422
+ let prev = 0;
423
+ for (const [i, t] of d.tiers.entries()) {
424
+ const upTo = Number(t.up_to);
425
+ if (!Number.isInteger(upTo) || upTo <= prev)
426
+ return `${plan}: tier ${i + 1} must end above ${prev} (whole number).`;
427
+ if (t.amount.trim() === '' || !Number.isFinite(Number(t.amount)) || Number(t.amount) < 0)
428
+ return `${plan}: tier ${i + 1} needs a price of 0 or more.`;
429
+ prev = upTo;
430
+ }
431
+ }
432
+ else if (d.amount !== undefined && (d.amount.trim() === '' || !Number.isFinite(Number(d.amount)) || Number(d.amount) < 0))
433
+ return `${plan}: the price must be 0 or more.`;
434
+ if (d.unit && !/^[A-Za-z][A-Za-z0-9 _-]{0,31}$/.test(d.unit))
435
+ return `${plan}: the unit is a short word, like "students".`;
436
+ return null;
437
+ }
438
+ /** The config document a draft turns into (only prices, units and hidden flags change; everything else is carried over). */
439
+ export function pricingDraftToConfig(config, draft) {
440
+ const plans = {};
441
+ for (const [name, spec] of Object.entries(config.plans ?? {})) {
442
+ const d = draft[name];
443
+ if (!d || !isSpec(spec.price)) {
444
+ plans[name] = spec;
445
+ continue;
446
+ }
447
+ const currency = spec.price.currency;
448
+ const price = d.tiers
449
+ ? { currency, ...(spec.price.interval ? { interval: spec.price.interval } : {}), ...(spec.price.interval_count ? { interval_count: spec.price.interval_count } : {}), tiers: d.tiers.map((t) => ({ up_to: Number(t.up_to), amount: toMinor(t.amount, currency) })) }
450
+ : { ...spec.price, amount: toMinor(d.amount ?? '0', currency) };
451
+ const next = { ...spec, price };
452
+ if (d.unit)
453
+ next.unit = d.unit;
454
+ else
455
+ delete next.unit;
456
+ if (d.hidden)
457
+ next.hidden = true;
458
+ else
459
+ delete next.hidden;
460
+ plans[name] = next;
461
+ }
462
+ return { ...config, plans };
463
+ }
464
+ function draftOf(config) {
465
+ const draft = {};
466
+ for (const [name, spec] of Object.entries(config.plans ?? {})) {
467
+ if (!isSpec(spec.price))
468
+ continue;
469
+ const currency = spec.price.currency;
470
+ draft[name] = spec.price.tiers
471
+ ? { tiers: spec.price.tiers.map((t) => ({ up_to: String(t.up_to), amount: toMajor(t.amount, currency) })), unit: spec.unit ?? '', hidden: !!spec.hidden }
472
+ : { amount: toMajor(spec.price.amount ?? 0, currency), unit: spec.unit ?? '', hidden: !!spec.hidden };
473
+ }
474
+ return draft;
475
+ }
476
+ /**
477
+ * An unstyled editor for the app's plans: one card per plan; a tiered plan's rows (from, up to, price) can be
478
+ * edited, added and removed; a flat plan's price can be edited; free, id-based and lookup-key plans are shown as
479
+ * they are. "Preview changes" lists what a save would do; "Save" applies it (a changed ladder is a new price and,
480
+ * with plan versioning, a new version — current subscribers stay on theirs until renewal or a migration);
481
+ * "Move current subscribers" migrates them, now (prorated at once) or at renewal, after a confirmation.
482
+ * Every element has a `bk-` class name for the app to style. Talks only to the app's own billingPricingRoutes().
483
+ */
484
+ export function PricingEditor(props) {
485
+ const base = (props.basePath ?? '/api/billing/pricing').replace(/\/+$/, '');
486
+ const doFetch = props.fetch ?? browserFetch;
487
+ const confirm = props.confirm ?? ((m) => (typeof window === 'undefined' ? true : window.confirm(m)));
488
+ const [config, setConfig] = useState(null);
489
+ const [versions, setVersions] = useState({});
490
+ const [draft, setDraft] = useState({});
491
+ const [changes, setChanges] = useState(null);
492
+ const [busy, setBusy] = useState(false);
493
+ const [error, setError] = useState(null);
494
+ const [message, setMessage] = useState(null);
495
+ const mounted = useRef(true);
496
+ useEffect(() => () => void (mounted.current = false), []);
497
+ const request = useCallback(async (method, path, body) => {
498
+ const res = await doFetch(`${base}${path}`, { method, headers: body !== undefined ? { 'Content-Type': 'application/json' } : {}, body: body !== undefined ? JSON.stringify(body) : undefined });
499
+ const data = (await res.json().catch(() => ({})));
500
+ if (!res.ok)
501
+ throw new Error(data.message ?? data.error ?? `Request failed (${res.status})`);
502
+ return data;
503
+ }, [base, doFetch]);
504
+ const load = useCallback(async () => {
505
+ const doc = await request('GET', '');
506
+ if (!mounted.current)
507
+ return;
508
+ setConfig(doc.config);
509
+ setVersions(doc.versions ?? {});
510
+ setDraft(draftOf(doc.config));
511
+ setChanges(null);
512
+ }, [request]);
513
+ useEffect(() => { load().catch((e) => mounted.current && setError(e.message)); }, [load]);
514
+ const run = async (fn) => {
515
+ setBusy(true);
516
+ setError(null);
517
+ setMessage(null);
518
+ try {
519
+ await fn();
520
+ }
521
+ catch (e) {
522
+ if (mounted.current)
523
+ setError(e.message);
524
+ }
525
+ finally {
526
+ if (mounted.current)
527
+ setBusy(false);
528
+ }
529
+ };
530
+ const problem = config ? Object.entries(draft).map(([plan, d]) => pricingDraftProblem(plan, d)).find(Boolean) ?? null : null;
531
+ const cls = ['bk-pricing', props.className].filter(Boolean).join(' ');
532
+ if (!config)
533
+ return h('div', { className: cls, 'aria-busy': !error }, error ? h('p', { role: 'alert', className: 'bk-error' }, error) : 'Loading prices…');
534
+ const update = (plan, fn) => { setChanges(null); setDraft((cur) => ({ ...cur, [plan]: fn(cur[plan]) })); };
535
+ const button = (label, onClick, disabled = false, extra = {}) => h('button', { type: 'button', disabled: busy || disabled, onClick: () => void onClick(), ...extra }, label);
536
+ const field = (label, value, change, extra = {}) => h('label', null, label, h('input', { value, disabled: busy, onChange: (event) => change(event.target.value), ...extra }));
537
+ const preview = () => run(async () => { const r = await request('POST', '/preview', { config: pricingDraftToConfig(config, draft) }); setChanges(r.changes); if (!r.changes.length)
538
+ setMessage('No changes.'); });
539
+ const save = () => run(async () => { const r = await request('POST', '/save', { config: pricingDraftToConfig(config, draft) }); props.onSaved?.(r); await load(); setMessage(r.changes.length ? 'Saved.' : 'No changes.'); });
540
+ const migrate = (plan, when) => run(async () => {
541
+ if (!confirm(when === 'now' ? `Move every current subscriber of "${plan}" to the current price now? The difference is charged or credited at once.` : `Move every current subscriber of "${plan}" to the current price at their next renewal?`))
542
+ return;
543
+ const r = await request('POST', '/migrate', { plan, when });
544
+ await load();
545
+ setMessage(`${r.migrated} subscriber${r.migrated === 1 ? '' : 's'} of ${plan} moved${when === 'period_end' ? ' at renewal' : ''}${r.errors.length ? `; ${r.errors.length} could not be moved` : ''}.`);
546
+ });
547
+ const cards = Object.entries(config.plans ?? {}).map(([plan, spec]) => {
548
+ const d = draft[plan];
549
+ const v = versions[plan];
550
+ const olderSubscribers = v ? v.versions.filter((x) => !x.current).reduce((n, x) => n + x.subscribers, 0) : 0;
551
+ const currency = isSpec(spec.price) ? spec.price.currency : null;
552
+ const interval = isSpec(spec.price) ? spec.price.interval ?? 'month' : null;
553
+ let body;
554
+ if (spec.free)
555
+ body = h('p', null, 'Free plan');
556
+ else if (!d || !isSpec(spec.price))
557
+ body = h('p', null, typeof spec.price === 'string' ? `Stripe price ${spec.price}` : spec.price && 'lookup_key' in spec.price ? `Stripe price with lookup key ${spec.price.lookup_key}` : 'No price');
558
+ else if (d.tiers) {
559
+ let from = 1;
560
+ const rows = d.tiers.map((t, i) => {
561
+ const row = h('tr', { key: i, className: 'bk-tier' }, h('td', null, String(from)), h('td', null, h('input', { type: 'number', min: from, step: 1, value: t.up_to, disabled: busy, 'aria-label': `Tier ${i + 1} up to`, onChange: (event) => update(plan, (x) => ({ ...x, tiers: x.tiers.map((y, j) => (j === i ? { ...y, up_to: event.target.value } : y)) })) })), h('td', null, h('input', { type: 'number', min: 0, step: 'any', value: t.amount, disabled: busy, 'aria-label': `Tier ${i + 1} price`, onChange: (event) => update(plan, (x) => ({ ...x, tiers: x.tiers.map((y, j) => (j === i ? { ...y, amount: event.target.value } : y)) })) })), h('td', null, button('Remove', () => update(plan, (x) => ({ ...x, tiers: x.tiers.filter((_, j) => j !== i) })), d.tiers.length <= 1, { 'aria-label': `Remove tier ${i + 1}` })));
562
+ from = (Number(t.up_to) || from) + 1;
563
+ return row;
564
+ });
565
+ body = h(Fragment, null, h('table', { className: 'bk-tiers' }, h('thead', null, h('tr', null, h('th', null, 'From'), h('th', null, 'Up to'), h('th', null, `Price per ${interval} (${currency.toUpperCase()})`), h('th', null, ''))), h('tbody', null, ...rows)), button('Add tier', () => update(plan, (x) => ({ ...x, tiers: [...x.tiers, { up_to: String((Number(x.tiers[x.tiers.length - 1].up_to) || 0) * 2 || 10), amount: x.tiers[x.tiers.length - 1].amount }] }))), h('p', { className: 'bk-hint' }, `Above ${d.tiers[d.tiers.length - 1].up_to || '?'} ${d.unit || 'units'}: not sold (custom pricing).`));
566
+ }
567
+ else
568
+ body = field(`Price per ${interval} (${currency.toUpperCase()})`, d.amount ?? '', (value) => update(plan, (x) => ({ ...x, amount: value })), { type: 'number', min: 0, step: 'any' });
569
+ return h('section', { key: plan, className: 'bk-plan' }, h('h3', null, plan), body, d ? field('Unit (what the quantity counts)', d.unit, (value) => update(plan, (x) => ({ ...x, unit: value }))) : null, d ? h('label', null, h('input', { type: 'checkbox', checked: d.hidden, disabled: busy, onChange: (event) => update(plan, (x) => ({ ...x, hidden: event.target.checked })) }), ' Hidden from the pricing page') : null, v && v.versioning ? h('p', { className: 'bk-versions' }, `Version ${v.current_version}${olderSubscribers ? `; ${olderSubscribers} subscriber${olderSubscribers === 1 ? '' : 's'} on older prices` : ''}`) : null, v && olderSubscribers ? h(Fragment, null, button('Move current subscribers at renewal', () => migrate(plan, 'period_end')), button('Move current subscribers now', () => migrate(plan, 'now'))) : null);
570
+ });
571
+ return h('section', { className: cls, 'aria-busy': busy }, h('h2', null, 'Prices'), error ? h('p', { role: 'alert', className: 'bk-error' }, error) : null, message ? h('p', { role: 'status' }, message) : null, ...cards, problem ? h('p', { role: 'alert', className: 'bk-error' }, problem) : null, h('div', { className: 'bk-actions' }, button('Preview changes', preview, !!problem), button('Save', save, !!problem), button('Discard', () => { setDraft(draftOf(config)); setChanges(null); })), changes ? h('section', { className: 'bk-changes', 'aria-label': 'Change preview' }, h('h3', null, 'What will change'), h('pre', null, formatChanges(changes)), changes.some((c) => c.kind === 'price') ? h('p', null, config.plan_versioning ? 'A changed price becomes a new version: current subscribers keep their price until their next renewal, or until you move them.' : 'Current subscribers move to the changed price from their next renewal.') : null) : null);
572
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hjam91/billing",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Zero-dependency client for a billing-kit service: cached, fail-open entitlement and feature checks, usage tracking, Stripe Checkout / portal, signed webhook verification, a Hono gate and an optional React billing card.",
5
5
  "keywords": [
6
6
  "billing",