@hjam91/billing 0.7.1 → 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/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 usageBuffer = [];
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 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}`);
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
- 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);
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);
273
+ }
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);
258
278
  }
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`);
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
- return { sent, dropped, pending: usageBuffer.length };
272
- })().finally(() => {
273
- flushing = null;
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 (!usageBuffer.length || flushing)
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: true };
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 (${usageBuffer.length} waiting)`, err);
352
- return { ...unverifiedCheck(accountId, featureId, true, 'fail_open', code), value, applied: false, replayed: false, event_id: null, queued: true };
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);
@@ -397,6 +461,8 @@ export function createBilling(opts) {
397
461
  email: p.email,
398
462
  covers: p.covers,
399
463
  promotion_code: p.promotionCode,
464
+ discount_code: p.discountCode,
465
+ offer_id: p.offerId,
400
466
  customer_name: p.customerName,
401
467
  });
402
468
  return {
@@ -434,6 +500,26 @@ export function createBilling(opts) {
434
500
  return r;
435
501
  },
436
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
+ },
437
523
  async attachAddOn(accountId, plan, o = {}) {
438
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 } : {}) });
439
525
  await cache.delete(key(accountId)).catch(() => undefined);
@@ -445,6 +531,18 @@ export function createBilling(opts) {
445
531
  return r;
446
532
  },
447
533
  plans: () => call('GET', '/v1/plans'),
534
+ checkDiscount: (accountId, code, o = {}) => call('POST', '/v1/discounts/check', { account_id: accountId, code, ...(o.plan ? { plan: o.plan } : {}) }),
535
+ async offers(accountId) {
536
+ const r = await call('GET', `/v1/accounts/${enc(accountId)}/offers`);
537
+ if (!Array.isArray(r.offers))
538
+ throw new BillingError(502, 'invalid_response', 'Billing service returned an invalid offer list');
539
+ return r.offers;
540
+ },
541
+ async acceptOffer(accountId, offerId) {
542
+ const s = await call('POST', `/v1/accounts/${enc(accountId)}/offers/${enc(offerId)}/accept`, {});
543
+ await cache.set(key(accountId), { value: { account_id: accountId, ...s.entitlement }, fetchedAt: now() }).catch(() => undefined);
544
+ return s;
545
+ },
448
546
  async setUsageSettings(accountId, st) {
449
547
  const body = {};
450
548
  if (st.spendCap !== 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
+ }