@fantastic.dev/better-stripe 0.60.1 → 0.62.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.
Files changed (95) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +5 -1
  3. package/dist/client/usage/index.d.ts +2 -0
  4. package/dist/client/usage/index.d.ts.map +1 -1
  5. package/dist/react/index.d.ts +17 -0
  6. package/dist/react/index.d.ts.map +1 -1
  7. package/dist/react/index.js +10 -0
  8. package/dist/react/index.js.map +1 -1
  9. package/dist/react/workflows/Pagination.d.ts +1 -0
  10. package/dist/react/workflows/Pagination.d.ts.map +1 -1
  11. package/dist/react/workflows/Pagination.js +1 -0
  12. package/dist/react/workflows/Pagination.js.map +1 -1
  13. package/dist/react/workflows/Usage.fixtures.d.ts +17 -0
  14. package/dist/react/workflows/Usage.fixtures.d.ts.map +1 -0
  15. package/dist/react/workflows/Usage.fixtures.js +79 -0
  16. package/dist/react/workflows/Usage.fixtures.js.map +1 -0
  17. package/dist/react/workflows/Usage.types.d.ts +25 -0
  18. package/dist/react/workflows/Usage.types.d.ts.map +1 -0
  19. package/dist/react/workflows/Usage.types.js +11 -0
  20. package/dist/react/workflows/Usage.types.js.map +1 -0
  21. package/dist/react/workflows/UsageAllowance.d.ts +14 -0
  22. package/dist/react/workflows/UsageAllowance.d.ts.map +1 -0
  23. package/dist/react/workflows/UsageAllowance.js +21 -0
  24. package/dist/react/workflows/UsageAllowance.js.map +1 -0
  25. package/dist/react/workflows/UsageBilling.d.ts +20 -0
  26. package/dist/react/workflows/UsageBilling.d.ts.map +1 -0
  27. package/dist/react/workflows/UsageBilling.js +40 -0
  28. package/dist/react/workflows/UsageBilling.js.map +1 -0
  29. package/dist/react/workflows/UsageConfiguration.d.ts +4 -0
  30. package/dist/react/workflows/UsageConfiguration.d.ts.map +1 -0
  31. package/dist/react/workflows/UsageConfiguration.js +19 -0
  32. package/dist/react/workflows/UsageConfiguration.js.map +1 -0
  33. package/dist/react/workflows/UsageConfiguration.types.d.ts +65 -0
  34. package/dist/react/workflows/UsageConfiguration.types.d.ts.map +1 -0
  35. package/dist/react/workflows/UsageConfiguration.types.js +2 -0
  36. package/dist/react/workflows/UsageConfiguration.types.js.map +1 -0
  37. package/dist/react/workflows/UsageCredits.d.ts +14 -0
  38. package/dist/react/workflows/UsageCredits.d.ts.map +1 -0
  39. package/dist/react/workflows/UsageCredits.js +25 -0
  40. package/dist/react/workflows/UsageCredits.js.map +1 -0
  41. package/dist/react/workflows/UsageHistory.d.ts +40 -0
  42. package/dist/react/workflows/UsageHistory.d.ts.map +1 -0
  43. package/dist/react/workflows/UsageHistory.js +74 -0
  44. package/dist/react/workflows/UsageHistory.js.map +1 -0
  45. package/dist/react/workflows/UsagePriceRow.d.ts +26 -0
  46. package/dist/react/workflows/UsagePriceRow.d.ts.map +1 -0
  47. package/dist/react/workflows/UsagePriceRow.js +40 -0
  48. package/dist/react/workflows/UsagePriceRow.js.map +1 -0
  49. package/dist/react/workflows/UsageSummary.d.ts +19 -0
  50. package/dist/react/workflows/UsageSummary.d.ts.map +1 -0
  51. package/dist/react/workflows/UsageSummary.js +54 -0
  52. package/dist/react/workflows/UsageSummary.js.map +1 -0
  53. package/dist/react/workflows/usage-configuration-validation.d.ts +4 -0
  54. package/dist/react/workflows/usage-configuration-validation.d.ts.map +1 -0
  55. package/dist/react/workflows/usage-configuration-validation.js +116 -0
  56. package/dist/react/workflows/usage-configuration-validation.js.map +1 -0
  57. package/dist/react/workflows/usage-format.d.ts +11 -0
  58. package/dist/react/workflows/usage-format.d.ts.map +1 -0
  59. package/dist/react/workflows/usage-format.js +43 -0
  60. package/dist/react/workflows/usage-format.js.map +1 -0
  61. package/dist/react/workflows/usage-scope.d.ts +5 -0
  62. package/dist/react/workflows/usage-scope.d.ts.map +1 -0
  63. package/dist/react/workflows/usage-scope.js +26 -0
  64. package/dist/react/workflows/usage-scope.js.map +1 -0
  65. package/dist/react/workflows/useUsageConfiguration.d.ts +4 -0
  66. package/dist/react/workflows/useUsageConfiguration.d.ts.map +1 -0
  67. package/dist/react/workflows/useUsageConfiguration.js +84 -0
  68. package/dist/react/workflows/useUsageConfiguration.js.map +1 -0
  69. package/docs/README.md +4 -0
  70. package/docs/react-api.md +6 -0
  71. package/docs/usage-configuration.md +150 -0
  72. package/docs/usage-react.md +182 -0
  73. package/package.json +4 -2
  74. package/src/client/usage/index.ts +3 -0
  75. package/src/react/index.ts +36 -0
  76. package/src/react/workflows/Pagination.tsx +2 -0
  77. package/src/react/workflows/Usage.fixtures.ts +88 -0
  78. package/src/react/workflows/Usage.test.tsx +373 -0
  79. package/src/react/workflows/Usage.types.ts +39 -0
  80. package/src/react/workflows/UsageAllowance.tsx +114 -0
  81. package/src/react/workflows/UsageBilling.tsx +90 -0
  82. package/src/react/workflows/UsageConfiguration.test.tsx +393 -0
  83. package/src/react/workflows/UsageConfiguration.tsx +135 -0
  84. package/src/react/workflows/UsageConfiguration.types.ts +67 -0
  85. package/src/react/workflows/UsageCredits.tsx +112 -0
  86. package/src/react/workflows/UsageHistory.test.tsx +206 -0
  87. package/src/react/workflows/UsageHistory.tsx +154 -0
  88. package/src/react/workflows/UsagePriceRow.test.tsx +140 -0
  89. package/src/react/workflows/UsagePriceRow.tsx +109 -0
  90. package/src/react/workflows/UsageSummary.tsx +204 -0
  91. package/src/react/workflows/usage-configuration-validation.test.ts +107 -0
  92. package/src/react/workflows/usage-configuration-validation.ts +152 -0
  93. package/src/react/workflows/usage-format.ts +48 -0
  94. package/src/react/workflows/usage-scope.ts +42 -0
  95. package/src/react/workflows/useUsageConfiguration.ts +99 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage-scope.js","sourceRoot":"","sources":["../../../src/react/workflows/usage-scope.ts"],"names":[],"mappings":"AAEA,MAAM,UAAU,mBAAmB,CACjC,KAAqB,EACrB,KAAwB;IAExB,OAAO,CACL,KAAK,CAAC,MAAM,CAAC,KAAK,KAAK,KAAK,CAAC,MAAM,CAA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,CAAC,SAAS,CAAC,KAAK,CAAC,MAAM,CAAC;gBAC1C,eAAe,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC,QAAQ,CAAC;gBACjE,eAAe,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,iBAAiB,CAAC,QAAQ,CAAC,CAAC,CAAC;QACvE,CAAC,KAAK,CAAC,OAAO,EAAE,MAAM,KAAK,WAAW;YACpC,eAAe,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAC;QAChD,CAAC,CAAC,KAAK,CAAC,QAAQ,IAAI,eAAe,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAC9D,CAAC;AACJ,CAAC"}
@@ -0,0 +1,4 @@
1
+ import type { UsageConfigurationProps, UsageConfigurationState } from "./UsageConfiguration.types.js";
2
+ /** Shared form lifecycle for component and HTTP adapters. Server authorization is mandatory. */
3
+ export declare function useUsageConfiguration(props: UsageConfigurationProps): UsageConfigurationState;
4
+ //# sourceMappingURL=useUsageConfiguration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUsageConfiguration.d.ts","sourceRoot":"","sources":["../../../src/react/workflows/useUsageConfiguration.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EACV,uBAAuB,EACvB,uBAAuB,EACxB,MAAM,+BAA+B,CAAC;AACvC,gGAAgG;AAChG,wBAAgB,qBAAqB,CACnC,KAAK,EAAE,uBAAuB,GAC7B,uBAAuB,CAmFzB"}
@@ -0,0 +1,84 @@
1
+ "use client";
2
+ import { useState } from "react";
3
+ import { defineUsagePlan } from "../../client/usage/contracts.js";
4
+ import { useWorkflowAction } from "./useWorkflowAction.js";
5
+ import { configurationFields, validateConfiguration, } from "./usage-configuration-validation.js";
6
+ /** Shared form lifecycle for component and HTTP adapters. Server authorization is mandatory. */
7
+ export function useUsageConfiguration(props) {
8
+ const key = JSON.stringify([props.scope, props.initial, props.meters]);
9
+ const initial = {
10
+ key,
11
+ meterId: props.initial.meterId ?? "",
12
+ fields: configurationFields(props.initial),
13
+ };
14
+ const [state, setState] = useState(initial);
15
+ if (state.key !== key)
16
+ setState(initial);
17
+ const disabled = !props.scope.canConfigure || props.scope.capability !== "issuer_native";
18
+ const immutable = state.meterId !== "";
19
+ const action = useWorkflowAction(async () => {
20
+ if (disabled)
21
+ throw new Error("Configuration is read-only for this scope.");
22
+ let value = validateConfiguration(state.fields, state.meterId);
23
+ if (immutable) {
24
+ const meter = props.meters.find((item) => item.id === state.meterId);
25
+ if (!meter?.active ||
26
+ JSON.stringify(validateConfiguration(configurationFields(meter.configuration), meter.id)) !== JSON.stringify(value))
27
+ throw new Error("Select an active managed meter with unchanged original terms.");
28
+ // Native intent fingerprints retain the original lexical decimal snapshot.
29
+ value = {
30
+ ...value,
31
+ plan: defineUsagePlan(meter.configuration.plan),
32
+ ...(value.creditPackage
33
+ ? {
34
+ creditPackage: {
35
+ ...value.creditPackage,
36
+ quantity: meter.configuration.creditPackage?.quantity ??
37
+ value.creditPackage.quantity,
38
+ },
39
+ }
40
+ : {}),
41
+ };
42
+ }
43
+ try {
44
+ await props.onSave(value);
45
+ }
46
+ catch {
47
+ throw new Error("Configuration could not be saved. Retry the same terms or ask an administrator to reconcile the operation.");
48
+ }
49
+ return "Configuration version saved. Existing subscriptions keep their original prices.";
50
+ }, key);
51
+ return {
52
+ fields: state.fields,
53
+ meterId: state.meterId,
54
+ immutable,
55
+ disabled,
56
+ isPending: action.isPending,
57
+ error: action.error,
58
+ message: action.result,
59
+ save: action.run,
60
+ setField: (field, value) => {
61
+ if (disabled || immutable || action.isPending)
62
+ return;
63
+ action.reset();
64
+ setState((current) => ({
65
+ ...current,
66
+ fields: { ...current.fields, [field]: value },
67
+ }));
68
+ },
69
+ selectMeter: (meterId) => {
70
+ if (disabled || action.isPending)
71
+ return;
72
+ const meter = props.meters.find((item) => item.id === meterId);
73
+ if (meterId && !meter?.active)
74
+ return;
75
+ action.reset();
76
+ setState({
77
+ key,
78
+ meterId,
79
+ fields: configurationFields(meter?.configuration ?? props.initial),
80
+ });
81
+ },
82
+ };
83
+ }
84
+ //# sourceMappingURL=useUsageConfiguration.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useUsageConfiguration.js","sourceRoot":"","sources":["../../../src/react/workflows/useUsageConfiguration.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AACb,OAAO,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACjC,OAAO,EAAE,eAAe,EAAE,MAAM,iCAAiC,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAC3D,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,qCAAqC,CAAC;AAK7C,gGAAgG;AAChG,MAAM,UAAU,qBAAqB,CACnC,KAA8B;IAE9B,MAAM,GAAG,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,CAAC,KAAK,EAAE,KAAK,CAAC,OAAO,EAAE,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC;IACvE,MAAM,OAAO,GAAG;QACd,GAAG;QACH,OAAO,EAAE,KAAK,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE;QACpC,MAAM,EAAE,mBAAmB,CAAC,KAAK,CAAC,OAAO,CAAC;KAC3C,CAAC;IACF,MAAM,CAAC,KAAK,EAAE,QAAQ,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC;IAC5C,IAAI,KAAK,CAAC,GAAG,KAAK,GAAG;QAAE,QAAQ,CAAC,OAAO,CAAC,CAAC;IACzC,MAAM,QAAQ,GACZ,CAAC,KAAK,CAAC,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,KAAK,CAAC,UAAU,KAAK,eAAe,CAAC;IAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,OAAO,KAAK,EAAE,CAAC;IACvC,MAAM,MAAM,GAAG,iBAAiB,CAAC,KAAK,IAAI,EAAE;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AAK,CAAC,MAAM;QACpB,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,SAAS;QACT,QAAQ;QACR,SAAS,EAAE,MAAM,CAAC,SAAS;QAC3B,KAAK,EAAE,MAAM,CAAC,KAAK;QACnB,OAAO,EAAE,MAAM,CAAC,MAAM;QACtB,IAAI,EAAE,MAAM,CAAC,GAAG;QAChB,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE;YACzB,IAAI,QAAQ,IAAI,SAAS,IAAI,MAAM,CAAC,SAAS;gBAAE,OAAO;YACtD,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,QAAQ,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;gBACrB,GAAG,OAAO;gBACV,MAAM,EAAE,EAAE,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,EAAE,KAAK,EAAE;aAC9C,CAAC,CAAC,CAAC;QACN,CAAC;QACD,WAAW,EAAE,CAAC,OAAO,EAAE,EAAE;YACvB,IAAI,QAAQ,IAAI,MAAM,CAAC,SAAS;gBAAE,OAAO;YACzC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,EAAE,KAAK,OAAO,CAAC,CAAC;YAC/D,IAAI,OAAO,IAAI,CAAC,KAAK,EAAE,MAAM;gBAAE,OAAO;YACtC,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,QAAQ,CAAC;gBACP,GAAG;gBACH,OAAO;gBACP,MAAM,EAAE,mBAAmB,CAAC,KAAK,EAAE,aAAa,IAAI,KAAK,CAAC,OAAO,CAAC;aACnE,CAAC,CAAC;QACL,CAAC;KACF,CAAC;AACJ,CAAC"}
package/docs/README.md CHANGED
@@ -76,3 +76,7 @@ Start with the [native Stripe setup guide](metering-setup.md), then read the
76
76
  - [Native usage settlement](./usage-settlement.md) covers original paid invoices, issuer-service credit purchases and affiliate recovery.
77
77
 
78
78
  - [Metered billing authorization](./usage-security.md) covers server ownership, work deduplication, native proof limits and retained recovery liabilities.
79
+
80
+ - [Reusable metered billing UI](usage-react.md) covers all three models, render props, authenticated adapters and bounded history.
81
+
82
+ - [Native usage configuration UI](usage-configuration.md) covers reusable forms, managed meter selection, price rows and authorized adapters.
package/docs/react-api.md CHANGED
@@ -282,3 +282,9 @@ function SellerDisputes({ stripeAccountId }: { stripeAccountId: string }) {
282
282
  );
283
283
  }
284
284
  ```
285
+
286
+ ## Metered billing
287
+
288
+ See [reusable metered billing UI](usage-react.md) for `UsageBilling`, `UsageSummary`, `UsageAllowance`, `UsageCredits`, `UsageHistory` and their hooks.
289
+
290
+ See [native usage configuration UI](usage-configuration.md) for `UsageConfiguration`, `useUsageConfiguration` and `UsagePriceRow`.
@@ -0,0 +1,150 @@
1
+ # Configure native usage billing in React
2
+
3
+ `UsageConfiguration`, `useUsageConfiguration` and `UsagePriceRow` are reusable,
4
+ unstyled package UI. Both component-backed Convex actions and authenticated HTTP
5
+ adapters use the same contract. No Metronome account or credentials are required.
6
+ Read [native catalog provisioning](usage-catalog.md), [usage views](usage-react.md)
7
+ and [authorization boundaries](usage-security.md) before wiring the adapter.
8
+
9
+ ```tsx
10
+ import {
11
+ UsageConfiguration,
12
+ type UsageConfigurationValue,
13
+ } from "@fantastic.dev/better-stripe/react";
14
+
15
+ const initial: UsageConfigurationValue = {
16
+ plan: {
17
+ key: "api-calls",
18
+ version: "v1",
19
+ model: "pay_as_you_go",
20
+ unit: { name: "call", precision: 0 },
21
+ rate: { currency: "usd", unitAmountDecimal: "2" },
22
+ },
23
+ eventName: "api_calls_v1",
24
+ displayName: "API calls",
25
+ };
26
+
27
+ <UsageConfiguration
28
+ scope={authorizedConfigurationScope}
29
+ initial={initial}
30
+ meters={authorizedManagedMeters}
31
+ onSave={saveAuthorizedConfiguration}
32
+ />;
33
+ ```
34
+
35
+ `scope` contains opaque `identityKey`, `accountKey` and `productKey`, a display
36
+ `ownershipLabel`, `role: "admin" | "seller"`, `canConfigure` and
37
+ `capability: "issuer_native" | "unsupported"`. Derive these on the host from the
38
+ signed-in actor and verified issuer account. They control browser state and
39
+ presentation. They do not authorize a server operation. Include actor changes in
40
+ `identityKey`, even if two actors share an account.
41
+
42
+ The form has no owner selector, provider secret input or browser Stripe callback.
43
+ The native APIs currently operate in the configured key's issuer realm, without
44
+ connected-account headers. Seller adapters must authorize the seller's product
45
+ within that supported realm; a role label does not enable arbitrary Connect
46
+ billing. A host must return unsupported for an ineligible provider/account setup.
47
+ These are BetterStripe components, not Stripe embedded catalog components.
48
+
49
+ ## Supported settings
50
+
51
+ The billing model selects the relevant fields:
52
+
53
+ - **Pay as you go:** exact price per whole unit, currency, billable unit and
54
+ quantity precision from 0 through 6.
55
+ - **Included monthly units plus overages:** the same rate as an overage rate,
56
+ positive included units, and a reset at the original monthly billing period.
57
+ Native pricing uses a graduated free first tier followed by an infinite paid
58
+ tier. This does not add a monthly subscription fee or authorize work.
59
+ - **Prepaid paid credits:** a paid credit package quantity, manual top-up and
60
+ reject-on-insufficient-credit policy. The package must have positive whole minor currency backing within the native
61
+ payment bound and supported charge increments. Each later reservation must
62
+ also have exact whole-minor backing. Fractional rates are supported when work
63
+ uses suitable batches; fractional-minor consumption is rejected without rounding. Original terms
64
+ remain attached to credits. Automatic top-up and a monetary wallet are not
65
+ supported. Credit purchases fund only the issuer's own services.
66
+
67
+ Rates shown in the form are **major currency units per whole billable unit**.
68
+ The submitted `plan.rate.unitAmountDecimal` is an exact string in **minor currency
69
+ units per whole billable unit**. For example, `0.00125 USD` becomes `"0.125"` minor
70
+ units. Precision 2 gives Stripe a scaled-unit rate of `"0.00125"` minor units.
71
+ The form uses the existing plan, quantity, native rate and credit cost validators.
72
+ It rejects excessive precision and bounds rather than rounding. Provider account,
73
+ minimum payment, currency and payment-method eligibility still require server
74
+ validation and native observations.
75
+
76
+ Monthly interval and sum aggregation are the current supported configuration.
77
+ Other intervals, count/last aggregation, general tiers and transformed quantities
78
+ need an explicit supported server adapter. The form does not imply support by
79
+ accepting those settings.
80
+
81
+ ## Immutable meter selection and versions
82
+
83
+ `meters` is an authorized subset/page of managed meters. Each entry contains `id`,
84
+ `active` and its original `configuration`. Do not pass arbitrary native meters
85
+ without first verifying/adopting them through the package. Do not describe a
86
+ partial page as complete inventory. Hosts can page or search their managed catalog
87
+ and replace the supplied subset.
88
+
89
+ Selecting an active meter loads its immutable original terms and disables edits.
90
+ Inactive meters cannot be selected. Choose **Create new meter version** to edit
91
+ new terms. The server must require a new plan version, event name and price lookup
92
+ key for changed terms. Saving does not migrate, cancel or reprice existing
93
+ subscriptions. Those keep their original price until an explicit authorized host
94
+ operation changes them.
95
+
96
+ `onSave` receives `{ plan, eventName, displayName, meterId?, creditPackage? }`.
97
+ For prepaid, `creditPackage` is `{ quantity, topUp: "manual" }`. It is configuration
98
+ only. Saving does not create a payment, grant credits or authorize consumption.
99
+ The host must:
100
+
101
+ 1. Authenticate the actor and authorize admin/seller access to the product.
102
+ 2. Resolve the Stripe realm, mode, product and permitted immutable plan identity
103
+ on the server. Ignore client attempts to choose financial ownership.
104
+ 3. Revalidate the plan and selected original meter. Call `ensureUsageMeter` or
105
+ verify/adopt the selected meter, then `ensureUsagePrice` with a stable lookup
106
+ key. Persist the validated package policy in the host's authorized product
107
+ configuration, not a second usage ledger.
108
+ 4. For later purchases, use the package's [credit workflow](usage-credits.md),
109
+ deriving `ownership: "issuer"` and `rollover: "retain_original_terms"` on the
110
+ server. Verify payment before granting spending capacity.
111
+ 5. Return only sanitized results. An uncertain create outcome must be reconciled
112
+ using the original keys. Do not invent new identities to retry.
113
+
114
+ The package catalog persists intents and verifies immutable provider terms. A
115
+ browser duplicate-submit lock is only a UI convenience. Host authorization and
116
+ package idempotency remain mandatory after reloads or across tabs.
117
+
118
+ ## State, styling and recovery
119
+
120
+ Inputs and save controls disable during submission. Validation errors identify
121
+ unsupported values. Provider errors use a sanitized retry/reconciliation message;
122
+ raw provider messages are not shown by the default UI. A successful save shows a
123
+ version confirmation. Changing scope, authoritative initial terms or meter choices
124
+ resets edits and discards delayed results. A read-only or unsupported host cannot
125
+ submit through the hook either.
126
+
127
+ Use `className`, `[data-better-stripe="usage-configuration"]`, ordinary semantic
128
+ HTML and associated labels to style the default form. A `children(state)` render
129
+ prop, or `useUsageConfiguration(props)`, exposes `fields`, `setField`, `meterId`,
130
+ `selectMeter`, `immutable`, `disabled`, `isPending`, `save`, `error` and `message`.
131
+ Keep immutable/disabled controls and error/status announcements accessible when
132
+ customizing. The hook retains the same validation and submission lifecycle.
133
+
134
+ `UsagePriceRow` accepts a discriminated `value`:
135
+
136
+ - `{ kind: "fixed", price }` reuses `PriceCard` formatting. Pass observed usage,
137
+ billing-scheme and transformation metadata when available. Metered, tiered,
138
+ transformed, missing amounts or unsupported charge units cannot masquerade as
139
+ fixed zero prices.
140
+ - `{ kind: "metered", price }` uses the managed `UsagePriceBinding` returned by
141
+ `getUsagePrice`. It displays the original plan version, exact whole-unit rate,
142
+ model, monthly interval, aggregation, precision and active state. Included
143
+ tiers and prepaid credit backing have separate explanations.
144
+ - `{ kind: "unsupported", reason: "tiered" | "transformed" | "other" }` labels
145
+ other observed terms explicitly. It never infers a free price from a null
146
+ amount.
147
+
148
+ Use `productName`, `className` or `children(value)` for the catalog row. It is
149
+ read-only. The form, catalog row and usage views share package contracts; the
150
+ example should compose them rather than implementing another pricing engine.
@@ -0,0 +1,182 @@
1
+ # Reusable metered billing UI
2
+
3
+ Import the metered views from `@fantastic.dev/better-stripe/react`. They use the
4
+ package's native usage observations and component accounting for all three models:
5
+ pay as you go, included monthly usage with overages, and prepaid credits.
6
+
7
+ The defaults are unstyled semantic HTML. Each view supports render props and a
8
+ `className`; stable `data-better-stripe` attributes identify its root. No Stripe
9
+ embedded metering component or browser provider credential is required.
10
+
11
+ ## One workflow, either host transport
12
+
13
+ `UsageBilling` and `useUsageBilling` accept an authenticated asynchronous loader.
14
+ The same loader contract works with a Convex query/action client or an HTTP API.
15
+ `UsageSummary`, `UsageAllowance` and `UsageCredits` also accept observations
16
+ directly, including reactive host-query results. Both routes use the same display
17
+ components and exact decimal formatting.
18
+
19
+ ```tsx
20
+ import {
21
+ UsageBilling,
22
+ type UsageBillingSnapshot,
23
+ type UsageViewScope,
24
+ } from "@fantastic.dev/better-stripe/react";
25
+
26
+ const view: UsageViewScope = {
27
+ identityKey: authenticatedSessionKey,
28
+ accountKey: authorizedTenantKey,
29
+ meterKey: originalMeterAndPriceVersionKey,
30
+ period: verifiedBillingPeriod,
31
+ currency: originalCurrency,
32
+ };
33
+
34
+ async function loadUsage(scope: UsageViewScope): Promise<UsageBillingSnapshot> {
35
+ const response = await fetch("/api/billing/usage", {
36
+ method: "POST",
37
+ credentials: "same-origin",
38
+ headers: { "content-type": "application/json" },
39
+ body: JSON.stringify({
40
+ meterKey: scope.meterKey,
41
+ period: scope.period,
42
+ currency: scope.currency,
43
+ }),
44
+ });
45
+ if (!response.ok) throw new Error("Usage read unavailable");
46
+ return response.json();
47
+ }
48
+
49
+ <UsageBilling scope={view} unit="API calls" load={loadUsage} />;
50
+ ```
51
+
52
+ The scope is a cache identity, not authorization. Update `identityKey` on logout,
53
+ login or membership changes. Include original plan/price version in `meterKey`.
54
+ Changing identity, tenant, meter/version, period or currency resets the workflow
55
+ and its history navigation. Responses from the previous scope cannot replace the
56
+ current view. Period/currency mismatches in returned snapshots fail closed.
57
+
58
+ Authenticate every host read, refresh and page. Resolve the current tenant and
59
+ original native binding on the server. Do not trust a browser-selected payer,
60
+ price, subscription, secret or scope claim. See [authorization](usage-security.md).
61
+
62
+ The host loader should assemble `UsageBillingSnapshot` from existing package APIs:
63
+
64
+ | Snapshot field | Authenticated server source |
65
+ | ------------------- | ----------------------------------------------------------------------------------------- |
66
+ | `summary` | `stripe.usage.getSummary`, wrapped as `available` with its `observedAt` |
67
+ | `provider` | `stripe.usage.getProviderUsage`, or a fresh authorized `observeProviderUsage` action |
68
+ | `allowance` | `stripe.usage.getAllowanceStatus` for an included model or a configured pay-as-you-go cap |
69
+ | `credits` | `stripe.usage.getCreditBalance` for the original prepaid binding |
70
+ | `purchase` | `stripe.usage.getCreditPurchase` for the authorized original purchase ID |
71
+ | `creditApplication` | Authorized `stripe.usage.reconcileCreditPurchase` for that same original purchase |
72
+
73
+ Wrap successful allowance/credit reads in `{ status: "available", observedAt,
74
+ value }`. Preserve `null` allowance as no configured policy. Return explicit
75
+ `unavailable` or `unsupported` observations when evidence cannot be read. Include
76
+ only fields relevant to the verified model. The UI does not initiate purchases,
77
+ configure limits, run work, reconcile funds automatically or poll Stripe.
78
+
79
+ For a reactive adapter, pass the same observations to `UsageSummary`,
80
+ `UsageAllowance` and `UsageCredits`. Treat `undefined` as loading. Clear results
81
+ when the authenticated scope changes; never pass a previous query's data as the
82
+ new scope's observation. The asynchronous workflow performs this reset itself.
83
+
84
+ ## All three models and observation states
85
+
86
+ `UsageSummary` displays the original plan/version, per-meter and subscription-item
87
+ breakdown, accepted/effective/provider-accepted quantities, nonzero delivery
88
+ states and estimated charge. It preserves exact quantity strings, including
89
+ values beyond JavaScript's safe floating-point range. `formatUsageEstimate`
90
+ converts native minor-unit decimal estimates into exact major currency decimals,
91
+ including fractional cents; unsupported amounts stay unavailable.
92
+
93
+ Loading, empty, partial, unavailable and unsupported are separate states. A
94
+ complete zero-event local summary is empty. An unavailable summary is never zero.
95
+ Native stale/partial aggregates and possible ingestion delay remain visible.
96
+ Unknown/rejected/held delivery is distinct from acceptance and aggregation.
97
+ Estimates never become finalized or paid invoice amounts in these views.
98
+
99
+ `UsageAllowance` shows consumed plus reserved progress, included and remaining
100
+ units, overage, soft warnings and hard-cap observations. Its progress bar is
101
+ normalized for presentation; its accessible value text retains exact quantities.
102
+ A display is never permission to start work. Use the server's atomic reservation
103
+ API. The period is the verified managed billing period with no rollover, not a
104
+ calendar reset performed by React.
105
+
106
+ `UsageCredits` shows available, reserved, consumed, expired and frozen quantities,
107
+ purchase pending/ready/frozen/canceled status, exhaustion and native application
108
+ proof status. A frozen grant may hold units even while the overall account is
109
+ open. Pending purchase payment does not grant units. Consumption is not another
110
+ cash collection or a withdrawable balance. Pass the original currency when
111
+ presenting an application proof without a balance or purchase observation.
112
+
113
+ Refresh is explicit. Existing observations shown during refresh or a failed
114
+ refresh are marked potentially stale. Loader errors use a sanitized message.
115
+ Host adapters must also sanitize returned observation reasons and custom history
116
+ content before sending them to a browser.
117
+
118
+ ## Bounded history
119
+
120
+ `UsageHistory<Row>` and `useUsageHistory<Row>` own cursor navigation, loading,
121
+ retry, scope reset and stale-request protection. They work with event, delivery,
122
+ allowance and credit history. The host provides a row key and presentation rather
123
+ than another pagination engine.
124
+
125
+ ```tsx
126
+ import { UsageHistory } from "@fantastic.dev/better-stripe/react";
127
+ import type { UsageEventView } from "@fantastic.dev/better-stripe/usage";
128
+
129
+ <UsageHistory<UsageEventView>
130
+ scope={view}
131
+ historyKey="accepted-events"
132
+ limit={25}
133
+ load={async (scope, page) => {
134
+ // This host endpoint authenticates this request and resolves its binding.
135
+ const result = await loadAuthorizedEventPage(scope, page);
136
+ return {
137
+ status: "available",
138
+ observedAt: result.observedAt,
139
+ value: {
140
+ records: result.events,
141
+ cursor: result.cursor,
142
+ isDone: result.isDone,
143
+ },
144
+ };
145
+ }}
146
+ getKey={(row) => row.receipt.eventId}
147
+ renderRecord={(row) => (
148
+ <p>
149
+ {row.record.sourceEventId}: {row.record.quantity}{" "}
150
+ {row.record.binding.plan.unit.name}, {row.delivery}
151
+ </p>
152
+ )}
153
+ />;
154
+ ```
155
+
156
+ Use `readCreditHistory`, `readCreditGrants`, `readAllowanceHistory` or
157
+ `readDeliveryHistory` in analogous authorized loaders. The component accepts
158
+ 1–100 rows per page and opaque cursors up to 2,048 characters. Change `historyKey`
159
+ when changing reader kind, filters or transport cache semantics. Reauthorize
160
+ every page; a cursor never grants access. Partial or empty nonterminal pages do
161
+ not mean no history. Incomplete pages never establish complete totals. Missing, empty or repeated
162
+ nonterminal cursors stop forward navigation while preserving Previous and retry.
163
+
164
+ Render props receive the same hook state: data, loading/error, refresh, page,
165
+ previous/next and completeness. Native buttons support keyboard navigation;
166
+ status/alert regions announce loading and errors. Maintain these behaviors when
167
+ replacing defaults with a design system.
168
+
169
+ ## Verification
170
+
171
+ The co-located React tests exercise large exact quantities, every billing model,
172
+ loading/empty/partial/stale/unsupported states, native lag, pending and held
173
+ credits, error sanitization, retries, cursor navigation and delayed responses
174
+ after each scope field changes. The packed consumer typechecks these public
175
+ exports. The deterministic browser fixture is
176
+ `scripts/fixtures/usage-ui.html`; it uses the package components and does not call
177
+ Stripe. Its UI captures are separate from native financial acceptance.
178
+
179
+ Run `pnpm run check:all` and verify your host's authorization and native setup
180
+ using the [setup guide](metering-setup.md). Package views do not replace the
181
+ [ledger](usage-ledger.md), [allowance](usage-limits.md) or
182
+ [paid-credit](usage-credits.md) work and recovery protocols.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.60.1",
3
+ "version": "0.62.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -111,7 +111,9 @@
111
111
  "docs/usage-corrections.md",
112
112
  "docs/usage-settlement.md",
113
113
  "docs/usage-security.md",
114
- "docs/evidence/native-metering"
114
+ "docs/usage-react.md",
115
+ "docs/evidence/native-metering",
116
+ "docs/usage-configuration.md"
115
117
  ],
116
118
  "scripts": {
117
119
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -108,3 +108,6 @@ export type { UsageInvoiceSettlementOptions } from "./settlement.js";
108
108
  export type { UsageCreditRevenue } from "./creditRevenue.js";
109
109
 
110
110
  export type { UsageCreditSettlementOptions } from "./creditSettlement.js";
111
+
112
+ export type { UsageEventView } from "./client.js";
113
+ export type { UsageCreditReconciliation } from "./creditObservation.js";
@@ -306,3 +306,39 @@ export type {
306
306
 
307
307
  // Pins end cursors for the component paginator, including reactive page splits.
308
308
  export { usePaginatedQuery as useComponentPaginatedQuery } from "convex-helpers/react";
309
+
310
+ // Native metered billing views, shared by authenticated component and HTTP adapters.
311
+ export { UsageBilling, useUsageBilling } from "./workflows/UsageBilling.js";
312
+ export type { UsageBillingProps } from "./workflows/UsageBilling.js";
313
+ export { UsageSummary } from "./workflows/UsageSummary.js";
314
+ export type { UsageSummaryProps } from "./workflows/UsageSummary.js";
315
+ export { UsageAllowance } from "./workflows/UsageAllowance.js";
316
+ export type { UsageAllowanceProps } from "./workflows/UsageAllowance.js";
317
+ export { UsageCredits } from "./workflows/UsageCredits.js";
318
+ export type { UsageCreditsProps } from "./workflows/UsageCredits.js";
319
+ export type {
320
+ UsageViewScope,
321
+ UsageBillingSnapshot,
322
+ } from "./workflows/Usage.types.js";
323
+ export { formatUsageEstimate } from "./workflows/usage-format.js";
324
+ export { UsageHistory, useUsageHistory } from "./workflows/UsageHistory.js";
325
+ export type {
326
+ UsageHistoryProps,
327
+ UsageHistoryPage,
328
+ } from "./workflows/UsageHistory.js";
329
+
330
+ export { UsageConfiguration } from "./workflows/UsageConfiguration.js";
331
+ export { useUsageConfiguration } from "./workflows/useUsageConfiguration.js";
332
+ export type {
333
+ UsageConfigurationProps,
334
+ UsageConfigurationScope,
335
+ UsageConfigurationValue,
336
+ UsageConfigurationFields,
337
+ UsageConfigurationState,
338
+ UsageMeterChoice,
339
+ } from "./workflows/UsageConfiguration.types.js";
340
+ export { UsagePriceRow } from "./workflows/UsagePriceRow.js";
341
+ export type {
342
+ UsagePriceRowProps,
343
+ UsageCatalogPrice,
344
+ } from "./workflows/UsagePriceRow.js";
@@ -11,6 +11,8 @@ export function useCursorPagination(scopeKey: string) {
11
11
  cursor: current.cursors[current.index],
12
12
  page: current.index + 1,
13
13
  canPrevious: current.index > 0,
14
+ hasCursor: (cursor: string) =>
15
+ current.cursors.slice(0, current.index + 1).includes(cursor),
14
16
  previous: () =>
15
17
  setState((previous) => ({
16
18
  ...previous,
@@ -0,0 +1,88 @@
1
+ import {
2
+ defineUsagePlan,
3
+ type UsageBillingModel,
4
+ } from "../../client/usage/contracts.js";
5
+ import { prepareUsageRecord } from "../../client/usage/records.js";
6
+ import { summarizeUsageRecords } from "../../client/usage/summary.js";
7
+ import type { UsageViewScope, UsageBillingSnapshot } from "./Usage.types.js";
8
+ export const usageScope: UsageViewScope = {
9
+ identityKey: "actor1",
10
+ accountKey: "tenant1",
11
+ meterKey: "calls-v1",
12
+ period: { start: 600, end: 1200 },
13
+ currency: "usd",
14
+ };
15
+ export function usageSnapshot(
16
+ quantity = "14",
17
+ model: UsageBillingModel = "pay_as_you_go",
18
+ ): UsageBillingSnapshot {
19
+ const record = prepareUsageRecord({
20
+ scope: {
21
+ stripeAccountId: "acct_platform",
22
+ customerAccount: "acct_buyer",
23
+ meterId: "mtr_calls",
24
+ livemode: false,
25
+ },
26
+ binding: {
27
+ stripeCustomerId: "cus_buyer",
28
+ stripePriceId: "price_calls",
29
+ eventName: "calls",
30
+ plan: defineUsagePlan({
31
+ key: "calls",
32
+ version: "v1",
33
+ model,
34
+ ...(model === "included_overage"
35
+ ? { includedQuantity: "10", reset: "billing_period" }
36
+ : model === "prepaid"
37
+ ? { insufficientBalance: "reject" }
38
+ : {}),
39
+ unit: { name: "call", precision: 6 },
40
+ rate: { currency: "usd", unitAmountDecimal: "2" },
41
+ }),
42
+ },
43
+ sourceEventId: "work1",
44
+ quantity,
45
+ occurredAt: 700,
46
+ });
47
+ const subscription = {
48
+ subscriptionId: "sub_calls",
49
+ subscriptionItemId: "si_calls",
50
+ stripePriceId: "price_calls",
51
+ period: usageScope.period,
52
+ interval: "month" as const,
53
+ };
54
+ return {
55
+ summary: {
56
+ status: "available",
57
+ observedAt: 700,
58
+ value: summarizeUsageRecords(
59
+ [
60
+ {
61
+ record,
62
+ subscription,
63
+ delivery: "unknown",
64
+ hasValidationError: false,
65
+ },
66
+ ],
67
+ { period: usageScope.period, complete: true, observedAt: 700 },
68
+ ),
69
+ },
70
+ provider: {
71
+ status: "unavailable",
72
+ reason: "provider_not_observed",
73
+ retryable: true,
74
+ },
75
+ };
76
+ }
77
+ export const creditBalance = {
78
+ availableQuantity: "0",
79
+ reservedQuantity: "2",
80
+ consumedQuantity: "8",
81
+ expiredQuantity: "0",
82
+ frozenQuantity: "0",
83
+ precision: 0,
84
+ currency: "usd",
85
+ unit: "call",
86
+ status: "available" as const,
87
+ cashCollection: "none" as const,
88
+ };