@fantastic.dev/better-stripe 0.62.0 → 0.64.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 (217) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +22 -2
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +550 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +275 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +550 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +275 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/financialOwnership.d.ts +2 -2
  12. package/dist/client/financialOwnership.d.ts.map +1 -1
  13. package/dist/client/financialOwnership.js +2 -2
  14. package/dist/client/financialOwnership.js.map +1 -1
  15. package/dist/client/paymentSource/resolver.d.ts +1 -0
  16. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  17. package/dist/client/paymentSource/resolver.js +11 -2
  18. package/dist/client/paymentSource/resolver.js.map +1 -1
  19. package/dist/client/paymentSource/zeroTierLines.d.ts +4 -0
  20. package/dist/client/paymentSource/zeroTierLines.d.ts.map +1 -0
  21. package/dist/client/paymentSource/zeroTierLines.js +35 -0
  22. package/dist/client/paymentSource/zeroTierLines.js.map +1 -0
  23. package/dist/client/payoutRevisionMigration.d.ts +37 -0
  24. package/dist/client/payoutRevisionMigration.d.ts.map +1 -0
  25. package/dist/client/payoutRevisionMigration.js +49 -0
  26. package/dist/client/payoutRevisionMigration.js.map +1 -0
  27. package/dist/client/publicTypes.d.ts +2 -0
  28. package/dist/client/publicTypes.d.ts.map +1 -1
  29. package/dist/client/reversalObservations.d.ts +62 -0
  30. package/dist/client/reversalObservations.d.ts.map +1 -0
  31. package/dist/client/reversalObservations.js +79 -0
  32. package/dist/client/reversalObservations.js.map +1 -0
  33. package/dist/client/usage/configuration.d.ts +13 -0
  34. package/dist/client/usage/configuration.d.ts.map +1 -0
  35. package/dist/client/usage/configuration.js +2 -0
  36. package/dist/client/usage/configuration.js.map +1 -0
  37. package/dist/client/usage/deliveryProvider.d.ts.map +1 -1
  38. package/dist/client/usage/deliveryProvider.js +16 -0
  39. package/dist/client/usage/deliveryProvider.js.map +1 -1
  40. package/dist/client/usage/index.d.ts +2 -0
  41. package/dist/client/usage/index.d.ts.map +1 -1
  42. package/dist/client/usage/invoiceSale.d.ts.map +1 -1
  43. package/dist/client/usage/invoiceSale.js +15 -2
  44. package/dist/client/usage/invoiceSale.js.map +1 -1
  45. package/dist/client/usage/observationClient.d.ts +2 -2
  46. package/dist/client/usage/observationClient.d.ts.map +1 -1
  47. package/dist/client/usage/views.d.ts +24 -0
  48. package/dist/client/usage/views.d.ts.map +1 -0
  49. package/dist/client/usage/views.js +2 -0
  50. package/dist/client/usage/views.js.map +1 -0
  51. package/dist/component/_generated/api.d.ts +28 -0
  52. package/dist/component/_generated/api.d.ts.map +1 -1
  53. package/dist/component/_generated/api.js.map +1 -1
  54. package/dist/component/_generated/component.d.ts +354 -0
  55. package/dist/component/_generated/component.d.ts.map +1 -1
  56. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  57. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  58. package/dist/component/connect/mutations.d.ts.map +1 -1
  59. package/dist/component/connect/mutations.js +2 -0
  60. package/dist/component/connect/mutations.js.map +1 -1
  61. package/dist/component/connect/reversalClaims.d.ts.map +1 -1
  62. package/dist/component/connect/reversalClaims.js +10 -1
  63. package/dist/component/connect/reversalClaims.js.map +1 -1
  64. package/dist/component/earnings/triggers.d.ts +408 -16
  65. package/dist/component/earnings/triggers.d.ts.map +1 -1
  66. package/dist/component/financialObservations/transferSchema.d.ts +1 -0
  67. package/dist/component/financialObservations/transferSchema.d.ts.map +1 -1
  68. package/dist/component/financialObservations/transferSchema.js +1 -0
  69. package/dist/component/financialObservations/transferSchema.js.map +1 -1
  70. package/dist/component/payoutRevisionJournal/mutations.d.ts +15 -0
  71. package/dist/component/payoutRevisionJournal/mutations.d.ts.map +1 -0
  72. package/dist/component/payoutRevisionJournal/mutations.js +11 -0
  73. package/dist/component/payoutRevisionJournal/mutations.js.map +1 -0
  74. package/dist/component/payoutRevisionJournal/schema.d.ts +45 -0
  75. package/dist/component/payoutRevisionJournal/schema.d.ts.map +1 -0
  76. package/dist/component/payoutRevisionJournal/schema.js +22 -0
  77. package/dist/component/payoutRevisionJournal/schema.js.map +1 -0
  78. package/dist/component/payoutRevisionJournal/state.d.ts +36 -0
  79. package/dist/component/payoutRevisionJournal/state.d.ts.map +1 -0
  80. package/dist/component/payoutRevisionJournal/state.js +111 -0
  81. package/dist/component/payoutRevisionJournal/state.js.map +1 -0
  82. package/dist/component/payoutRevisionMigration/mutations.d.ts +36 -0
  83. package/dist/component/payoutRevisionMigration/mutations.d.ts.map +1 -0
  84. package/dist/component/payoutRevisionMigration/mutations.js +126 -0
  85. package/dist/component/payoutRevisionMigration/mutations.js.map +1 -0
  86. package/dist/component/payoutRevisionMigration/queries.d.ts +38 -0
  87. package/dist/component/payoutRevisionMigration/queries.d.ts.map +1 -0
  88. package/dist/component/payoutRevisionMigration/queries.js +39 -0
  89. package/dist/component/payoutRevisionMigration/queries.js.map +1 -0
  90. package/dist/component/payoutRevisionMigration/schema.d.ts +115 -0
  91. package/dist/component/payoutRevisionMigration/schema.d.ts.map +1 -0
  92. package/dist/component/payoutRevisionMigration/schema.js +52 -0
  93. package/dist/component/payoutRevisionMigration/schema.js.map +1 -0
  94. package/dist/component/payoutSnapshots/legacyRevisionWriter.d.ts +4 -0
  95. package/dist/component/payoutSnapshots/legacyRevisionWriter.d.ts.map +1 -0
  96. package/dist/component/payoutSnapshots/legacyRevisionWriter.js +33 -0
  97. package/dist/component/payoutSnapshots/legacyRevisionWriter.js.map +1 -0
  98. package/dist/component/payoutSnapshots/revisions.d.ts.map +1 -1
  99. package/dist/component/payoutSnapshots/revisions.js +23 -29
  100. package/dist/component/payoutSnapshots/revisions.js.map +1 -1
  101. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  102. package/dist/component/refundSync/mutations.d.ts +1 -1
  103. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  104. package/dist/component/reversalObservations/capture.d.ts +6 -0
  105. package/dist/component/reversalObservations/capture.d.ts.map +1 -0
  106. package/dist/component/reversalObservations/capture.js +96 -0
  107. package/dist/component/reversalObservations/capture.js.map +1 -0
  108. package/dist/component/reversalObservations/indexSlice.d.ts +29 -0
  109. package/dist/component/reversalObservations/indexSlice.d.ts.map +1 -0
  110. package/dist/component/reversalObservations/indexSlice.js +101 -0
  111. package/dist/component/reversalObservations/indexSlice.js.map +1 -0
  112. package/dist/component/reversalObservations/integrity.d.ts +25 -0
  113. package/dist/component/reversalObservations/integrity.d.ts.map +1 -0
  114. package/dist/component/reversalObservations/integrity.js +19 -0
  115. package/dist/component/reversalObservations/integrity.js.map +1 -0
  116. package/dist/component/reversalObservations/mutations.d.ts +37 -0
  117. package/dist/component/reversalObservations/mutations.d.ts.map +1 -0
  118. package/dist/component/reversalObservations/mutations.js +181 -0
  119. package/dist/component/reversalObservations/mutations.js.map +1 -0
  120. package/dist/component/reversalObservations/pagination.d.ts +34 -0
  121. package/dist/component/reversalObservations/pagination.d.ts.map +1 -0
  122. package/dist/component/reversalObservations/pagination.js +31 -0
  123. package/dist/component/reversalObservations/pagination.js.map +1 -0
  124. package/dist/component/reversalObservations/queries.d.ts +221 -0
  125. package/dist/component/reversalObservations/queries.d.ts.map +1 -0
  126. package/dist/component/reversalObservations/queries.js +114 -0
  127. package/dist/component/reversalObservations/queries.js.map +1 -0
  128. package/dist/component/reversalObservations/references.d.ts +17 -0
  129. package/dist/component/reversalObservations/references.d.ts.map +1 -0
  130. package/dist/component/reversalObservations/references.js +95 -0
  131. package/dist/component/reversalObservations/references.js.map +1 -0
  132. package/dist/component/reversalObservations/schema.d.ts +525 -0
  133. package/dist/component/reversalObservations/schema.d.ts.map +1 -0
  134. package/dist/component/reversalObservations/schema.js +92 -0
  135. package/dist/component/reversalObservations/schema.js.map +1 -0
  136. package/dist/component/reversalObservations/selectors.d.ts +3 -0
  137. package/dist/component/reversalObservations/selectors.d.ts.map +1 -0
  138. package/dist/component/reversalObservations/selectors.js +8 -0
  139. package/dist/component/reversalObservations/selectors.js.map +1 -0
  140. package/dist/component/reversalObservations/state.d.ts +34 -0
  141. package/dist/component/reversalObservations/state.d.ts.map +1 -0
  142. package/dist/component/reversalObservations/state.js +34 -0
  143. package/dist/component/reversalObservations/state.js.map +1 -0
  144. package/dist/component/schema.d.ts +275 -0
  145. package/dist/component/schema.js +10 -0
  146. package/dist/component/schema.js.map +1 -1
  147. package/dist/component/usage/allowance.fixtures.d.ts +291 -16
  148. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  149. package/dist/component/usageCredits/accounting.fixtures.d.ts +275 -0
  150. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  151. package/dist/react/workflows/Usage.types.d.ts +2 -23
  152. package/dist/react/workflows/Usage.types.d.ts.map +1 -1
  153. package/dist/react/workflows/Usage.types.js.map +1 -1
  154. package/dist/react/workflows/UsageConfiguration.types.d.ts +3 -11
  155. package/dist/react/workflows/UsageConfiguration.types.d.ts.map +1 -1
  156. package/docs/README.md +4 -1
  157. package/docs/client-api.md +6 -0
  158. package/docs/financial-observations.md +51 -8
  159. package/docs/payout-revision-migration.md +54 -0
  160. package/docs/react-workflows-audit.md +73 -2
  161. package/docs/usage-configuration.md +4 -0
  162. package/docs/usage-delivery.md +4 -0
  163. package/docs/usage-example.md +250 -0
  164. package/docs/usage-react.md +4 -0
  165. package/docs/usage-settlement.md +8 -3
  166. package/package.json +4 -2
  167. package/src/client/financialOwnership.ts +2 -2
  168. package/src/client/paymentSource/resolver.ts +14 -2
  169. package/src/client/paymentSource/zeroTierLines.ts +42 -0
  170. package/src/client/payoutRevisionMigration.test.ts +40 -0
  171. package/src/client/payoutRevisionMigration.ts +96 -0
  172. package/src/client/publicTypes.ts +15 -0
  173. package/src/client/reversalObservations.test.ts +69 -0
  174. package/src/client/reversalObservations.ts +151 -0
  175. package/src/client/usage/configuration.ts +9 -0
  176. package/src/client/usage/deliveryProvider.test.ts +77 -37
  177. package/src/client/usage/deliveryProvider.ts +19 -0
  178. package/src/client/usage/index.ts +4 -0
  179. package/src/client/usage/invoiceSale.test.ts +68 -0
  180. package/src/client/usage/invoiceSale.ts +20 -2
  181. package/src/client/usage/views.ts +23 -0
  182. package/src/component/_generated/api.ts +28 -0
  183. package/src/component/_generated/component.ts +423 -0
  184. package/src/component/connect/mutations.ts +2 -0
  185. package/src/component/connect/reversalClaims.ts +13 -1
  186. package/src/component/financialObservations/transferSchema.ts +1 -0
  187. package/src/component/payoutRevisionJournal/mutations.ts +11 -0
  188. package/src/component/payoutRevisionJournal/schema.ts +34 -0
  189. package/src/component/payoutRevisionJournal/state.ts +141 -0
  190. package/src/component/payoutRevisionMigration/mutations.ts +135 -0
  191. package/src/component/payoutRevisionMigration/queries.ts +50 -0
  192. package/src/component/payoutRevisionMigration/schema.ts +51 -0
  193. package/src/component/payoutSnapshots/legacy-revisions.test.ts +246 -0
  194. package/src/component/payoutSnapshots/legacyRevisionWriter.ts +39 -0
  195. package/src/component/payoutSnapshots/revision-journal-callbacks.test.ts +160 -0
  196. package/src/component/payoutSnapshots/revision-journal-held.test.ts +94 -0
  197. package/src/component/payoutSnapshots/revision-journal.test.ts +310 -0
  198. package/src/component/payoutSnapshots/revision-migration.test.ts +128 -0
  199. package/src/component/payoutSnapshots/revisions.ts +22 -30
  200. package/src/component/reversalObservations/boundaries.test.ts +62 -0
  201. package/src/component/reversalObservations/capture-integrity.test.ts +119 -0
  202. package/src/component/reversalObservations/capture.ts +129 -0
  203. package/src/component/reversalObservations/continuation.test.ts +131 -0
  204. package/src/component/reversalObservations/indexSlice.ts +124 -0
  205. package/src/component/reversalObservations/integrity.ts +31 -0
  206. package/src/component/reversalObservations/lifecycle.test.ts +81 -0
  207. package/src/component/reversalObservations/mutations.ts +211 -0
  208. package/src/component/reversalObservations/pagination.ts +40 -0
  209. package/src/component/reversalObservations/provenance.test.ts +167 -0
  210. package/src/component/reversalObservations/queries.ts +121 -0
  211. package/src/component/reversalObservations/references.ts +134 -0
  212. package/src/component/reversalObservations/schema.ts +100 -0
  213. package/src/component/reversalObservations/selectors.ts +9 -0
  214. package/src/component/reversalObservations/state.ts +42 -0
  215. package/src/component/schema.ts +18 -0
  216. package/src/react/workflows/Usage.types.ts +5 -29
  217. package/src/react/workflows/UsageConfiguration.types.ts +3 -11
@@ -97,11 +97,82 @@ defaults all use the public `AffiliatePayoutEditor`. It owns percentage/fixed
97
97
  amount validation, commission-term selection, clear/inherit behavior, edit
98
98
  versions, pending state, and errors. `PlanPricingEditor` owns the monthly-price
99
99
  and sale-fee form. The example binds both to Convex functions and supplies shadcn
100
- markup. Rule resolution, Stripe metadata, first-invoice claims, fee accounting,
101
- and transfer execution remain backend application policy.
100
+ markup. The host resolves inherited rules, chooses referral attribution and
101
+ commission terms, and supplies the resulting policy to the package. BetterStripe
102
+ owns financial allocation, transfer execution, replay safety and recovery. These
103
+ server responsibilities are detailed in the boundary audit below.
102
104
 
103
105
  Browser regression checks cover equal cards/layouts in API and package views,
104
106
  referral-sales pagination, inline payout controls, and plan pricing. Sandbox QA
105
107
  covers all five checkout integrations, declined-card retries, inherited and fixed
106
108
  commissions, and Forever/One-time subscription renewals using Stripe test clocks.
107
109
  Existing subscriptions keep their monthly price and saved commission term.
110
+
111
+ ## Package and example boundary
112
+
113
+ This source audit covers checkout, catalog, buyer billing, accounts/onboarding,
114
+ seller and affiliate reporting, payouts, refunds, disputes, recovery, and setup.
115
+ It checks ownership of the implementation; the historical sandbox checks above
116
+ are separate evidence, not a claim that every live flow ran again for this audit.
117
+
118
+ | Concern | Package implementation | Example wiring that remains |
119
+ | ----------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
120
+ | Checkout | `CheckoutChooser`, session/PaymentIntent workflows, email validation and payment confirmation | `components/checkout-types.tsx`, session/payment-intent adapters, route selection, buyer/store lookup and referral metadata |
121
+ | Catalog and billing | Product/price controllers, subscription commands, invoice readers, portal creation | Authorized Convex bindings, allowed products, tier names, plan selection and proration policy |
122
+ | Accounts and onboarding | Account configuration, requirements, onboarding workflows and Connect embeds | Persona/store selection, account ownership and navigation |
123
+ | Reporting and payouts | Earnings derivation, currency formatting, payout classification, pagination and payout workers | Store/user joins, collection bindings, cron installation and styled rows/cards |
124
+ | Refunds and disputes | Refund commands and observations, evidence controllers, clawback/recovery records and execution | Original-owner authorization, source routing, selected liability policy and case links |
125
+ | Durable financial work | `balanceFundingWorkflow`, `costRecoveryWorkflow`, provider execution, stable operation identities and reconciliation | Credential-bearing provider action adapters, consent records, host request status and explicit scheduling policy |
126
+ | Setup and testing | Reusable task/action state and setup UI | Sandbox-only accounts, prices, cards, test clocks, reset/seed orchestration and fixture assertions |
127
+
128
+ ### Concrete adapters
129
+
130
+ - `example/src/components/checkout-form-fields.tsx` renders the package's
131
+ `CheckoutFormState`. It forwards `submit`, input values, pending state and errors.
132
+ It must not confirm a payment or duplicate email validation.
133
+ - `example/src/lib/stripe-hooks.ts` binds package hook factories and pagination to Convex
134
+ function references. `current-subscription.ts` and `store-earnings.ts` re-export
135
+ package selectors.
136
+ - `example/src/lib/format-amount.ts` re-exports the package's `formatPrice` as a local name.
137
+ Buyer billing, checkout previews and product pickers also use `formatPrice`.
138
+ Seller payout history uses `formatPayoutAmount`, including its explicit fallback
139
+ for unsupported display precision. Currency conversion
140
+ must not assume `amount / 100`; JPY has different units, and observed ISK/UGX
141
+ fractional balances need the package's display rules. Charge eligibility and
142
+ bank-payout eligibility still use their respective package validators.
143
+ - `example/convex/storefront/checkout.ts` selects the authorized buyer, seller, eligible
144
+ product and referral policy before calling `stripe.createCheckoutSession`.
145
+ The demo's `avery` code and store-plan metadata are application policy.
146
+ - `example/convex/settlement/workflow/actions.ts` and
147
+ `example/convex/sellerCosts/recoveryInvoices/workflow/actions.ts` authorize the original
148
+ host job and pass credentials to `stripe.costRecovery.executeGroupProvider`.
149
+ Provider write/reconciliation behavior stays in the package.
150
+ - `example/convex/storeBalance/workflow/internal/actions.ts` joins the seller's consent and
151
+ request to package preparation/apply operations. Its bounded observation cadence
152
+ and host status projection remain local. It uses `financialRetryDecision` and
153
+ does not reinterpret an unknown provider write as success.
154
+ - `example/convex/sellerCosts/invoiceRecoverySource.ts` and `unsettledCostSource.ts` read
155
+ provider objects to find the demo's original recovery group or store sale. Their
156
+ `example:store:*` and `sale_v1` bindings are application-specific. Package
157
+ reconciliation still verifies funding and allocations before moving money.
158
+
159
+ ### Rules for changes
160
+
161
+ Add a reusable Stripe protocol, monetary validator, workflow controller, pagination
162
+ controller or unstyled renderer under `src/client`, `src/component` or `src/react`.
163
+ Expose it through the appropriate public entry point and test it without example
164
+ personas, routes or schema. Use it from the example through a small binding or
165
+ render-prop adapter. Different integration tabs may have different markup, but
166
+ should share package-owned validation, units and action state.
167
+
168
+ Keep authentication, ownership checks, business policy and application joins on
169
+ the host server. A component ID, account ID, role switch or metadata field never
170
+ authorizes a caller. The demo's identity model is not production authentication.
171
+ Do not move store/user tables or sandbox fixture orchestration into the package
172
+ just to reduce the example's line count.
173
+
174
+ Payment acceptance and fulfillment are separate responsibilities. BetterStripe
175
+ supplies verified payment records and hooks; the consuming application decides
176
+ whether payment unlocks a file, account access, a license or another benefit.
177
+ It must make those effects idempotent and choose its refund/access policy. The
178
+ example should not grow a download service, entitlement engine or shipping system.
@@ -93,6 +93,10 @@ key for changed terms. Saving does not migrate, cancel or reprice existing
93
93
  subscriptions. Those keep their original price until an explicit authorized host
94
94
  operation changes them.
95
95
 
96
+ Server adapters can import the `UsageConfigurationValue` type from
97
+ `@fantastic.dev/better-stripe/usage` without loading React types. The React entry
98
+ point continues to re-export it for UI consumers.
99
+
96
100
  `onSave` receives `{ plan, eventName, displayName, meterId?, creditPackage? }`.
97
101
  For prepaid, `creditPackage` is `{ quantity, topUp: "manual" }`. It is configuration
98
102
  only. Saving does not create a payment, grant credits or authorize consumption.
@@ -92,6 +92,10 @@ window. Automatic sends also stop 23 hours after the first send attempt. Stripe
92
92
  retains deduplication for at least 24 hours, not forever. A historical acceptance
93
93
  receipt remains valid after these windows expire, but does not authorize replay.
94
94
  The adapter never changes the original occurrence time to make an event eligible.
95
+ For a sandbox subscription attached to a test clock, delivery additionally reads
96
+ the native clock and checks its 35-day past/5-minute future window. An advancing
97
+ or unavailable clock holds delivery. A timestamp outside its native window is
98
+ rejected before sending. Production source timestamps remain unchanged.
95
99
 
96
100
  ## Status and operational controls
97
101
 
@@ -0,0 +1,250 @@
1
+ # Run all three native billing models
2
+
3
+ The example at `/demo/metered-usage` uses the public BetterStripe package against a
4
+ Stripe sandbox. It provisions a dedicated Accounts v2 customer, test clock,
5
+ product, meter, price and managed subscription per persona and model. Usage,
6
+ delivery, allowance reservations, credits, corrections and settlement live in the
7
+ component. The example stores fixture provenance and synthetic application work.
8
+
9
+ Start with [sandbox setup](metering-setup.md). Use your existing Stripe sandbox;
10
+ no Metronome account or token is needed. Run the example backend and frontend
11
+ from the `example` directory with `pnpm dev`. Keep test keys in the backend
12
+ Convex environment. Do not copy secret values into commands, screenshots, source
13
+ files or browser storage.
14
+
15
+ ## Demo security model
16
+
17
+ This repository's persona switcher is a test-only convenience, not authentication.
18
+ Choose Customer, Seller or Admin, then Metered billing. Each operation rechecks
19
+ the server's persona binding and test key. If an authenticated identity is present,
20
+ it must match the persona's stored token identifier. Visitor and affiliate
21
+ personas cannot operate the workflow. Do not expose these demo endpoints as a
22
+ production billing service.
23
+
24
+ In your app, replace the persona lookup with real authentication and server-owned
25
+ customer, product, entitlement and recipient authorization. Never trust a browser
26
+ account ID, product ID, price, rate or settlement policy. See
27
+ [authorization and recovery](usage-security.md).
28
+
29
+ Admin and seller personas can configure the unit, precision, currency, exact price,
30
+ version and model-specific terms before setup. Customers run the server-owned
31
+ defaults. Setup retries retain the original native identities and configuration.
32
+ A saved meter and subscription keep their original terms. Archive a resolved run
33
+ before configuring its replacement.
34
+
35
+ ## Pay as you go
36
+
37
+ 1. Select Pay as you go, then Set up sandbox.
38
+ 2. Run five units three times. The default price is USD 1 per call.
39
+ 3. Replay last work. Its source identity, quantity and occurrence time stay fixed;
40
+ the synthetic application work and usage acceptance happen once.
41
+ 4. Observe native usage. If delivery is queued, use Resume queued deliveries.
42
+ Stripe aggregation is asynchronous. Refresh until the aggregate is 15.
43
+ 5. Close or resume original billing period. This fences new work, checks complete
44
+ local/native equality, drains reservations and checks every correction and
45
+ purchase intent. It advances only this run's test clock.
46
+ 6. Resume after the clock is ready. The server finds the unique original cycle
47
+ invoice, verifies its meter lines, finalizes it and pays with Stripe's sandbox
48
+ card. The default invoice is USD 15.
49
+
50
+ The outcome separately shows invoice payment, original cash verification, actual
51
+ processing fees and any verified recipient transfers. A paid invoice alone does
52
+ not imply that settlement is ready.
53
+
54
+ ## Included monthly usage and overages
55
+
56
+ Select Included monthly usage. The defaults include ten calls per original
57
+ monthly period, then USD 1 per additional call. Run three five-unit jobs. The
58
+ package allowance view shows 15 consumed, ten included, five billable overage
59
+ units and the soft-limit warning at 12. The native invoice is USD 5.
60
+
61
+ Closing the period observes the next native subscription period. When that period
62
+ is active on the Convex server, its separate allowance starts at zero consumed
63
+ and ten remaining included units. The old period and history stay unchanged. A
64
+ test clock can move ahead of real time; future renewal allowance is explicitly
65
+ unavailable. Its view stays read-only until the period is active on the server and
66
+ new event times are inside the provider's real acceptance window. This demo does not forge
67
+ future work timestamps to simulate another month's consumption.
68
+
69
+ ## Paid prepaid credits
70
+
71
+ 1. Select Prepaid credits and set up its dedicated sandbox resources.
72
+ 2. Run five units before funding. Work is held and does not execute.
73
+ 3. Create credit purchase. The default original purchase is ten units for USD 10.
74
+ Pending payment grants no usable credit.
75
+ 4. Confirm sandbox card. The backend uses Stripe's test card and the package
76
+ verifies the original captured PaymentIntent, customer and paid credit grant.
77
+ 5. Run two five-unit jobs. Replay a successful job before creating another one to
78
+ demonstrate idempotency. Another five-unit job is denied after exhaustion.
79
+ 6. Observe native usage, then close and resume the period. The native credit grant
80
+ covers the consumption invoice. The demo refuses to pay any positive prepaid
81
+ invoice remainder with a second cash payment.
82
+
83
+ The USD 10 purchase is the only cash source. Credit consumption collects no new
84
+ cash. The package reconciles native credit transactions against complete invoice
85
+ history. Unavailable observations are shown explicitly, never as a zero balance.
86
+
87
+ For production, send the package purchase result's `clientSecret` only to the
88
+ properly authenticated purchaser's Stripe payment UI. Do not store or log it.
89
+ Confirming a payment in the UI is not proof of usable credits; call
90
+ `observeCreditPurchase` and wait for the verified ready grant. See
91
+ [paid credit accounting](usage-credits.md).
92
+
93
+ Prepaid is limited to the issuer's own services. A seller persona cannot redeem
94
+ credits into reseller proceeds. An authorized affiliate can be paid once from the
95
+ original purchase; usage does not produce another affiliate sale.
96
+
97
+ ## Corrections and retained failures
98
+
99
+ Before closing, Correct last accepted event cancels its original native event
100
+ through the package. Repeated correction requests keep the same correction ID.
101
+ Wait for confirmation and native reaggregation. A new application job can then
102
+ use the released capacity. For example, record 15 units, cancel the last five,
103
+ then record a different five-unit job. Effective usage is 15, and history retains
104
+ 20 originally accepted units plus the five canceled units.
105
+
106
+ Unknown delivery outcomes stay held. Resume queued deliveries schedules only
107
+ records that the package still classifies as queued; it never resends unknown
108
+ attempts. Do not replace the source event ID, change the occurrence time, create
109
+ a new run to relabel the same work or invent a provider event identifier. Resolve
110
+ the original attempt with verified native evidence using the operational runbook.
111
+ A billing or cleanup guard failure preserves all work, purchase and correction
112
+ intents for reconciliation.
113
+
114
+ The fixture timestamps _new synthetic jobs_ at its retained test clock's original
115
+ period start. This keeps native meter events and paid grants on the same logical
116
+ clock. Retrying a job never changes that timestamp. Real applications must use
117
+ the actual occurrence time of their business event. Delivery checks both real
118
+ provider limits and an attached sandbox clock before a native event write.
119
+
120
+ ## Ownership and routing
121
+
122
+ Customer and admin runs use direct issuer billing. Seller runs pin their original
123
+ server-owned seller account and, when available, an existing demo affiliate at
124
+ setup. The demo policy is a 10% inclusive platform fee and a 20% affiliate share
125
+ of the eligible remainder, with recurring commission eligibility. The package
126
+ uses actual processing fees and verifies native payment provenance, recipient
127
+ capabilities and transfer identity. Unsupported Connect configurations remain
128
+ held. Accounts v2 payer configuration is separate from merchant or recipient
129
+ configuration; a customer account is not automatically eligible to receive money.
130
+ Prepaid settlement retains issuer revenue and accepts only eligible affiliate
131
+ policy, never seller or collaborator redemption.
132
+
133
+ ## Scoped cleanup and reset
134
+
135
+ Cleanup re-reads the original paid invoice, payment and settlement before stopping
136
+ resources. Saved success alone cannot authorize a reset after a refund, dispute or
137
+ incomplete settlement recovery. Unavailable fresh evidence keeps the run retained.
138
+
139
+ Use Archive or resume scoped cleanup after the original invoice and cash evidence
140
+ are verified. It refuses unresolved delivery, corrections, reservations, purchases,
141
+ credit backing or settlement. Unspent paid credits require verified refund or
142
+ expiry; cleanup cannot wipe them.
143
+
144
+ Cleanup requests period-end cancellation, advances only the owned test clock to
145
+ the cancellation boundary, checks the final native cycle invoice and retires the
146
+ managed enrollment. It deactivates only the owned price, meter and product. It
147
+ retains the native payer, clock, invoice/payment evidence and every component
148
+ history record. It does not clear any Convex table or another developer's data.
149
+ After successful archival, Start new sandbox run creates new isolated resources.
150
+ Admin or seller can save a new version before starting that replacement.
151
+
152
+ Empty or unresolved runs can require operator reconciliation rather than automatic
153
+ archive. In particular, unknown provider outcomes must remain visible and retained.
154
+ Never delete a clock or payer to make financial evidence disappear.
155
+
156
+ ## Model configuration snippets
157
+
158
+ Use the same versioned unit and exact minor-currency rate in each model:
159
+
160
+ ```ts
161
+ import { defineUsagePlan } from "@fantastic.dev/better-stripe/usage";
162
+ const terms = {
163
+ key: "api-calls",
164
+ version: "v1",
165
+ unit: { name: "call", precision: 0 },
166
+ rate: { currency: "usd", unitAmountDecimal: "100" },
167
+ } as const;
168
+ ```
169
+
170
+ Pay as you go bills every effective unit:
171
+
172
+ ```ts
173
+ const payAsYouGo = defineUsagePlan({ ...terms, model: "pay_as_you_go" });
174
+ ```
175
+
176
+ Included monthly usage grants ten units before overages in each original period:
177
+
178
+ ```ts
179
+ const included = defineUsagePlan({
180
+ ...terms,
181
+ model: "included_overage",
182
+ includedQuantity: "10",
183
+ reset: "billing_period",
184
+ });
185
+ ```
186
+
187
+ Prepaid consumption requires verified paid grants and rejects insufficient credit:
188
+
189
+ ```ts
190
+ const prepaid = defineUsagePlan({
191
+ ...terms,
192
+ model: "prepaid",
193
+ insufficientBalance: "reject",
194
+ });
195
+ // After server authorization and native binding setup:
196
+ const purchase = await stripe.usage.purchaseCredits(
197
+ ctx,
198
+ {
199
+ ...originalCreditBinding,
200
+ purchaseId: originalBusinessPurchaseId,
201
+ quantity: "10",
202
+ ownership: "issuer",
203
+ rollover: "retain_original_terms",
204
+ },
205
+ { stripeSecretKey },
206
+ );
207
+ // Return clientSecret only to the authorized purchaser's payment UI.
208
+ // Observe the original purchase after payment; wait for its ready grant.
209
+ ```
210
+
211
+ Use `ensureUsageMeter`, `ensureUsagePrice` and `usage.ensureSubscription` to bind
212
+ the chosen plan to the server-authorized native payer. The exact implementations
213
+ are in the example's `meteredUsage/setup.ts` and `meteredUsage/funding.ts`.
214
+
215
+ ## Package calls behind the example
216
+
217
+ Server code imports neutral types from `@fantastic.dev/better-stripe/usage`; UI
218
+ code uses `@fantastic.dev/better-stripe/react`. The example backend lives under
219
+ `example/convex/meteredUsage`. Its atomic synthetic-work mutation follows this
220
+ pattern, using server-authorized original terms:
221
+
222
+ ```ts
223
+ const reservation =
224
+ model === "prepaid"
225
+ ? await stripe.usage.reserveCredits(ctx, { event, subscription })
226
+ : await stripe.usage.reserveAllowance(ctx, { event, subscription });
227
+ // Handle denied/released reservations before doing any application work.
228
+ const receipt = await stripe.usage.record(ctx, {
229
+ event,
230
+ subscription,
231
+ reservationId: reservation.reservationId,
232
+ });
233
+ // Persist synthetic DB work and receipt in this same mutation transaction.
234
+ ```
235
+
236
+ Schedule delivery from an action after the transaction commits:
237
+
238
+ ```ts
239
+ await stripe.usage.startDelivery(ctx, {
240
+ scope: original.scope,
241
+ eventId: receipt.eventId,
242
+ provider: internal.meteredUsage.delivery.deliver,
243
+ });
244
+ ```
245
+
246
+ For external application work, use a durable idempotent work protocol with the
247
+ original business identity. A database transaction cannot make an external side
248
+ effect atomic. See [ledger](usage-ledger.md), [delivery](usage-delivery.md),
249
+ [limits](usage-limits.md), [corrections](usage-corrections.md) and
250
+ [settlement](usage-settlement.md) for the complete contracts.
@@ -180,3 +180,7 @@ Run `pnpm run check:all` and verify your host's authorization and native setup
180
180
  using the [setup guide](metering-setup.md). Package views do not replace the
181
181
  [ledger](usage-ledger.md), [allowance](usage-limits.md) or
182
182
  [paid-credit](usage-credits.md) work and recovery protocols.
183
+
184
+ Server adapters can import the `UsageViewScope` and `UsageBillingSnapshot` types
185
+ from `@fantastic.dev/better-stripe/usage` without importing React types. The React
186
+ entry point retains its existing exports.
@@ -78,13 +78,18 @@ invoice. Refunds and disputes do not reset eligibility.
78
78
  An unpaid draft/open invoice returns `not_ready/provider_pending`. Missing fees
79
79
  remain `not_ready/fee_pending`. Zero paid invoices and refunded/disputed sources
80
80
  are not payable. Incomplete or ambiguous funding, credit-funded/partial/multiple
81
- payments, multiple priced invoice lines, proration, mismatched original periods,
81
+ payments, unrelated priced invoice lines, proration, mismatched original periods,
82
82
  converted settlement currencies and automatic destination/on-behalf-of charges
83
83
  are held through explicit non-ready outcomes. The method does not guess a
84
84
  multi-product allocation or take over existing destination-charge fee handling.
85
85
  Fixed-plus-metered invoices remain readable with the ordinary invoice APIs, but
86
- this automatic settlement method requires one original priced line. Treat these
87
- limits as unsupported settlement combinations, not as zero proceeds.
86
+ this automatic settlement method requires one paid original meter line. Native
87
+ included-overage invoices can also contain one zero-priced included-tier line.
88
+ Both lines must retain the same original price, product, subscription item,
89
+ period, currency and mode, with no credit adjustments. The complete independent
90
+ line-item read must match both original IDs. Additional paid lines, duplicate IDs
91
+ and foreign zero-priced siblings remain unsupported. Treat unsupported settlement
92
+ combinations as unavailable evidence rather than zero proceeds.
88
93
 
89
94
  ## Prepaid issuer-service revenue
90
95
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.62.0",
3
+ "version": "0.64.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -113,7 +113,9 @@
113
113
  "docs/usage-security.md",
114
114
  "docs/usage-react.md",
115
115
  "docs/evidence/native-metering",
116
- "docs/usage-configuration.md"
116
+ "docs/usage-configuration.md",
117
+ "docs/usage-example.md",
118
+ "docs/payout-revision-migration.md"
117
119
  ],
118
120
  "scripts": {
119
121
  "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
@@ -6,7 +6,7 @@ import {
6
6
  assertSelector,
7
7
  } from "../component/financialOwnership/helpers.js";
8
8
  import type { registrationDoc } from "../component/financialOwnership/schema.js";
9
- import { FinancialObservationsHost } from "./financialObservations.js";
9
+ import { ReversalObservationsHost } from "./reversalObservations.js";
10
10
  import type { Component, RunCtx } from "./helpers.js";
11
11
  import { runMutationOrThrow } from "./helpers.js";
12
12
  import { componentRef } from "./webhooks/helpers.js";
@@ -111,6 +111,6 @@ export class FinancialOwnershipClient {
111
111
  }
112
112
  }
113
113
  /** Extends the existing facade without expanding its frozen entry-file budget. */
114
- export abstract class FinancialOwnershipHost extends FinancialObservationsHost {
114
+ export abstract class FinancialOwnershipHost extends ReversalObservationsHost {
115
115
  readonly financialOwnership = new FinancialOwnershipClient(this.component);
116
116
  }
@@ -1,3 +1,4 @@
1
+ import { zeroTierLinesMatch } from "./zeroTierLines.js";
1
2
  import type Stripe from "stripe";
2
3
  import type {
3
4
  FinancialOutcome,
@@ -53,6 +54,7 @@ export async function resolveVerifiedPaymentSource(
53
54
  customerId: string;
54
55
  invoiceLine?: {
55
56
  id: string;
57
+ zeroAmountLineIds?: string[];
56
58
  subscriptionItemId: string;
57
59
  period: { start: number; end: number };
58
60
  };
@@ -324,8 +326,18 @@ export async function resolveVerifiedPaymentSource(
324
326
  ),
325
327
  );
326
328
  if (lines.status !== "complete") return lines;
327
- requireSource(lines.data.length === 1, reject("unsupported_source"));
328
- const line = lines.data[0]!;
329
+ const zeroIds = eligibility?.invoiceLine?.zeroAmountLineIds ?? [];
330
+ const line = zeroIds.length
331
+ ? lines.data.find((row) => row.id === eligibility!.invoiceLine!.id)
332
+ : lines.data[0];
333
+ requireSource(
334
+ line &&
335
+ (zeroIds.length
336
+ ? zeroTierLinesMatch(lines.data, line, zeroIds)
337
+ : lines.data.length === 1),
338
+ reject("unsupported_source"),
339
+ );
340
+ if (!line) return reject("unsupported_source");
329
341
  requireSource(
330
342
  line.object === "line_item" &&
331
343
  line.invoice === invoice.id &&
@@ -0,0 +1,42 @@
1
+ import type Stripe from "stripe";
2
+ /** Only explicitly pinned zero-priced siblings of one paid graduated tier are eligible. */
3
+ export function zeroTierLinesMatch(
4
+ lines: Stripe.InvoiceLineItem[],
5
+ paid: Stripe.InvoiceLineItem,
6
+ ids: readonly string[],
7
+ ): boolean {
8
+ if (
9
+ ids.length !== 1 ||
10
+ lines.length !== 2 ||
11
+ new Set(lines.map((row) => row.id)).size !== 2
12
+ )
13
+ return false;
14
+ const free = lines.find((row) => row.id === ids[0]);
15
+ if (!free || free.id === paid.id) return false;
16
+ const parent = free.parent?.subscription_item_details;
17
+ const original = paid.parent?.subscription_item_details;
18
+ const price = free.pricing?.price_details;
19
+ const originalPrice = paid.pricing?.price_details;
20
+ return (
21
+ free.object === "line_item" &&
22
+ free.invoice === paid.invoice &&
23
+ free.livemode === paid.livemode &&
24
+ free.amount === 0 &&
25
+ free.currency === paid.currency &&
26
+ free.period.start === paid.period.start &&
27
+ free.period.end === paid.period.end &&
28
+ !!parent &&
29
+ !parent.proration &&
30
+ parent.subscription === original?.subscription &&
31
+ parent.subscription_item === original?.subscription_item &&
32
+ free.pricing?.type === "price_details" &&
33
+ !!price &&
34
+ price.price === originalPrice?.price &&
35
+ price.product === originalPrice?.product &&
36
+ (free.pretax_credit_amounts ?? []).length === 0 &&
37
+ (free.quantity_decimal != null
38
+ ? /^\d{1,30}(\.\d{1,12})?$/.test(free.quantity_decimal.toString()) &&
39
+ /[1-9]/.test(free.quantity_decimal.toString())
40
+ : Number.isSafeInteger(free.quantity) && free.quantity! > 0)
41
+ );
42
+ }
@@ -0,0 +1,40 @@
1
+ // @vitest-environment edge-runtime
2
+ import { expect, it } from "vitest";
3
+ import schema from "../component/schema.js";
4
+ import { BetterStripe } from "./index.js";
5
+ import type { RunCtx } from "./helpers.js";
6
+ import { components, initConvexTest } from "./setup.test.js";
7
+ const modules = import.meta.glob("../component/**/*.ts");
8
+ it("runs the trusted migration through the public facade without Stripe or financial writes", async () => {
9
+ const t = initConvexTest();
10
+ t.registerComponent("betterStripe", schema, modules);
11
+ const client = new BetterStripe(components.betterStripe);
12
+ const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
13
+ const migration = client.payoutRevisionMigration;
14
+ expect(await migration.activateAccount(ctx, { accountId: "opaque" })).toEqual(
15
+ { accountId: "opaque", status: "activated" },
16
+ );
17
+ let job = await migration.begin(ctx, { operationKey: "public-pass" });
18
+ expect(await migration.get(ctx, { jobId: job._id })).toEqual(job);
19
+ while (job.status !== "finished")
20
+ job = await migration.resume(ctx, {
21
+ jobId: job._id,
22
+ expectedStep: job.step,
23
+ });
24
+ expect(job).toMatchObject({ status: "finished", visited: 0 });
25
+ expect(
26
+ await migration.results(ctx, {
27
+ jobId: job._id,
28
+ paginationOpts: { numItems: 1, cursor: null },
29
+ }),
30
+ ).toMatchObject({ page: [], isDone: true });
31
+ expect(() =>
32
+ migration.resume(ctx, { jobId: job._id, expectedStep: -1 }),
33
+ ).toThrow();
34
+ expect(() =>
35
+ migration.results(ctx, {
36
+ jobId: job._id,
37
+ paginationOpts: { numItems: 101, cursor: null },
38
+ }),
39
+ ).toThrow();
40
+ });
@@ -0,0 +1,96 @@
1
+ import type { PaginationResult } from "convex/server";
2
+ import type { Infer } from "convex/values";
3
+ import { z } from "zod";
4
+ import { FinancialObservationsHost } from "./financialObservations.js";
5
+ import { runMutationOrThrow, type Component, type RunCtx } from "./helpers.js";
6
+ import { componentRef } from "./webhooks/helpers.js";
7
+ import { observationPagination } from "./observationPagination.js";
8
+ import type { activationResult } from "../component/payoutRevisionJournal/schema.js";
9
+ import type {
10
+ jobDoc,
11
+ resultDoc,
12
+ } from "../component/payoutRevisionMigration/schema.js";
13
+ export type PayoutRevisionActivation = Infer<typeof activationResult>;
14
+ export type PayoutRevisionMigrationState = Infer<typeof jobDoc>;
15
+ export type PayoutRevisionMigrationResult = Infer<typeof resultDoc>;
16
+ const jobId = z.string().min(1).max(256);
17
+ /** Trusted host maintenance only. Authorize every call; completion is not financial coverage. */
18
+ export class PayoutRevisionMigrationClient {
19
+ constructor(private component: Component) {}
20
+ activateAccount(
21
+ ctx: RunCtx,
22
+ input: { accountId: string },
23
+ ): Promise<PayoutRevisionActivation> {
24
+ const args = z.object({ accountId: z.string() }).strict().parse(input);
25
+ return runMutationOrThrow(
26
+ ctx,
27
+ componentRef(
28
+ this.component,
29
+ "payoutRevisionJournal/mutations/activateAccount",
30
+ ),
31
+ args,
32
+ );
33
+ }
34
+ begin(
35
+ ctx: RunCtx,
36
+ input: { operationKey: string },
37
+ ): Promise<PayoutRevisionMigrationState> {
38
+ const args = z
39
+ .object({ operationKey: z.string().min(1).max(256) })
40
+ .strict()
41
+ .parse(input);
42
+ return runMutationOrThrow(
43
+ ctx,
44
+ componentRef(this.component, "payoutRevisionMigration/mutations/begin"),
45
+ args,
46
+ );
47
+ }
48
+ resume(
49
+ ctx: RunCtx,
50
+ input: { jobId: string; expectedStep: number },
51
+ ): Promise<PayoutRevisionMigrationState> {
52
+ const args = z
53
+ .object({
54
+ jobId,
55
+ expectedStep: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
56
+ })
57
+ .strict()
58
+ .parse(input);
59
+ return runMutationOrThrow(
60
+ ctx,
61
+ componentRef(this.component, "payoutRevisionMigration/mutations/resume"),
62
+ args,
63
+ );
64
+ }
65
+ get(
66
+ ctx: RunCtx,
67
+ input: { jobId: string },
68
+ ): Promise<PayoutRevisionMigrationState | null> {
69
+ const args = z.object({ jobId }).strict().parse(input);
70
+ return ctx.runQuery(
71
+ componentRef(this.component, "payoutRevisionMigration/queries/get"),
72
+ args,
73
+ );
74
+ }
75
+ results(
76
+ ctx: RunCtx,
77
+ input: {
78
+ jobId: string;
79
+ paginationOpts: z.input<typeof observationPagination>;
80
+ },
81
+ ): Promise<PaginationResult<PayoutRevisionMigrationResult>> {
82
+ const args = z
83
+ .object({ jobId, paginationOpts: observationPagination })
84
+ .strict()
85
+ .parse(input);
86
+ return ctx.runQuery(
87
+ componentRef(this.component, "payoutRevisionMigration/queries/results"),
88
+ args,
89
+ );
90
+ }
91
+ }
92
+ export abstract class PayoutRevisionMigrationHost extends FinancialObservationsHost {
93
+ readonly payoutRevisionMigration = new PayoutRevisionMigrationClient(
94
+ this.component,
95
+ );
96
+ }
@@ -103,3 +103,18 @@ export type {
103
103
  AccountByStripeIdOptions,
104
104
  SubscriptionByStripeIdOptions,
105
105
  } from "./originalIdReadOptions.js";
106
+
107
+ export type {
108
+ PayoutRevisionActivation,
109
+ PayoutRevisionMigrationState,
110
+ PayoutRevisionMigrationResult,
111
+ } from "./payoutRevisionMigration.js";
112
+
113
+ export type {
114
+ ReversalObservation,
115
+ ReversalObservationSlice,
116
+ ReversalObservationPayload,
117
+ ReversalObservationState,
118
+ ReversalObservationResult,
119
+ ReversalObservationPage,
120
+ } from "./reversalObservations.js";