@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,372 @@
1
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
2
+ import type { UsageCorrectionOptions } from "./correctionTerms.js";
3
+ import type { UsageReceipt } from "./boundaries.js";
4
+ import type { UsageSubscriptionView } from "./subscriptionTerms.js";
5
+ import { internalMutationGeneric } from "convex/server";
6
+ import { v } from "convex/values";
7
+ import { schema, modules } from "../../test.js";
8
+ import { vi } from "vitest";
9
+ import { BetterStripe } from "../index.js";
10
+ import type { RunCtx } from "../helpers.js";
11
+ import { componentRef } from "../webhooks/helpers.js";
12
+ import { fixture } from "./subscriptionTransport.fixtures.js";
13
+ import { request } from "./subscription.fixtures.js";
14
+ const response = (value: unknown) =>
15
+ new Response(JSON.stringify(value), {
16
+ headers: { "content-type": "application/json" },
17
+ });
18
+ type CorrectionState = {
19
+ status: string;
20
+ missingEvidence: boolean;
21
+ advanceAtInvoiceRead: number;
22
+ failFirstAdjustment: boolean;
23
+ invalidCash: boolean;
24
+ paidAdjustment: boolean;
25
+ refundSucceeded: boolean;
26
+ voidedNote: boolean;
27
+ truncatedNote: boolean;
28
+ foreignLine: boolean;
29
+ finalizeOnAdjust: boolean;
30
+ finalized: boolean;
31
+ creditNoteAmount: number;
32
+ foreignNote: boolean;
33
+ };
34
+ export async function setupCorrection(
35
+ withAllowance = false,
36
+ periodEnd = 1200,
37
+ ): Promise<{
38
+ f: ReturnType<typeof fixture>;
39
+ client: BetterStripe;
40
+ options: UsageDeliveryProviderOptions;
41
+ correction: UsageCorrectionOptions;
42
+ receipt: UsageReceipt;
43
+ calls: Array<{ body: URLSearchParams; key: string | null }>;
44
+ state: CorrectionState;
45
+ original: UsageSubscriptionView["bindings"][number];
46
+ }> {
47
+ vi.useFakeTimers();
48
+ vi.setSystemTime(700000);
49
+ const state: CorrectionState = {
50
+ advanceAtInvoiceRead: 0,
51
+ status: "pending",
52
+ missingEvidence: false,
53
+ failFirstAdjustment: false,
54
+ invalidCash: false,
55
+ paidAdjustment: false,
56
+ refundSucceeded: true,
57
+ voidedNote: false,
58
+ truncatedNote: false,
59
+ foreignLine: false,
60
+ finalizeOnAdjust: false,
61
+ finalized: false,
62
+ creditNoteAmount: 4,
63
+ foreignNote: false,
64
+ };
65
+ const calls: Array<{ body: URLSearchParams; key: string | null }> = [];
66
+ const f = fixture(false, false, async (input, init) => {
67
+ const path = new URL(input).pathname;
68
+ if (path === "/v1/credit_notes/cn_fix")
69
+ return response({
70
+ id: "cn_fix",
71
+ object: "credit_note",
72
+ livemode: false,
73
+ customer_account: state.foreignNote ? "acct_other" : "acct_buyer",
74
+ customer: "cus_buyer",
75
+ invoice: "in_usage",
76
+ currency: "usd",
77
+ status: state.voidedNote ? "void" : "issued",
78
+ amount: state.creditNoteAmount,
79
+ total: state.creditNoteAmount,
80
+ subtotal: state.creditNoteAmount,
81
+ discount_amount: 0,
82
+ amount_shipping: 0,
83
+ total_taxes: state.missingEvidence ? undefined : [],
84
+ pre_payment_amount: state.paidAdjustment ? 0 : state.creditNoteAmount,
85
+ post_payment_amount: state.paidAdjustment ? state.creditNoteAmount : 0,
86
+ customer_balance_transaction: null,
87
+ out_of_band_amount: 0,
88
+ refunds: state.paidAdjustment
89
+ ? [
90
+ {
91
+ type: "refund",
92
+ refund: "re_fix",
93
+ amount_refunded: state.creditNoteAmount,
94
+ },
95
+ ]
96
+ : [],
97
+ pretax_credit_amounts: [],
98
+ lines: {
99
+ has_more: state.truncatedNote,
100
+ data: [
101
+ {
102
+ id: "cnli_fix",
103
+ type: "invoice_line_item",
104
+ invoice_line_item: "il_usage",
105
+ amount: state.creditNoteAmount,
106
+ livemode: false,
107
+ discount_amount: 0,
108
+ taxes: [],
109
+ pretax_credit_amounts: [],
110
+ },
111
+ ],
112
+ },
113
+ });
114
+ if (path === "/v1/invoices/in_usage")
115
+ return response({
116
+ id: "in_usage",
117
+ object: "invoice",
118
+ livemode: false,
119
+ customer_account: "acct_buyer",
120
+ customer: "cus_buyer",
121
+ currency: "usd",
122
+ status: state.paidAdjustment ? "paid" : "open",
123
+ status_transitions: { finalized_at: 701 },
124
+ parent: {
125
+ type: "subscription_details",
126
+ subscription_details: { subscription: "sub_calls" },
127
+ },
128
+ lines: {
129
+ has_more: false,
130
+ data: [
131
+ {
132
+ id: "il_usage",
133
+ amount: 12,
134
+ currency: "usd",
135
+ pricing: {
136
+ price_details: {
137
+ price: state.foreignLine ? "price_other" : "price_calls",
138
+ },
139
+ },
140
+ period: { start: 600, end: periodEnd },
141
+ parent: {
142
+ subscription_item_details: {
143
+ subscription_item: "si_calls",
144
+ subscription: "sub_calls",
145
+ proration: false,
146
+ },
147
+ },
148
+ quantity_decimal: state.missingEvidence ? undefined : "6",
149
+ pretax_credit_amounts: [],
150
+ discount_amounts: [],
151
+ taxes: [],
152
+ },
153
+ ],
154
+ },
155
+ });
156
+ if (path === "/v1/refunds/re_fix")
157
+ return response({
158
+ id: "re_fix",
159
+ object: "refund",
160
+ status: state.refundSucceeded ? "succeeded" : "pending",
161
+ amount: state.creditNoteAmount,
162
+ currency: "usd",
163
+ payment_intent: "pi_invoice",
164
+ charge: "ch_invoice",
165
+ });
166
+ if (path === "/v1/payment_intents/pi_invoice")
167
+ return response({
168
+ id: "pi_invoice",
169
+ object: "payment_intent",
170
+ livemode: false,
171
+ customer_account: "acct_buyer",
172
+ customer: "cus_buyer",
173
+ status: "succeeded",
174
+ currency: "usd",
175
+ amount: 12,
176
+ amount_received: 12,
177
+ latest_charge: "ch_invoice",
178
+ });
179
+ if (path === "/v1/charges/ch_invoice")
180
+ return response({
181
+ id: "ch_invoice",
182
+ object: "charge",
183
+ payment_intent: "pi_invoice",
184
+ livemode: false,
185
+ customer: "cus_buyer",
186
+ currency: "usd",
187
+ paid: true,
188
+ captured: true,
189
+ status: "succeeded",
190
+ disputed: false,
191
+ amount: 12,
192
+ amount_captured: state.invalidCash ? 12.5 : 12,
193
+ amount_refunded: state.creditNoteAmount,
194
+ });
195
+ if (path === "/v1/invoice_payments")
196
+ return response({
197
+ has_more: false,
198
+ data: [
199
+ {
200
+ id: "inpay_usage",
201
+ object: "invoice_payment",
202
+ amount_requested: 12,
203
+ invoice: "in_usage",
204
+ status: "paid",
205
+ currency: "usd",
206
+ amount_paid: 12,
207
+ payment: { type: "payment_intent", payment_intent: "pi_invoice" },
208
+ },
209
+ ],
210
+ });
211
+ if (path === "/v1/invoices") {
212
+ if (state.advanceAtInvoiceRead) {
213
+ vi.advanceTimersByTime(state.advanceAtInvoiceRead);
214
+ state.advanceAtInvoiceRead = 0;
215
+ }
216
+ return response({
217
+ data: state.finalized
218
+ ? [
219
+ {
220
+ id: "in_usage",
221
+ livemode: false,
222
+ customer_account: "acct_buyer",
223
+ customer: "cus_buyer",
224
+ status: "open",
225
+ currency: "usd",
226
+ parent: {
227
+ type: "subscription_details",
228
+ subscription_details: { subscription: "sub_calls" },
229
+ },
230
+ status_transitions: { finalized_at: 701 },
231
+ lines: {
232
+ has_more: false,
233
+ data: [
234
+ {
235
+ pricing: { price_details: { price: "price_calls" } },
236
+ period: { start: 600, end: periodEnd },
237
+ quantity_decimal: state.missingEvidence ? undefined : "6",
238
+ },
239
+ ],
240
+ },
241
+ },
242
+ ]
243
+ : [],
244
+ has_more: false,
245
+ });
246
+ }
247
+ if (path === "/v1/billing/meter_event_adjustments") {
248
+ if (state.finalizeOnAdjust) state.finalized = true;
249
+ const body = new URLSearchParams(String(init?.body));
250
+ calls.push({
251
+ body,
252
+ key: new Headers(init?.headers).get("idempotency-key"),
253
+ });
254
+ if (state.failFirstAdjustment) {
255
+ state.failFirstAdjustment = false;
256
+ throw new Error("private provider response sk_test_private");
257
+ }
258
+ return response({
259
+ object: "billing.meter_event_adjustment",
260
+ livemode: false,
261
+ status: state.status,
262
+ event_name: "calls",
263
+ type: "cancel",
264
+ cancel: { identifier: body.get("cancel[identifier]") },
265
+ });
266
+ }
267
+ return undefined;
268
+ });
269
+ f.t.registerComponent("betterStripe", schema, {
270
+ ...modules,
271
+ "./component/testSetup.ts": () =>
272
+ Promise.resolve({
273
+ delivered: internalMutationGeneric({
274
+ args: { eventId: v.id("usageEvents") },
275
+ returns: v.null(),
276
+ handler: async (ctx, args) => {
277
+ const row = await ctx.db
278
+ .query("usageOutbox")
279
+ .withIndex("by_event", (q) => q.eq("eventId", args.eventId))
280
+ .unique();
281
+ await ctx.db.patch(row!._id, {
282
+ state: "provider_accepted",
283
+ attempts: 1,
284
+ firstSendAt: 700,
285
+ definitionVersion: 1,
286
+ receipt: { identifier: row!.providerIdentifier, created: 700 },
287
+ });
288
+ return null;
289
+ },
290
+ }),
291
+ }),
292
+ });
293
+ const client = new BetterStripe(f.component),
294
+ options = {
295
+ stripeSecretKey: "sk_test_subscription",
296
+ httpClient: f.httpClient,
297
+ };
298
+ let managed = await f.t.action((ctx) =>
299
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
300
+ );
301
+ if (periodEnd !== 1200) {
302
+ for (const item of f.state.native!.items.data)
303
+ item.current_period_end = periodEnd;
304
+ managed = await f.t.action((ctx) =>
305
+ client.usage.observeSubscription(
306
+ ctx as RunCtx,
307
+ {
308
+ scope: {
309
+ stripeAccountId: "acct_platform",
310
+ customerAccount: "acct_buyer",
311
+ livemode: false,
312
+ },
313
+ requestId: request.requestId,
314
+ },
315
+ options,
316
+ ),
317
+ );
318
+ }
319
+ const original = managed.bindings[0];
320
+ if (withAllowance)
321
+ await f.t.action((ctx) =>
322
+ client.usage.configureAllowance(ctx as RunCtx, {
323
+ ...original,
324
+ expectedRevision: 0,
325
+ policy: {
326
+ reset: "billing_period",
327
+ rollover: "none",
328
+ entitled: true,
329
+ overage: "allow",
330
+ limit: { mode: "hard", quantity: "12" },
331
+ },
332
+ }),
333
+ );
334
+ const event = {
335
+ scope: original.scope,
336
+ binding: original.binding,
337
+ sourceEventId: "work1",
338
+ quantity: "6",
339
+ occurredAt: 700,
340
+ };
341
+ const reservation = withAllowance
342
+ ? await f.t.action((ctx) =>
343
+ client.usage.reserveAllowance(ctx as RunCtx, {
344
+ event,
345
+ subscription: original.subscription,
346
+ }),
347
+ )
348
+ : null;
349
+ const receipt = await f.t.action((ctx) =>
350
+ client.usage.record(ctx as RunCtx, {
351
+ event,
352
+ subscription: original.subscription,
353
+ ...(reservation && reservation.state !== "denied"
354
+ ? { reservationId: reservation.reservationId }
355
+ : {}),
356
+ }),
357
+ );
358
+ await f.t.action((ctx) =>
359
+ ctx.runMutation(componentRef(f.component, "testSetup/delivered"), {
360
+ eventId: receipt.eventId,
361
+ }),
362
+ );
363
+ const correction = {
364
+ scope: original.scope,
365
+ eventId: receipt.eventId,
366
+ correctionId: "fix1",
367
+ actor: "operator1",
368
+ reason: "duplicate activity",
369
+ operation: "cancel",
370
+ } as const;
371
+ return { f, client, options, correction, receipt, calls, state, original };
372
+ }
@@ -88,3 +88,14 @@ export type {
88
88
  UsageLimitPolicy,
89
89
  } from "./allowanceTerms.js";
90
90
  export type { UsageAllowanceReservation } from "./allowanceClient.js";
91
+
92
+ export type {
93
+ UsageCorrectionOptions,
94
+ UsageCorrectionView,
95
+ UsageInvoiceCorrectionOptions,
96
+ UsageInvoiceCorrectionEvidence,
97
+ } from "./correctionTerms.js";
98
+ export type {
99
+ UsageCorrectionHistoryPage,
100
+ UsageCorrectionHistoryRecord,
101
+ } from "./correctionRead.js";
@@ -1,3 +1,4 @@
1
+ import { readCorrectionEvidence } from "./correctionRead.js";
1
2
  import type { Doc } from "../../component/_generated/dataModel.js";
2
3
  import type { UsageDeliveryRef } from "./deliveryClient.js";
3
4
  import { observeUsageInvoice } from "./invoiceObservation.js";
@@ -198,13 +199,19 @@ export class UsageObservationClient extends UsageDeliveryClient {
198
199
  }
199
200
  async getReconciliation(ctx: RunCtx, input: UsageReconciliationOptions) {
200
201
  const opts = observationOptions(input);
201
- const [local, aggregate] = await Promise.all([
202
+ const [local, aggregate, corrections] = await Promise.all([
202
203
  this.getSummary(ctx, {
203
204
  scope: opts.scope,
204
205
  period: opts.period,
205
206
  maxRecords: input.maxRecords,
206
207
  }),
207
208
  this.getProviderUsage(ctx, input),
209
+ readCorrectionEvidence(this.component, ctx, {
210
+ scope: opts.scope,
211
+ period: opts.period,
212
+ limit: 100,
213
+ cursor: null,
214
+ }),
208
215
  ]);
209
216
  return {
210
217
  local,
@@ -215,11 +222,18 @@ export class UsageObservationClient extends UsageDeliveryClient {
215
222
  reason: "invoice_not_observed",
216
223
  retryable: true,
217
224
  },
218
- correctionHistory: {
219
- status: "unsupported" as const,
220
- reason: "corrections_not_configured",
221
- retryable: false,
222
- },
225
+ correctionHistory: corrections.records.length
226
+ ? {
227
+ status: "available" as const,
228
+ observedAt: Math.floor(Date.now() / 1000),
229
+ value: corrections,
230
+ }
231
+ : {
232
+ status: "unsupported" as const,
233
+ reason: "corrections_not_configured",
234
+ retryable: false,
235
+ legacyHistoryMissing: corrections.legacyHistoryMissing,
236
+ },
223
237
  };
224
238
  }
225
239
  async reconcile(
@@ -44,7 +44,13 @@ export type PreparedUsageRecord = Omit<
44
44
  };
45
45
  };
46
46
  export type UsageDeliveryState =
47
- "queued" | "sending" | "provider_accepted" | "rejected" | "unknown" | "held";
47
+ | "canceled"
48
+ | "queued"
49
+ | "sending"
50
+ | "provider_accepted"
51
+ | "rejected"
52
+ | "unknown"
53
+ | "held";
48
54
 
49
55
  /**
50
56
  * Validate and snapshot a record before acceptance. This pure helper does not
@@ -24,6 +24,9 @@ export type UsageLocalGroup = {
24
24
  acceptedScaledQuantity: string;
25
25
  providerAcceptedScaledQuantity: string;
26
26
  acceptedQuantity: string;
27
+ canceledQuantity: string;
28
+ effectiveQuantity: string;
29
+ effectiveScaledQuantity: string;
27
30
  providerAcceptedQuantity: string;
28
31
  eventCount: number;
29
32
  validationErrorEventCount: number;
@@ -65,6 +68,7 @@ const unavailable = (reason: string) => ({
65
68
  retryable: false,
66
69
  });
67
70
  const states: UsageDeliveryState[] = [
71
+ "canceled",
68
72
  "queued",
69
73
  "sending",
70
74
  "provider_accepted",
@@ -101,7 +105,8 @@ export function summarizeUsageRecords(
101
105
  options.period.end === subscription.period.end;
102
106
  const eligible =
103
107
  options.complete && (plan.model !== "included_overage" || fullPeriod);
104
- let chargeable = accepted;
108
+ const effective = accepted - sums.canceled;
109
+ let chargeable = effective;
105
110
  let included: UsageLocalGroup["included"] = unavailable(
106
111
  plan.model === "included_overage"
107
112
  ? options.complete
@@ -113,15 +118,15 @@ export function summarizeUsageRecords(
113
118
  const allowance = BigInt(
114
119
  parseUsageQuantity(plan.includedQuantity, precision).scaledQuantity,
115
120
  );
116
- chargeable = accepted > allowance ? accepted - allowance : 0n;
121
+ chargeable = effective > allowance ? effective - allowance : 0n;
117
122
  included = {
118
123
  status: "available",
119
124
  observedAt: options.observedAt,
120
125
  value: {
121
126
  included: decimalFromScaled(allowance, precision),
122
- consumed: decimalFromScaled(accepted, precision),
127
+ consumed: decimalFromScaled(effective, precision),
123
128
  remaining: decimalFromScaled(
124
- allowance > accepted ? allowance - accepted : 0n,
129
+ allowance > effective ? allowance - effective : 0n,
125
130
  precision,
126
131
  ),
127
132
  overage: decimalFromScaled(chargeable, precision),
@@ -134,6 +139,9 @@ export function summarizeUsageRecords(
134
139
  acceptedScaledQuantity: accepted.toString(),
135
140
  providerAcceptedScaledQuantity: sums.provider_accepted.toString(),
136
141
  acceptedQuantity: decimalFromScaled(accepted, precision),
142
+ canceledQuantity: decimalFromScaled(sums.canceled, precision),
143
+ effectiveQuantity: decimalFromScaled(effective, precision),
144
+ effectiveScaledQuantity: effective.toString(),
137
145
  providerAcceptedQuantity: decimalFromScaled(
138
146
  sums.provider_accepted,
139
147
  precision,
@@ -54,3 +54,14 @@ export type {
54
54
  UsageLimitPolicy,
55
55
  } from "./usage/allowanceTerms.js";
56
56
  export type { UsageAllowanceReservation } from "./usage/allowanceClient.js";
57
+
58
+ export type {
59
+ UsageCorrectionOptions,
60
+ UsageCorrectionView,
61
+ UsageInvoiceCorrectionOptions,
62
+ UsageInvoiceCorrectionEvidence,
63
+ } from "./usage/correctionTerms.js";
64
+ export type {
65
+ UsageCorrectionHistoryPage,
66
+ UsageCorrectionHistoryRecord,
67
+ } from "./usage/correctionRead.js";
@@ -171,6 +171,12 @@ import type * as usageAllowance_queries from "../usageAllowance/queries.js";
171
171
  import type * as usageAllowance_reservations from "../usageAllowance/reservations.js";
172
172
  import type * as usageCatalog_mutations from "../usageCatalog/mutations.js";
173
173
  import type * as usageCatalog_queries from "../usageCatalog/queries.js";
174
+ import type * as usageCorrections_accounting from "../usageCorrections/accounting.js";
175
+ import type * as usageCorrections_cancellation from "../usageCorrections/cancellation.js";
176
+ import type * as usageCorrections_helpers from "../usageCorrections/helpers.js";
177
+ import type * as usageCorrections_invoice from "../usageCorrections/invoice.js";
178
+ import type * as usageCorrections_mutations from "../usageCorrections/mutations.js";
179
+ import type * as usageCorrections_queries from "../usageCorrections/queries.js";
174
180
  import type * as usageCredits_helpers from "../usageCredits/helpers.js";
175
181
  import type * as usageCredits_mutations from "../usageCredits/mutations.js";
176
182
  import type * as usageCredits_purchase from "../usageCredits/purchase.js";
@@ -369,6 +375,12 @@ const fullApi: ApiFromModules<{
369
375
  "usageAllowance/reservations": typeof usageAllowance_reservations;
370
376
  "usageCatalog/mutations": typeof usageCatalog_mutations;
371
377
  "usageCatalog/queries": typeof usageCatalog_queries;
378
+ "usageCorrections/accounting": typeof usageCorrections_accounting;
379
+ "usageCorrections/cancellation": typeof usageCorrections_cancellation;
380
+ "usageCorrections/helpers": typeof usageCorrections_helpers;
381
+ "usageCorrections/invoice": typeof usageCorrections_invoice;
382
+ "usageCorrections/mutations": typeof usageCorrections_mutations;
383
+ "usageCorrections/queries": typeof usageCorrections_queries;
372
384
  "usageCredits/helpers": typeof usageCredits_helpers;
373
385
  "usageCredits/mutations": typeof usageCredits_mutations;
374
386
  "usageCredits/purchase": typeof usageCredits_purchase;