@fantastic.dev/better-stripe 0.58.0 → 0.59.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 (198) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +238 -18
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +119 -9
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +238 -18
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +119 -9
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/usage/allowanceClient.d.ts +1 -1
  12. package/dist/client/usage/client.d.ts +2 -2
  13. package/dist/client/usage/client.d.ts.map +1 -1
  14. package/dist/client/usage/client.js +2 -2
  15. package/dist/client/usage/client.js.map +1 -1
  16. package/dist/client/usage/correctionClient.d.ts +33 -0
  17. package/dist/client/usage/correctionClient.d.ts.map +1 -0
  18. package/dist/client/usage/correctionClient.js +27 -0
  19. package/dist/client/usage/correctionClient.js.map +1 -0
  20. package/dist/client/usage/correctionEligibility.d.ts +4 -0
  21. package/dist/client/usage/correctionEligibility.d.ts.map +1 -0
  22. package/dist/client/usage/correctionEligibility.js +7 -0
  23. package/dist/client/usage/correctionEligibility.js.map +1 -0
  24. package/dist/client/usage/correctionInvoice.d.ts +9 -0
  25. package/dist/client/usage/correctionInvoice.d.ts.map +1 -0
  26. package/dist/client/usage/correctionInvoice.js +218 -0
  27. package/dist/client/usage/correctionInvoice.js.map +1 -0
  28. package/dist/client/usage/correctionInvoiceProof.d.ts +29 -0
  29. package/dist/client/usage/correctionInvoiceProof.d.ts.map +1 -0
  30. package/dist/client/usage/correctionInvoiceProof.js +41 -0
  31. package/dist/client/usage/correctionInvoiceProof.js.map +1 -0
  32. package/dist/client/usage/correctionProofs.d.ts +36 -0
  33. package/dist/client/usage/correctionProofs.d.ts.map +1 -0
  34. package/dist/client/usage/correctionProofs.js +41 -0
  35. package/dist/client/usage/correctionProofs.js.map +1 -0
  36. package/dist/client/usage/correctionProvider.d.ts +6 -0
  37. package/dist/client/usage/correctionProvider.d.ts.map +1 -0
  38. package/dist/client/usage/correctionProvider.js +243 -0
  39. package/dist/client/usage/correctionProvider.js.map +1 -0
  40. package/dist/client/usage/correctionRead.d.ts +27 -0
  41. package/dist/client/usage/correctionRead.d.ts.map +1 -0
  42. package/dist/client/usage/correctionRead.js +36 -0
  43. package/dist/client/usage/correctionRead.js.map +1 -0
  44. package/dist/client/usage/correctionTerms.d.ts +64 -0
  45. package/dist/client/usage/correctionTerms.d.ts.map +1 -0
  46. package/dist/client/usage/correctionTerms.js +65 -0
  47. package/dist/client/usage/correctionTerms.js.map +1 -0
  48. package/dist/client/usage/correctionTransport.fixtures.d.ts +37 -0
  49. package/dist/client/usage/correctionTransport.fixtures.d.ts.map +1 -0
  50. package/dist/client/usage/correctionTransport.fixtures.js +322 -0
  51. package/dist/client/usage/correctionTransport.fixtures.js.map +1 -0
  52. package/dist/client/usage/creditClient.d.ts +1 -1
  53. package/dist/client/usage/index.d.ts +2 -0
  54. package/dist/client/usage/index.d.ts.map +1 -1
  55. package/dist/client/usage/observationClient.d.ts +20 -0
  56. package/dist/client/usage/observationClient.d.ts.map +1 -1
  57. package/dist/client/usage/observationClient.js +20 -6
  58. package/dist/client/usage/observationClient.js.map +1 -1
  59. package/dist/client/usage/records.d.ts +1 -1
  60. package/dist/client/usage/records.d.ts.map +1 -1
  61. package/dist/client/usage/records.js.map +1 -1
  62. package/dist/client/usage/summary.d.ts +3 -0
  63. package/dist/client/usage/summary.d.ts.map +1 -1
  64. package/dist/client/usage/summary.js +9 -4
  65. package/dist/client/usage/summary.js.map +1 -1
  66. package/dist/client/usageExports.d.ts +2 -0
  67. package/dist/client/usageExports.d.ts.map +1 -1
  68. package/dist/component/_generated/api.d.ts +12 -0
  69. package/dist/component/_generated/api.d.ts.map +1 -1
  70. package/dist/component/_generated/api.js.map +1 -1
  71. package/dist/component/_generated/component.d.ts +255 -14
  72. package/dist/component/_generated/component.d.ts.map +1 -1
  73. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  74. package/dist/component/accountClosure/mutations.js +13 -0
  75. package/dist/component/accountClosure/mutations.js.map +1 -1
  76. package/dist/component/balanceFunding/mutations.d.ts +27 -27
  77. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  78. package/dist/component/earnings/triggers.d.ts +212 -26
  79. package/dist/component/earnings/triggers.d.ts.map +1 -1
  80. package/dist/component/schema.d.ts +119 -9
  81. package/dist/component/schema.js +4 -0
  82. package/dist/component/schema.js.map +1 -1
  83. package/dist/component/usage/queries.d.ts +2 -2
  84. package/dist/component/usage/schema.d.ts +18 -13
  85. package/dist/component/usage/schema.d.ts.map +1 -1
  86. package/dist/component/usage/schema.js +2 -1
  87. package/dist/component/usage/schema.js.map +1 -1
  88. package/dist/component/usageAllowance/queries.d.ts +1 -1
  89. package/dist/component/usageAllowance/queries.d.ts.map +1 -1
  90. package/dist/component/usageAllowance/queries.js +10 -1
  91. package/dist/component/usageAllowance/queries.js.map +1 -1
  92. package/dist/component/usageAllowance/schema.d.ts +5 -5
  93. package/dist/component/usageAllowance/schema.d.ts.map +1 -1
  94. package/dist/component/usageAllowance/schema.js +1 -1
  95. package/dist/component/usageAllowance/schema.js.map +1 -1
  96. package/dist/component/usageCorrections/accounting.d.ts +5 -0
  97. package/dist/component/usageCorrections/accounting.d.ts.map +1 -0
  98. package/dist/component/usageCorrections/accounting.js +55 -0
  99. package/dist/component/usageCorrections/accounting.js.map +1 -0
  100. package/dist/component/usageCorrections/cancellation.d.ts +6 -0
  101. package/dist/component/usageCorrections/cancellation.d.ts.map +1 -0
  102. package/dist/component/usageCorrections/cancellation.js +29 -0
  103. package/dist/component/usageCorrections/cancellation.js.map +1 -0
  104. package/dist/component/usageCorrections/helpers.d.ts +60 -0
  105. package/dist/component/usageCorrections/helpers.d.ts.map +1 -0
  106. package/dist/component/usageCorrections/helpers.js +52 -0
  107. package/dist/component/usageCorrections/helpers.js.map +1 -0
  108. package/dist/component/usageCorrections/invoice.d.ts +38 -0
  109. package/dist/component/usageCorrections/invoice.d.ts.map +1 -0
  110. package/dist/component/usageCorrections/invoice.js +82 -0
  111. package/dist/component/usageCorrections/invoice.js.map +1 -0
  112. package/dist/component/usageCorrections/mutations.d.ts +121 -0
  113. package/dist/component/usageCorrections/mutations.d.ts.map +1 -0
  114. package/dist/component/usageCorrections/mutations.js +256 -0
  115. package/dist/component/usageCorrections/mutations.js.map +1 -0
  116. package/dist/component/usageCorrections/queries.d.ts +115 -0
  117. package/dist/component/usageCorrections/queries.d.ts.map +1 -0
  118. package/dist/component/usageCorrections/queries.js +84 -0
  119. package/dist/component/usageCorrections/queries.js.map +1 -0
  120. package/dist/component/usageCorrections/schema.d.ts +248 -0
  121. package/dist/component/usageCorrections/schema.d.ts.map +1 -0
  122. package/dist/component/usageCorrections/schema.js +74 -0
  123. package/dist/component/usageCorrections/schema.js.map +1 -0
  124. package/dist/component/usageCredits/queries.d.ts +1 -1
  125. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  126. package/dist/component/usageCredits/queries.js +6 -0
  127. package/dist/component/usageCredits/queries.js.map +1 -1
  128. package/dist/component/usageCredits/schema.d.ts +5 -5
  129. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  130. package/dist/component/usageCredits/schema.js +1 -1
  131. package/dist/component/usageCredits/schema.js.map +1 -1
  132. package/dist/component/usageDelivery/fields.d.ts +2 -2
  133. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  134. package/dist/component/usageDelivery/fields.js +1 -1
  135. package/dist/component/usageDelivery/fields.js.map +1 -1
  136. package/dist/component/usageDelivery/helpers.d.ts +7 -6
  137. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  138. package/dist/component/usageDelivery/mutations.d.ts +6 -6
  139. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  140. package/dist/component/usageDelivery/mutations.js +9 -1
  141. package/dist/component/usageDelivery/mutations.js.map +1 -1
  142. package/dist/component/usageDelivery/queries.d.ts +8 -6
  143. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  144. package/dist/component/usageDelivery/schema.d.ts +4 -4
  145. package/dist/component/usageDelivery/steps.d.ts +2 -2
  146. package/dist/component/usageDelivery/steps.js +1 -1
  147. package/dist/component/usageDelivery/steps.js.map +1 -1
  148. package/dist/component/usageObservations/queries.d.ts.map +1 -1
  149. package/dist/component/usageObservations/queries.js +4 -2
  150. package/dist/component/usageObservations/queries.js.map +1 -1
  151. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -1
  152. package/dist/component/usageSubscriptions/retirement.js +24 -2
  153. package/dist/component/usageSubscriptions/retirement.js.map +1 -1
  154. package/docs/README.md +2 -0
  155. package/docs/usage-corrections.md +249 -0
  156. package/docs/usage-limits.md +1 -1
  157. package/package.json +2 -1
  158. package/src/client/usage/client.ts +2 -2
  159. package/src/client/usage/correctionClient.test.ts +153 -0
  160. package/src/client/usage/correctionClient.ts +62 -0
  161. package/src/client/usage/correctionCredits.test.ts +156 -0
  162. package/src/client/usage/correctionEligibility.ts +14 -0
  163. package/src/client/usage/correctionInvoice.test.ts +127 -0
  164. package/src/client/usage/correctionInvoice.ts +269 -0
  165. package/src/client/usage/correctionInvoiceProof.ts +40 -0
  166. package/src/client/usage/correctionProofs.ts +40 -0
  167. package/src/client/usage/correctionProvider.ts +326 -0
  168. package/src/client/usage/correctionRead.ts +73 -0
  169. package/src/client/usage/correctionRecovery.test.ts +113 -0
  170. package/src/client/usage/correctionTerms.ts +98 -0
  171. package/src/client/usage/correctionTransport.fixtures.ts +372 -0
  172. package/src/client/usage/index.ts +11 -0
  173. package/src/client/usage/observationClient.ts +20 -6
  174. package/src/client/usage/records.ts +7 -1
  175. package/src/client/usage/summary.ts +12 -4
  176. package/src/client/usageExports.ts +11 -0
  177. package/src/component/_generated/api.ts +12 -0
  178. package/src/component/_generated/component.ts +330 -2
  179. package/src/component/accountClosure/mutations.ts +17 -0
  180. package/src/component/schema.ts +8 -0
  181. package/src/component/usage/schema.ts +2 -0
  182. package/src/component/usageAllowance/queries.ts +8 -1
  183. package/src/component/usageAllowance/schema.ts +1 -0
  184. package/src/component/usageCorrections/accounting.ts +79 -0
  185. package/src/component/usageCorrections/cancellation.ts +32 -0
  186. package/src/component/usageCorrections/corrections.test.ts +389 -0
  187. package/src/component/usageCorrections/helpers.ts +57 -0
  188. package/src/component/usageCorrections/invoice.ts +103 -0
  189. package/src/component/usageCorrections/mutations.ts +278 -0
  190. package/src/component/usageCorrections/queries.ts +94 -0
  191. package/src/component/usageCorrections/schema.ts +90 -0
  192. package/src/component/usageCredits/queries.ts +4 -0
  193. package/src/component/usageCredits/schema.ts +1 -0
  194. package/src/component/usageDelivery/fields.ts +1 -0
  195. package/src/component/usageDelivery/mutations.ts +8 -3
  196. package/src/component/usageDelivery/steps.ts +1 -1
  197. package/src/component/usageObservations/queries.ts +5 -2
  198. package/src/component/usageSubscriptions/retirement.ts +31 -2
@@ -0,0 +1,249 @@
1
+ # Usage corrections and invoice adjustments
2
+
3
+ Correct the original activity through `stripe.usage.requestCorrection`. The package
4
+ retains the immutable event, original subscription/price terms, acceptance receipt,
5
+ delivery history, native outcome and quantity-accounting provenance. Corrections
6
+ never create another cash collection, transfer or commission.
7
+
8
+ Authenticate the operator and authorize the exact original activity on the server.
9
+ Resolve the payer and realm from trusted ownership records. Derive `actor` from the
10
+ signed-in operator, and use an opaque actor ID and a reason without private customer
11
+ information. A browser must not supply another payer, native proof or provider key.
12
+
13
+ ```ts
14
+ const result = await stripe.usage.requestCorrection(
15
+ ctx,
16
+ {
17
+ scope: original.scope,
18
+ eventId: originalReceipt.eventId,
19
+ correctionId: operatorCommand.id,
20
+ actor: authorizedOperator.id,
21
+ reason: "duplicate_activity",
22
+ operation: "cancel",
23
+ },
24
+ { stripeSecretKey: process.env.STRIPE_SECRET_KEY },
25
+ );
26
+ ```
27
+
28
+ Run native operations in an action or durable host worker. The same Stripe sandbox
29
+ and server-side key used by the rest of BetterStripe is sufficient. No Metronome
30
+ account or credential is required. Provider keys and raw provider error bodies do
31
+ not enter component history or workflow state.
32
+
33
+ A correction ID is immutable within its realm, payer, meter and mode. Retries keep
34
+ its original actor, reason, event and quantity. Changed requests conflict. Only one
35
+ full event-cancellation operation can claim an event. The original business source
36
+ identity stays retained, including after cancellation or a new subscription.
37
+
38
+ ## Full event cancellation
39
+
40
+ For an event that has never started delivery, pay-as-you-go and included-usage
41
+ cancellation completes in the same component transaction as its terminal delivery
42
+ state and quantity restoration. Prepaid first verifies the original successful
43
+ payment, native grant and available backing. It restores only the event's original
44
+ grant allocations, without minting another grant or refunding cash.
45
+
46
+ The original `record` receipt remains unchanged. Read `getDelivery` for its current
47
+ `canceled` state. Canceled delivery cannot start or resume. Summaries retain raw
48
+ `acceptedQuantity`, and expose `canceledQuantity`, `effectiveQuantity` and
49
+ `effectiveScaledQuantity`. Included consumption and cost estimates use effective
50
+ quantity. The event and its original native receipt remain available for audit.
51
+
52
+ For provider-accepted events, BetterStripe sends a native Meter Event Adjustment
53
+ using the retained event name and native identifier. It checks the original realm,
54
+ Accounts v2 payer, mapped Customer, exact meter, subscription item, price and period.
55
+ The package uses a conservative 23-hour window after Stripe's original receipt,
56
+ within Stripe's 24-hour cancellation window. It also closes this path before the
57
+ managed billing period closes.
58
+
59
+ The native v1 adjustment response has no adjustment ID. `nativeAdjustmentId` is
60
+ therefore `null`; the stable correction operation key and original native event
61
+ identifier are retained instead. The package does not invent an adjustment ID,
62
+ retrieval endpoint or completion webhook.
63
+
64
+ A native `pending` response becomes `provider_accepted`, with
65
+ `nativeStatus: "pending"` and `restoredQuantity: "0"`. It does not prove that usage
66
+ was removed from billing. Repeating the command returns that recorded pending
67
+ outcome. A summary or invoice preview is not proof that this individual event was
68
+ canceled. An unresolved pending result needs explicit operator investigation.
69
+
70
+ A native `complete` response can restore units once only after invoice checks
71
+ before and after the request establish that billing remains open and no applicable
72
+ finalized usage invoice was found. Prepaid additionally rechecks payment/grant
73
+ backing after cancellation. If an invoice finalized during cancellation, the
74
+ result retains native completion but becomes `invoice_adjustment_required`, with
75
+ no restored units. Incomplete invoice history stays held.
76
+
77
+ Included allowance restoration updates the original period counter and keeps all
78
+ policy revisions and reservations. It does not grant units in a later period.
79
+ Prepaid restoration retains the original purchase, currency, version, rate,
80
+ allocation and expiry. Refunded, disputed, frozen, expired or unavailable backing
81
+ cannot become spendable through a correction. Use
82
+ [credit reconciliation and recovery](./usage-credits.md) for those cases.
83
+
84
+ ## Unknown outcomes and recovery
85
+
86
+ A full correction holds further event delivery while it is unresolved. An
87
+ in-flight or unknown original send cannot be treated as unsent. Let the original
88
+ durable delivery workflow recover its receipt; do not fabricate provider success.
89
+
90
+ Native correction writes use one stable idempotency key. A lost response becomes
91
+ `held` with `provider_outcome_unknown`, and never restores quantity. Retrying the
92
+ same command uses that key and request. Concurrent attempts have a 15-minute lease;
93
+ a crashed attempt retains its identity and can retry after the lease. Receipt
94
+ storage failure can recover through the same retained operation rather than a
95
+ new cancellation command.
96
+
97
+ The package stops native retries 23 hours after the first correction attempt or
98
+ when the original receipt's cancellation window or billing period closes. A provably
99
+ unsent prepaid event can still complete local cancellation later after fresh
100
+ payment/grant verification; no native cancellation write is needed. The package
101
+ returns held or invoice-adjustment-required evidence for operator resolution.
102
+ Do not retry old commands under new IDs, delete an outbox entry or alter the
103
+ original occurrence time to bypass these bounds.
104
+
105
+ Confirmed full cancellation can resolve that event's validation error for
106
+ retirement while preserving every error record. The retirement audit checks at
107
+ most 100 retained validation errors and stays held if the evidence exceeds that
108
+ bound or any error lacks proven cancellation.
109
+
110
+ Pending native corrections and required financial adjustments block managed
111
+ subscription retirement and account closure. New correction work cannot start
112
+ after account closure has begun. Reads retain historical evidence.
113
+
114
+ ## Partial quantities and finalized invoices
115
+
116
+ Native Meter Event Adjustments cancel a whole event. Passing an optional
117
+ `quantity` smaller than the original quantity returns `unsupported` with
118
+ `partial_event_requires_replacement_or_invoice_adjustment`. It neither changes the
119
+ original event nor restores units or stops valid delivery. Zero quantities and
120
+ amounts larger than the original are rejected. Do not send negative meter events
121
+ or change an immutable event's payload to simulate a partial correction.
122
+
123
+ A partial replacement is a separately authorized business operation, not an
124
+ implicit refund or new source identity. BetterStripe does not automatically compose
125
+ full cancellation and replacement across asynchronous native outcomes. Use an
126
+ explicit operator workflow and preserve both references if that composition is
127
+ needed. Never grant units while the original cancellation remains pending.
128
+
129
+ An expired cancellation window, a closed period or a finalized usage invoice
130
+ requires an invoice adjustment. A meter cancellation cannot establish that a
131
+ finalized invoice was reduced or that cash was refunded. Use the native Stripe
132
+ credit-note workflow and the existing authorized BetterStripe refund workflow.
133
+ Link an existing refund to the credit note when appropriate. Do not issue a second
134
+ refund merely because a credit note or usage correction is recorded.
135
+
136
+ `observeInvoiceCorrection` verifies and adopts an already issued native credit
137
+ note. It performs provider reads and records evidence. It does not create a credit
138
+ note, refund, customer-balance wallet or new financial settlement.
139
+
140
+ ```ts
141
+ const observed = await stripe.usage.observeInvoiceCorrection(
142
+ ctx,
143
+ {
144
+ scope: original.scope,
145
+ eventId: originalReceipt.eventId,
146
+ correctionId: operatorCommand.id,
147
+ invoiceId: "in_original",
148
+ creditNoteId: "cn_original_adjustment",
149
+ amount: 4, // Exact positive minor currency units authorized by the operator.
150
+ },
151
+ { stripeSecretKey: process.env.STRIPE_SECRET_KEY },
152
+ );
153
+ ```
154
+
155
+ This supports partial or full monetary adjustment against one original, unprorated
156
+ native usage invoice line in the original period and currency. The supplied amount
157
+ must exactly match the credit note. The native invoice, credit-note customer,
158
+ subscription item, price and line identities must agree. A credit note or refund
159
+ can be claimed by only one correction operation in the native realm and mode.
160
+ Changed adoption terms conflict.
161
+
162
+ For a post-payment adjustment, the reader verifies the original paid InvoicePayment,
163
+ PaymentIntent, captured Charge and succeeded linked Refund, with exact safe integer
164
+ amounts and matching currency/payer. A paid invoice alone is not proof of new cash.
165
+ Pre-payment invoice credits have no cash refund. They can even move an invoice to
166
+ `paid` by reducing its amount due to zero; that does not create payment proceeds.
167
+ A verified pre-payment credit-note void is recorded as a reversal with no cash or
168
+ unit restoration. Earlier issued evidence remains in history.
169
+
170
+ The observer returns a correction view when verified, or `{ status: "held", reason }`
171
+ when native evidence is unavailable or unsupported. Handle that union explicitly.
172
+ A verified view exposes `invoiceAdjustment` with the original amount, currency,
173
+ invoice line and any original payment/charge/refund references. `cashCollection`
174
+ always remains `"none"`.
175
+
176
+ A financial adjustment returns `resolution: "invoice_credit"`, retains valid usage
177
+ and its consumed units, and reports `restoredQuantity: "0"`. It cannot silently
178
+ cancel an event or restore credits. Existing seller/affiliate refund, dispute,
179
+ processing-cost and recovery protocols remain authoritative.
180
+
181
+ The bounded v1 observer holds incomplete pages, custom/multiple credit-note lines,
182
+ prorations, taxes/discount combinations, customer-balance or out-of-band adjustments,
183
+ pending refunds, foreign sources and unverified payment mappings. It reads at most
184
+ 100 invoices in cancellation preflight and requires complete embedded invoice/note
185
+ lines. It does not turn a partial page into a successful adjustment.
186
+
187
+ Prepaid invoice-credit adoption returns `held` with
188
+ `prepaid_credit_reconciliation_required`. Billing credit-grant application,
189
+ reinstatement, purchase refunds and local quantity restoration are different
190
+ operations. Use the original credit purchase's reconciliation/refund APIs and
191
+ native credit eligibility rules. A credit note, refund or reinstated native balance
192
+ must never independently mint local spendable units.
193
+
194
+ ## Scoped history and reconciliation
195
+
196
+ ```ts
197
+ const correction = await stripe.usage.getCorrection(ctx, {
198
+ scope: original.scope,
199
+ eventId: originalReceipt.eventId,
200
+ correctionId: operatorCommand.id,
201
+ });
202
+ const page = await stripe.usage.readCorrectionHistory(ctx, {
203
+ scope: original.scope,
204
+ eventId: originalReceipt.eventId,
205
+ limit: 25,
206
+ cursor: null,
207
+ });
208
+ const periodHistory = await stripe.usage.readCorrectionPeriodHistory(ctx, {
209
+ scope: original.scope,
210
+ period: original.subscription.period,
211
+ limit: 25,
212
+ cursor: null,
213
+ });
214
+ ```
215
+
216
+ Readers enforce the exact scope and page limits of 1–100. Each history record
217
+ retains original event/subscription snapshots, request identity, actor/reason and
218
+ sanitized native/accounting evidence. The package also decodes `record`,
219
+ `subscription`, `evidence` and `recordedAt` for typed consumers. Follow the returned
220
+ cursor until `isDone`.
221
+ `coverage: "not_recorded"` means no correction evidence was recorded on that page;
222
+ it is not proof that no external or legacy correction ever happened. Undated
223
+ legacy period records set `legacyHistoryMissing`.
224
+
225
+ `getReconciliation` exposes recorded correction history when evidence exists,
226
+ including its cursor and completeness. Without evidence it preserves typed
227
+ unsupported availability. Confirmed quantity cancellation is included in local
228
+ allowance and credit/invoice reconciliation; an unproven canceled projection is
229
+ held rather than counted as a zero charge. Financial adjustments remain separate
230
+ from quantity totals.
231
+
232
+ A correction view is a retained observation, with `observedAt`; it does not poll
233
+ Stripe automatically. Re-observe native invoice adjustments when their state
234
+ changes. Loading, stale, held and partial histories must remain visible in host UI.
235
+
236
+ History is retained with limits of 100 operations per event and 1000 history rows
237
+ per operation. Quota exhaustion fails the accounting transaction atomically.
238
+ Do not delete evidence to make room or release unknown liabilities during rollback.
239
+ Use existing delivery holds while investigating and resume only work whose native
240
+ and original financial outcome is known.
241
+
242
+ Native references: [Meter Event Adjustment API](https://docs.stripe.com/api/billing/meter-event-adjustment/create),
243
+ [credit notes](https://docs.stripe.com/invoicing/dashboard/credit-notes), and
244
+ [retrieving a credit note](https://docs.stripe.com/api/credit_notes/retrieve).
245
+
246
+ A delivery explicitly rejected by the provider with no acceptance receipt can
247
+ also be canceled locally. The original rejection and correction history remain
248
+ available. Paid credits require fresh verification of their original backing
249
+ before restoration. Unknown or in-flight delivery never qualifies for this path.
@@ -128,7 +128,7 @@ Committed usage cannot be released. Delivery rejection, uncertainty, delayed
128
128
  native aggregates or an unpaid invoice do not restore allowance. Corrections
129
129
  retain the original event and terms and require an auditable correction outcome;
130
130
  never decrement counters based on an invoice preview or an optimistic UI action.
131
- The correction workflow is documented separately as it becomes available.
131
+ See the [auditable correction workflow](./usage-corrections.md).
132
132
 
133
133
  ## Edit access policy without resetting consumption
134
134
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.58.0",
3
+ "version": "0.59.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -108,6 +108,7 @@
108
108
  "docs/usage-subscriptions.md",
109
109
  "docs/usage-credits.md",
110
110
  "docs/usage-limits.md",
111
+ "docs/usage-corrections.md",
111
112
  "docs/evidence/native-metering"
112
113
  ],
113
114
  "scripts": {
@@ -1,4 +1,4 @@
1
- import { UsageAllowanceClient } from "./allowanceClient.js";
1
+ import { UsageCorrectionClient } from "./correctionClient.js";
2
2
  import type { Component, RunCtx } from "../helpers.js";
3
3
  import { runMutationOrThrow } from "../helpers.js";
4
4
  import { componentRef } from "../webhooks/helpers.js";
@@ -46,7 +46,7 @@ function decode({ event, delivery }: StoredView): UsageEventView {
46
46
  };
47
47
  }
48
48
  /** Trusted host facade. Authenticate and authorize each exact scope first. */
49
- export class UsageLedgerClient extends UsageAllowanceClient {
49
+ export class UsageLedgerClient extends UsageCorrectionClient {
50
50
  constructor(component: Component) {
51
51
  super(component);
52
52
  }
@@ -0,0 +1,153 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { setupCorrection } from "./correctionTransport.fixtures.js";
4
+ afterEach(() => vi.useRealTimers());
5
+ it("uses the original native identifier and stable operation key without claiming pending cancellation complete", async () => {
6
+ const { f, client, options, correction, receipt, calls } =
7
+ await setupCorrection();
8
+ const result = await f.t.action((ctx) =>
9
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
10
+ );
11
+ expect(result).toMatchObject({
12
+ state: "provider_accepted",
13
+ nativeStatus: "pending",
14
+ nativeAdjustmentId: null,
15
+ restoredQuantity: "0",
16
+ cashConsequence: "none",
17
+ });
18
+ expect(
19
+ await f.t.action((ctx) =>
20
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
21
+ ),
22
+ ).toEqual(result);
23
+ expect(calls).toHaveLength(1);
24
+ expect(calls[0].body.get("cancel[identifier]")).toBe(
25
+ `bs_usage_${receipt.eventId}`,
26
+ );
27
+ expect(calls[0].key).toMatch(/^bs_usage_correction_/);
28
+ });
29
+
30
+ it("retains units if an invoice finalizes while the native cancellation is processing", async () => {
31
+ const { f, client, options, correction, state } = await setupCorrection();
32
+ state.status = "complete";
33
+ state.finalizeOnAdjust = true;
34
+ expect(
35
+ await f.t.action((ctx) =>
36
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
37
+ ),
38
+ ).toMatchObject({
39
+ state: "invoice_adjustment_required",
40
+ nativeStatus: "complete",
41
+ invoiceId: "in_usage",
42
+ restoredQuantity: "0",
43
+ cashConsequence: "operator_resolution_required",
44
+ });
45
+ });
46
+
47
+ it("exposes bounded correction evidence beside original usage and preserves unknown legacy coverage", async () => {
48
+ const { f, client, options, correction, original } = await setupCorrection();
49
+ const before = await f.t.query((ctx) =>
50
+ client.usage.readCorrectionHistory(ctx as RunCtx, {
51
+ scope: correction.scope,
52
+ eventId: correction.eventId,
53
+ limit: 1,
54
+ cursor: null,
55
+ }),
56
+ );
57
+ expect(before).toMatchObject({ records: [], coverage: "not_recorded" });
58
+ await f.t.action((ctx) =>
59
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
60
+ );
61
+ const page = await f.t.query((ctx) =>
62
+ client.usage.readCorrectionHistory(ctx as RunCtx, {
63
+ scope: correction.scope,
64
+ eventId: correction.eventId,
65
+ limit: 1,
66
+ cursor: null,
67
+ }),
68
+ );
69
+ expect(page.records).toHaveLength(1);
70
+ expect(page.isDone).toBe(false);
71
+ expect(page.coverage).toBe("recorded");
72
+ const status = await f.t.query((ctx) =>
73
+ client.usage.getReconciliation(ctx as RunCtx, {
74
+ scope: original.scope,
75
+ binding: original.binding,
76
+ subscription: original.subscription,
77
+ period: original.subscription.period,
78
+ }),
79
+ );
80
+ expect(status.correctionHistory).toMatchObject({
81
+ status: "available",
82
+ value: { coverage: "recorded" },
83
+ });
84
+ });
85
+
86
+ it("adopts a verified partial native invoice credit without erasing valid usage or issuing another refund", async () => {
87
+ const { f, client, options, correction } = await setupCorrection();
88
+ const partial = { ...correction, quantity: "2" };
89
+ expect(
90
+ await f.t.action((ctx) =>
91
+ client.usage.requestCorrection(ctx as RunCtx, partial, options),
92
+ ),
93
+ ).toMatchObject({ state: "unsupported", restoredQuantity: "0" });
94
+ const input = {
95
+ scope: correction.scope,
96
+ eventId: correction.eventId,
97
+ correctionId: correction.correctionId,
98
+ invoiceId: "in_usage",
99
+ creditNoteId: "cn_fix",
100
+ amount: 4,
101
+ };
102
+ const adopted = await f.t.action((ctx) =>
103
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
104
+ );
105
+ expect(adopted).toMatchObject({
106
+ state: "confirmed",
107
+ resolution: "invoice_credit",
108
+ creditNoteId: "cn_fix",
109
+ restoredQuantity: "0",
110
+ cashConsequence: "verified_external_adjustment",
111
+ });
112
+ expect(
113
+ await f.t.action((ctx) =>
114
+ client.usage.observeInvoiceCorrection(ctx as RunCtx, input, options),
115
+ ),
116
+ ).toEqual(adopted);
117
+ expect(
118
+ (
119
+ await f.t.query((ctx) =>
120
+ client.usage.getDelivery(ctx as RunCtx, {
121
+ scope: correction.scope,
122
+ eventId: correction.eventId,
123
+ }),
124
+ )
125
+ ).state,
126
+ ).toBe("provider_accepted");
127
+ });
128
+
129
+ it("restores included units once after complete native cancellation and reconciles the retained original ledger", async () => {
130
+ const { f, client, options, correction, original, state } =
131
+ await setupCorrection(true);
132
+ state.status = "complete";
133
+ expect(
134
+ await f.t.action((ctx) =>
135
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
136
+ ),
137
+ ).toMatchObject({ state: "confirmed", restoredQuantity: "6" });
138
+ expect(
139
+ await f.t.action((ctx) =>
140
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
141
+ ),
142
+ ).toMatchObject({ restoredQuantity: "6" });
143
+ expect(
144
+ await f.t.query((ctx) =>
145
+ client.usage.getAllowanceStatus(ctx as RunCtx, original),
146
+ ),
147
+ ).toMatchObject({ consumedQuantity: "0", remainingIncludedQuantity: "10" });
148
+ expect(
149
+ await f.t.query((ctx) =>
150
+ client.usage.reconcileAllowance(ctx as RunCtx, original),
151
+ ),
152
+ ).toMatchObject({ status: "matched", acceptedScaledQuantity: "0" });
153
+ });
@@ -0,0 +1,62 @@
1
+ import { observeInvoiceCorrection } from "./correctionInvoice.js";
2
+ import type { UsageInvoiceCorrectionOptions } from "./correctionTerms.js";
3
+ import { readCorrectionEvidence } from "./correctionRead.js";
4
+ import { scopeSchema, type UsageScope } from "./records.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import { correctionView } from "./correctionTerms.js";
8
+ import type { UsagePeriod } from "./boundaries.js";
9
+ import { UsageAllowanceClient } from "./allowanceClient.js";
10
+ import type { RunCtx } from "../helpers.js";
11
+ import { requestUsageCorrection } from "./correctionProvider.js";
12
+ import type { UsageCorrectionOptions } from "./correctionTerms.js";
13
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
14
+ /** Host authenticates and authorizes the actor and original activity before calling. */
15
+ export class UsageCorrectionClient extends UsageAllowanceClient {
16
+ async getCorrection(
17
+ ctx: RunCtx,
18
+ input: { scope: UsageScope; eventId: string; correctionId: string },
19
+ ) {
20
+ const row = (await ctx.runQuery(
21
+ componentRef(this.component, "usageCorrections/queries/get"),
22
+ { ...input, scope: scopeSchema.parse(input.scope) },
23
+ )) as Doc<"usageCorrections"> | null;
24
+ return row ? correctionView(row) : null;
25
+ }
26
+ readCorrectionHistory(
27
+ ctx: RunCtx,
28
+ input: {
29
+ scope: UsageScope;
30
+ eventId: string;
31
+ limit: number;
32
+ cursor: string | null;
33
+ },
34
+ ) {
35
+ return readCorrectionEvidence(this.component, ctx, input);
36
+ }
37
+ readCorrectionPeriodHistory(
38
+ ctx: RunCtx,
39
+ input: {
40
+ scope: UsageScope;
41
+ period: UsagePeriod;
42
+ limit: number;
43
+ cursor: string | null;
44
+ },
45
+ ) {
46
+ return readCorrectionEvidence(this.component, ctx, input);
47
+ }
48
+ observeInvoiceCorrection(
49
+ ctx: RunCtx,
50
+ input: UsageInvoiceCorrectionOptions,
51
+ options: UsageDeliveryProviderOptions,
52
+ ) {
53
+ return observeInvoiceCorrection(this.component, ctx, input, options);
54
+ }
55
+ requestCorrection(
56
+ ctx: RunCtx,
57
+ input: UsageCorrectionOptions,
58
+ options: UsageDeliveryProviderOptions = {},
59
+ ) {
60
+ return requestUsageCorrection(this.component, ctx, input, options);
61
+ }
62
+ }
@@ -0,0 +1,156 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import { componentRef } from "../webhooks/helpers.js";
4
+ import { BetterStripe } from "../index.js";
5
+ import type { RunCtx } from "../helpers.js";
6
+ import { creditFixture } from "./creditTransport.fixtures.js";
7
+ afterEach(() => vi.useRealTimers());
8
+ async function ready() {
9
+ const f = creditFixture(),
10
+ client = new BetterStripe(f.component),
11
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
12
+ const view = await f.ready();
13
+ await f.t.action((ctx) =>
14
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
15
+ );
16
+ f.state.paid = true;
17
+ await f.t.action((ctx) =>
18
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
19
+ );
20
+ const event = {
21
+ scope: f.purchase.scope,
22
+ binding: f.purchase.binding,
23
+ sourceEventId: "work1",
24
+ quantity: "6",
25
+ occurredAt: 700,
26
+ },
27
+ subscription = view.bindings[0].subscription;
28
+ const reservation = await f.t.action((ctx) =>
29
+ client.usage.reserveCredits(ctx as RunCtx, { event, subscription }),
30
+ );
31
+ const receipt = await f.t.action((ctx) =>
32
+ client.usage.record(ctx as RunCtx, {
33
+ event,
34
+ subscription,
35
+ reservationId: reservation.reservationId,
36
+ }),
37
+ );
38
+ const correction = {
39
+ scope: event.scope,
40
+ eventId: receipt.eventId,
41
+ correctionId: "fix1",
42
+ actor: "operator1",
43
+ reason: "duplicate activity",
44
+ operation: "cancel",
45
+ } as const;
46
+ return { f, client, options, correction };
47
+ }
48
+ it("restores original paid-grant quantity once for an unsent cancellation without minting a grant or refund", async () => {
49
+ const { f, client, options, correction } = await ready();
50
+ expect(
51
+ await f.t.action((ctx) =>
52
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
53
+ ),
54
+ ).toMatchObject({
55
+ state: "confirmed",
56
+ restoredQuantity: "6",
57
+ cashConsequence: "none",
58
+ });
59
+ expect(
60
+ await f.t.action((ctx) =>
61
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
62
+ ),
63
+ ).toMatchObject({ state: "confirmed", restoredQuantity: "6" });
64
+ expect(
65
+ await f.t.query((ctx) =>
66
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
67
+ ),
68
+ ).toMatchObject({
69
+ availableQuantity: "10",
70
+ consumedQuantity: "0",
71
+ status: "available",
72
+ });
73
+ expect(
74
+ f.calls.filter(
75
+ (c) => c.path === "/v1/billing/credit_grants" && c.method === "POST",
76
+ ),
77
+ ).toHaveLength(1);
78
+ expect(
79
+ f.calls.filter((c) => c.path.includes("refund") && c.method === "POST"),
80
+ ).toHaveLength(0);
81
+ });
82
+ it("holds prepaid restoration if its original purchase was refunded or its native credit is unavailable", async () => {
83
+ for (const recovery of ["refund", "unavailable"]) {
84
+ const { f, client, options, correction } = await ready();
85
+ if (recovery === "refund") f.state.refunded = true;
86
+ else f.state.nativeAvailable = 0;
87
+ expect(
88
+ await f.t.action((ctx) =>
89
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
90
+ ),
91
+ ).toMatchObject({ state: "held", restoredQuantity: "0" });
92
+ expect(
93
+ await f.t.query((ctx) =>
94
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
95
+ ),
96
+ ).toMatchObject({ consumedQuantity: "6" });
97
+ }
98
+ });
99
+ it("can verify and cancel provably unsent prepaid usage after a delayed credential recovery", async () => {
100
+ const { f, client, options, correction } = await ready();
101
+ expect(
102
+ await f.t.action((ctx) =>
103
+ client.usage.requestCorrection(ctx as RunCtx, correction),
104
+ ),
105
+ ).toMatchObject({ state: "held", restoredQuantity: "0" });
106
+ vi.advanceTimersByTime(24 * 3600 * 1000);
107
+ expect(
108
+ await f.t.action((ctx) =>
109
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
110
+ ),
111
+ ).toMatchObject({ state: "confirmed", restoredQuantity: "6" });
112
+ expect(
113
+ await f.t.query((ctx) =>
114
+ client.usage.getCreditBalance(ctx as RunCtx, f.purchase),
115
+ ),
116
+ ).toMatchObject({ availableQuantity: "10", consumedQuantity: "0" });
117
+ });
118
+
119
+ it("restores a known rejected prepaid delivery only after fresh backing verification", async () => {
120
+ for (const refunded of [false, true]) {
121
+ const { f, client, options, correction } = await ready();
122
+ workflowTest.register(f.t, "betterStripe/workflow");
123
+ const delivery = { scope: correction.scope, eventId: correction.eventId };
124
+ await f.t.mutation(
125
+ componentRef(f.component, "usageDelivery/mutations/start"),
126
+ {
127
+ ...delivery,
128
+ provider: "function://provider",
129
+ definitionVersion: 1,
130
+ },
131
+ );
132
+ const claim = (await f.t.mutation(
133
+ componentRef(f.component, "usageDelivery/steps/claim"),
134
+ delivery,
135
+ )) as { request: Record<string, unknown> };
136
+ await f.t.mutation(componentRef(f.component, "usageDelivery/steps/save"), {
137
+ ...claim.request,
138
+ outcome: { status: "rejected" },
139
+ });
140
+ f.state.refunded = refunded;
141
+ expect(
142
+ await f.t.action((ctx) =>
143
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
144
+ ),
145
+ ).toMatchObject({
146
+ state: refunded ? "held" : "confirmed",
147
+ restoredQuantity: refunded ? "0" : "6",
148
+ });
149
+ expect(
150
+ f.calls.filter(
151
+ (c) =>
152
+ c.path.includes("meter_event_adjustments") && c.method === "POST",
153
+ ),
154
+ ).toHaveLength(0);
155
+ }
156
+ });
@@ -0,0 +1,14 @@
1
+ import type { Doc } from "../../component/_generated/dataModel.js";
2
+ /** Local restoration requires proof that no native meter event was accepted. */
3
+ export function locallyCancelable(
4
+ outbox: Pick<
5
+ Doc<"usageOutbox">,
6
+ "attempts" | "firstSendAt" | "receipt" | "state" | "reason"
7
+ >,
8
+ ): boolean {
9
+ return (
10
+ !outbox.receipt &&
11
+ ((outbox.attempts === 0 && outbox.firstSendAt === undefined) ||
12
+ (outbox.state === "rejected" && outbox.reason === "provider_rejected"))
13
+ );
14
+ }