@hjam91/billing 0.9.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,31 @@ 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
+
31
+ ## 0.10.0: tiered plans (priced by a count your app reports)
32
+
33
+ ```ts
34
+ // billing.config.ts — the ladder is the source of truth; the service renders it as one tiered Stripe price
35
+ plans: { masjid: { price: { currency: 'usd', interval: 'month', tiers: [{ up_to: 10, amount: 2500 }, { up_to: 25, amount: 3900 }, { up_to: 500, amount: 19900 }] }, unit: 'students' } }
36
+
37
+ await billing.checkout({ accountId, plan: 'masjid', quantity: students, successUrl, cancelUrl }); // starts at the right tier
38
+ const r = await billing.setQuantity(accountId, students); // idempotent: unchanged | applied (now, prorated up a tier; no proration within) | scheduled (down a tier, period end) | requires_action
39
+ if (r.subscription?.over_max) contactUs(r.subscription.reported_quantity); // past the ladder: still active, held at the top tier
40
+ const { plans } = await billing.plans(); // plan.tiers [{from, up_to, amount}], max_quantity, unit
41
+ await billing.changePlan(accountId, 'masjid', { quantity: 6 }); // another ladder, with the count
42
+ ```
43
+
44
+ Above the ladder, Checkout and plan changes throw `custom_pricing_required`; the owner sets a custom plan or exempts the account.
45
+ `setQuantity` is `changeQuantity` under its new name. Needs a service on migration 0018.
46
+
22
47
  ## 0.8.0: discounts and offers
23
48
 
24
49
  Needs a billing service with migration 0016. Owner-made discount codes customers type, and automatic offers.
package/dist/config.d.ts CHANGED
@@ -20,11 +20,20 @@
20
20
  */
21
21
  export type FeatureType = 'boolean' | 'metered' | 'static' | 'credit_system';
22
22
  export interface PriceSpec {
23
- /** Minor units (1900 = $19.00). */
24
- amount: number;
23
+ /** Minor units (1900 = $19.00). Omitted when `tiers` prices the plan. */
24
+ amount?: number;
25
25
  currency: string;
26
26
  interval?: 'day' | 'week' | 'month' | 'year';
27
27
  interval_count?: number;
28
+ /**
29
+ * 0.10: a ladder — the plan is priced by its quantity (a count the app reports: students, seats) in flat tiers.
30
+ * Ascending `up_to` boundaries (inclusive), a flat `amount` for the whole tier; the last `up_to` is the most the
31
+ * plan sells (above it: custom pricing). The service renders it as one volume-tiered price.
32
+ */
33
+ tiers?: Array<{
34
+ up_to: number;
35
+ amount: number;
36
+ }>;
28
37
  }
29
38
  /** true / false for an on/off feature, or the allowance of a counted one. */
30
39
  export type ItemSpec = boolean | {
@@ -58,6 +67,8 @@ export interface PlanSpec {
58
67
  hidden?: true;
59
68
  trial_days?: number;
60
69
  items?: Record<string, ItemSpec>;
70
+ /** 0.10: what the quantity counts ("students"), shown on the pricing page. */
71
+ unit?: string;
61
72
  }
62
73
  export interface BillingConfig {
63
74
  automatic_tax?: boolean;
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/index.d.ts CHANGED
@@ -333,6 +333,15 @@ export interface Billing {
333
333
  changeQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<AccountStatus & {
334
334
  change: PlanChange;
335
335
  }>;
336
+ /**
337
+ * 0.10: report the subscription's quantity (on a tiered plan, the count it is priced by: students, seats). Idempotent and
338
+ * cheap: call it on every change and in a daily reconcile. Up a tier: now, prorated; down a tier: at the period end;
339
+ * within a tier: quantity only, no proration; above the ladder: held at the top tier with `change.over_max`.
340
+ * The same as changeQuantity (its name since 0.9).
341
+ */
342
+ setQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<AccountStatus & {
343
+ change: PlanChange;
344
+ }>;
336
345
  previewQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<ChangePreview>;
337
346
  cancelScheduledChange(accountId: string, select?: Omit<SubscriptionSelector, 'all'>): Promise<AccountStatus>;
338
347
  /** Create a subscription billed by invoice, when enabled in the app's billing policy. */
@@ -388,5 +397,7 @@ export interface PlanChangeOptions {
388
397
  prorationDate?: number;
389
398
  subscriptionId?: string;
390
399
  coversAccountId?: string;
400
+ /** 0.10: set the quantity with the plan change (the count on a tiered plan), in one prorated step. Above the ladder: custom_pricing_required. */
401
+ quantity?: number;
391
402
  }
392
403
  export declare function createBilling(opts: BillingOptions): Billing;
package/dist/index.js CHANGED
@@ -60,6 +60,7 @@ export const BATCH_LIMIT = 200;
60
60
  const changeBody = (accountId, plan, o = {}) => ({
61
61
  account_id: accountId,
62
62
  plan,
63
+ ...(o.quantity !== undefined ? { quantity: o.quantity } : {}),
63
64
  ...(o.when ? { when: o.when } : {}),
64
65
  ...(o.proration ? { proration: o.proration } : {}),
65
66
  ...(o.prorationDate !== undefined ? { proration_date: o.prorationDate } : {}),
@@ -500,6 +501,9 @@ export function createBilling(opts) {
500
501
  return r;
501
502
  },
502
503
  previewChange: (accountId, plan, o) => call('POST', '/v1/subscriptions/change/preview', changeBody(accountId, plan, o)),
504
+ async setQuantity(accountId, quantity, o = {}) {
505
+ return self.changeQuantity(accountId, quantity, o);
506
+ },
503
507
  async changeQuantity(accountId, quantity, o = {}) {
504
508
  const { plan: _plan, ...body } = changeBody(accountId, '', o);
505
509
  const result = await call('POST', '/v1/subscriptions/quantity', { ...body, quantity });
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/dist/types.d.ts CHANGED
@@ -208,10 +208,16 @@ export type BillingEvent = EntitlementChangedEvent | UsageEvent;
208
208
  export interface PlanChange {
209
209
  quantity?: number;
210
210
  from_quantity?: number;
211
- status: 'applied' | 'scheduled' | 'requires_action';
211
+ /** 'unchanged' (0.10): the reported quantity was already in place; nothing was sent to the provider. */
212
+ status: 'applied' | 'scheduled' | 'requires_action' | 'unchanged';
212
213
  plan: string;
213
214
  from_plan: string | null;
214
- direction: 'upgrade' | 'downgrade' | 'interval';
215
+ direction: 'upgrade' | 'downgrade' | 'interval' | 'none';
216
+ /** 0.10, tiered plans: the count was above the ladder; the subscription is held at the top tier (see SubscriptionView.over_max). */
217
+ over_max?: boolean;
218
+ reported_quantity?: number | null;
219
+ /** 0.10: an unchanged report canceled a pending downgrade. */
220
+ schedule_canceled?: boolean;
215
221
  effective_at: string | null;
216
222
  /** requires_action: the invoice page where the customer completes 3DS / pays. */
217
223
  action_url: string | null;
@@ -255,6 +261,18 @@ export interface PublicPlan {
255
261
  amount: number;
256
262
  expires_in_days?: number;
257
263
  }>;
264
+ /** 0.10: a tiered plan's ladder, from its config: the flat amount (minor units) for each range of the quantity. */
265
+ tiers?: PlanTier[];
266
+ /** 0.10: the most a tiered plan sells; above it the service refuses Checkout and flags a subscription `over_max`. */
267
+ max_quantity?: number;
268
+ /** 0.10: what the quantity counts ("students"). */
269
+ unit?: string;
270
+ }
271
+ /** One tier of a tiered plan (since 0.10.0). `from`..`up_to` inclusive, `amount` is the flat price of the tier. */
272
+ export interface PlanTier {
273
+ from: number;
274
+ up_to: number;
275
+ amount: number;
258
276
  }
259
277
  /** A discount as an app shows it (since 0.8.0). Amounts in minor units. */
260
278
  export interface DiscountView {
@@ -328,6 +346,17 @@ export interface SubscriptionView {
328
346
  quantity: number;
329
347
  effective_at: string;
330
348
  };
349
+ /** 0.10, tiered plans: the tier the current quantity falls in. */
350
+ tier?: PlanTier & {
351
+ currency: string;
352
+ interval: string | null;
353
+ };
354
+ /** 0.10, tiered plans: the ladder's top boundary. */
355
+ max_quantity?: number;
356
+ /** 0.10: the app reported a count above the ladder; the subscription stays at the top tier and access continues ("contact us"). */
357
+ over_max?: boolean;
358
+ /** 0.10: that reported count (null within the ladder). */
359
+ reported_quantity?: number | null;
331
360
  invoice?: {
332
361
  id: string;
333
362
  due_at: string | null;
@@ -453,7 +482,7 @@ export interface EntitlementChangedEvent {
453
482
  /** Error codes the API returns (stable; branch on these, not on messages). */
454
483
  export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
455
484
  /** 0.7 security: the service is locked down (only the owner key works). */
456
- | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
485
+ | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'custom_pricing_required' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
457
486
  /** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
458
487
  | 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
459
488
  /** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hjam91/billing",
3
- "version": "0.9.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",