@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,389 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { afterEach, expect, it, vi } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+ import {
6
+ request,
7
+ nativeSubscription,
8
+ } from "../../client/usage/subscription.fixtures.js";
9
+ const ref = (name: string) =>
10
+ makeFunctionReference<"mutation">(`usageCorrections/mutations:${name}`);
11
+ const record = makeFunctionReference<"mutation">("usage/mutations:record");
12
+ const read = makeFunctionReference<"query">(
13
+ "usageCorrections/queries:readHistory",
14
+ );
15
+ async function setup() {
16
+ vi.useFakeTimers();
17
+ vi.setSystemTime(700000);
18
+ const t = convexTest(schema, modules),
19
+ meter = request.meters[0];
20
+ const event = {
21
+ ...meter,
22
+ binding: {
23
+ ...meter.binding,
24
+ plan: {
25
+ key: "calls",
26
+ version: "v1",
27
+ model: "pay_as_you_go",
28
+ unit: { name: "call", precision: 0 },
29
+ rate: { currency: "usd", unitAmountDecimal: "2" },
30
+ },
31
+ },
32
+ sourceEventId: "work1",
33
+ quantity: "6",
34
+ occurredAt: 700,
35
+ };
36
+ const subscription = {
37
+ subscriptionId: "sub_calls",
38
+ subscriptionItemId: "si_calls",
39
+ stripePriceId: "price_calls",
40
+ period: { start: 600, end: 1200 },
41
+ interval: "month",
42
+ };
43
+ const args = {
44
+ inputJson: JSON.stringify(event),
45
+ subscriptionJson: JSON.stringify(subscription),
46
+ },
47
+ receipt = await t.mutation(record, args);
48
+ const correction = {
49
+ scope: event.scope,
50
+ eventId: receipt.eventId,
51
+ correctionId: "fix1",
52
+ actor: "operator1",
53
+ reason: "duplicate business activity",
54
+ operation: "cancel",
55
+ };
56
+ return { t, event, subscription, args, receipt, correction };
57
+ }
58
+ afterEach(() => vi.useRealTimers());
59
+ it("cancels unsent usage once, preserves its immutable receipt and cannot be resumed into billing", async () => {
60
+ const { t, args, receipt, correction } = await setup();
61
+ const first = await t.mutation(ref("prepare"), {
62
+ inputJson: JSON.stringify(correction),
63
+ });
64
+ expect(first).toMatchObject({
65
+ state: "confirmed",
66
+ reason: "canceled_before_delivery",
67
+ cashConsequence: "none",
68
+ });
69
+ expect(
70
+ await t.mutation(ref("prepare"), { inputJson: JSON.stringify(correction) }),
71
+ ).toEqual(first);
72
+ expect(await t.mutation(record, args)).toEqual(receipt);
73
+ const status = await t.mutation(
74
+ makeFunctionReference<"mutation">("usageDelivery/mutations:resume"),
75
+ { scope: correction.scope, eventId: correction.eventId },
76
+ );
77
+ expect(status.state).toBe("canceled");
78
+ expect(
79
+ await t.mutation(
80
+ makeFunctionReference<"mutation">("usageDelivery/steps:claim"),
81
+ { scope: correction.scope, eventId: correction.eventId },
82
+ ),
83
+ ).toEqual({ kind: "done" });
84
+ const page = await t.query(read, {
85
+ scope: correction.scope,
86
+ eventId: correction.eventId,
87
+ paginationOpts: { numItems: 1, cursor: null },
88
+ });
89
+ expect(page.page).toHaveLength(1);
90
+ expect(page.page[0].recordJson).toContain('"sourceEventId":"work1"');
91
+ });
92
+ it("excludes confirmed cancellation from billable estimates while retaining raw accepted quantity", async () => {
93
+ const { t, correction } = await setup();
94
+ await t.mutation(ref("prepare"), { inputJson: JSON.stringify(correction) });
95
+ const result = await t.query(
96
+ makeFunctionReference<"query">("usageObservations/queries:summary"),
97
+ {
98
+ scope: correction.scope,
99
+ period: { start: 600, end: 1200 },
100
+ maxRecords: 100,
101
+ },
102
+ );
103
+ expect(JSON.parse(result).groups[0]).toMatchObject({
104
+ acceptedQuantity: "6",
105
+ canceledQuantity: "6",
106
+ effectiveQuantity: "0",
107
+ estimate: {
108
+ status: "available",
109
+ value: { amountDecimal: "0", currency: "usd" },
110
+ },
111
+ });
112
+ });
113
+ it("holds native pending cancellation and completes once with original native receipt", async () => {
114
+ const { t, correction, receipt } = await setup();
115
+ await t.run(async (ctx) => {
116
+ const row = (await ctx.db.query("usageOutbox").first())!;
117
+ await ctx.db.patch("usageOutbox", row._id, {
118
+ state: "provider_accepted",
119
+ attempts: 1,
120
+ firstSendAt: 700,
121
+ receipt: { identifier: row.providerIdentifier, created: 700 },
122
+ });
123
+ });
124
+ const row = await t.mutation(ref("prepare"), {
125
+ inputJson: JSON.stringify(correction),
126
+ });
127
+ expect(row.state).toBe("requested");
128
+ const attempt = await t.mutation(ref("claim"), { key: row.key });
129
+ const proof = {
130
+ status: "pending",
131
+ eventName: "calls",
132
+ identifier: `bs_usage_${receipt.eventId}`,
133
+ livemode: false,
134
+ nativeAdjustmentId: null,
135
+ creditBackingVerified: false,
136
+ };
137
+ const saved = await t.mutation(ref("save"), {
138
+ key: row.key,
139
+ attempt: attempt.attempt,
140
+ outcomeJson: JSON.stringify(proof),
141
+ });
142
+ expect(saved).toMatchObject({
143
+ state: "provider_accepted",
144
+ restoredQuantity: "0",
145
+ nativeStatus: "pending",
146
+ });
147
+ expect((await t.mutation(ref("claim"), { key: row.key })).kind).toBe("done");
148
+ });
149
+ it("keeps pending native corrections attached to the payer before account closure", async () => {
150
+ const { t, correction } = await setup();
151
+ await t.run(async (ctx) => {
152
+ const row = (await ctx.db.query("usageOutbox").first())!;
153
+ await ctx.db.patch("usageOutbox", row._id, {
154
+ state: "provider_accepted",
155
+ attempts: 1,
156
+ firstSendAt: 700,
157
+ receipt: { identifier: row.providerIdentifier, created: 700 },
158
+ });
159
+ });
160
+ await t.mutation(ref("prepare"), { inputJson: JSON.stringify(correction) });
161
+ await expect(
162
+ t.mutation(
163
+ makeFunctionReference<"mutation">("accountClosure/mutations:prepare"),
164
+ { stripeAccountId: correction.scope.customerAccount },
165
+ ),
166
+ ).rejects.toThrow(/correction/i);
167
+ });
168
+ it("rejects new correction work after account closure starts", async () => {
169
+ const { t, correction } = await setup();
170
+ await t.mutation(
171
+ makeFunctionReference<"mutation">("accountClosure/mutations:prepare"),
172
+ { stripeAccountId: correction.scope.customerAccount },
173
+ );
174
+ await expect(
175
+ t.mutation(ref("prepare"), { inputJson: JSON.stringify(correction) }),
176
+ ).rejects.toThrow(/closure/i);
177
+ });
178
+ it("isolates guessed correction/event references and rejects changed/reassigned operation keys", async () => {
179
+ const { t, correction, args, event } = await setup();
180
+ await t.mutation(ref("prepare"), { inputJson: JSON.stringify(correction) });
181
+ const foreign = { ...correction.scope, customerAccount: "acct_other" };
182
+ await expect(
183
+ t.query(read, {
184
+ scope: foreign,
185
+ eventId: correction.eventId,
186
+ paginationOpts: { numItems: 1, cursor: null },
187
+ }),
188
+ ).rejects.toThrow(/scope/i);
189
+ await expect(
190
+ t.mutation(ref("prepare"), {
191
+ inputJson: JSON.stringify({ ...correction, scope: foreign }),
192
+ }),
193
+ ).rejects.toThrow(/scope/i);
194
+ await expect(
195
+ t.mutation(ref("prepare"), {
196
+ inputJson: JSON.stringify({ ...correction, actor: "differentActor" }),
197
+ }),
198
+ ).rejects.toThrow(/replay conflict/i);
199
+ const second = await t.mutation(record, {
200
+ ...args,
201
+ inputJson: JSON.stringify({ ...event, sourceEventId: "work2" }),
202
+ });
203
+ await expect(
204
+ t.mutation(ref("prepare"), {
205
+ inputJson: JSON.stringify({ ...correction, eventId: second.eventId }),
206
+ }),
207
+ ).rejects.toThrow(/replay conflict/i);
208
+ });
209
+ it("lets only one competing full correction claim an event and preserves an unsupported partial request", async () => {
210
+ const { t, correction } = await setup();
211
+ const partial = await t.mutation(ref("prepare"), {
212
+ inputJson: JSON.stringify({
213
+ ...correction,
214
+ correctionId: "partial",
215
+ quantity: "2",
216
+ }),
217
+ });
218
+ expect(partial).toMatchObject({
219
+ state: "unsupported",
220
+ restoredQuantity: "0",
221
+ });
222
+ const results = await Promise.allSettled(
223
+ ["fixA", "fixB"].map((correctionId) =>
224
+ t.mutation(ref("prepare"), {
225
+ inputJson: JSON.stringify({ ...correction, correctionId }),
226
+ }),
227
+ ),
228
+ );
229
+ expect(results.filter((r) => r.status === "fulfilled")).toHaveLength(1);
230
+ expect(results.filter((r) => r.status === "rejected")).toHaveLength(1);
231
+ const page = await t.query(read, {
232
+ scope: correction.scope,
233
+ eventId: correction.eventId,
234
+ paginationOpts: { numItems: 1, cursor: null },
235
+ });
236
+ expect(page.isDone).toBe(false);
237
+ expect(page.page).toHaveLength(1);
238
+ });
239
+ it("does not finalize financial adoption while a native cancellation attempt owns its lease", async () => {
240
+ const { t, correction } = await setup();
241
+ await t.run(async (ctx) => {
242
+ const outbox = (await ctx.db.query("usageOutbox").first())!;
243
+ await ctx.db.patch("usageOutbox", outbox._id, {
244
+ state: "provider_accepted",
245
+ attempts: 1,
246
+ firstSendAt: 700,
247
+ receipt: { identifier: outbox.providerIdentifier, created: 700 },
248
+ });
249
+ });
250
+ const row = await t.mutation(ref("prepare"), {
251
+ inputJson: JSON.stringify(correction),
252
+ });
253
+ await t.mutation(ref("claim"), { key: row.key });
254
+ const proof = {
255
+ creditNoteStatus: "issued",
256
+ stripeAccountId: "acct_platform",
257
+ livemode: false,
258
+ customerAccount: "acct_buyer",
259
+ stripeCustomerId: "cus_buyer",
260
+ subscriptionId: "sub_calls",
261
+ subscriptionItemId: "si_calls",
262
+ stripePriceId: "price_calls",
263
+ period: { start: 600, end: 1200 },
264
+ creditNoteId: "cn_fix",
265
+ invoiceId: "in_usage",
266
+ invoiceLineId: "il_usage",
267
+ currency: "usd",
268
+ amount: 4,
269
+ prePaymentAmount: 4,
270
+ postPaymentAmount: 0,
271
+ paymentIntentId: null,
272
+ chargeId: null,
273
+ refundId: null,
274
+ };
275
+ await expect(
276
+ t.mutation(
277
+ makeFunctionReference<"mutation">("usageCorrections/mutations:adopt"),
278
+ { key: row.key, proofJson: JSON.stringify(proof) },
279
+ ),
280
+ ).rejects.toThrow(/active.*attempt/i);
281
+ });
282
+
283
+ it("retires corrected usage without deleting its original native validation-error history", async () => {
284
+ const { t, event, correction } = await setup();
285
+ const prepareEnrollment = makeFunctionReference<"mutation">(
286
+ "usageSubscriptions/mutations:prepare",
287
+ ),
288
+ saveEnrollment = makeFunctionReference<"mutation">(
289
+ "usageSubscriptions/mutations:save",
290
+ );
291
+ const intent = await t.mutation(prepareEnrollment, {
292
+ termsJson: JSON.stringify({
293
+ ...request,
294
+ meters: [{ scope: event.scope, binding: event.binding }],
295
+ }),
296
+ method: "direct",
297
+ });
298
+ const native = nativeSubscription();
299
+ await t.mutation(saveEnrollment, {
300
+ key: intent.key,
301
+ nativeJson: JSON.stringify(native),
302
+ startedAt: Date.now(),
303
+ });
304
+ await t.run(async (ctx) => {
305
+ const outbox = (await ctx.db.query("usageOutbox").first())!;
306
+ await ctx.db.patch("usageOutbox", outbox._id, {
307
+ state: "provider_accepted",
308
+ attempts: 1,
309
+ firstSendAt: 700,
310
+ receipt: { identifier: outbox.providerIdentifier, created: 700 },
311
+ });
312
+ await ctx.db.insert("usageDeliveryErrors", {
313
+ scopeKey: outbox.scopeKey,
314
+ eventId: correction.eventId,
315
+ code: "meter_event_invalid_value",
316
+ providerEventId: "evt_error",
317
+ observedAt: 700,
318
+ dedupe: "original_error",
319
+ });
320
+ });
321
+ const row = await t.mutation(ref("prepare"), {
322
+ inputJson: JSON.stringify(correction),
323
+ }),
324
+ attempt = await t.mutation(ref("claim"), { key: row.key });
325
+ await t.mutation(ref("save"), {
326
+ key: row.key,
327
+ attempt: attempt.attempt,
328
+ outcomeJson: JSON.stringify({
329
+ status: "complete",
330
+ eventName: "calls",
331
+ identifier: `bs_usage_${correction.eventId}`,
332
+ livemode: false,
333
+ nativeAdjustmentId: null,
334
+ creditBackingVerified: false,
335
+ billingSafe: true,
336
+ }),
337
+ });
338
+ vi.setSystemTime(1400000);
339
+ native.status = "canceled";
340
+ await t.mutation(saveEnrollment, {
341
+ key: intent.key,
342
+ nativeJson: JSON.stringify(native),
343
+ startedAt: Date.now(),
344
+ });
345
+ await t.mutation(
346
+ makeFunctionReference<"mutation">("usageSubscriptions/mutations:retire"),
347
+ {
348
+ key: intent.key,
349
+ proofJson: JSON.stringify({
350
+ invoiceId: "in_closeout",
351
+ stripeAccountId: "acct_platform",
352
+ customerAccount: "acct_buyer",
353
+ stripeCustomerId: "cus_buyer",
354
+ livemode: false,
355
+ subscriptionId: "sub_calls",
356
+ status: "open",
357
+ finalizedAt: 1300,
358
+ billingReason: "subscription_cycle",
359
+ periodEnd: 1200,
360
+ }),
361
+ },
362
+ );
363
+ expect(
364
+ await t.run((ctx) => ctx.db.query("usageDeliveryErrors").take(10)),
365
+ ).toHaveLength(1);
366
+ });
367
+
368
+ it("locally cancels known rejected delivery but keeps ambiguous delivery held", async () => {
369
+ for (const state of ["rejected", "unknown"] as const) {
370
+ const { t, correction } = await setup();
371
+ await t.run(async (ctx) => {
372
+ const outbox = (await ctx.db.query("usageOutbox").first())!;
373
+ await ctx.db.patch("usageOutbox", outbox._id, {
374
+ state,
375
+ attempts: 1,
376
+ firstSendAt: 700,
377
+ reason:
378
+ state === "rejected"
379
+ ? "provider_rejected"
380
+ : "provider_outcome_unknown",
381
+ });
382
+ });
383
+ const result = await t.mutation(ref("prepare"), {
384
+ inputJson: JSON.stringify(correction),
385
+ });
386
+ expect(result.state).toBe(state === "rejected" ? "confirmed" : "requested");
387
+ expect(result.restoredQuantity).toBe(state === "rejected" ? "6" : "0");
388
+ }
389
+ });
@@ -0,0 +1,57 @@
1
+ import type { Value } from "convex/values";
2
+ import { convexToJson } from "convex/values";
3
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
4
+ import type { Doc } from "../_generated/dataModel.js";
5
+ import { correctionRequest } from "../../client/usage/correctionTerms.js";
6
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
7
+ import { scopeKey } from "../usage/helpers.js";
8
+ export const canonical = (value: Value) => JSON.stringify(convexToJson(value));
9
+ export function json(text: string) {
10
+ if (new TextEncoder().encode(text).length > 8192)
11
+ throw new Error("Correction payload exceeds size limit");
12
+ return JSON.parse(text) as unknown;
13
+ }
14
+ export async function input(text: string) {
15
+ const request = correctionRequest.parse(json(text));
16
+ return {
17
+ request,
18
+ inputJson: canonical(request),
19
+ scopeKey: scopeKey(request.scope),
20
+ key: await canonicalFingerprint([request.scope, request.correctionId]),
21
+ };
22
+ }
23
+ export async function operation(ctx: QueryCtx, key: string) {
24
+ const row = await ctx.db
25
+ .query("usageCorrections")
26
+ .withIndex("by_key", (q) => q.eq("key", key))
27
+ .unique();
28
+ if (!row) throw new Error("Usage correction unavailable");
29
+ return row;
30
+ }
31
+ export { correctionView as view } from "../../client/usage/correctionTerms.js";
32
+ export async function history(
33
+ ctx: MutationCtx,
34
+ original: Doc<"usageCorrections">,
35
+ evidence: Value,
36
+ ) {
37
+ const row = await operation(ctx, original.key);
38
+ if (row.historyCount >= 1000)
39
+ throw new Error("Correction history quota exhausted");
40
+ await ctx.db.insert("usageCorrectionHistory", {
41
+ key: row.key,
42
+ scopeKey: row.scopeKey,
43
+ eventId: row.eventId,
44
+ sequence: row.historyCount + 1,
45
+ state: row.state,
46
+ reason: row.reason,
47
+ recordJson: row.recordJson,
48
+ subscriptionJson: row.subscriptionJson,
49
+ evidenceJson: canonical(evidence),
50
+ occurredAt: JSON.parse(row.recordJson).occurredAt,
51
+ at: Math.floor(Date.now() / 1000),
52
+ });
53
+ await ctx.db.patch("usageCorrections", row._id, {
54
+ historyCount: row.historyCount + 1,
55
+ observedAt: Math.floor(Date.now() / 1000),
56
+ });
57
+ }
@@ -0,0 +1,103 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import { json, canonical, operation, history, view } from "./helpers.js";
3
+ import { invoiceCorrectionProof } from "../../client/usage/correctionInvoiceProof.js";
4
+ import { subscriptionSnapshot } from "../usage/helpers.js";
5
+ import type { PreparedUsageRecord } from "../../client/usage/records.js";
6
+ export async function adoptInvoiceCorrection(
7
+ ctx: MutationCtx,
8
+ args: { key: string; proofJson: string },
9
+ ) {
10
+ const row = await operation(ctx, args.key),
11
+ proof = invoiceCorrectionProof.parse(json(args.proofJson)),
12
+ proofJson = canonical({ ...proof, creditNoteStatus: "issued" });
13
+ if ((row.leaseUntil ?? 0) > Date.now() / 1000)
14
+ throw new Error(
15
+ "Active native correction attempt must finish before financial adoption",
16
+ );
17
+ const event = JSON.parse(row.recordJson) as PreparedUsageRecord,
18
+ sub = subscriptionSnapshot(row.subscriptionJson);
19
+ if (
20
+ proof.stripeAccountId !== event.scope.stripeAccountId ||
21
+ proof.livemode !== event.scope.livemode ||
22
+ proof.customerAccount !== event.scope.customerAccount ||
23
+ proof.stripeCustomerId !== event.binding.stripeCustomerId ||
24
+ proof.subscriptionId !== sub.subscriptionId ||
25
+ proof.subscriptionItemId !== sub.subscriptionItemId ||
26
+ proof.stripePriceId !== event.binding.stripePriceId ||
27
+ proof.period.start !== sub.period.start ||
28
+ proof.period.end !== sub.period.end ||
29
+ proof.currency !== event.binding.plan.rate.currency ||
30
+ proof.amount !== proof.prePaymentAmount + proof.postPaymentAmount ||
31
+ (proof.postPaymentAmount > 0 &&
32
+ (!proof.refundId || !proof.paymentIntentId || !proof.chargeId))
33
+ )
34
+ throw new Error("Invoice correction provenance mismatch");
35
+ if (row.adjustmentJson) {
36
+ if (row.adjustmentJson !== proofJson)
37
+ throw new Error("Invoice adjustment replay conflict");
38
+ if (
39
+ row.nativeCreditNoteStatus === "void" ||
40
+ row.nativeCreditNoteStatus === proof.creditNoteStatus
41
+ )
42
+ return row;
43
+ }
44
+ if (
45
+ (row.state === "confirmed" && !row.adjustmentJson) ||
46
+ event.binding.plan.model === "prepaid"
47
+ )
48
+ throw new Error(
49
+ "Invoice credit cannot restore native usage or prepaid units",
50
+ );
51
+ for (const source of [
52
+ proof.creditNoteId,
53
+ ...(proof.refundId ? [proof.refundId] : []),
54
+ ]) {
55
+ const key = canonical([
56
+ event.scope.stripeAccountId,
57
+ event.scope.livemode,
58
+ source,
59
+ ]);
60
+ const prior = await ctx.db
61
+ .query("usageCorrectionClaims")
62
+ .withIndex("by_key", (q) => q.eq("key", key))
63
+ .unique();
64
+ if (
65
+ prior &&
66
+ (prior.operationKey !== row.key || prior.proofJson !== proofJson)
67
+ )
68
+ throw new Error("Native financial adjustment already claimed");
69
+ if (!prior)
70
+ await ctx.db.insert("usageCorrectionClaims", {
71
+ key,
72
+ operationKey: row.key,
73
+ proofJson,
74
+ });
75
+ }
76
+ await ctx.db.patch("usageCorrections", row._id, {
77
+ state: "confirmed",
78
+ resolution: "invoice_credit",
79
+ reason:
80
+ proof.creditNoteStatus === "void"
81
+ ? "native_invoice_credit_voided"
82
+ : "verified_native_invoice_credit",
83
+ nativeCreditNoteStatus: proof.creditNoteStatus,
84
+ creditNoteId: proof.creditNoteId,
85
+ invoiceId: proof.invoiceId,
86
+ refundId: proof.refundId ?? undefined,
87
+ adjustmentJson: proofJson,
88
+ cashConsequence:
89
+ proof.creditNoteStatus === "void"
90
+ ? "none"
91
+ : "verified_external_adjustment",
92
+ restoredQuantity: "0",
93
+ leaseUntil: 0,
94
+ });
95
+ const saved = await operation(ctx, row.key);
96
+ await history(ctx, saved, {
97
+ proof,
98
+ result: view(saved),
99
+ usageTreatment: "retain_original_consumption",
100
+ cashCollection: "none",
101
+ });
102
+ return operation(ctx, row.key);
103
+ }