@hjam91/billing 0.8.0 → 0.9.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 +94 -0
- package/dist/admin.d.ts +58 -0
- package/dist/admin.js +4 -0
- package/dist/config.d.ts +4 -0
- package/dist/hono.js +84 -1
- package/dist/index.d.ts +36 -1
- package/dist/index.js +125 -41
- package/dist/react.d.ts +98 -1
- package/dist/react.js +206 -5
- package/dist/types.d.ts +16 -2
- package/dist/usage.d.ts +39 -0
- package/dist/usage.js +65 -0
- package/package.json +7 -2
package/README.md
CHANGED
|
@@ -46,6 +46,12 @@ for (const o of await billing.offers(orgId)) {
|
|
|
46
46
|
`offers()`, `createOffer({name, audience, …terms, afterDays?, withinDays?, headline?, active?})`,
|
|
47
47
|
`updateOffer(id, {active?, headline?, name?, afterDays?, withinDays?})` (never the money). Creating needs a key with
|
|
48
48
|
the `pricing` scope; on an app billed through the service owner's Stripe account only the owner creates them.
|
|
49
|
+
- Admin, since 0.9.0: `redemptions({accountId?})` answers `{redemptions: RedemptionAdminView[]}`, every code and offer
|
|
50
|
+
redemption newest first (at most 1000) with its subscription, `plan`, `subscription_status` and `discount_active`
|
|
51
|
+
(the subscription still carries a discount); `read` scope. `removeDiscount(accountId, {subscriptionId?})` ends the
|
|
52
|
+
discount on the account's own live discounted subscriptions so the next invoice is full price, and answers the
|
|
53
|
+
account status (`support` scope, like `cancel`; 404 `discount_not_found` when there is none, 409
|
|
54
|
+
`operation_in_progress` under a pending plan change). The code or offer itself is untouched.
|
|
49
55
|
- `billingRoutes` (Hono) adds `GET /offers`, `POST /discount {code, plan?}`, `POST /accept-offer {offer_id}`, and
|
|
50
56
|
`discount_code` / `offer_id` on `POST /checkout`; a refused code answers its `reason`.
|
|
51
57
|
|
|
@@ -174,3 +180,91 @@ needs Node >= 22.18; `.json` / `.mjs` configs work on any supported Node.
|
|
|
174
180
|
|
|
175
181
|
Full API documentation will be published at a public URL (placeholder: _API docs link_). Every export carries TSDoc in
|
|
176
182
|
its `.d.ts`.
|
|
183
|
+
|
|
184
|
+
## Durable usage delivery
|
|
185
|
+
|
|
186
|
+
`flushUsage()` checks each event's result. Applied and replayed events are acknowledged;
|
|
187
|
+
permanent refusals are retained as rejected records, and transient failures retain their
|
|
188
|
+
original idempotency key for retry. An HTTP 200 with missing results does not acknowledge
|
|
189
|
+
usage. Inspect `usageStatus()` and `rejectedUsage()`, correct the cause, then call
|
|
190
|
+
`retryUsage(recordIds)` and `flushUsage()`.
|
|
191
|
+
|
|
192
|
+
The default queue is bounded and process-local. For Cloudflare D1, apply
|
|
193
|
+
`USAGE_QUEUE_SCHEMA` to your app database once and configure the adapter:
|
|
194
|
+
|
|
195
|
+
```ts
|
|
196
|
+
import { createBilling, d1UsageStore } from '@hjam91/billing';
|
|
197
|
+
const billing = createBilling({ baseUrl, appId, secret, usageStore: d1UsageStore(env.DB) });
|
|
198
|
+
await billing.track(accountId, 'credits', 1, { idempotencyKey: jobId });
|
|
199
|
+
ctx.waitUntil(billing.flushUsage());
|
|
200
|
+
const { pending, rejected, oldestPendingAt } = await billing.usageStatus();
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
A configured persistent queue writes the event before attempting its first request.
|
|
204
|
+
Schedule `flushUsage()` in a background job as well, so idle apps recover after an outage.
|
|
205
|
+
Storage failures are logged and never reported as successful persistence. Queue scope
|
|
206
|
+
includes service URL and app ID. Keep the database server-side: records may contain the
|
|
207
|
+
usage properties supplied by your app. Delivery is at least once; service idempotency
|
|
208
|
+
prevents duplicate counting. The service retains deduplication keys for 90 days, so recover
|
|
209
|
+
or resolve rejected records within that window rather than replaying older records blindly.
|
|
210
|
+
|
|
211
|
+
Custom stores implement `UsageStore` from `@hjam91/billing/usage`: `put`, `remove`, `list`
|
|
212
|
+
and `status`. Resolve each operation only after durable storage succeeds. Operations may
|
|
213
|
+
be called concurrently; the application owns retention and access control.
|
|
214
|
+
|
|
215
|
+
## Seat quantities and invoice billing
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
const preview = await billing.previewQuantity(accountId, 12, { subscriptionId });
|
|
219
|
+
await billing.changeQuantity(accountId, 12, {
|
|
220
|
+
subscriptionId, prorationDate: preview.proration_date,
|
|
221
|
+
});
|
|
222
|
+
await billing.cancelScheduledChange(accountId, { subscriptionId });
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
Quantity changes use the same explicit proration and scheduling options as plan changes.
|
|
226
|
+
Scheduled changes appear on `SubscriptionView.scheduled_change`. The application must
|
|
227
|
+
check that the signed-in user can manage the account before invoking these actions.
|
|
228
|
+
|
|
229
|
+
Business billing is opt-in through app settings or config-as-code: `automatic_tax`,
|
|
230
|
+
`collect_tax_id`, `collection_method` and `days_until_due`. For an app configured with
|
|
231
|
+
`collection_method: 'send_invoice'`, use `invoiceSubscription(accountId, plan, {email,
|
|
232
|
+
quantity, customerName})`; its result includes the hosted invoice URL and due date.
|
|
233
|
+
Automatic card collection remains the default. Configure the relevant Stripe tax settings
|
|
234
|
+
before enabling automatic tax.
|
|
235
|
+
|
|
236
|
+
Support integrations can list `admin.purchases(accountId)` and call
|
|
237
|
+
`admin.refundPurchase(accountId, purchaseId, {access: 'keep' | 'revoke', note})`. The
|
|
238
|
+
service computes the full remaining refundable amount. The explicit access policy controls
|
|
239
|
+
remaining credits and lifetime access; it does not reverse already consumed credits.
|
|
240
|
+
|
|
241
|
+
## Complete billing page
|
|
242
|
+
|
|
243
|
+
`BillingPanel` builds on the same `billingRoutes` authorization checks as `BillingCard`:
|
|
244
|
+
|
|
245
|
+
```tsx
|
|
246
|
+
import { BillingPanel } from '@hjam91/billing/react';
|
|
247
|
+
|
|
248
|
+
<BillingPanel
|
|
249
|
+
basePath="/api/billing"
|
|
250
|
+
locale="en-US"
|
|
251
|
+
onError={(error) => reportBillingError(error.code, error.status)}
|
|
252
|
+
/>
|
|
253
|
+
```
|
|
254
|
+
|
|
255
|
+
It includes plan and seat selection, a proration preview before confirmation, scheduled-change cancellation,
|
|
256
|
+
discount codes and eligible offers, credit balances and purchases, overage spending limits, and automatic top-up
|
|
257
|
+
settings. Automatic charges require the user's explicit checkbox consent. Plan changes use the subscription owned
|
|
258
|
+
by the current account; the app's `canManage` callback still guards every action. Multiple subscriptions get a
|
|
259
|
+
selector. `BillingCard` remains available for the compact status/portal experience.
|
|
260
|
+
|
|
261
|
+
Set `invoiceBilling` only for an app configured for invoice collection. This replaces the new-subscription Checkout
|
|
262
|
+
button with a billing-address form and **Request invoice**. Existing invoices show their due date and a hosted
|
|
263
|
+
payment link. Invoice collection, tax calculation and tax-ID collection are service policy; no Stripe secret belongs
|
|
264
|
+
in the browser.
|
|
265
|
+
|
|
266
|
+
For your own markup, `useBillingManagement()` exposes `previewPlan`, `previewQuantity`, `confirmChange`,
|
|
267
|
+
`cancelScheduledChange`, `checkDiscount`, `checkout`, `acceptOffer`, `purchaseCredits`, `saveUsageSettings`,
|
|
268
|
+
`requestInvoice`, and the current `plans`, `balances`, `offers`. Preserve the returned preview when confirming;
|
|
269
|
+
`confirmChange` sends its proration date and subscription selector. Errors retain `code`, `status` and `details`
|
|
270
|
+
through `BillingBrowserError` and the `onError` callback. All components are unstyled with `bk-` classes.
|
package/dist/admin.d.ts
CHANGED
|
@@ -121,6 +121,33 @@ export interface OfferAdminView {
|
|
|
121
121
|
created_at: string;
|
|
122
122
|
updated_at: string;
|
|
123
123
|
}
|
|
124
|
+
/**
|
|
125
|
+
* One redemption of a discount code (kind 'code') or an offer (kind 'offer'), as the owner sees it
|
|
126
|
+
* (GET /admin/apps/:app/redemptions; since 0.9.0).
|
|
127
|
+
*/
|
|
128
|
+
export interface RedemptionAdminView {
|
|
129
|
+
kind: 'code' | 'offer';
|
|
130
|
+
/** dsc_… (code) or ofr_… (offer). */
|
|
131
|
+
id: string;
|
|
132
|
+
/** The code (kind 'code'), else null. */
|
|
133
|
+
code: string | null;
|
|
134
|
+
/** The offer's name (kind 'offer'), else null. */
|
|
135
|
+
name: string | null;
|
|
136
|
+
/** The terms, as discountView shows them. */
|
|
137
|
+
discount: DiscountView;
|
|
138
|
+
account_id: string;
|
|
139
|
+
/** ISO. */
|
|
140
|
+
redeemed_at: string;
|
|
141
|
+
via: 'checkout' | 'accept';
|
|
142
|
+
stripe_subscription_id: string | null;
|
|
143
|
+
/** The subscription's status; null when the service has no subscription row for it. */
|
|
144
|
+
subscription_status: string | null;
|
|
145
|
+
plan: string | null;
|
|
146
|
+
/** The subscription is live and still carries a discount (percent / amount set, ends_at null or in the future). */
|
|
147
|
+
discount_active: boolean;
|
|
148
|
+
/** ISO; null = no end (or no discount). */
|
|
149
|
+
discount_ends_at: string | null;
|
|
150
|
+
}
|
|
124
151
|
/** The money of a code or an offer: percentOff XOR amountOff + currency (minor units). */
|
|
125
152
|
interface DiscountTermsParams {
|
|
126
153
|
percentOff?: number;
|
|
@@ -162,7 +189,23 @@ export interface OfferPatch {
|
|
|
162
189
|
afterDays?: number;
|
|
163
190
|
withinDays?: number | null;
|
|
164
191
|
}
|
|
192
|
+
export interface PurchaseRefundResult {
|
|
193
|
+
purchase_id: string;
|
|
194
|
+
refund_id: string | null;
|
|
195
|
+
status: string;
|
|
196
|
+
amount: number;
|
|
197
|
+
currency: string;
|
|
198
|
+
access: 'keep' | 'revoke';
|
|
199
|
+
account: AccountStatus;
|
|
200
|
+
}
|
|
165
201
|
export interface BillingAdmin {
|
|
202
|
+
purchases(accountId: string): Promise<{
|
|
203
|
+
purchases: Record<string, unknown>[];
|
|
204
|
+
}>;
|
|
205
|
+
refundPurchase(accountId: string, purchaseId: string, opts: {
|
|
206
|
+
access: 'keep' | 'revoke';
|
|
207
|
+
note?: string;
|
|
208
|
+
}): Promise<PurchaseRefundResult>;
|
|
166
209
|
/** The app's configuration (read). */
|
|
167
210
|
app(): Promise<Record<string, unknown>>;
|
|
168
211
|
/** Change policy (config scope): trial_days, grace_days, launched_at, prelaunch, trial_anchor, allow_promotion_codes, grace_on, refund_policy / revoke_on_refund, immediate_cancel_policy. */
|
|
@@ -272,6 +315,21 @@ export interface BillingAdmin {
|
|
|
272
315
|
createOffer(p: CreateOfferParams): Promise<OfferAdminView>;
|
|
273
316
|
/** Switch an offer on / off, reword it or move its window — never its money (config; since 0.8.0). */
|
|
274
317
|
updateOffer(id: string, patch: OfferPatch): Promise<OfferAdminView>;
|
|
318
|
+
/** Every code and offer redemption, newest first (at most 1000), or one account's (read; since 0.9.0). */
|
|
319
|
+
redemptions(opts?: {
|
|
320
|
+
accountId?: string;
|
|
321
|
+
}): Promise<{
|
|
322
|
+
redemptions: RedemptionAdminView[];
|
|
323
|
+
}>;
|
|
324
|
+
/**
|
|
325
|
+
* Ends the discount on the account's OWN live subscriptions that carry one (or the one named, by its sub_row_… or
|
|
326
|
+
* Stripe id), so the next invoice is full price; the code or offer itself is untouched (support scope, like cancel;
|
|
327
|
+
* since 0.9.0). 404 discount_not_found when there is nothing to remove; 409 operation_in_progress under a pending
|
|
328
|
+
* plan change.
|
|
329
|
+
*/
|
|
330
|
+
removeDiscount(accountId: string, params?: {
|
|
331
|
+
subscriptionId?: string;
|
|
332
|
+
}): Promise<AccountStatus>;
|
|
275
333
|
}
|
|
276
334
|
export declare function createBillingAdmin(opts: BillingAdminOptions): BillingAdmin;
|
|
277
335
|
export {};
|
package/dist/admin.js
CHANGED
|
@@ -110,6 +110,10 @@ export function createBillingAdmin(opts) {
|
|
|
110
110
|
...(x.afterDays !== undefined ? { after_days: x.afterDays } : {}),
|
|
111
111
|
...(x.withinDays !== undefined ? { within_days: x.withinDays } : {}),
|
|
112
112
|
})).offer,
|
|
113
|
+
redemptions: (o = {}) => call('GET', `/redemptions${o.accountId ? `?account=${enc(o.accountId)}` : ''}`),
|
|
114
|
+
removeDiscount: (accountId, p = {}) => call('POST', `/accounts/${enc(accountId)}/discount/remove`, p.subscriptionId ? { subscription_id: p.subscriptionId } : {}),
|
|
115
|
+
purchases: (accountId) => call('GET', `/accounts/${enc(accountId)}/purchases`),
|
|
116
|
+
refundPurchase: (accountId, purchaseId, o) => call('POST', `/accounts/${enc(accountId)}/purchases/${enc(purchaseId)}/refund`, o),
|
|
113
117
|
invoices: (accountId, o = {}) => call('GET', `/accounts/${enc(accountId)}/invoices${o.limit ? `?limit=${o.limit}` : ''}`),
|
|
114
118
|
refund: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/refunds`, {
|
|
115
119
|
invoice_id: p.invoiceId,
|
package/dist/config.d.ts
CHANGED
|
@@ -60,6 +60,10 @@ export interface PlanSpec {
|
|
|
60
60
|
items?: Record<string, ItemSpec>;
|
|
61
61
|
}
|
|
62
62
|
export interface BillingConfig {
|
|
63
|
+
automatic_tax?: boolean;
|
|
64
|
+
collect_tax_id?: boolean;
|
|
65
|
+
collection_method?: 'charge_automatically' | 'send_invoice';
|
|
66
|
+
days_until_due?: number;
|
|
63
67
|
features?: Array<{
|
|
64
68
|
id: string;
|
|
65
69
|
name?: string;
|
package/dist/hono.js
CHANGED
|
@@ -183,15 +183,98 @@ export function billingRoutes(billing, opts) {
|
|
|
183
183
|
return asError(c, err);
|
|
184
184
|
}
|
|
185
185
|
});
|
|
186
|
+
for (const resource of ['plans', 'balances'])
|
|
187
|
+
r.get(`/${resource}`, async (c) => {
|
|
188
|
+
const accountId = await opts.getAccountId(c);
|
|
189
|
+
if (!accountId)
|
|
190
|
+
return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
|
|
191
|
+
try {
|
|
192
|
+
return c.json(resource === 'plans' ? await billing.plans() : await billing.balances(accountId));
|
|
193
|
+
}
|
|
194
|
+
catch (err) {
|
|
195
|
+
return asError(c, err);
|
|
196
|
+
}
|
|
197
|
+
});
|
|
186
198
|
r.post('/:action', async (c) => {
|
|
187
199
|
const accountId = await opts.getAccountId(c);
|
|
188
200
|
if (!accountId)
|
|
189
201
|
return c.json({ error: BILLING_ACCOUNT_REQUIRED }, 401);
|
|
190
202
|
if (!(await opts.canManage(c, accountId)))
|
|
191
203
|
return c.json({ error: 'forbidden', message: 'You cannot manage billing for this account' }, 403);
|
|
192
|
-
|
|
204
|
+
let body;
|
|
205
|
+
try {
|
|
206
|
+
const raw = await c.req.text();
|
|
207
|
+
const parsed = raw.trim() ? JSON.parse(raw) : {};
|
|
208
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
209
|
+
throw new Error('object required');
|
|
210
|
+
body = parsed;
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return c.json({ error: 'invalid_json', message: 'A JSON object is required' }, 400);
|
|
214
|
+
}
|
|
215
|
+
if ((body.when !== undefined && body.when !== 'now' && body.when !== 'period_end')
|
|
216
|
+
|| (body.proration !== undefined && !['create_prorations', 'always_invoice', 'none'].includes(String(body.proration)))
|
|
217
|
+
|| (body.proration_date !== undefined && (!Number.isSafeInteger(body.proration_date) || Number(body.proration_date) < 0))
|
|
218
|
+
|| (body.subscription_id !== undefined && typeof body.subscription_id !== 'string')
|
|
219
|
+
|| (body.covers_account_id !== undefined && typeof body.covers_account_id !== 'string'))
|
|
220
|
+
return c.json({ error: 'invalid_field', message: 'Invalid subscription change options' }, 400);
|
|
221
|
+
const changeOptions = {
|
|
222
|
+
...(body.when === 'now' || body.when === 'period_end' ? { when: body.when } : {}),
|
|
223
|
+
...(body.proration === 'create_prorations' || body.proration === 'always_invoice' || body.proration === 'none' ? { proration: body.proration } : {}),
|
|
224
|
+
...(typeof body.proration_date === 'number' ? { prorationDate: body.proration_date } : {}),
|
|
225
|
+
...(typeof body.subscription_id === 'string' ? { subscriptionId: body.subscription_id } : {}),
|
|
226
|
+
...(typeof body.covers_account_id === 'string' ? { coversAccountId: body.covers_account_id } : {}),
|
|
227
|
+
};
|
|
193
228
|
try {
|
|
194
229
|
switch (c.req.param('action')) {
|
|
230
|
+
case 'invoice-subscription': {
|
|
231
|
+
if (typeof body.plan !== 'string' || !body.plan || (opts.plans && !opts.plans.includes(body.plan)))
|
|
232
|
+
return c.json({ error: 'unknown_plan' }, 400);
|
|
233
|
+
if (body.quantity !== undefined && (!Number.isSafeInteger(body.quantity) || Number(body.quantity) < 1))
|
|
234
|
+
return c.json({ error: 'invalid_field', message: 'quantity must be a positive integer' }, 400);
|
|
235
|
+
const address = body.billing_address;
|
|
236
|
+
if (address !== undefined && (!address || typeof address !== 'object' || Array.isArray(address) || !/^[A-Za-z]{2}$/.test(String(address.country ?? '')) || Object.entries(address).some(([key, value]) => !['country', 'line1', 'line2', 'city', 'state', 'postal_code'].includes(key) || typeof value !== 'string')))
|
|
237
|
+
return c.json({ error: 'invalid_field', message: 'billing_address needs a two-letter country and string address fields' }, 400);
|
|
238
|
+
return c.json({ ...(await billing.invoiceSubscription(accountId, body.plan, { quantity: body.quantity, email: (await opts.getEmail?.(c)) ?? undefined, ...(address ? { billingAddress: address } : {}) })), viewer_can_manage: true });
|
|
239
|
+
}
|
|
240
|
+
case 'preview-change':
|
|
241
|
+
case 'change-plan': {
|
|
242
|
+
if (typeof body.plan !== 'string' || !body.plan || (opts.plans && !opts.plans.includes(body.plan)))
|
|
243
|
+
return c.json({ error: 'unknown_plan' }, 400);
|
|
244
|
+
return c.json(c.req.param('action') === 'preview-change'
|
|
245
|
+
? await billing.previewChange(accountId, body.plan, changeOptions)
|
|
246
|
+
: { ...(await billing.changePlan(accountId, body.plan, changeOptions)), viewer_can_manage: true });
|
|
247
|
+
}
|
|
248
|
+
case 'preview-quantity':
|
|
249
|
+
case 'change-quantity': {
|
|
250
|
+
if (!Number.isSafeInteger(body.quantity) || Number(body.quantity) < 1)
|
|
251
|
+
return c.json({ error: 'invalid_field', message: 'quantity must be a positive integer' }, 400);
|
|
252
|
+
return c.json(c.req.param('action') === 'preview-quantity'
|
|
253
|
+
? await billing.previewQuantity(accountId, Number(body.quantity), changeOptions)
|
|
254
|
+
: { ...(await billing.changeQuantity(accountId, Number(body.quantity), changeOptions)), viewer_can_manage: true });
|
|
255
|
+
}
|
|
256
|
+
case 'cancel-schedule':
|
|
257
|
+
return c.json({ ...(await billing.cancelScheduledChange(accountId, changeOptions)), viewer_can_manage: true });
|
|
258
|
+
case 'topup': {
|
|
259
|
+
if (typeof body.product !== 'string' || !body.product)
|
|
260
|
+
return c.json({ error: 'invalid_field', message: 'product is required' }, 400);
|
|
261
|
+
if (body.quantity !== undefined && (!Number.isSafeInteger(body.quantity) || Number(body.quantity) < 1))
|
|
262
|
+
return c.json({ error: 'invalid_field', message: 'quantity must be a positive integer' }, 400);
|
|
263
|
+
const url = resolveReturn(c);
|
|
264
|
+
return c.json(await billing.topUp({ accountId, product: body.product, quantity: body.quantity, successUrl: url, cancelUrl: url, email: (await opts.getEmail?.(c)) ?? undefined }));
|
|
265
|
+
}
|
|
266
|
+
case 'usage-settings': {
|
|
267
|
+
const cap = body.spend_cap;
|
|
268
|
+
if (cap !== undefined && cap !== null && (typeof cap !== 'object' || Array.isArray(cap) || !Number.isSafeInteger(cap.amount) || Number(cap.amount) < 0 || typeof cap.currency !== 'string'))
|
|
269
|
+
return c.json({ error: 'invalid_field', message: 'spend_cap must contain amount and currency, or be null' }, 400);
|
|
270
|
+
const rules = body.auto_topups;
|
|
271
|
+
if (rules !== undefined && (!Array.isArray(rules) || rules.some((rule) => !rule || typeof rule !== 'object' || typeof rule.feature_id !== 'string' || typeof rule.product !== 'string' || typeof rule.auto !== 'boolean' || !Number.isFinite(rule.threshold) || rule.threshold < 0 || !Number.isSafeInteger(rule.max_per_month) || rule.max_per_month < 1)))
|
|
272
|
+
return c.json({ error: 'invalid_field', message: 'Each top-up rule needs a feature, product, threshold, explicit auto choice and monthly limit' }, 400);
|
|
273
|
+
return c.json(await billing.setUsageSettings(accountId, {
|
|
274
|
+
...(cap !== undefined ? { spendCap: cap } : {}),
|
|
275
|
+
...(Array.isArray(rules) ? { autoTopups: rules.map((r) => ({ featureId: r.feature_id, product: r.product, threshold: r.threshold, auto: r.auto, maxPerMonth: r.max_per_month })) } : {}),
|
|
276
|
+
}));
|
|
277
|
+
}
|
|
195
278
|
case 'checkout': {
|
|
196
279
|
const plan = typeof body.plan === 'string' ? body.plan : '';
|
|
197
280
|
if (!plan || (opts.plans && !opts.plans.includes(plan)))
|
package/dist/index.d.ts
CHANGED
|
@@ -27,11 +27,13 @@
|
|
|
27
27
|
* that in the app before calling checkout/portal/setAutoRenew.
|
|
28
28
|
*/
|
|
29
29
|
import { type CacheStore } from './cache.js';
|
|
30
|
+
import { type UsageRecord, type UsageStatus, type UsageStore } from './usage.js';
|
|
31
|
+
export { memoryUsageStore, d1UsageStore, USAGE_QUEUE_SCHEMA, type UsageRecord, type UsageStatus, type UsageStore, type UsageDatabase } from './usage.js';
|
|
30
32
|
import type { AccountInput, AccountStatus, Balances, ChangePreview, CheckResult, DiscountCheck, EntitlementResult, Lock, OfferView, PlanChange, PublicPlan, TrackResult, UpsertResult, UsageSettingsInput } from './types.js';
|
|
31
33
|
export * from './types.js';
|
|
32
34
|
export { BillingError, isOutage, killSignal } from './errors.js';
|
|
33
35
|
export { type BillingConfig, type ConfigChange, type ConfigPushResult, type PlanSpec, type PriceSpec, defineConfig, formatChanges } from './config.js';
|
|
34
|
-
export { type AppHealth, type BillingAdmin, type BillingAdminOptions, type CreateDiscountParams, type CreateOfferParams, type DiscountCodeAdminView, type InvoiceView, type OfferAdminView, type OfferPatch, type RefundParams, type RefundResult, createBillingAdmin } from './admin.js';
|
|
36
|
+
export { type AppHealth, type BillingAdmin, type BillingAdminOptions, type CreateDiscountParams, type CreateOfferParams, type DiscountCodeAdminView, type InvoiceView, type OfferAdminView, type OfferPatch, type RedemptionAdminView, type RefundParams, type RefundResult, type PurchaseRefundResult, createBillingAdmin } from './admin.js';
|
|
35
37
|
export { type CacheEntry, type CacheStore, memoryStore } from './cache.js';
|
|
36
38
|
export { BillingWebhookError, type BillingWebhookErrorCode, type VerifyOptions, verifyBillingEvent, verifyBillingWebhook } from './webhook.js';
|
|
37
39
|
/** What `onError` receives for every failed entitlement check. */
|
|
@@ -103,6 +105,8 @@ export interface BillingOptions {
|
|
|
103
105
|
usageBufferSize?: number;
|
|
104
106
|
/** A buffered track is dropped (and logged) after this many failed sends. Default 5. Since 0.5.0. */
|
|
105
107
|
usageMaxAttempts?: number;
|
|
108
|
+
/** Optional persistent delivery queue. Apply the adapter schema before use. */
|
|
109
|
+
usageStore?: UsageStore;
|
|
106
110
|
}
|
|
107
111
|
/** Options of `track()` (since 0.5.0). */
|
|
108
112
|
export interface TrackOptions {
|
|
@@ -126,6 +130,14 @@ export interface DeleteAccountResult {
|
|
|
126
130
|
/** What the service keeps after deletion (hashed trial marks, one audit entry). */
|
|
127
131
|
retained?: string[];
|
|
128
132
|
}
|
|
133
|
+
export interface BillingAddress {
|
|
134
|
+
country: string;
|
|
135
|
+
line1?: string;
|
|
136
|
+
line2?: string;
|
|
137
|
+
city?: string;
|
|
138
|
+
state?: string;
|
|
139
|
+
postal_code?: string;
|
|
140
|
+
}
|
|
129
141
|
export interface CheckoutParams {
|
|
130
142
|
accountId: string;
|
|
131
143
|
plan: string;
|
|
@@ -279,6 +291,10 @@ export interface Billing {
|
|
|
279
291
|
dropped: number;
|
|
280
292
|
pending: number;
|
|
281
293
|
}>;
|
|
294
|
+
usageStatus(): Promise<UsageStatus>;
|
|
295
|
+
rejectedUsage(limit?: number): Promise<UsageRecord[]>;
|
|
296
|
+
/** Retry selected rejected records after correcting their cause; original idempotency keys are kept. */
|
|
297
|
+
retryUsage(ids: string[]): Promise<number>;
|
|
282
298
|
/** Every balance of the account, its grants, held locks, auto top-ups and spend cap. Throws BillingError. Since 0.6.0. */
|
|
283
299
|
balances(accountId: string): Promise<Balances>;
|
|
284
300
|
/**
|
|
@@ -314,6 +330,25 @@ export interface Billing {
|
|
|
314
330
|
}>;
|
|
315
331
|
/** What changePlan would cost: amount due now, the next invoice, the lines. Since 0.7.0. */
|
|
316
332
|
previewChange(accountId: string, plan: string, opts?: PlanChangeOptions): Promise<ChangePreview>;
|
|
333
|
+
changeQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<AccountStatus & {
|
|
334
|
+
change: PlanChange;
|
|
335
|
+
}>;
|
|
336
|
+
previewQuantity(accountId: string, quantity: number, opts?: PlanChangeOptions): Promise<ChangePreview>;
|
|
337
|
+
cancelScheduledChange(accountId: string, select?: Omit<SubscriptionSelector, 'all'>): Promise<AccountStatus>;
|
|
338
|
+
/** Create a subscription billed by invoice, when enabled in the app's billing policy. */
|
|
339
|
+
invoiceSubscription(accountId: string, plan: string, opts?: {
|
|
340
|
+
quantity?: number;
|
|
341
|
+
email?: string;
|
|
342
|
+
customerName?: string;
|
|
343
|
+
billingAddress?: BillingAddress;
|
|
344
|
+
}): Promise<AccountStatus & {
|
|
345
|
+
invoice: {
|
|
346
|
+
id: string | null;
|
|
347
|
+
status: string | null;
|
|
348
|
+
hosted_invoice_url: string | null;
|
|
349
|
+
due_at: string | null;
|
|
350
|
+
};
|
|
351
|
+
}>;
|
|
317
352
|
/** Attaches an add-on plan (or sets its quantity) on the account's own subscription. Since 0.7.0. */
|
|
318
353
|
attachAddOn(accountId: string, plan: string, opts?: {
|
|
319
354
|
quantity?: number;
|
package/dist/index.js
CHANGED
|
@@ -27,6 +27,8 @@
|
|
|
27
27
|
* that in the app before calling checkout/portal/setAutoRenew.
|
|
28
28
|
*/
|
|
29
29
|
import { memoryStore } from "./cache.js";
|
|
30
|
+
import { memoryUsageStore, usageOutcome } from "./usage.js";
|
|
31
|
+
export { memoryUsageStore, d1UsageStore, USAGE_QUEUE_SCHEMA } from "./usage.js";
|
|
30
32
|
export * from "./types.js";
|
|
31
33
|
export { BillingError, isOutage, killSignal } from "./errors.js";
|
|
32
34
|
import { BillingError, isOutage, killSignal } from "./errors.js";
|
|
@@ -197,7 +199,8 @@ export function createBilling(opts) {
|
|
|
197
199
|
// ---------------------------------------------------------------- features (0.5.0)
|
|
198
200
|
const bufferSize = opts.usageBufferSize ?? 1000;
|
|
199
201
|
const maxAttempts = opts.usageMaxAttempts ?? 5;
|
|
200
|
-
const
|
|
202
|
+
const usageStore = opts.usageStore ?? memoryUsageStore();
|
|
203
|
+
const usageScope = JSON.stringify([base, opts.appId]);
|
|
201
204
|
let flushing = null;
|
|
202
205
|
const randomKey = () => `sdk-${globalThis.crypto?.randomUUID?.() ?? `${now()}-${Math.random().toString(36).slice(2)}`}`;
|
|
203
206
|
const unverifiedCheck = (accountId, featureId, allowed, source, error) => ({
|
|
@@ -228,55 +231,86 @@ export function createBilling(opts) {
|
|
|
228
231
|
const e = err;
|
|
229
232
|
(isOutage(e) ? log.warn : log.error).call(log, `[billing] ${what} (${e?.code ?? 'error'}: ${e?.message ?? err})`);
|
|
230
233
|
}
|
|
231
|
-
function
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
234
|
+
async function rejectUsage(row, error) {
|
|
235
|
+
await usageStore.put({ ...row, status: 'rejected', error });
|
|
236
|
+
log.error(`[billing] usage rejected: ${row.body.feature_id} for ${row.body.account_id} (${error})`);
|
|
237
|
+
}
|
|
238
|
+
async function enqueue(body, existing) {
|
|
239
|
+
const row = existing ?? { scope: usageScope, id: randomKey(), body, attempts: 1, createdAt: now(), status: 'pending' };
|
|
240
|
+
try {
|
|
241
|
+
await usageStore.put(row);
|
|
242
|
+
const pending = await usageStore.list(usageScope, 'pending', bufferSize + 1);
|
|
243
|
+
for (const old of pending.slice(0, Math.max(0, pending.length - bufferSize))) {
|
|
244
|
+
await rejectUsage(old, `usage buffer full (${bufferSize})`);
|
|
245
|
+
if (old.id === row.id)
|
|
246
|
+
return null;
|
|
247
|
+
}
|
|
248
|
+
return row;
|
|
249
|
+
}
|
|
250
|
+
catch (err) {
|
|
251
|
+
reportUsage('could not persist usage for retry', err);
|
|
252
|
+
return null;
|
|
236
253
|
}
|
|
237
254
|
}
|
|
238
255
|
async function flushUsage() {
|
|
239
256
|
if (flushing)
|
|
240
257
|
return flushing;
|
|
241
258
|
flushing = (async () => {
|
|
242
|
-
let sent = 0;
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
await
|
|
248
|
-
|
|
249
|
-
sent += chunk.length;
|
|
250
|
-
}
|
|
251
|
-
catch (err) {
|
|
252
|
-
if (!isOutage(err) && !(killSignal(err) && !killDeny)) {
|
|
253
|
-
// The service refused the batch itself (auth / config): retrying cannot help.
|
|
254
|
-
usageBuffer.splice(0, chunk.length);
|
|
255
|
-
dropped += chunk.length;
|
|
256
|
-
reportUsage(`dropped ${chunk.length} buffered usage event(s): the service refused them`, err);
|
|
259
|
+
let sent = 0, dropped = 0, pending = 0;
|
|
260
|
+
try {
|
|
261
|
+
// Each record is attempted at most once per flush, including when a response is ambiguous.
|
|
262
|
+
const seen = new Set();
|
|
263
|
+
while (true) {
|
|
264
|
+
const chunk = (await usageStore.list(usageScope, 'pending', 1000)).filter((r) => !seen.has(r.id));
|
|
265
|
+
if (!chunk.length)
|
|
257
266
|
break;
|
|
267
|
+
for (const row of chunk)
|
|
268
|
+
seen.add(row.id);
|
|
269
|
+
let results;
|
|
270
|
+
try {
|
|
271
|
+
const answer = await call('POST', '/v1/track/batch', { events: chunk.map((x) => x.body) });
|
|
272
|
+
results = Array.isArray(answer.results) && answer.results.length === chunk.length ? answer.results : chunk.map(() => null);
|
|
258
273
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
274
|
+
catch (err) {
|
|
275
|
+
const retry = killSignal(err) ? !killDeny : isOutage(err);
|
|
276
|
+
results = chunk.map(() => ({ error: retry ? 'storage_unavailable' : 'delivery_refused' }));
|
|
277
|
+
reportUsage('buffered usage delivery failed', err);
|
|
278
|
+
}
|
|
279
|
+
for (const [i, row] of chunk.entries()) {
|
|
280
|
+
const result = results[i];
|
|
281
|
+
const outcome = usageOutcome(result);
|
|
282
|
+
if (outcome === 'sent') {
|
|
283
|
+
await usageStore.remove(usageScope, row.id);
|
|
284
|
+
sent++;
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
const updated = { ...row, attempts: row.attempts + 1 };
|
|
288
|
+
const error = String(result?.error ?? result?.reason ?? 'invalid_response');
|
|
289
|
+
if (outcome === 'rejected' || updated.attempts >= maxAttempts) {
|
|
290
|
+
await rejectUsage(updated, outcome === 'rejected' ? error : `${error} after ${maxAttempts} attempts`);
|
|
291
|
+
dropped++;
|
|
292
|
+
}
|
|
293
|
+
else
|
|
294
|
+
await usageStore.put({ ...updated, error });
|
|
295
|
+
}
|
|
267
296
|
}
|
|
268
|
-
break;
|
|
269
297
|
}
|
|
270
298
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
299
|
+
catch (err) {
|
|
300
|
+
reportUsage('usage queue storage failed; unacknowledged records remain retryable', err);
|
|
301
|
+
}
|
|
302
|
+
try {
|
|
303
|
+
pending = (await usageStore.status(usageScope)).pending;
|
|
304
|
+
}
|
|
305
|
+
catch (err) {
|
|
306
|
+
reportUsage('usage queue status unavailable', err);
|
|
307
|
+
}
|
|
308
|
+
return { sent, dropped, pending };
|
|
309
|
+
})().finally(() => { flushing = null; });
|
|
275
310
|
return flushing;
|
|
276
311
|
}
|
|
277
|
-
/** Sends what is buffered behind a successful call (the service is evidently up). */
|
|
278
312
|
const flushBehind = (waitUntil) => {
|
|
279
|
-
if (
|
|
313
|
+
if (flushing)
|
|
280
314
|
return;
|
|
281
315
|
const p = flushUsage().catch(() => undefined);
|
|
282
316
|
(waitUntil ?? opts.waitUntil)?.(p);
|
|
@@ -329,8 +363,23 @@ export function createBilling(opts) {
|
|
|
329
363
|
...(o.properties ? { properties: o.properties } : {}),
|
|
330
364
|
...(o.checkAndTrack ? { check_and_track: true } : {}),
|
|
331
365
|
};
|
|
366
|
+
const initial = opts.usageStore ? { scope: usageScope, id: randomKey(), body, attempts: 0, createdAt: now(), status: 'pending' } : undefined;
|
|
367
|
+
const persisted = initial ? await enqueue(body, initial) : null;
|
|
332
368
|
try {
|
|
333
369
|
const r = await call('POST', '/v1/track', body);
|
|
370
|
+
if (usageOutcome(r) === 'retry')
|
|
371
|
+
throw new BillingError(502, 'invalid_response', 'Billing service did not acknowledge the usage event');
|
|
372
|
+
if (persisted) {
|
|
373
|
+
try {
|
|
374
|
+
if (usageOutcome(r) === 'rejected')
|
|
375
|
+
await rejectUsage(persisted, r.reason ?? 'refused');
|
|
376
|
+
else if (usageOutcome(r) === 'sent')
|
|
377
|
+
await usageStore.remove(usageScope, persisted.id);
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
reportUsage('usage acknowledgment could not be persisted; original key retained', error);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
334
383
|
flushBehind(o.waitUntil);
|
|
335
384
|
return { ...r, source: 'live' };
|
|
336
385
|
}
|
|
@@ -339,17 +388,19 @@ export function createBilling(opts) {
|
|
|
339
388
|
const kill = killSignal(err);
|
|
340
389
|
if (kill && !killDeny) {
|
|
341
390
|
// Kill switch, fail_open: the usage is kept for a retry once the app is re-enabled (bounded buffer).
|
|
342
|
-
enqueue(body);
|
|
391
|
+
const queued = !!(await enqueue(body, persisted ? { ...persisted, attempts: 1 } : undefined));
|
|
343
392
|
log.error(`[billing] !!! KILL SWITCH (${kill}): track ${featureId} for ${accountId} queued (onKill: fail_open)`);
|
|
344
|
-
return { ...unverifiedCheck(accountId, featureId, failOpen, failOpen ? 'fail_open' : 'error', code), value, applied: false, replayed: false, event_id: null, queued
|
|
393
|
+
return { ...unverifiedCheck(accountId, featureId, failOpen, failOpen ? 'fail_open' : 'error', code), value, applied: false, replayed: false, event_id: null, queued };
|
|
345
394
|
}
|
|
346
395
|
if (kill || !isOutage(err)) {
|
|
396
|
+
if (persisted)
|
|
397
|
+
await rejectUsage(persisted, code).catch((e) => reportUsage('usage rejection could not be persisted', e));
|
|
347
398
|
reportUsage(`track ${featureId} for ${accountId} refused`, err);
|
|
348
399
|
return { ...unverifiedCheck(accountId, featureId, false, 'error', code), value, applied: false, replayed: false, event_id: null };
|
|
349
400
|
}
|
|
350
|
-
enqueue(body);
|
|
351
|
-
reportUsage(`track ${featureId} for ${accountId} queued for a retry
|
|
352
|
-
return { ...unverifiedCheck(accountId, featureId, true, 'fail_open', code), value, applied: false, replayed: false, event_id: null, queued
|
|
401
|
+
const queued = !!(await enqueue(body, persisted ? { ...persisted, attempts: 1 } : undefined));
|
|
402
|
+
reportUsage(`track ${featureId} for ${accountId} ${queued ? 'queued for a retry' : 'could not be queued'}`, err);
|
|
403
|
+
return { ...unverifiedCheck(accountId, featureId, true, 'fail_open', code), value, applied: false, replayed: false, event_id: null, queued };
|
|
353
404
|
}
|
|
354
405
|
},
|
|
355
406
|
async setUsage(accountId, featureId, value) {
|
|
@@ -357,6 +408,19 @@ export function createBilling(opts) {
|
|
|
357
408
|
return { ...r, source: 'live' };
|
|
358
409
|
},
|
|
359
410
|
flushUsage,
|
|
411
|
+
usageStatus: () => usageStore.status(usageScope),
|
|
412
|
+
rejectedUsage: (limit = 100) => usageStore.list(usageScope, 'rejected', Math.max(1, Math.min(1000, limit))),
|
|
413
|
+
async retryUsage(ids) {
|
|
414
|
+
const selected = new Set(ids);
|
|
415
|
+
const records = await usageStore.list(usageScope, 'rejected', 1000);
|
|
416
|
+
let retried = 0;
|
|
417
|
+
for (const row of records)
|
|
418
|
+
if (selected.has(row.id)) {
|
|
419
|
+
if (await enqueue(row.body, { ...row, status: 'pending', attempts: 0, error: undefined }))
|
|
420
|
+
retried++;
|
|
421
|
+
}
|
|
422
|
+
return retried;
|
|
423
|
+
},
|
|
360
424
|
async getEntitlement(accountId, callOpts = {}) {
|
|
361
425
|
const entry = await cache.get(key(accountId)).catch((e) => {
|
|
362
426
|
log.warn('[billing] cache read failed', e);
|
|
@@ -436,6 +500,26 @@ export function createBilling(opts) {
|
|
|
436
500
|
return r;
|
|
437
501
|
},
|
|
438
502
|
previewChange: (accountId, plan, o) => call('POST', '/v1/subscriptions/change/preview', changeBody(accountId, plan, o)),
|
|
503
|
+
async changeQuantity(accountId, quantity, o = {}) {
|
|
504
|
+
const { plan: _plan, ...body } = changeBody(accountId, '', o);
|
|
505
|
+
const result = await call('POST', '/v1/subscriptions/quantity', { ...body, quantity });
|
|
506
|
+
await self.invalidate(accountId).catch(() => undefined);
|
|
507
|
+
return result;
|
|
508
|
+
},
|
|
509
|
+
previewQuantity(accountId, quantity, o = {}) {
|
|
510
|
+
const { plan: _plan, ...body } = changeBody(accountId, '', o);
|
|
511
|
+
return call('POST', '/v1/subscriptions/quantity/preview', { ...body, quantity });
|
|
512
|
+
},
|
|
513
|
+
async cancelScheduledChange(accountId, select = {}) {
|
|
514
|
+
const result = await call('DELETE', '/v1/subscriptions/schedule', { account_id: accountId, ...selectorBody(select) });
|
|
515
|
+
await self.invalidate(accountId).catch(() => undefined);
|
|
516
|
+
return result;
|
|
517
|
+
},
|
|
518
|
+
async invoiceSubscription(accountId, plan, o = {}) {
|
|
519
|
+
const result = await call('POST', '/v1/subscriptions/invoice', { account_id: accountId, plan, quantity: o.quantity, email: o.email, customer_name: o.customerName, billing_address: o.billingAddress });
|
|
520
|
+
await self.invalidate(accountId).catch(() => undefined);
|
|
521
|
+
return result;
|
|
522
|
+
},
|
|
439
523
|
async attachAddOn(accountId, plan, o = {}) {
|
|
440
524
|
const r = await call('POST', '/v1/subscriptions/add-ons', { account_id: accountId, plan, ...(o.quantity ? { quantity: o.quantity } : {}), ...(o.subscriptionId ? { subscription_id: o.subscriptionId } : {}) });
|
|
441
525
|
await cache.delete(key(accountId)).catch(() => undefined);
|
package/dist/react.d.ts
CHANGED
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
* <BillingCard basePath="/api/billing" plan="pro" />
|
|
15
15
|
*/
|
|
16
16
|
import { type ReactElement, type ReactNode } from 'react';
|
|
17
|
-
import type { AccountStatus, FeatureReason, FeatureType } from './types.js';
|
|
17
|
+
import type { AccountStatus, Balances, ChangePreview, DiscountCheck, FeatureReason, FeatureType, OfferView, PlanChange, PublicPlan } from './types.js';
|
|
18
18
|
/** What the app's GET {basePath} returns: the service status + whether this viewer may manage it. */
|
|
19
19
|
export type BillingStatus = AccountStatus & {
|
|
20
20
|
viewer_can_manage?: boolean;
|
|
@@ -117,3 +117,100 @@ export interface GateProps extends UseFeatureOptions {
|
|
|
117
117
|
}
|
|
118
118
|
/** <Gate feature="export" fallback={<Upgrade />}>…</Gate> — renders children only when the feature is allowed. */
|
|
119
119
|
export declare function Gate(props: GateProps): ReactElement | null;
|
|
120
|
+
/** A structured error from the app's billing routes, safe to use in a browser. */
|
|
121
|
+
export declare class BillingBrowserError extends Error {
|
|
122
|
+
readonly status: number;
|
|
123
|
+
readonly code: string;
|
|
124
|
+
readonly details: Record<string, unknown>;
|
|
125
|
+
constructor(status: number, code: string, message: string, details?: Record<string, unknown>);
|
|
126
|
+
}
|
|
127
|
+
export interface BillingManagementOptions extends UseBillingOptions {
|
|
128
|
+
initialPlans?: PublicPlan[];
|
|
129
|
+
initialBalances?: Balances;
|
|
130
|
+
initialOffers?: OfferView[];
|
|
131
|
+
onError?: (error: BillingBrowserError) => void;
|
|
132
|
+
}
|
|
133
|
+
export interface BillingChangeRequest {
|
|
134
|
+
when?: 'now' | 'period_end';
|
|
135
|
+
subscription_id?: string;
|
|
136
|
+
covers_account_id?: string;
|
|
137
|
+
}
|
|
138
|
+
export interface BillingPreview {
|
|
139
|
+
kind: 'plan' | 'quantity';
|
|
140
|
+
request: BillingChangeRequest & {
|
|
141
|
+
plan?: string;
|
|
142
|
+
quantity?: number;
|
|
143
|
+
};
|
|
144
|
+
quote: ChangePreview;
|
|
145
|
+
}
|
|
146
|
+
export interface BillingUsageSettings {
|
|
147
|
+
spend_cap?: {
|
|
148
|
+
amount: number;
|
|
149
|
+
currency: string;
|
|
150
|
+
} | null;
|
|
151
|
+
auto_topups?: Array<{
|
|
152
|
+
feature_id: string;
|
|
153
|
+
product: string;
|
|
154
|
+
threshold: number;
|
|
155
|
+
auto: boolean;
|
|
156
|
+
max_per_month: number;
|
|
157
|
+
}>;
|
|
158
|
+
}
|
|
159
|
+
export interface BillingInvoiceAddress {
|
|
160
|
+
country: string;
|
|
161
|
+
line1?: string;
|
|
162
|
+
line2?: string;
|
|
163
|
+
city?: string;
|
|
164
|
+
state?: string;
|
|
165
|
+
postal_code?: string;
|
|
166
|
+
}
|
|
167
|
+
/** Full billing-page actions. Amounts in the returned quotes and balances are currency minor units. */
|
|
168
|
+
export declare function useBillingManagement(opts?: BillingManagementOptions): {
|
|
169
|
+
plans: PublicPlan[];
|
|
170
|
+
balances: Balances | null;
|
|
171
|
+
offers: OfferView[];
|
|
172
|
+
loading: boolean;
|
|
173
|
+
busy: boolean;
|
|
174
|
+
error: string | null;
|
|
175
|
+
lastError: BillingBrowserError | null;
|
|
176
|
+
message: string | null;
|
|
177
|
+
refresh: () => Promise<void | undefined>;
|
|
178
|
+
previewPlan: (plan: string, options?: BillingChangeRequest) => Promise<BillingPreview | undefined>;
|
|
179
|
+
previewQuantity: (quantity: number, options?: BillingChangeRequest) => Promise<BillingPreview | undefined>;
|
|
180
|
+
confirmChange: (preview: BillingPreview) => Promise<(AccountStatus & {
|
|
181
|
+
change?: PlanChange;
|
|
182
|
+
}) | undefined>;
|
|
183
|
+
cancelScheduledChange: (options?: BillingChangeRequest) => Promise<(AccountStatus & {
|
|
184
|
+
change?: PlanChange;
|
|
185
|
+
}) | undefined>;
|
|
186
|
+
checkDiscount: (code: string, plan?: string) => Promise<DiscountCheck | undefined>;
|
|
187
|
+
checkout: (plan: string, options?: {
|
|
188
|
+
quantity?: number;
|
|
189
|
+
discount_code?: string;
|
|
190
|
+
offer_id?: string;
|
|
191
|
+
}) => Promise<void | undefined>;
|
|
192
|
+
acceptOffer: (offerId: string) => Promise<(AccountStatus & {
|
|
193
|
+
change?: PlanChange;
|
|
194
|
+
}) | undefined>;
|
|
195
|
+
requestInvoice: (plan: string, quantity?: number, billingAddress?: BillingInvoiceAddress) => Promise<(AccountStatus & {
|
|
196
|
+
invoice: {
|
|
197
|
+
hosted_invoice_url: string | null;
|
|
198
|
+
};
|
|
199
|
+
}) | undefined>;
|
|
200
|
+
purchaseCredits: (product: string, quantity?: number) => Promise<void | undefined>;
|
|
201
|
+
saveUsageSettings: (settings: BillingUsageSettings) => Promise<void | undefined>;
|
|
202
|
+
status: BillingStatus | null;
|
|
203
|
+
/** True until the first load settles (one-shot: never flips back). */
|
|
204
|
+
booting: boolean;
|
|
205
|
+
subscribe(plan: string, quantity?: number): Promise<void>;
|
|
206
|
+
openPortal(): Promise<void>;
|
|
207
|
+
setAutoRenew(on: boolean): Promise<void>;
|
|
208
|
+
};
|
|
209
|
+
export interface BillingPanelProps extends BillingManagementOptions {
|
|
210
|
+
className?: string;
|
|
211
|
+
locale?: string;
|
|
212
|
+
/** Offer invoice terms instead of Checkout. Enable only for an app configured for invoice billing. */
|
|
213
|
+
invoiceBilling?: boolean;
|
|
214
|
+
}
|
|
215
|
+
/** A complete, unstyled billing page. Its routes use the signed-in account and the app's canManage gate. */
|
|
216
|
+
export declare function BillingPanel(props: BillingPanelProps): ReactElement;
|
package/dist/react.js
CHANGED
|
@@ -14,9 +14,10 @@
|
|
|
14
14
|
* <BillingCard basePath="/api/billing" plan="pro" />
|
|
15
15
|
*/
|
|
16
16
|
import { Fragment, createElement as h, useCallback, useEffect, useRef, useState } from 'react';
|
|
17
|
+
const browserFetch = (input, init) => fetch(input, { credentials: 'same-origin', ...init });
|
|
17
18
|
export function useBilling(opts = {}) {
|
|
18
19
|
const base = (opts.basePath ?? '/api/billing').replace(/\/+$/, '');
|
|
19
|
-
const doFetch = opts.fetch ??
|
|
20
|
+
const doFetch = opts.fetch ?? browserFetch;
|
|
20
21
|
const navigate = opts.navigate ?? ((url) => window.location.assign(url));
|
|
21
22
|
const [status, setStatus] = useState(opts.initialStatus ?? null);
|
|
22
23
|
const [booting, setBooting] = useState(!opts.initialStatus);
|
|
@@ -33,9 +34,7 @@ export function useBilling(opts = {}) {
|
|
|
33
34
|
if (!res.ok)
|
|
34
35
|
throw new Error(data?.message ?? data?.error ?? `HTTP ${res.status}`);
|
|
35
36
|
return data;
|
|
36
|
-
},
|
|
37
|
-
// `fetch` is configuration: read on the first render only.
|
|
38
|
-
[base]);
|
|
37
|
+
}, [base, doFetch]);
|
|
39
38
|
const refresh = useCallback(async () => {
|
|
40
39
|
try {
|
|
41
40
|
const s = await request('GET', '');
|
|
@@ -61,7 +60,7 @@ export function useBilling(opts = {}) {
|
|
|
61
60
|
return () => {
|
|
62
61
|
mounted.current = false;
|
|
63
62
|
};
|
|
64
|
-
}, []);
|
|
63
|
+
}, [refresh, opts.initialStatus]);
|
|
65
64
|
const act = useCallback(async (fn) => {
|
|
66
65
|
setBusy(true);
|
|
67
66
|
setError(null);
|
|
@@ -209,3 +208,205 @@ export function Gate(props) {
|
|
|
209
208
|
return h(Fragment, null, children);
|
|
210
209
|
return (typeof fallback === 'function' ? fallback(f.check) : (fallback ?? null));
|
|
211
210
|
}
|
|
211
|
+
/** A structured error from the app's billing routes, safe to use in a browser. */
|
|
212
|
+
export class BillingBrowserError extends Error {
|
|
213
|
+
status;
|
|
214
|
+
code;
|
|
215
|
+
details;
|
|
216
|
+
constructor(status, code, message, details = {}) {
|
|
217
|
+
super(message);
|
|
218
|
+
this.name = 'BillingBrowserError';
|
|
219
|
+
this.status = status;
|
|
220
|
+
this.code = code;
|
|
221
|
+
this.details = details;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
/** Full billing-page actions. Amounts in the returned quotes and balances are currency minor units. */
|
|
225
|
+
export function useBillingManagement(opts = {}) {
|
|
226
|
+
const billing = useBilling(opts);
|
|
227
|
+
const base = (opts.basePath ?? '/api/billing').replace(/\/+$/, '');
|
|
228
|
+
const fetcher = opts.fetch ?? browserFetch;
|
|
229
|
+
const [plans, setPlans] = useState(opts.initialPlans ?? []);
|
|
230
|
+
const [balances, setBalances] = useState(opts.initialBalances ?? null);
|
|
231
|
+
const [offers, setOffers] = useState(opts.initialOffers ?? []);
|
|
232
|
+
const [loading, setLoading] = useState(opts.initialPlans === undefined || opts.initialBalances === undefined || opts.initialOffers === undefined);
|
|
233
|
+
const [acting, setActing] = useState(false);
|
|
234
|
+
const [failure, setFailure] = useState(null);
|
|
235
|
+
const [message, setMessage] = useState(null);
|
|
236
|
+
const mounted = useRef(false), inFlight = useRef(false), onError = useRef(opts.onError);
|
|
237
|
+
onError.current = opts.onError;
|
|
238
|
+
const request = useCallback(async (method, path, body) => {
|
|
239
|
+
let response;
|
|
240
|
+
try {
|
|
241
|
+
response = await fetcher(`${base}${path}`, { method, headers: body === undefined ? undefined : { 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
242
|
+
}
|
|
243
|
+
catch (error) {
|
|
244
|
+
throw new BillingBrowserError(0, 'network_error', error?.message ?? 'Billing unavailable');
|
|
245
|
+
}
|
|
246
|
+
const data = await response.json().catch(() => null);
|
|
247
|
+
if (!response.ok)
|
|
248
|
+
throw new BillingBrowserError(response.status, typeof data?.error === 'string' ? data.error : 'billing_error', typeof data?.message === 'string' ? data.message : `HTTP ${response.status}`, data ?? {});
|
|
249
|
+
if (!data || typeof data !== 'object' || Array.isArray(data))
|
|
250
|
+
throw new BillingBrowserError(502, 'invalid_response', 'Billing returned an invalid response');
|
|
251
|
+
return data;
|
|
252
|
+
}, [base, fetcher]);
|
|
253
|
+
const report = useCallback((cause) => {
|
|
254
|
+
const error = cause instanceof BillingBrowserError ? cause : new BillingBrowserError(0, 'billing_error', cause?.message ?? 'Billing unavailable');
|
|
255
|
+
if (mounted.current)
|
|
256
|
+
setFailure(error);
|
|
257
|
+
try {
|
|
258
|
+
onError.current?.(error);
|
|
259
|
+
}
|
|
260
|
+
catch { /* reporting never changes the outcome */ }
|
|
261
|
+
}, []);
|
|
262
|
+
const load = useCallback(async () => {
|
|
263
|
+
const [catalog, credits, available] = await Promise.all([
|
|
264
|
+
request('GET', '/plans'), request('GET', '/balances'), request('GET', '/offers'),
|
|
265
|
+
]);
|
|
266
|
+
if (mounted.current) {
|
|
267
|
+
setPlans(catalog.plans);
|
|
268
|
+
setBalances(credits);
|
|
269
|
+
setOffers(available.offers);
|
|
270
|
+
}
|
|
271
|
+
}, [request]);
|
|
272
|
+
useEffect(() => {
|
|
273
|
+
mounted.current = true;
|
|
274
|
+
let cancelled = false;
|
|
275
|
+
if (opts.initialPlans === undefined || opts.initialBalances === undefined || opts.initialOffers === undefined) {
|
|
276
|
+
void load().catch((error) => { if (!cancelled)
|
|
277
|
+
report(error); }).finally(() => { if (!cancelled)
|
|
278
|
+
setLoading(false); });
|
|
279
|
+
}
|
|
280
|
+
return () => { cancelled = true; mounted.current = false; };
|
|
281
|
+
}, [load, report]);
|
|
282
|
+
const run = async (action) => {
|
|
283
|
+
if (inFlight.current)
|
|
284
|
+
return undefined;
|
|
285
|
+
inFlight.current = true;
|
|
286
|
+
setActing(true);
|
|
287
|
+
setFailure(null);
|
|
288
|
+
setMessage(null);
|
|
289
|
+
try {
|
|
290
|
+
return await action();
|
|
291
|
+
}
|
|
292
|
+
catch (error) {
|
|
293
|
+
report(error);
|
|
294
|
+
return undefined;
|
|
295
|
+
}
|
|
296
|
+
finally {
|
|
297
|
+
inFlight.current = false;
|
|
298
|
+
if (mounted.current)
|
|
299
|
+
setActing(false);
|
|
300
|
+
}
|
|
301
|
+
};
|
|
302
|
+
const refresh = async () => { await billing.refresh(); await load(); };
|
|
303
|
+
const navigate = opts.navigate ?? ((url) => window.location.assign(url));
|
|
304
|
+
const changed = async (path, body) => {
|
|
305
|
+
const result = await request('POST', path, body);
|
|
306
|
+
if (result.change?.status === 'requires_action' && result.change.action_url)
|
|
307
|
+
navigate(result.change.action_url);
|
|
308
|
+
else
|
|
309
|
+
setMessage(result.change?.status === 'scheduled' ? `Change scheduled${result.change.effective_at ? ` for ${fmtDate(result.change.effective_at)}` : ''}.` : 'Billing updated.');
|
|
310
|
+
await refresh();
|
|
311
|
+
return result;
|
|
312
|
+
};
|
|
313
|
+
return {
|
|
314
|
+
...billing, plans, balances, offers, loading, busy: billing.busy || acting,
|
|
315
|
+
error: failure?.message ?? billing.error, lastError: failure, message,
|
|
316
|
+
refresh: () => run(refresh),
|
|
317
|
+
previewPlan: (plan, options = {}) => run(async () => ({ kind: 'plan', request: { ...options, plan }, quote: await request('POST', '/preview-change', { ...options, plan }) })),
|
|
318
|
+
previewQuantity: (quantity, options = {}) => run(async () => ({ kind: 'quantity', request: { ...options, quantity }, quote: await request('POST', '/preview-quantity', { ...options, quantity }) })),
|
|
319
|
+
confirmChange: (preview) => run(() => changed(preview.kind === 'plan' ? '/change-plan' : '/change-quantity', { ...preview.request, when: preview.quote.when, proration: preview.quote.proration, proration_date: preview.quote.proration_date })),
|
|
320
|
+
cancelScheduledChange: (options = {}) => run(() => changed('/cancel-schedule', options)),
|
|
321
|
+
checkDiscount: (code, plan) => run(() => request('POST', '/discount', { code, plan })),
|
|
322
|
+
checkout: (plan, options = {}) => run(async () => { const result = await request('POST', '/checkout', { ...options, plan }); navigate(result.url); }),
|
|
323
|
+
acceptOffer: (offerId) => run(() => changed('/accept-offer', { offer_id: offerId })),
|
|
324
|
+
requestInvoice: (plan, quantity = 1, billingAddress) => run(async () => {
|
|
325
|
+
const result = await request('POST', '/invoice-subscription', { plan, quantity, billing_address: billingAddress });
|
|
326
|
+
await refresh();
|
|
327
|
+
setMessage('Invoice created.');
|
|
328
|
+
if (result.invoice.hosted_invoice_url)
|
|
329
|
+
navigate(result.invoice.hosted_invoice_url);
|
|
330
|
+
return result;
|
|
331
|
+
}),
|
|
332
|
+
purchaseCredits: (product, quantity = 1) => run(async () => { const result = await request('POST', '/topup', { product, quantity }); navigate(result.url); }),
|
|
333
|
+
saveUsageSettings: (settings) => run(async () => { await request('POST', '/usage-settings', settings); await load(); setMessage('Usage settings saved.'); }),
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
const currencyDigits = (currency) => new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions().maximumFractionDigits ?? 2;
|
|
337
|
+
const money = (amount, currency, locale) => {
|
|
338
|
+
if (!currency)
|
|
339
|
+
return String(amount);
|
|
340
|
+
try {
|
|
341
|
+
return new Intl.NumberFormat(locale, { style: 'currency', currency }).format(amount / 10 ** currencyDigits(currency));
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
return `${amount} ${currency}`;
|
|
345
|
+
}
|
|
346
|
+
};
|
|
347
|
+
/** A complete, unstyled billing page. Its routes use the signed-in account and the app's canManage gate. */
|
|
348
|
+
export function BillingPanel(props) {
|
|
349
|
+
const b = useBillingManagement(props);
|
|
350
|
+
const [plan, setPlan] = useState(''), [subscriptionId, setSubscriptionId] = useState('');
|
|
351
|
+
const [quantity, setQuantity] = useState(''), [when, setWhen] = useState('now');
|
|
352
|
+
const [preview, setPreview] = useState(null);
|
|
353
|
+
const [code, setCode] = useState(''), [discount, setDiscount] = useState(null);
|
|
354
|
+
const [product, setProduct] = useState(''), [packQuantity, setPackQuantity] = useState('1');
|
|
355
|
+
const [cap, setCap] = useState(''), [capCurrency, setCapCurrency] = useState('usd');
|
|
356
|
+
const [feature, setFeature] = useState(''), [threshold, setThreshold] = useState('10'), [monthlyMax, setMonthlyMax] = useState('1'), [auto, setAuto] = useState(false);
|
|
357
|
+
const [invoiceCountry, setInvoiceCountry] = useState(''), [invoiceStreet, setInvoiceStreet] = useState(''), [invoiceCity, setInvoiceCity] = useState(''), [invoiceState, setInvoiceState] = useState(''), [invoicePostal, setInvoicePostal] = useState('');
|
|
358
|
+
const subscriptions = b.status?.subscriptions.length ? b.status.subscriptions : b.status?.subscription ? [b.status.subscription] : [];
|
|
359
|
+
const selectedSub = subscriptions.find((s) => s.id === subscriptionId) ?? subscriptions.find((s) => s.id === b.status?.subscription?.id) ?? subscriptions[0];
|
|
360
|
+
const selectedPlan = plan || selectedSub?.plan || b.plans.find((p) => p.kind === 'subscription')?.plan || '';
|
|
361
|
+
const packs = b.plans.filter((p) => p.kind === 'pack');
|
|
362
|
+
const selectedProduct = product || packs[0]?.plan || '';
|
|
363
|
+
const creditFeatures = Object.keys(b.balances?.features ?? {}).filter((id) => packs.some((p) => p.grants?.some((g) => g.feature_id === id)));
|
|
364
|
+
const selectedFeature = feature || creditFeatures[0] || '';
|
|
365
|
+
useEffect(() => {
|
|
366
|
+
const saved = b.balances?.spend_cap;
|
|
367
|
+
if (saved) {
|
|
368
|
+
setCapCurrency(saved.currency);
|
|
369
|
+
setCap(String(saved.amount / 10 ** currencyDigits(saved.currency)));
|
|
370
|
+
}
|
|
371
|
+
else
|
|
372
|
+
setCap('');
|
|
373
|
+
}, [b.balances]);
|
|
374
|
+
useEffect(() => {
|
|
375
|
+
const rule = b.balances?.auto_topups.find((r) => r.feature_id === selectedFeature);
|
|
376
|
+
setAuto(rule?.auto ?? false);
|
|
377
|
+
setThreshold(String(rule?.threshold ?? 10));
|
|
378
|
+
setMonthlyMax(String(rule?.max_per_month ?? 1));
|
|
379
|
+
if (rule)
|
|
380
|
+
setProduct(rule.product);
|
|
381
|
+
}, [b.balances, selectedFeature]);
|
|
382
|
+
const cls = ['bk-panel', props.className].filter(Boolean).join(' ');
|
|
383
|
+
if (b.booting)
|
|
384
|
+
return h('div', { className: cls, 'aria-busy': true }, 'Loading billing…');
|
|
385
|
+
if (!b.status)
|
|
386
|
+
return h('div', { className: cls, role: 'alert' }, b.error ?? 'Billing unavailable.');
|
|
387
|
+
const model = billingCardModel(b.status, props.locale);
|
|
388
|
+
const canManage = b.status.viewer_can_manage !== false;
|
|
389
|
+
const canPurchase = canManage && !b.status.exempt && !b.status.covered_by_account_id;
|
|
390
|
+
const canChange = canManage && b.status.can_manage && !!selectedSub;
|
|
391
|
+
const selector = selectedSub ? { subscription_id: selectedSub.id, when } : { when };
|
|
392
|
+
const seats = Number(quantity || selectedSub?.quantity || 1);
|
|
393
|
+
const validSeats = Number.isSafeInteger(seats) && seats > 0;
|
|
394
|
+
const button = (label, onClick, disabled = false) => h('button', { type: 'button', disabled: b.busy || disabled, onClick: () => void onClick() }, label);
|
|
395
|
+
const input = (label, value, change, type = 'text', extra = {}) => h('label', null, label, h('input', { type, value, disabled: b.busy, onChange: (event) => change(event.target.value), ...extra }));
|
|
396
|
+
const option = (value, label = value) => h('option', { key: value, value }, label);
|
|
397
|
+
const selectedPack = packs.find((p) => p.plan === selectedProduct);
|
|
398
|
+
const validPack = !!selectedPack && Number.isSafeInteger(Number(packQuantity)) && Number(packQuantity) > 0;
|
|
399
|
+
const selectedCurrency = capCurrency.trim().toLowerCase();
|
|
400
|
+
let capMinor = NaN;
|
|
401
|
+
try {
|
|
402
|
+
capMinor = Math.round(Number(cap) * 10 ** currencyDigits(selectedCurrency));
|
|
403
|
+
}
|
|
404
|
+
catch { /* disabled until valid */ }
|
|
405
|
+
return h('section', { className: cls, 'aria-busy': b.busy || b.loading }, h('h2', null, model.title), ...model.lines.map((line, i) => h('p', { key: i }, line)), b.error ? h('p', { role: 'alert', className: 'bk-error' }, b.error) : null, b.message ? h('p', { role: 'status' }, b.message) : null, model.showManage ? button('Manage billing', b.openPortal) : null, model.showAutoRenew ? h('label', null, h('input', { type: 'checkbox', checked: b.status.auto_renew, disabled: b.busy, onChange: (event) => void b.setAutoRenew(event.target.checked) }), ' Auto-renew') : null, canChange && subscriptions.length > 1 ? h('label', null, 'Subscription', h('select', { value: selectedSub?.id, disabled: b.busy, onChange: (event) => { setSubscriptionId(event.target.value); setPlan(''); setQuantity(''); setPreview(null); } }, ...subscriptions.map((s) => option(s.id, `${s.plan ?? 'Subscription'} × ${s.quantity}`)))) : null, canChange || canPurchase ? h('fieldset', { disabled: b.busy }, h('legend', null, 'Plan'), h('label', null, 'Choose a plan', h('select', { value: selectedPlan, onChange: (event) => { setPlan(event.target.value); setPreview(null); setDiscount(null); } }, option('', 'Select a plan'), ...b.plans.filter((p) => p.kind === 'subscription' || p.kind === 'lifetime').map((p) => option(p.plan, `${p.plan}${p.price?.unit_amount != null ? ` — ${money(p.price.unit_amount, p.price.currency, props.locale)}${p.price.interval ? ` / ${p.price.interval}` : ''}` : ''}`)))), canChange ? h(Fragment, null, h('label', null, 'When', h('select', { value: when, onChange: (event) => { setWhen(event.target.value); setPreview(null); } }, option('now', 'Now'), option('period_end', 'At renewal'))), button('Preview plan change', async () => { const result = await b.previewPlan(selectedPlan, selector); if (result)
|
|
406
|
+
setPreview(result); }, !selectedPlan || selectedPlan === selectedSub?.plan), input('Seats', quantity || String(selectedSub?.quantity ?? 1), (value) => { setQuantity(value); setPreview(null); }, 'number', { min: 1, step: 1 }), button('Preview seat change', async () => { const result = await b.previewQuantity(seats, selector); if (result)
|
|
407
|
+
setPreview(result); }, !validSeats || seats === selectedSub?.quantity)) : h(Fragment, null, !props.invoiceBilling ? input('Discount code', code, (value) => { setCode(value); setDiscount(null); }) : null, !props.invoiceBilling ? button('Check code', async () => { const result = await b.checkDiscount(code, selectedPlan); if (result)
|
|
408
|
+
setDiscount(result); }, !code.trim() || !selectedPlan) : null, !props.invoiceBilling && discount ? h('p', { role: 'status' }, discount.valid ? discount.discount.label : `Code unavailable: ${discount.reason.replaceAll('_', ' ')}`) : null, props.invoiceBilling
|
|
409
|
+
? h(Fragment, null, input('Billing country (two-letter code)', invoiceCountry, setInvoiceCountry, 'text', { maxLength: 2, autoComplete: 'country' }), input('Street address', invoiceStreet, setInvoiceStreet, 'text', { autoComplete: 'address-line1' }), input('City', invoiceCity, setInvoiceCity, 'text', { autoComplete: 'address-level2' }), input('State or region', invoiceState, setInvoiceState, 'text', { autoComplete: 'address-level1' }), input('Postal code', invoicePostal, setInvoicePostal, 'text', { autoComplete: 'postal-code' }), button('Request invoice', () => b.requestInvoice(selectedPlan, 1, { country: invoiceCountry.toUpperCase(), line1: invoiceStreet, city: invoiceCity, state: invoiceState, postal_code: invoicePostal }), !selectedPlan || !/^[A-Za-z]{2}$/.test(invoiceCountry)))
|
|
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
|
+
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
|
+
}
|
package/dist/types.d.ts
CHANGED
|
@@ -196,7 +196,7 @@ export interface UsageSettingsInput {
|
|
|
196
196
|
export interface UsageEvent {
|
|
197
197
|
id: string;
|
|
198
198
|
/** 0.6 usage events, and (since 0.7.0, only the types the app chose in event_types) lifecycle events. */
|
|
199
|
-
type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed';
|
|
199
|
+
type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed' | 'invoice.payment_action_required';
|
|
200
200
|
created: string;
|
|
201
201
|
app_id: string;
|
|
202
202
|
account_id: string;
|
|
@@ -206,6 +206,8 @@ export interface UsageEvent {
|
|
|
206
206
|
export type BillingEvent = EntitlementChangedEvent | UsageEvent;
|
|
207
207
|
/** POST /v1/subscriptions/change (since 0.7.0): what happened to the plan. */
|
|
208
208
|
export interface PlanChange {
|
|
209
|
+
quantity?: number;
|
|
210
|
+
from_quantity?: number;
|
|
209
211
|
status: 'applied' | 'scheduled' | 'requires_action';
|
|
210
212
|
plan: string;
|
|
211
213
|
from_plan: string | null;
|
|
@@ -217,6 +219,8 @@ export interface PlanChange {
|
|
|
217
219
|
}
|
|
218
220
|
/** POST /v1/subscriptions/change/preview (since 0.7.0). Amounts in minor units. */
|
|
219
221
|
export interface ChangePreview {
|
|
222
|
+
quantity?: number;
|
|
223
|
+
from_quantity?: number;
|
|
220
224
|
plan: string;
|
|
221
225
|
from_plan: string | null;
|
|
222
226
|
direction: 'upgrade' | 'downgrade' | 'interval';
|
|
@@ -319,6 +323,16 @@ export interface EntitlementResult extends Entitlement {
|
|
|
319
323
|
error?: string;
|
|
320
324
|
}
|
|
321
325
|
export interface SubscriptionView {
|
|
326
|
+
scheduled_change?: {
|
|
327
|
+
plan: string;
|
|
328
|
+
quantity: number;
|
|
329
|
+
effective_at: string;
|
|
330
|
+
};
|
|
331
|
+
invoice?: {
|
|
332
|
+
id: string;
|
|
333
|
+
due_at: string | null;
|
|
334
|
+
hosted_invoice_url: string | null;
|
|
335
|
+
};
|
|
322
336
|
id: string;
|
|
323
337
|
plan: string | null;
|
|
324
338
|
quantity: number;
|
|
@@ -439,7 +453,7 @@ export interface EntitlementChangedEvent {
|
|
|
439
453
|
/** Error codes the API returns (stable; branch on these, not on messages). */
|
|
440
454
|
export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
|
|
441
455
|
/** 0.7 security: the service is locked down (only the owner key works). */
|
|
442
|
-
| 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | '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' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
|
|
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'
|
|
443
457
|
/** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
|
|
444
458
|
| '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'
|
|
445
459
|
/** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Pluggable usage delivery storage. Store operations must be durable before resolving. */
|
|
2
|
+
export interface UsageRecord {
|
|
3
|
+
scope: string;
|
|
4
|
+
id: string;
|
|
5
|
+
body: Record<string, unknown>;
|
|
6
|
+
attempts: number;
|
|
7
|
+
createdAt: number;
|
|
8
|
+
status: 'pending' | 'rejected';
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface UsageStatus {
|
|
12
|
+
pending: number;
|
|
13
|
+
rejected: number;
|
|
14
|
+
oldestPendingAt: number | null;
|
|
15
|
+
}
|
|
16
|
+
export interface UsageStore {
|
|
17
|
+
put(record: UsageRecord): Promise<void>;
|
|
18
|
+
remove(scope: string, id: string): Promise<void>;
|
|
19
|
+
list(scope: string, status: UsageRecord['status'], limit: number): Promise<UsageRecord[]>;
|
|
20
|
+
status(scope: string): Promise<UsageStatus>;
|
|
21
|
+
}
|
|
22
|
+
/** Process-local default. A persistent implementation can be shared by successive SDK instances. */
|
|
23
|
+
export declare function memoryUsageStore(maxRejected?: number): UsageStore;
|
|
24
|
+
/** Apply this schema in the consuming app's database before using d1UsageStore. */
|
|
25
|
+
export declare const USAGE_QUEUE_SCHEMA = "CREATE TABLE IF NOT EXISTS billing_usage_queue (\n scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL,\n created_at INTEGER NOT NULL, status TEXT NOT NULL, error TEXT, PRIMARY KEY (scope, id)\n);\nCREATE INDEX IF NOT EXISTS billing_usage_pending ON billing_usage_queue (scope, status, created_at, id);";
|
|
26
|
+
export interface UsageDatabase {
|
|
27
|
+
prepare(sql: string): {
|
|
28
|
+
bind(...args: (string | number | null)[]): {
|
|
29
|
+
run(): Promise<unknown>;
|
|
30
|
+
all<T>(): Promise<{
|
|
31
|
+
results: T[];
|
|
32
|
+
}>;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Cloudflare D1 adapter, without importing a platform package. Event keys survive process restarts. */
|
|
37
|
+
export declare function d1UsageStore(db: UsageDatabase): UsageStore;
|
|
38
|
+
/** A per-event failure inside a successful HTTP batch response. */
|
|
39
|
+
export declare function usageOutcome(result: unknown): 'sent' | 'retry' | 'rejected';
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Process-local default. A persistent implementation can be shared by successive SDK instances. */
|
|
2
|
+
export function memoryUsageStore(maxRejected = 1000) {
|
|
3
|
+
const rows = new Map();
|
|
4
|
+
const key = (scope, id) => JSON.stringify([scope, id]);
|
|
5
|
+
return {
|
|
6
|
+
async put(row) {
|
|
7
|
+
rows.set(key(row.scope, row.id), structuredClone(row));
|
|
8
|
+
const rejected = [...rows.values()].filter((r) => r.scope === row.scope && r.status === 'rejected');
|
|
9
|
+
for (const r of rejected.slice(0, Math.max(0, rejected.length - maxRejected)))
|
|
10
|
+
rows.delete(key(r.scope, r.id));
|
|
11
|
+
},
|
|
12
|
+
async remove(scope, id) { rows.delete(key(scope, id)); },
|
|
13
|
+
async list(scope, status, limit) {
|
|
14
|
+
return structuredClone([...rows.values()].filter((r) => r.scope === scope && r.status === status)
|
|
15
|
+
.sort((a, b) => a.createdAt - b.createdAt).slice(0, limit));
|
|
16
|
+
},
|
|
17
|
+
async status(scope) {
|
|
18
|
+
const all = [...rows.values()].filter((r) => r.scope === scope);
|
|
19
|
+
const pending = all.filter((r) => r.status === 'pending');
|
|
20
|
+
return { pending: pending.length, rejected: all.length - pending.length, oldestPendingAt: pending.length ? Math.min(...pending.map((r) => r.createdAt)) : null };
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Apply this schema in the consuming app's database before using d1UsageStore. */
|
|
25
|
+
export const USAGE_QUEUE_SCHEMA = `CREATE TABLE IF NOT EXISTS billing_usage_queue (
|
|
26
|
+
scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL,
|
|
27
|
+
created_at INTEGER NOT NULL, status TEXT NOT NULL, error TEXT, PRIMARY KEY (scope, id)
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS billing_usage_pending ON billing_usage_queue (scope, status, created_at, id);`;
|
|
30
|
+
/** Cloudflare D1 adapter, without importing a platform package. Event keys survive process restarts. */
|
|
31
|
+
export function d1UsageStore(db) {
|
|
32
|
+
return {
|
|
33
|
+
async put(r) {
|
|
34
|
+
await db.prepare(`INSERT INTO billing_usage_queue (scope,id,body,attempts,created_at,status,error) VALUES (?,?,?,?,?,?,?)
|
|
35
|
+
ON CONFLICT(scope,id) DO UPDATE SET body=excluded.body,attempts=excluded.attempts,status=excluded.status,error=excluded.error`)
|
|
36
|
+
.bind(r.scope, r.id, JSON.stringify(r.body), r.attempts, r.createdAt, r.status, r.error ?? null).run();
|
|
37
|
+
},
|
|
38
|
+
async remove(scope, id) { await db.prepare('DELETE FROM billing_usage_queue WHERE scope=? AND id=?').bind(scope, id).run(); },
|
|
39
|
+
async list(scope, status, limit) {
|
|
40
|
+
const r = await db.prepare('SELECT * FROM billing_usage_queue WHERE scope=? AND status=? ORDER BY created_at,id LIMIT ?').bind(scope, status, limit)
|
|
41
|
+
.all();
|
|
42
|
+
return r.results.map((x) => ({ scope: x.scope, id: x.id, body: JSON.parse(x.body), attempts: x.attempts, createdAt: x.created_at, status: x.status, ...(x.error ? { error: x.error } : {}) }));
|
|
43
|
+
},
|
|
44
|
+
async status(scope) {
|
|
45
|
+
const r = await db.prepare(`SELECT SUM(status='pending') AS pending,SUM(status='rejected') AS rejected,
|
|
46
|
+
MIN(CASE WHEN status='pending' THEN created_at END) AS oldestPendingAt FROM billing_usage_queue WHERE scope=?`).bind(scope)
|
|
47
|
+
.all();
|
|
48
|
+
const row = r.results[0];
|
|
49
|
+
return { pending: row?.pending ?? 0, rejected: row?.rejected ?? 0, oldestPendingAt: row?.oldestPendingAt ?? null };
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** A per-event failure inside a successful HTTP batch response. */
|
|
54
|
+
export function usageOutcome(result) {
|
|
55
|
+
if (!result || typeof result !== 'object')
|
|
56
|
+
return 'retry';
|
|
57
|
+
const r = result;
|
|
58
|
+
if (r.applied === true || r.replayed === true)
|
|
59
|
+
return 'sent';
|
|
60
|
+
if (typeof r.error === 'string')
|
|
61
|
+
return ['internal', 'storage_unavailable', 'stripe_error', 'network_error', 'timeout', 'rate_limited', 'service_locked_down', 'app_disabled'].includes(r.error) ? 'retry' : 'rejected';
|
|
62
|
+
if (r.allowed === false)
|
|
63
|
+
return 'rejected';
|
|
64
|
+
return 'retry';
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hjam91/billing",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.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",
|
|
@@ -48,7 +48,12 @@
|
|
|
48
48
|
"import": "./dist/config.js",
|
|
49
49
|
"default": "./dist/config.js"
|
|
50
50
|
},
|
|
51
|
-
"./package.json": "./package.json"
|
|
51
|
+
"./package.json": "./package.json",
|
|
52
|
+
"./usage": {
|
|
53
|
+
"types": "./dist/usage.d.ts",
|
|
54
|
+
"import": "./dist/usage.js",
|
|
55
|
+
"default": "./dist/usage.js"
|
|
56
|
+
}
|
|
52
57
|
},
|
|
53
58
|
"bin": {
|
|
54
59
|
"billing-cli": "dist/cli.mjs"
|