@hjam91/billing 0.10.0 → 0.12.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 +9 -0
- package/dist/config.d.ts +13 -0
- package/dist/hono.d.ts +36 -0
- package/dist/hono.js +125 -0
- package/dist/react.d.ts +42 -0
- package/dist/react.js +169 -0
- package/dist/types.d.ts +1 -1
- package/package.json +1 -1
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/config.d.ts
CHANGED
|
@@ -69,10 +69,23 @@ export interface PlanSpec {
|
|
|
69
69
|
items?: Record<string, ItemSpec>;
|
|
70
70
|
/** 0.10: what the quantity counts ("students"), shown on the pricing page. */
|
|
71
71
|
unit?: string;
|
|
72
|
+
/**
|
|
73
|
+
* 0.12: the Stripe product tax code of the plan's product (txcd_10103001 = SaaS, business use). Stripe Tax and
|
|
74
|
+
* Managed Payments (on by default for new Stripe accounts; Stripe is the merchant of record and refuses a Checkout
|
|
75
|
+
* whose product has no tax code) compute tax from it. Changing it updates the product; it is never a new price.
|
|
76
|
+
*/
|
|
77
|
+
tax_code?: string;
|
|
78
|
+
/** 0.12: 'exclusive' (tax added on top of the price) or 'inclusive' (tax inside it), on every price the kit makes for the plan. */
|
|
79
|
+
tax_behavior?: 'exclusive' | 'inclusive';
|
|
72
80
|
}
|
|
73
81
|
export interface BillingConfig {
|
|
74
82
|
automatic_tax?: boolean;
|
|
75
83
|
collect_tax_id?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* 0.12: Stripe Managed Payments (Stripe as merchant of record: tax, disputes, support). Every subscription and
|
|
86
|
+
* one-time Checkout asks for it; automatic_tax / collect_tax_id are then ignored; plans need a tax_code.
|
|
87
|
+
*/
|
|
88
|
+
managed_payments?: boolean;
|
|
76
89
|
collection_method?: 'charge_automatically' | 'send_invoice';
|
|
77
90
|
days_until_due?: number;
|
|
78
91
|
features?: Array<{
|
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,45 @@ 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
|
+
tax_code?: string;
|
|
241
|
+
}>;
|
|
242
|
+
/** A Stripe product tax code (txcd_ and eight digits); the SaaS one is the usual choice for an app. */
|
|
243
|
+
export declare const TAX_CODE: RegExp;
|
|
244
|
+
export declare const TAX_CODE_SAAS = "txcd_10103001";
|
|
245
|
+
/** Validates a draft the way the service will (so the message appears before a round trip). Returns the problem in words, or null. */
|
|
246
|
+
export declare function pricingDraftProblem(plan: string, d: Draft[string]): string | null;
|
|
247
|
+
/** The config document a draft turns into (only prices, units, tax codes and hidden flags change; everything else is carried over). */
|
|
248
|
+
export declare function pricingDraftToConfig(config: BillingConfig, draft: Draft): BillingConfig;
|
|
249
|
+
/**
|
|
250
|
+
* An unstyled editor for the app's plans: one card per plan; a tiered plan's rows (from, up to, price) can be
|
|
251
|
+
* edited, added and removed; a flat plan's price can be edited; free, id-based and lookup-key plans are shown as
|
|
252
|
+
* they are. "Preview changes" lists what a save would do; "Save" applies it (a changed ladder is a new price and,
|
|
253
|
+
* with plan versioning, a new version — current subscribers stay on theirs until renewal or a migration);
|
|
254
|
+
* "Move current subscribers" migrates them, now (prorated at once) or at renewal, after a confirmation.
|
|
255
|
+
* Every element has a `bk-` class name for the app to style. Talks only to the app's own billingPricingRoutes().
|
|
256
|
+
*/
|
|
257
|
+
export declare function PricingEditor(props: PricingEditorProps): ReactElement;
|
|
258
|
+
export {};
|
package/dist/react.js
CHANGED
|
@@ -410,3 +410,172 @@ 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
|
+
/** A Stripe product tax code (txcd_ and eight digits); the SaaS one is the usual choice for an app. */
|
|
415
|
+
export const TAX_CODE = /^txcd_\d{8}$/;
|
|
416
|
+
export const TAX_CODE_SAAS = 'txcd_10103001';
|
|
417
|
+
const isSpec = (p) => !!p && typeof p === 'object' && ('tiers' in p || 'amount' in p);
|
|
418
|
+
const toMajor = (minor, currency) => (minor / 10 ** currencyDigits(currency)).toString();
|
|
419
|
+
const toMinor = (major, currency) => Math.round(Number(major) * 10 ** currencyDigits(currency));
|
|
420
|
+
/** Validates a draft the way the service will (so the message appears before a round trip). Returns the problem in words, or null. */
|
|
421
|
+
export function pricingDraftProblem(plan, d) {
|
|
422
|
+
if (d.tiers) {
|
|
423
|
+
if (!d.tiers.length)
|
|
424
|
+
return `${plan}: a ladder needs at least one tier.`;
|
|
425
|
+
let prev = 0;
|
|
426
|
+
for (const [i, t] of d.tiers.entries()) {
|
|
427
|
+
const upTo = Number(t.up_to);
|
|
428
|
+
if (!Number.isInteger(upTo) || upTo <= prev)
|
|
429
|
+
return `${plan}: tier ${i + 1} must end above ${prev} (whole number).`;
|
|
430
|
+
if (t.amount.trim() === '' || !Number.isFinite(Number(t.amount)) || Number(t.amount) < 0)
|
|
431
|
+
return `${plan}: tier ${i + 1} needs a price of 0 or more.`;
|
|
432
|
+
prev = upTo;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
else if (d.amount !== undefined && (d.amount.trim() === '' || !Number.isFinite(Number(d.amount)) || Number(d.amount) < 0))
|
|
436
|
+
return `${plan}: the price must be 0 or more.`;
|
|
437
|
+
if (d.unit && !/^[A-Za-z][A-Za-z0-9 _-]{0,31}$/.test(d.unit))
|
|
438
|
+
return `${plan}: the unit is a short word, like "students".`;
|
|
439
|
+
if (d.tax_code?.trim() && !TAX_CODE.test(d.tax_code.trim()))
|
|
440
|
+
return `${plan}: the tax code looks like ${TAX_CODE_SAAS} (Stripe's code for SaaS, business use).`;
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
/** The config document a draft turns into (only prices, units, tax codes and hidden flags change; everything else is carried over). */
|
|
444
|
+
export function pricingDraftToConfig(config, draft) {
|
|
445
|
+
const plans = {};
|
|
446
|
+
for (const [name, spec] of Object.entries(config.plans ?? {})) {
|
|
447
|
+
const d = draft[name];
|
|
448
|
+
if (!d || !isSpec(spec.price)) {
|
|
449
|
+
plans[name] = spec;
|
|
450
|
+
continue;
|
|
451
|
+
}
|
|
452
|
+
const currency = spec.price.currency;
|
|
453
|
+
const price = d.tiers
|
|
454
|
+
? { 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) })) }
|
|
455
|
+
: { ...spec.price, amount: toMinor(d.amount ?? '0', currency) };
|
|
456
|
+
const next = { ...spec, price };
|
|
457
|
+
if (d.unit)
|
|
458
|
+
next.unit = d.unit;
|
|
459
|
+
else
|
|
460
|
+
delete next.unit;
|
|
461
|
+
if (d.tax_code?.trim())
|
|
462
|
+
next.tax_code = d.tax_code.trim();
|
|
463
|
+
else
|
|
464
|
+
delete next.tax_code;
|
|
465
|
+
if (d.hidden)
|
|
466
|
+
next.hidden = true;
|
|
467
|
+
else
|
|
468
|
+
delete next.hidden;
|
|
469
|
+
plans[name] = next;
|
|
470
|
+
}
|
|
471
|
+
return { ...config, plans };
|
|
472
|
+
}
|
|
473
|
+
function draftOf(config) {
|
|
474
|
+
const draft = {};
|
|
475
|
+
for (const [name, spec] of Object.entries(config.plans ?? {})) {
|
|
476
|
+
if (!isSpec(spec.price))
|
|
477
|
+
continue;
|
|
478
|
+
const currency = spec.price.currency;
|
|
479
|
+
draft[name] = spec.price.tiers
|
|
480
|
+
? { tiers: spec.price.tiers.map((t) => ({ up_to: String(t.up_to), amount: toMajor(t.amount, currency) })), unit: spec.unit ?? '', hidden: !!spec.hidden, tax_code: spec.tax_code ?? '' }
|
|
481
|
+
: { amount: toMajor(spec.price.amount ?? 0, currency), unit: spec.unit ?? '', hidden: !!spec.hidden, tax_code: spec.tax_code ?? '' };
|
|
482
|
+
}
|
|
483
|
+
return draft;
|
|
484
|
+
}
|
|
485
|
+
/**
|
|
486
|
+
* An unstyled editor for the app's plans: one card per plan; a tiered plan's rows (from, up to, price) can be
|
|
487
|
+
* edited, added and removed; a flat plan's price can be edited; free, id-based and lookup-key plans are shown as
|
|
488
|
+
* they are. "Preview changes" lists what a save would do; "Save" applies it (a changed ladder is a new price and,
|
|
489
|
+
* with plan versioning, a new version — current subscribers stay on theirs until renewal or a migration);
|
|
490
|
+
* "Move current subscribers" migrates them, now (prorated at once) or at renewal, after a confirmation.
|
|
491
|
+
* Every element has a `bk-` class name for the app to style. Talks only to the app's own billingPricingRoutes().
|
|
492
|
+
*/
|
|
493
|
+
export function PricingEditor(props) {
|
|
494
|
+
const base = (props.basePath ?? '/api/billing/pricing').replace(/\/+$/, '');
|
|
495
|
+
const doFetch = props.fetch ?? browserFetch;
|
|
496
|
+
const confirm = props.confirm ?? ((m) => (typeof window === 'undefined' ? true : window.confirm(m)));
|
|
497
|
+
const [config, setConfig] = useState(null);
|
|
498
|
+
const [versions, setVersions] = useState({});
|
|
499
|
+
const [draft, setDraft] = useState({});
|
|
500
|
+
const [changes, setChanges] = useState(null);
|
|
501
|
+
const [busy, setBusy] = useState(false);
|
|
502
|
+
const [error, setError] = useState(null);
|
|
503
|
+
const [message, setMessage] = useState(null);
|
|
504
|
+
const mounted = useRef(true);
|
|
505
|
+
useEffect(() => () => void (mounted.current = false), []);
|
|
506
|
+
const request = useCallback(async (method, path, body) => {
|
|
507
|
+
const res = await doFetch(`${base}${path}`, { method, headers: body !== undefined ? { 'Content-Type': 'application/json' } : {}, body: body !== undefined ? JSON.stringify(body) : undefined });
|
|
508
|
+
const data = (await res.json().catch(() => ({})));
|
|
509
|
+
if (!res.ok)
|
|
510
|
+
throw new Error(data.message ?? data.error ?? `Request failed (${res.status})`);
|
|
511
|
+
return data;
|
|
512
|
+
}, [base, doFetch]);
|
|
513
|
+
const load = useCallback(async () => {
|
|
514
|
+
const doc = await request('GET', '');
|
|
515
|
+
if (!mounted.current)
|
|
516
|
+
return;
|
|
517
|
+
setConfig(doc.config);
|
|
518
|
+
setVersions(doc.versions ?? {});
|
|
519
|
+
setDraft(draftOf(doc.config));
|
|
520
|
+
setChanges(null);
|
|
521
|
+
}, [request]);
|
|
522
|
+
useEffect(() => { load().catch((e) => mounted.current && setError(e.message)); }, [load]);
|
|
523
|
+
const run = async (fn) => {
|
|
524
|
+
setBusy(true);
|
|
525
|
+
setError(null);
|
|
526
|
+
setMessage(null);
|
|
527
|
+
try {
|
|
528
|
+
await fn();
|
|
529
|
+
}
|
|
530
|
+
catch (e) {
|
|
531
|
+
if (mounted.current)
|
|
532
|
+
setError(e.message);
|
|
533
|
+
}
|
|
534
|
+
finally {
|
|
535
|
+
if (mounted.current)
|
|
536
|
+
setBusy(false);
|
|
537
|
+
}
|
|
538
|
+
};
|
|
539
|
+
const problem = config ? Object.entries(draft).map(([plan, d]) => pricingDraftProblem(plan, d)).find(Boolean) ?? null : null;
|
|
540
|
+
const cls = ['bk-pricing', props.className].filter(Boolean).join(' ');
|
|
541
|
+
if (!config)
|
|
542
|
+
return h('div', { className: cls, 'aria-busy': !error }, error ? h('p', { role: 'alert', className: 'bk-error' }, error) : 'Loading prices…');
|
|
543
|
+
const update = (plan, fn) => { setChanges(null); setDraft((cur) => ({ ...cur, [plan]: fn(cur[plan]) })); };
|
|
544
|
+
const button = (label, onClick, disabled = false, extra = {}) => h('button', { type: 'button', disabled: busy || disabled, onClick: () => void onClick(), ...extra }, label);
|
|
545
|
+
const field = (label, value, change, extra = {}) => h('label', null, label, h('input', { value, disabled: busy, onChange: (event) => change(event.target.value), ...extra }));
|
|
546
|
+
const preview = () => run(async () => { const r = await request('POST', '/preview', { config: pricingDraftToConfig(config, draft) }); setChanges(r.changes); if (!r.changes.length)
|
|
547
|
+
setMessage('No changes.'); });
|
|
548
|
+
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.'); });
|
|
549
|
+
const migrate = (plan, when) => run(async () => {
|
|
550
|
+
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?`))
|
|
551
|
+
return;
|
|
552
|
+
const r = await request('POST', '/migrate', { plan, when });
|
|
553
|
+
await load();
|
|
554
|
+
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` : ''}.`);
|
|
555
|
+
});
|
|
556
|
+
const cards = Object.entries(config.plans ?? {}).map(([plan, spec]) => {
|
|
557
|
+
const d = draft[plan];
|
|
558
|
+
const v = versions[plan];
|
|
559
|
+
const olderSubscribers = v ? v.versions.filter((x) => !x.current).reduce((n, x) => n + x.subscribers, 0) : 0;
|
|
560
|
+
const currency = isSpec(spec.price) ? spec.price.currency : null;
|
|
561
|
+
const interval = isSpec(spec.price) ? spec.price.interval ?? 'month' : null;
|
|
562
|
+
let body;
|
|
563
|
+
if (spec.free)
|
|
564
|
+
body = h('p', null, 'Free plan');
|
|
565
|
+
else if (!d || !isSpec(spec.price))
|
|
566
|
+
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');
|
|
567
|
+
else if (d.tiers) {
|
|
568
|
+
let from = 1;
|
|
569
|
+
const rows = d.tiers.map((t, i) => {
|
|
570
|
+
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}` })));
|
|
571
|
+
from = (Number(t.up_to) || from) + 1;
|
|
572
|
+
return row;
|
|
573
|
+
});
|
|
574
|
+
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).`));
|
|
575
|
+
}
|
|
576
|
+
else
|
|
577
|
+
body = field(`Price per ${interval} (${currency.toUpperCase()})`, d.amount ?? '', (value) => update(plan, (x) => ({ ...x, amount: value })), { type: 'number', min: 0, step: 'any' });
|
|
578
|
+
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 ? field(`Tax code (Stripe product tax code; ${TAX_CODE_SAAS} = SaaS, business use)`, d.tax_code ?? '', (value) => update(plan, (x) => ({ ...x, tax_code: value })), { placeholder: TAX_CODE_SAAS }) : 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);
|
|
579
|
+
});
|
|
580
|
+
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);
|
|
581
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -482,7 +482,7 @@ export interface EntitlementChangedEvent {
|
|
|
482
482
|
/** Error codes the API returns (stable; branch on these, not on messages). */
|
|
483
483
|
export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
|
|
484
484
|
/** 0.7 security: the service is locked down (only the owner key works). */
|
|
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'
|
|
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' | 'tax_behavior_locked' | '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'
|
|
486
486
|
/** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
|
|
487
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'
|
|
488
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.
|
|
3
|
+
"version": "0.12.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",
|