@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,278 @@
1
+ import { locallyCancelable } from "../../client/usage/correctionEligibility.js";
2
+ import { adoptInvoiceCorrection } from "./invoice.js";
3
+ import { closureByStripeId } from "../accountClosure/helpers.js";
4
+ import { correctionOutcome } from "../../client/usage/correctionProofs.js";
5
+ import { v } from "convex/values";
6
+ import { mutation } from "../_generated/server.js";
7
+ import { read } from "../usageDelivery/helpers.js";
8
+ import { parseUsageQuantity } from "../../client/usage/contracts.js";
9
+ import { input, operation, history, view, json } from "./helpers.js";
10
+ import { restore } from "./accounting.js";
11
+ import { operationDoc } from "./schema.js";
12
+ export const prepare = mutation({
13
+ args: { inputJson: v.string() },
14
+ returns: operationDoc,
15
+ handler: async (ctx, args) => {
16
+ const original = await input(args.inputJson),
17
+ { event, outbox, record } = await read(ctx, {
18
+ scope: original.request.scope,
19
+ eventId: original.request
20
+ .eventId as import("../_generated/dataModel.js").Id<"usageEvents">,
21
+ });
22
+ const prior = await ctx.db
23
+ .query("usageCorrections")
24
+ .withIndex("by_key", (q) => q.eq("key", original.key))
25
+ .unique();
26
+ if (prior) {
27
+ if (prior.inputJson !== original.inputJson)
28
+ throw new Error("Usage correction replay conflict");
29
+ return prior;
30
+ }
31
+ for (const account of [
32
+ record.scope.stripeAccountId,
33
+ record.scope.customerAccount,
34
+ ])
35
+ if (await closureByStripeId(ctx, account))
36
+ throw new Error("Account closure prevents new usage correction");
37
+ const quantity = parseUsageQuantity(
38
+ original.request.quantity ?? record.quantity,
39
+ record.binding.plan.unit.precision,
40
+ );
41
+ if (
42
+ BigInt(quantity.scaledQuantity) > BigInt(record.scaledQuantity) ||
43
+ quantity.scaledQuantity === "0"
44
+ )
45
+ throw new Error("Invalid usage correction quantity");
46
+ const rows = await ctx.db
47
+ .query("usageCorrections")
48
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
49
+ .take(101);
50
+ if (rows.length >= 100)
51
+ throw new Error("Retained event correction quota exhausted");
52
+ const partial = quantity.scaledQuantity !== record.scaledQuantity;
53
+ if (
54
+ !partial &&
55
+ rows.some(
56
+ (row) =>
57
+ row.scaledQuantity === record.scaledQuantity &&
58
+ row.state !== "unsupported",
59
+ )
60
+ )
61
+ throw new Error("Original usage already has a correction operation");
62
+ const unsent = locallyCancelable(outbox);
63
+ const prepaid = record.binding.plan.model === "prepaid";
64
+ const state = partial
65
+ ? ("unsupported" as const)
66
+ : unsent && !prepaid
67
+ ? ("confirmed" as const)
68
+ : ("requested" as const);
69
+ const reason = partial
70
+ ? "partial_event_requires_replacement_or_invoice_adjustment"
71
+ : state === "confirmed"
72
+ ? outbox.state === "rejected"
73
+ ? "canceled_after_delivery_rejection"
74
+ : "canceled_before_delivery"
75
+ : unsent
76
+ ? "credit_backing_verification_required"
77
+ : "native_cancellation_required";
78
+ const id = await ctx.db.insert("usageCorrections", {
79
+ stripeAccountId: record.scope.stripeAccountId,
80
+ customerAccount: record.scope.customerAccount,
81
+ key: original.key,
82
+ scopeKey: original.scopeKey,
83
+ eventId: event._id,
84
+ correctionId: original.request.correctionId,
85
+ inputJson: original.inputJson,
86
+ recordJson: event.recordJson,
87
+ subscriptionJson: event.subscriptionJson,
88
+ quantity: quantity.quantity,
89
+ scaledQuantity: quantity.scaledQuantity,
90
+ state,
91
+ reason,
92
+ firstAttemptAt: Math.floor(Date.now() / 1000),
93
+ attempt: 0,
94
+ restoredQuantity: state === "confirmed" ? quantity.quantity : "0",
95
+ historyCount: 0,
96
+ cashConsequence: "none",
97
+ });
98
+ const row = (await ctx.db.get("usageCorrections", id))!;
99
+ if (!partial) {
100
+ await ctx.db.patch("usageOutbox", outbox._id, {
101
+ held: true,
102
+ correctionKey: row.key,
103
+ ...(state === "confirmed"
104
+ ? { state: "canceled" as const, reason: "usage_canceled" as const }
105
+ : {}),
106
+ });
107
+ if (state === "confirmed") await restore(ctx, row, event);
108
+ }
109
+ await history(ctx, row, {
110
+ request: original.request,
111
+ providerIdentifier: outbox.providerIdentifier,
112
+ originalReceipt: outbox.receipt ?? null,
113
+ result: view(row),
114
+ });
115
+ return operation(ctx, row.key);
116
+ },
117
+ });
118
+
119
+ export const claim = mutation({
120
+ args: { key: v.string() },
121
+ returns: v.object({
122
+ kind: v.union(v.literal("ready"), v.literal("busy"), v.literal("done")),
123
+ attempt: v.number(),
124
+ }),
125
+ handler: async (ctx, args) => {
126
+ const row = await operation(ctx, args.key),
127
+ now = Math.floor(Date.now() / 1000);
128
+ if (
129
+ [
130
+ "confirmed",
131
+ "unsupported",
132
+ "provider_accepted",
133
+ "invoice_adjustment_required",
134
+ ].includes(row.state)
135
+ )
136
+ return { kind: "done" as const, attempt: row.attempt };
137
+ if ((row.leaseUntil ?? 0) > now)
138
+ return { kind: "busy" as const, attempt: row.attempt };
139
+ const source = await read(ctx, {
140
+ scope: JSON.parse(row.inputJson).scope,
141
+ eventId: row.eventId,
142
+ });
143
+ const neverDelivered = locallyCancelable(source.outbox);
144
+ if (
145
+ !neverDelivered &&
146
+ row.attemptedAt !== undefined &&
147
+ now - row.attemptedAt >= 23 * 3600
148
+ ) {
149
+ await ctx.db.patch("usageCorrections", row._id, {
150
+ state: "held",
151
+ reason: "native_retry_window_expired",
152
+ leaseUntil: 0,
153
+ });
154
+ await history(ctx, row, { safeRetryWindowExpired: true });
155
+ return { kind: "done" as const, attempt: row.attempt };
156
+ }
157
+ const originalScope = JSON.parse(row.recordJson).scope;
158
+ for (const account of [
159
+ originalScope.stripeAccountId,
160
+ originalScope.customerAccount,
161
+ ])
162
+ if (await closureByStripeId(ctx, account))
163
+ throw new Error(
164
+ "Account closure prevents correction provider operation",
165
+ );
166
+ const attempt = row.attempt + 1;
167
+ await ctx.db.patch("usageCorrections", row._id, {
168
+ attempt,
169
+ attemptedAt: row.attemptedAt ?? now,
170
+ leaseUntil: now + 900,
171
+ });
172
+ await history(ctx, row, { phase: "attempt", attempt });
173
+ return { kind: "ready" as const, attempt };
174
+ },
175
+ });
176
+ export const save = mutation({
177
+ args: { key: v.string(), attempt: v.number(), outcomeJson: v.string() },
178
+ returns: operationDoc,
179
+ handler: async (ctx, args) => {
180
+ const row = await operation(ctx, args.key);
181
+ if (row.state === "confirmed") return row;
182
+ if (row.attempt !== args.attempt || row.attemptedAt === undefined)
183
+ throw new Error("Stale correction receipt");
184
+ const result = correctionOutcome.parse(json(args.outcomeJson));
185
+ const request = JSON.parse(row.inputJson),
186
+ { event, outbox, record } = await read(ctx, {
187
+ scope: request.scope,
188
+ eventId: row.eventId,
189
+ });
190
+ if (outbox.correctionKey !== row.key)
191
+ throw new Error("Correction outbox identity mismatch");
192
+ if (result.status === "pending" || result.status === "complete") {
193
+ if (
194
+ !outbox.receipt ||
195
+ outbox.receipt.identifier !== result.identifier ||
196
+ result.identifier !== outbox.providerIdentifier ||
197
+ result.eventName !== record.binding.eventName ||
198
+ result.livemode !== record.scope.livemode
199
+ )
200
+ throw new Error("Native correction receipt scope mismatch");
201
+ const confirm =
202
+ result.status === "complete" &&
203
+ result.billingSafe &&
204
+ (record.binding.plan.model !== "prepaid" ||
205
+ result.creditBackingVerified);
206
+ await ctx.db.patch("usageCorrections", row._id, {
207
+ state: confirm
208
+ ? "confirmed"
209
+ : result.status === "pending"
210
+ ? "provider_accepted"
211
+ : !result.billingSafe
212
+ ? "invoice_adjustment_required"
213
+ : "held",
214
+ reason: confirm
215
+ ? "native_cancellation_complete"
216
+ : result.status === "pending"
217
+ ? "native_cancellation_pending"
218
+ : !result.billingSafe
219
+ ? "native_invoice_finalized_or_unresolved"
220
+ : "credit_backing_requires_reconciliation",
221
+ invoiceId: result.invoiceId,
222
+ cashConsequence:
223
+ result.status === "complete" && !result.billingSafe
224
+ ? "operator_resolution_required"
225
+ : "none",
226
+ nativeStatus: result.status,
227
+ nativeAdjustmentId: result.nativeAdjustmentId ?? undefined,
228
+ leaseUntil: 0,
229
+ restoredQuantity: confirm ? row.quantity : "0",
230
+ });
231
+ } else if (result.status === "local_complete") {
232
+ if (!locallyCancelable(outbox) || record.binding.plan.model !== "prepaid")
233
+ throw new Error("Unsent credit correction provenance mismatch");
234
+ await ctx.db.patch("usageCorrections", row._id, {
235
+ state: "confirmed",
236
+ reason:
237
+ outbox.state === "rejected"
238
+ ? "canceled_after_delivery_rejection"
239
+ : "canceled_before_delivery",
240
+ leaseUntil: 0,
241
+ restoredQuantity: row.quantity,
242
+ });
243
+ } else if ("reason" in result) {
244
+ await ctx.db.patch("usageCorrections", row._id, {
245
+ state: result.status,
246
+ reason: result.reason,
247
+ invoiceId: result.invoiceId,
248
+ leaseUntil: 0,
249
+ cashConsequence:
250
+ result.status === "invoice_adjustment_required"
251
+ ? "operator_resolution_required"
252
+ : "none",
253
+ });
254
+ }
255
+ const saved = await operation(ctx, row.key);
256
+ if (saved.state === "confirmed") {
257
+ await restore(ctx, row, event);
258
+ await ctx.db.patch("usageOutbox", outbox._id, {
259
+ state: "canceled",
260
+ held: true,
261
+ reason: "usage_canceled",
262
+ });
263
+ }
264
+ await history(ctx, saved, {
265
+ attempt: args.attempt,
266
+ providerIdentifier: outbox.providerIdentifier,
267
+ outcome: result,
268
+ result: view(saved),
269
+ });
270
+ return operation(ctx, row.key);
271
+ },
272
+ });
273
+
274
+ export const adopt = mutation({
275
+ args: { key: v.string(), proofJson: v.string() },
276
+ returns: operationDoc,
277
+ handler: adoptInvoiceCorrection,
278
+ });
@@ -0,0 +1,94 @@
1
+ import { scopeValidator } from "../usage/schema.js";
2
+ import { scopeKey } from "../usage/helpers.js";
3
+ import { validateUsagePageRequest } from "../../client/usage/boundaries.js";
4
+ import {
5
+ paginationOptsValidator,
6
+ paginationResultValidator,
7
+ } from "convex/server";
8
+ import { paginator } from "convex-helpers/server/pagination";
9
+ import { v } from "convex/values";
10
+ import { query } from "../_generated/server.js";
11
+ import schema from "../schema.js";
12
+ import { refFields } from "../usageDelivery/schema.js";
13
+ import { read } from "../usageDelivery/helpers.js";
14
+ import { canonicalFingerprint } from "../operationEvidence/canonical.js";
15
+ import { historyDoc, operationDoc } from "./schema.js";
16
+ export const readHistory = query({
17
+ args: { ...refFields, paginationOpts: paginationOptsValidator },
18
+ returns: paginationResultValidator(historyDoc),
19
+ handler: async (ctx, args) => {
20
+ await read(ctx, args);
21
+ if (
22
+ !Number.isInteger(args.paginationOpts.numItems) ||
23
+ args.paginationOpts.numItems < 1 ||
24
+ args.paginationOpts.numItems > 100
25
+ )
26
+ throw new Error("Invalid correction history page");
27
+ return paginator(ctx.db, schema)
28
+ .query("usageCorrectionHistory")
29
+ .withIndex("by_event", (q) => q.eq("eventId", args.eventId))
30
+ .order("asc")
31
+ .paginate({
32
+ ...args.paginationOpts,
33
+ maximumRowsRead: 200,
34
+ maximumBytesRead: 1000000,
35
+ });
36
+ },
37
+ });
38
+
39
+ export const get = query({
40
+ args: { ...refFields, correctionId: v.string() },
41
+ returns: v.union(operationDoc, v.null()),
42
+ handler: async (ctx, args) => {
43
+ await read(ctx, args);
44
+ if (!args.correctionId || args.correctionId.length > 100)
45
+ throw new Error("Invalid correction identity");
46
+ const key = await canonicalFingerprint([args.scope, args.correctionId]);
47
+ const row = await ctx.db
48
+ .query("usageCorrections")
49
+ .withIndex("by_key", (q) => q.eq("key", key))
50
+ .unique();
51
+ return row?.eventId === args.eventId ? row : null;
52
+ },
53
+ });
54
+
55
+ export const periodHistory = query({
56
+ args: {
57
+ scope: scopeValidator,
58
+ period: v.object({ start: v.number(), end: v.number() }),
59
+ paginationOpts: paginationOptsValidator,
60
+ },
61
+ returns: v.object({
62
+ ...paginationResultValidator(historyDoc).fields,
63
+ legacyHistoryMissing: v.boolean(),
64
+ }),
65
+ handler: async (ctx, args) => {
66
+ validateUsagePageRequest({
67
+ period: args.period,
68
+ limit: args.paginationOpts.numItems,
69
+ cursor: args.paginationOpts.cursor,
70
+ });
71
+ const key = scopeKey(args.scope);
72
+ const legacy = await ctx.db
73
+ .query("usageCorrectionHistory")
74
+ .withIndex("by_scope_occurrence", (q) =>
75
+ q.eq("scopeKey", key).eq("occurredAt", undefined),
76
+ )
77
+ .first();
78
+ const result = await paginator(ctx.db, schema)
79
+ .query("usageCorrectionHistory")
80
+ .withIndex("by_scope_occurrence", (q) =>
81
+ q
82
+ .eq("scopeKey", key)
83
+ .gte("occurredAt", args.period.start)
84
+ .lt("occurredAt", args.period.end),
85
+ )
86
+ .order("asc")
87
+ .paginate({
88
+ ...args.paginationOpts,
89
+ maximumRowsRead: 200,
90
+ maximumBytesRead: 1000000,
91
+ });
92
+ return { ...result, legacyHistoryMissing: legacy !== null };
93
+ },
94
+ });
@@ -0,0 +1,90 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ export const state = v.union(
4
+ v.literal("requested"),
5
+ v.literal("provider_accepted"),
6
+ v.literal("confirmed"),
7
+ v.literal("held"),
8
+ v.literal("unsupported"),
9
+ v.literal("invoice_adjustment_required"),
10
+ );
11
+ export const fields = {
12
+ stripeAccountId: v.optional(v.string()),
13
+ customerAccount: v.optional(v.string()),
14
+ observedAt: v.optional(v.number()),
15
+ nativeCreditNoteStatus: v.optional(
16
+ v.union(v.literal("issued"), v.literal("void")),
17
+ ),
18
+ resolution: v.optional(
19
+ v.union(v.literal("event_cancellation"), v.literal("invoice_credit")),
20
+ ),
21
+ adjustmentJson: v.optional(v.string()),
22
+ key: v.string(),
23
+ scopeKey: v.string(),
24
+ eventId: v.id("usageEvents"),
25
+ correctionId: v.string(),
26
+ inputJson: v.string(),
27
+ recordJson: v.string(),
28
+ subscriptionJson: v.string(),
29
+ quantity: v.string(),
30
+ scaledQuantity: v.string(),
31
+ state,
32
+ reason: v.string(),
33
+ firstAttemptAt: v.number(),
34
+ attemptedAt: v.optional(v.number()),
35
+ leaseUntil: v.optional(v.number()),
36
+ attempt: v.number(),
37
+ nativeAdjustmentId: v.optional(v.string()),
38
+ nativeStatus: v.optional(
39
+ v.union(v.literal("pending"), v.literal("complete")),
40
+ ),
41
+ invoiceId: v.optional(v.string()),
42
+ creditNoteId: v.optional(v.string()),
43
+ refundId: v.optional(v.string()),
44
+ cashConsequence: v.union(
45
+ v.literal("none"),
46
+ v.literal("operator_resolution_required"),
47
+ v.literal("verified_external_adjustment"),
48
+ ),
49
+ restoredQuantity: v.string(),
50
+ historyCount: v.number(),
51
+ };
52
+ export const operationDoc = v.object({
53
+ _id: v.id("usageCorrections"),
54
+ _creationTime: v.number(),
55
+ ...fields,
56
+ });
57
+ export const operationsTable = defineTable(fields)
58
+ .index("by_key", ["key"])
59
+ .index("by_event", ["eventId"])
60
+ .index("by_scope", ["scopeKey"])
61
+ .index("by_scope_state", ["scopeKey", "state"])
62
+ .index("by_realm_state", ["stripeAccountId", "state"])
63
+ .index("by_payer_state", ["customerAccount", "state"]);
64
+ export const historyFields = {
65
+ key: v.string(),
66
+ scopeKey: v.string(),
67
+ eventId: v.id("usageEvents"),
68
+ sequence: v.number(),
69
+ state,
70
+ reason: v.string(),
71
+ recordJson: v.string(),
72
+ subscriptionJson: v.string(),
73
+ evidenceJson: v.string(),
74
+ occurredAt: v.optional(v.number()),
75
+ at: v.number(),
76
+ };
77
+ export const historyDoc = v.object({
78
+ _id: v.id("usageCorrectionHistory"),
79
+ _creationTime: v.number(),
80
+ ...historyFields,
81
+ });
82
+ export const historyTable = defineTable(historyFields)
83
+ .index("by_event", ["eventId"])
84
+ .index("by_scope_time", ["scopeKey", "at"])
85
+ .index("by_scope_occurrence", ["scopeKey", "occurredAt"]);
86
+ export const claimsTable = defineTable({
87
+ key: v.string(),
88
+ operationKey: v.string(),
89
+ proofJson: v.string(),
90
+ }).index("by_key", ["key"]);
@@ -1,3 +1,4 @@
1
+ import { verifiedCancellation } from "../usageCorrections/cancellation.js";
1
2
  import { scopeValidator } from "../usage/schema.js";
2
3
  import { scopeKey } from "../usage/helpers.js";
3
4
  import { account, purchase } from "./helpers.js";
@@ -210,6 +211,9 @@ export const invoiceUsage = query({
210
211
  .query("usageDeliveryErrors")
211
212
  .withIndex("by_event", (q) => q.eq("eventId", row._id))
212
213
  .first();
214
+ const canceled = await verifiedCancellation(ctx, row, outbox);
215
+ if (canceled === "confirmed") continue;
216
+ if (canceled === "unverified") valid = false;
213
217
  if (outbox?.state !== "provider_accepted" || error) valid = false;
214
218
  quantity += BigInt(event.scaledQuantity);
215
219
  }
@@ -89,6 +89,7 @@ export const historyFields = {
89
89
  v.literal("observation"),
90
90
  v.literal("recovery"),
91
91
  v.literal("closure"),
92
+ v.literal("correction"),
92
93
  ),
93
94
  sourceKey: v.string(),
94
95
  fingerprint: v.string(),
@@ -1,6 +1,7 @@
1
1
  import { defineTable } from "convex/server";
2
2
  import { v } from "convex/values";
3
3
  export const reason = v.union(
4
+ v.literal("usage_canceled"),
4
5
  v.literal("billing_period_closed"),
5
6
  v.literal("rate_limited"),
6
7
  v.literal("provider_unavailable"),
@@ -63,9 +63,13 @@ export const start = mutation({
63
63
  definitionVersion: 1,
64
64
  });
65
65
  if (
66
- !["provider_accepted", "rejected", "unknown", "held"].includes(
67
- outbox.state,
68
- )
66
+ ![
67
+ "canceled",
68
+ "provider_accepted",
69
+ "rejected",
70
+ "unknown",
71
+ "held",
72
+ ].includes(outbox.state)
69
73
  )
70
74
  await launch(ctx, { scope: args.scope, eventId: args.eventId }, outbox);
71
75
  return await currentStatus(ctx, (await read(ctx, args)).outbox);
@@ -98,6 +102,7 @@ export const resume = mutation({
98
102
  returns: status,
99
103
  handler: async (ctx, args) => {
100
104
  const { outbox } = await read(ctx, args);
105
+ if (outbox.correctionKey) return await currentStatus(ctx, outbox);
101
106
  if (
102
107
  outbox.state === "unknown" ||
103
108
  ["provider_accepted", "rejected"].includes(outbox.state) ||
@@ -18,7 +18,7 @@ export const claim = internalMutation({
18
18
  now = Math.floor(Date.now() / 1000);
19
19
  if (
20
20
  outbox.held ||
21
- ["provider_accepted", "rejected", "unknown", "held"].includes(
21
+ ["canceled", "provider_accepted", "rejected", "unknown", "held"].includes(
22
22
  outbox.state,
23
23
  )
24
24
  )
@@ -1,3 +1,4 @@
1
+ import { verifiedCancellation } from "../usageCorrections/cancellation.js";
1
2
  import {
2
3
  paginationOptsValidator,
3
4
  paginationResultValidator,
@@ -54,11 +55,13 @@ export const summary = query({
54
55
  .first(),
55
56
  ]);
56
57
  if (!outbox) throw new Error("Usage outbox invariant violated");
58
+ const canceled = await verifiedCancellation(ctx, event, outbox);
57
59
  return {
58
60
  record: JSON.parse(event.recordJson) as PreparedUsageRecord,
59
61
  subscription: subscriptionSnapshot(event.subscriptionJson),
60
- delivery: outbox.state,
61
- hasValidationError: error !== null,
62
+ delivery:
63
+ canceled === "unverified" ? ("held" as const) : outbox.state,
64
+ hasValidationError: canceled !== "confirmed" && error !== null,
62
65
  };
63
66
  }),
64
67
  );
@@ -1,3 +1,7 @@
1
+ import {
2
+ unresolvedCorrectionStates,
3
+ verifiedCancellation,
4
+ } from "../usageCorrections/cancellation.js";
1
5
  import { retirementProof } from "../../client/usage/subscriptionInvoiceSchema.js";
2
6
  import type { MutationCtx } from "../_generated/server.js";
3
7
  import type { Doc } from "../_generated/dataModel.js";
@@ -41,6 +45,16 @@ export async function retireEnrollment(
41
45
  throw new Error("Cancellation command is still pending");
42
46
  for (const meter of terms.meters) {
43
47
  const key = scopeKey(meter.scope);
48
+ for (const state of unresolvedCorrectionStates) {
49
+ const pendingCorrection = await ctx.db
50
+ .query("usageCorrections")
51
+ .withIndex("by_scope_state", (q) =>
52
+ q.eq("scopeKey", key).eq("state", state),
53
+ )
54
+ .first();
55
+ if (pendingCorrection)
56
+ throw new Error("Enrollment has unresolved usage corrections");
57
+ }
44
58
  for (const state of [
45
59
  "queued",
46
60
  "sending",
@@ -66,8 +80,23 @@ export async function retireEnrollment(
66
80
  const errors = await ctx.db
67
81
  .query("usageDeliveryErrors")
68
82
  .withIndex("by_scope", (q) => q.eq("scopeKey", key))
69
- .take(1);
70
- if (reservations.length || errors.length)
83
+ .take(101);
84
+ let unresolvedErrors = errors.length > 100;
85
+ for (const error of errors.slice(0, 100)) {
86
+ const event = await ctx.db.get("usageEvents", error.eventId);
87
+ const outbox = event
88
+ ? await ctx.db
89
+ .query("usageOutbox")
90
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
91
+ .unique()
92
+ : null;
93
+ if (
94
+ !event ||
95
+ (await verifiedCancellation(ctx, event, outbox)) !== "confirmed"
96
+ )
97
+ unresolvedErrors = true;
98
+ }
99
+ if (reservations.length || unresolvedErrors)
71
100
  throw new Error(
72
101
  "Enrollment has pending reservations or validation errors",
73
102
  );