@hjam91/billing 0.8.0 → 0.10.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/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";
@@ -58,6 +60,7 @@ export const BATCH_LIMIT = 200;
58
60
  const changeBody = (accountId, plan, o = {}) => ({
59
61
  account_id: accountId,
60
62
  plan,
63
+ ...(o.quantity !== undefined ? { quantity: o.quantity } : {}),
61
64
  ...(o.when ? { when: o.when } : {}),
62
65
  ...(o.proration ? { proration: o.proration } : {}),
63
66
  ...(o.prorationDate !== undefined ? { proration_date: o.prorationDate } : {}),
@@ -197,7 +200,8 @@ export function createBilling(opts) {
197
200
  // ---------------------------------------------------------------- features (0.5.0)
198
201
  const bufferSize = opts.usageBufferSize ?? 1000;
199
202
  const maxAttempts = opts.usageMaxAttempts ?? 5;
200
- const usageBuffer = [];
203
+ const usageStore = opts.usageStore ?? memoryUsageStore();
204
+ const usageScope = JSON.stringify([base, opts.appId]);
201
205
  let flushing = null;
202
206
  const randomKey = () => `sdk-${globalThis.crypto?.randomUUID?.() ?? `${now()}-${Math.random().toString(36).slice(2)}`}`;
203
207
  const unverifiedCheck = (accountId, featureId, allowed, source, error) => ({
@@ -228,55 +232,86 @@ export function createBilling(opts) {
228
232
  const e = err;
229
233
  (isOutage(e) ? log.warn : log.error).call(log, `[billing] ${what} (${e?.code ?? 'error'}: ${e?.message ?? err})`);
230
234
  }
231
- function enqueue(body) {
232
- usageBuffer.push({ body, attempts: 1 });
233
- while (usageBuffer.length > bufferSize) {
234
- const lost = usageBuffer.shift();
235
- log.error(`[billing] usage buffer full (${bufferSize}): dropped ${lost.body.feature_id} for ${lost.body.account_id}`);
235
+ async function rejectUsage(row, error) {
236
+ await usageStore.put({ ...row, status: 'rejected', error });
237
+ log.error(`[billing] usage rejected: ${row.body.feature_id} for ${row.body.account_id} (${error})`);
238
+ }
239
+ async function enqueue(body, existing) {
240
+ const row = existing ?? { scope: usageScope, id: randomKey(), body, attempts: 1, createdAt: now(), status: 'pending' };
241
+ try {
242
+ await usageStore.put(row);
243
+ const pending = await usageStore.list(usageScope, 'pending', bufferSize + 1);
244
+ for (const old of pending.slice(0, Math.max(0, pending.length - bufferSize))) {
245
+ await rejectUsage(old, `usage buffer full (${bufferSize})`);
246
+ if (old.id === row.id)
247
+ return null;
248
+ }
249
+ return row;
250
+ }
251
+ catch (err) {
252
+ reportUsage('could not persist usage for retry', err);
253
+ return null;
236
254
  }
237
255
  }
238
256
  async function flushUsage() {
239
257
  if (flushing)
240
258
  return flushing;
241
259
  flushing = (async () => {
242
- let sent = 0;
243
- let dropped = 0;
244
- while (usageBuffer.length) {
245
- const chunk = usageBuffer.slice(0, 1000);
246
- try {
247
- await call('POST', '/v1/track/batch', { events: chunk.map((x) => x.body) });
248
- usageBuffer.splice(0, chunk.length);
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);
260
+ let sent = 0, dropped = 0, pending = 0;
261
+ try {
262
+ // Each record is attempted at most once per flush, including when a response is ambiguous.
263
+ const seen = new Set();
264
+ while (true) {
265
+ const chunk = (await usageStore.list(usageScope, 'pending', 1000)).filter((r) => !seen.has(r.id));
266
+ if (!chunk.length)
257
267
  break;
268
+ for (const row of chunk)
269
+ seen.add(row.id);
270
+ let results;
271
+ try {
272
+ const answer = await call('POST', '/v1/track/batch', { events: chunk.map((x) => x.body) });
273
+ results = Array.isArray(answer.results) && answer.results.length === chunk.length ? answer.results : chunk.map(() => null);
258
274
  }
259
- for (const x of chunk)
260
- x.attempts++;
261
- const dead = usageBuffer.filter((x) => x.attempts >= maxAttempts);
262
- if (dead.length) {
263
- for (const x of dead)
264
- usageBuffer.splice(usageBuffer.indexOf(x), 1);
265
- dropped += dead.length;
266
- log.error(`[billing] dropped ${dead.length} usage event(s) after ${maxAttempts} attempts (${err?.code ?? 'error'}): usage is never fatal, but it is lost`);
275
+ catch (err) {
276
+ const retry = killSignal(err) ? !killDeny : isOutage(err);
277
+ results = chunk.map(() => ({ error: retry ? 'storage_unavailable' : 'delivery_refused' }));
278
+ reportUsage('buffered usage delivery failed', err);
279
+ }
280
+ for (const [i, row] of chunk.entries()) {
281
+ const result = results[i];
282
+ const outcome = usageOutcome(result);
283
+ if (outcome === 'sent') {
284
+ await usageStore.remove(usageScope, row.id);
285
+ sent++;
286
+ }
287
+ else {
288
+ const updated = { ...row, attempts: row.attempts + 1 };
289
+ const error = String(result?.error ?? result?.reason ?? 'invalid_response');
290
+ if (outcome === 'rejected' || updated.attempts >= maxAttempts) {
291
+ await rejectUsage(updated, outcome === 'rejected' ? error : `${error} after ${maxAttempts} attempts`);
292
+ dropped++;
293
+ }
294
+ else
295
+ await usageStore.put({ ...updated, error });
296
+ }
267
297
  }
268
- break;
269
298
  }
270
299
  }
271
- return { sent, dropped, pending: usageBuffer.length };
272
- })().finally(() => {
273
- flushing = null;
274
- });
300
+ catch (err) {
301
+ reportUsage('usage queue storage failed; unacknowledged records remain retryable', err);
302
+ }
303
+ try {
304
+ pending = (await usageStore.status(usageScope)).pending;
305
+ }
306
+ catch (err) {
307
+ reportUsage('usage queue status unavailable', err);
308
+ }
309
+ return { sent, dropped, pending };
310
+ })().finally(() => { flushing = null; });
275
311
  return flushing;
276
312
  }
277
- /** Sends what is buffered behind a successful call (the service is evidently up). */
278
313
  const flushBehind = (waitUntil) => {
279
- if (!usageBuffer.length || flushing)
314
+ if (flushing)
280
315
  return;
281
316
  const p = flushUsage().catch(() => undefined);
282
317
  (waitUntil ?? opts.waitUntil)?.(p);
@@ -329,8 +364,23 @@ export function createBilling(opts) {
329
364
  ...(o.properties ? { properties: o.properties } : {}),
330
365
  ...(o.checkAndTrack ? { check_and_track: true } : {}),
331
366
  };
367
+ const initial = opts.usageStore ? { scope: usageScope, id: randomKey(), body, attempts: 0, createdAt: now(), status: 'pending' } : undefined;
368
+ const persisted = initial ? await enqueue(body, initial) : null;
332
369
  try {
333
370
  const r = await call('POST', '/v1/track', body);
371
+ if (usageOutcome(r) === 'retry')
372
+ throw new BillingError(502, 'invalid_response', 'Billing service did not acknowledge the usage event');
373
+ if (persisted) {
374
+ try {
375
+ if (usageOutcome(r) === 'rejected')
376
+ await rejectUsage(persisted, r.reason ?? 'refused');
377
+ else if (usageOutcome(r) === 'sent')
378
+ await usageStore.remove(usageScope, persisted.id);
379
+ }
380
+ catch (error) {
381
+ reportUsage('usage acknowledgment could not be persisted; original key retained', error);
382
+ }
383
+ }
334
384
  flushBehind(o.waitUntil);
335
385
  return { ...r, source: 'live' };
336
386
  }
@@ -339,17 +389,19 @@ export function createBilling(opts) {
339
389
  const kill = killSignal(err);
340
390
  if (kill && !killDeny) {
341
391
  // Kill switch, fail_open: the usage is kept for a retry once the app is re-enabled (bounded buffer).
342
- enqueue(body);
392
+ const queued = !!(await enqueue(body, persisted ? { ...persisted, attempts: 1 } : undefined));
343
393
  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: true };
394
+ return { ...unverifiedCheck(accountId, featureId, failOpen, failOpen ? 'fail_open' : 'error', code), value, applied: false, replayed: false, event_id: null, queued };
345
395
  }
346
396
  if (kill || !isOutage(err)) {
397
+ if (persisted)
398
+ await rejectUsage(persisted, code).catch((e) => reportUsage('usage rejection could not be persisted', e));
347
399
  reportUsage(`track ${featureId} for ${accountId} refused`, err);
348
400
  return { ...unverifiedCheck(accountId, featureId, false, 'error', code), value, applied: false, replayed: false, event_id: null };
349
401
  }
350
- enqueue(body);
351
- reportUsage(`track ${featureId} for ${accountId} queued for a retry (${usageBuffer.length} waiting)`, err);
352
- return { ...unverifiedCheck(accountId, featureId, true, 'fail_open', code), value, applied: false, replayed: false, event_id: null, queued: true };
402
+ const queued = !!(await enqueue(body, persisted ? { ...persisted, attempts: 1 } : undefined));
403
+ reportUsage(`track ${featureId} for ${accountId} ${queued ? 'queued for a retry' : 'could not be queued'}`, err);
404
+ return { ...unverifiedCheck(accountId, featureId, true, 'fail_open', code), value, applied: false, replayed: false, event_id: null, queued };
353
405
  }
354
406
  },
355
407
  async setUsage(accountId, featureId, value) {
@@ -357,6 +409,19 @@ export function createBilling(opts) {
357
409
  return { ...r, source: 'live' };
358
410
  },
359
411
  flushUsage,
412
+ usageStatus: () => usageStore.status(usageScope),
413
+ rejectedUsage: (limit = 100) => usageStore.list(usageScope, 'rejected', Math.max(1, Math.min(1000, limit))),
414
+ async retryUsage(ids) {
415
+ const selected = new Set(ids);
416
+ const records = await usageStore.list(usageScope, 'rejected', 1000);
417
+ let retried = 0;
418
+ for (const row of records)
419
+ if (selected.has(row.id)) {
420
+ if (await enqueue(row.body, { ...row, status: 'pending', attempts: 0, error: undefined }))
421
+ retried++;
422
+ }
423
+ return retried;
424
+ },
360
425
  async getEntitlement(accountId, callOpts = {}) {
361
426
  const entry = await cache.get(key(accountId)).catch((e) => {
362
427
  log.warn('[billing] cache read failed', e);
@@ -436,6 +501,29 @@ export function createBilling(opts) {
436
501
  return r;
437
502
  },
438
503
  previewChange: (accountId, plan, o) => call('POST', '/v1/subscriptions/change/preview', changeBody(accountId, plan, o)),
504
+ async setQuantity(accountId, quantity, o = {}) {
505
+ return self.changeQuantity(accountId, quantity, o);
506
+ },
507
+ async changeQuantity(accountId, quantity, o = {}) {
508
+ const { plan: _plan, ...body } = changeBody(accountId, '', o);
509
+ const result = await call('POST', '/v1/subscriptions/quantity', { ...body, quantity });
510
+ await self.invalidate(accountId).catch(() => undefined);
511
+ return result;
512
+ },
513
+ previewQuantity(accountId, quantity, o = {}) {
514
+ const { plan: _plan, ...body } = changeBody(accountId, '', o);
515
+ return call('POST', '/v1/subscriptions/quantity/preview', { ...body, quantity });
516
+ },
517
+ async cancelScheduledChange(accountId, select = {}) {
518
+ const result = await call('DELETE', '/v1/subscriptions/schedule', { account_id: accountId, ...selectorBody(select) });
519
+ await self.invalidate(accountId).catch(() => undefined);
520
+ return result;
521
+ },
522
+ async invoiceSubscription(accountId, plan, o = {}) {
523
+ 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 });
524
+ await self.invalidate(accountId).catch(() => undefined);
525
+ return result;
526
+ },
439
527
  async attachAddOn(accountId, plan, o = {}) {
440
528
  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
529
  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 ?? ((input, init) => fetch(input, { credentials: 'same-origin', ...init }));
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
- }, []); // load once on mount
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
+ }