@fantastic.dev/better-stripe 0.58.0 → 0.60.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 (294) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +3 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +888 -62
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +428 -15
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +856 -30
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +444 -31
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/index.d.ts +4 -0
  12. package/dist/client/index.d.ts.map +1 -1
  13. package/dist/client/paymentSource/resolver.d.ts +12 -1
  14. package/dist/client/paymentSource/resolver.d.ts.map +1 -1
  15. package/dist/client/paymentSource/resolver.fixtures.d.ts +220 -0
  16. package/dist/client/paymentSource/resolver.fixtures.d.ts.map +1 -0
  17. package/dist/client/paymentSource/resolver.fixtures.js +189 -0
  18. package/dist/client/paymentSource/resolver.fixtures.js.map +1 -0
  19. package/dist/client/paymentSource/resolver.js +28 -3
  20. package/dist/client/paymentSource/resolver.js.map +1 -1
  21. package/dist/client/settlement/execution.d.ts +25 -0
  22. package/dist/client/settlement/execution.d.ts.map +1 -1
  23. package/dist/client/settlement/execution.js +2 -0
  24. package/dist/client/settlement/execution.js.map +1 -1
  25. package/dist/client/usage/allowanceClient.d.ts +1 -1
  26. package/dist/client/usage/catalogPrices.d.ts +1 -1
  27. package/dist/client/usage/catalogPrices.d.ts.map +1 -1
  28. package/dist/client/usage/catalogPrices.js +4 -4
  29. package/dist/client/usage/catalogPrices.js.map +1 -1
  30. package/dist/client/usage/client.d.ts +2 -2
  31. package/dist/client/usage/client.d.ts.map +1 -1
  32. package/dist/client/usage/client.js +2 -2
  33. package/dist/client/usage/client.js.map +1 -1
  34. package/dist/client/usage/correctionClient.d.ts +33 -0
  35. package/dist/client/usage/correctionClient.d.ts.map +1 -0
  36. package/dist/client/usage/correctionClient.js +27 -0
  37. package/dist/client/usage/correctionClient.js.map +1 -0
  38. package/dist/client/usage/correctionEligibility.d.ts +4 -0
  39. package/dist/client/usage/correctionEligibility.d.ts.map +1 -0
  40. package/dist/client/usage/correctionEligibility.js +7 -0
  41. package/dist/client/usage/correctionEligibility.js.map +1 -0
  42. package/dist/client/usage/correctionInvoice.d.ts +9 -0
  43. package/dist/client/usage/correctionInvoice.d.ts.map +1 -0
  44. package/dist/client/usage/correctionInvoice.js +218 -0
  45. package/dist/client/usage/correctionInvoice.js.map +1 -0
  46. package/dist/client/usage/correctionInvoiceProof.d.ts +29 -0
  47. package/dist/client/usage/correctionInvoiceProof.d.ts.map +1 -0
  48. package/dist/client/usage/correctionInvoiceProof.js +41 -0
  49. package/dist/client/usage/correctionInvoiceProof.js.map +1 -0
  50. package/dist/client/usage/correctionProofs.d.ts +36 -0
  51. package/dist/client/usage/correctionProofs.d.ts.map +1 -0
  52. package/dist/client/usage/correctionProofs.js +41 -0
  53. package/dist/client/usage/correctionProofs.js.map +1 -0
  54. package/dist/client/usage/correctionProvider.d.ts +6 -0
  55. package/dist/client/usage/correctionProvider.d.ts.map +1 -0
  56. package/dist/client/usage/correctionProvider.js +243 -0
  57. package/dist/client/usage/correctionProvider.js.map +1 -0
  58. package/dist/client/usage/correctionRead.d.ts +27 -0
  59. package/dist/client/usage/correctionRead.d.ts.map +1 -0
  60. package/dist/client/usage/correctionRead.js +36 -0
  61. package/dist/client/usage/correctionRead.js.map +1 -0
  62. package/dist/client/usage/correctionTerms.d.ts +64 -0
  63. package/dist/client/usage/correctionTerms.d.ts.map +1 -0
  64. package/dist/client/usage/correctionTerms.js +65 -0
  65. package/dist/client/usage/correctionTerms.js.map +1 -0
  66. package/dist/client/usage/correctionTransport.fixtures.d.ts +37 -0
  67. package/dist/client/usage/correctionTransport.fixtures.d.ts.map +1 -0
  68. package/dist/client/usage/correctionTransport.fixtures.js +322 -0
  69. package/dist/client/usage/correctionTransport.fixtures.js.map +1 -0
  70. package/dist/client/usage/creditClient.d.ts +1 -1
  71. package/dist/client/usage/creditRevenue.d.ts +22 -0
  72. package/dist/client/usage/creditRevenue.d.ts.map +1 -0
  73. package/dist/client/usage/creditRevenue.js +118 -0
  74. package/dist/client/usage/creditRevenue.js.map +1 -0
  75. package/dist/client/usage/creditSettlement.d.ts +29 -0
  76. package/dist/client/usage/creditSettlement.d.ts.map +1 -0
  77. package/dist/client/usage/creditSettlement.fixtures.d.ts +215 -0
  78. package/dist/client/usage/creditSettlement.fixtures.d.ts.map +1 -0
  79. package/dist/client/usage/creditSettlement.fixtures.js +59 -0
  80. package/dist/client/usage/creditSettlement.fixtures.js.map +1 -0
  81. package/dist/client/usage/creditSettlement.js +70 -0
  82. package/dist/client/usage/creditSettlement.js.map +1 -0
  83. package/dist/client/usage/creditTransport.fixtures.d.ts +7 -1
  84. package/dist/client/usage/creditTransport.fixtures.d.ts.map +1 -1
  85. package/dist/client/usage/creditTransport.fixtures.js +25 -4
  86. package/dist/client/usage/creditTransport.fixtures.js.map +1 -1
  87. package/dist/client/usage/index.d.ts +6 -0
  88. package/dist/client/usage/index.d.ts.map +1 -1
  89. package/dist/client/usage/invoiceSale.d.ts +22 -0
  90. package/dist/client/usage/invoiceSale.d.ts.map +1 -0
  91. package/dist/client/usage/invoiceSale.fixtures.d.ts +285 -0
  92. package/dist/client/usage/invoiceSale.fixtures.d.ts.map +1 -0
  93. package/dist/client/usage/invoiceSale.fixtures.js +104 -0
  94. package/dist/client/usage/invoiceSale.fixtures.js.map +1 -0
  95. package/dist/client/usage/invoiceSale.js +117 -0
  96. package/dist/client/usage/invoiceSale.js.map +1 -0
  97. package/dist/client/usage/observationClient.d.ts +20 -0
  98. package/dist/client/usage/observationClient.d.ts.map +1 -1
  99. package/dist/client/usage/observationClient.js +20 -6
  100. package/dist/client/usage/observationClient.js.map +1 -1
  101. package/dist/client/usage/records.d.ts +1 -1
  102. package/dist/client/usage/records.d.ts.map +1 -1
  103. package/dist/client/usage/records.js.map +1 -1
  104. package/dist/client/usage/settlement.d.ts +32 -0
  105. package/dist/client/usage/settlement.d.ts.map +1 -0
  106. package/dist/client/usage/settlement.js +60 -0
  107. package/dist/client/usage/settlement.js.map +1 -0
  108. package/dist/client/usage/settlementClient.d.ts +51 -0
  109. package/dist/client/usage/settlementClient.d.ts.map +1 -0
  110. package/dist/client/usage/settlementClient.js +35 -0
  111. package/dist/client/usage/settlementClient.js.map +1 -0
  112. package/dist/client/usage/summary.d.ts +3 -0
  113. package/dist/client/usage/summary.d.ts.map +1 -1
  114. package/dist/client/usage/summary.js +9 -4
  115. package/dist/client/usage/summary.js.map +1 -1
  116. package/dist/client/usageExports.d.ts +2 -0
  117. package/dist/client/usageExports.d.ts.map +1 -1
  118. package/dist/component/_generated/api.d.ts +12 -0
  119. package/dist/component/_generated/api.d.ts.map +1 -1
  120. package/dist/component/_generated/api.js.map +1 -1
  121. package/dist/component/_generated/component.d.ts +380 -14
  122. package/dist/component/_generated/component.d.ts.map +1 -1
  123. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  124. package/dist/component/accountClosure/mutations.js +13 -0
  125. package/dist/component/accountClosure/mutations.js.map +1 -1
  126. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  127. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  128. package/dist/component/earnings/triggers.d.ts +368 -32
  129. package/dist/component/earnings/triggers.d.ts.map +1 -1
  130. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -1
  131. package/dist/component/financialObservations/settlementHelpers.js +2 -0
  132. package/dist/component/financialObservations/settlementHelpers.js.map +1 -1
  133. package/dist/component/recoveryWorkflow/helpers.d.ts +25 -0
  134. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -1
  135. package/dist/component/recoveryWorkflow/mutations.d.ts +25 -0
  136. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -1
  137. package/dist/component/recoveryWorkflow/queries.d.ts +50 -0
  138. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -1
  139. package/dist/component/recoveryWorkflow/schema.d.ts +566 -10
  140. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -1
  141. package/dist/component/schema.d.ts +428 -15
  142. package/dist/component/schema.js +4 -0
  143. package/dist/component/schema.js.map +1 -1
  144. package/dist/component/settlement/mutations.d.ts +50 -0
  145. package/dist/component/settlement/mutations.d.ts.map +1 -1
  146. package/dist/component/settlement/mutations.js +8 -1
  147. package/dist/component/settlement/mutations.js.map +1 -1
  148. package/dist/component/settlement/queries.d.ts +25 -0
  149. package/dist/component/settlement/queries.d.ts.map +1 -1
  150. package/dist/component/settlement/schema.d.ts +128 -1
  151. package/dist/component/settlement/schema.d.ts.map +1 -1
  152. package/dist/component/settlement/schema.js +22 -0
  153. package/dist/component/settlement/schema.js.map +1 -1
  154. package/dist/component/usage/queries.d.ts +2 -2
  155. package/dist/component/usage/schema.d.ts +18 -13
  156. package/dist/component/usage/schema.d.ts.map +1 -1
  157. package/dist/component/usage/schema.js +2 -1
  158. package/dist/component/usage/schema.js.map +1 -1
  159. package/dist/component/usageAllowance/queries.d.ts +1 -1
  160. package/dist/component/usageAllowance/queries.d.ts.map +1 -1
  161. package/dist/component/usageAllowance/queries.js +10 -1
  162. package/dist/component/usageAllowance/queries.js.map +1 -1
  163. package/dist/component/usageAllowance/schema.d.ts +5 -5
  164. package/dist/component/usageAllowance/schema.d.ts.map +1 -1
  165. package/dist/component/usageAllowance/schema.js +1 -1
  166. package/dist/component/usageAllowance/schema.js.map +1 -1
  167. package/dist/component/usageCorrections/accounting.d.ts +5 -0
  168. package/dist/component/usageCorrections/accounting.d.ts.map +1 -0
  169. package/dist/component/usageCorrections/accounting.js +55 -0
  170. package/dist/component/usageCorrections/accounting.js.map +1 -0
  171. package/dist/component/usageCorrections/cancellation.d.ts +6 -0
  172. package/dist/component/usageCorrections/cancellation.d.ts.map +1 -0
  173. package/dist/component/usageCorrections/cancellation.js +29 -0
  174. package/dist/component/usageCorrections/cancellation.js.map +1 -0
  175. package/dist/component/usageCorrections/helpers.d.ts +60 -0
  176. package/dist/component/usageCorrections/helpers.d.ts.map +1 -0
  177. package/dist/component/usageCorrections/helpers.js +52 -0
  178. package/dist/component/usageCorrections/helpers.js.map +1 -0
  179. package/dist/component/usageCorrections/invoice.d.ts +38 -0
  180. package/dist/component/usageCorrections/invoice.d.ts.map +1 -0
  181. package/dist/component/usageCorrections/invoice.js +82 -0
  182. package/dist/component/usageCorrections/invoice.js.map +1 -0
  183. package/dist/component/usageCorrections/mutations.d.ts +121 -0
  184. package/dist/component/usageCorrections/mutations.d.ts.map +1 -0
  185. package/dist/component/usageCorrections/mutations.js +256 -0
  186. package/dist/component/usageCorrections/mutations.js.map +1 -0
  187. package/dist/component/usageCorrections/queries.d.ts +115 -0
  188. package/dist/component/usageCorrections/queries.d.ts.map +1 -0
  189. package/dist/component/usageCorrections/queries.js +84 -0
  190. package/dist/component/usageCorrections/queries.js.map +1 -0
  191. package/dist/component/usageCorrections/schema.d.ts +248 -0
  192. package/dist/component/usageCorrections/schema.d.ts.map +1 -0
  193. package/dist/component/usageCorrections/schema.js +74 -0
  194. package/dist/component/usageCorrections/schema.js.map +1 -0
  195. package/dist/component/usageCredits/queries.d.ts +1 -1
  196. package/dist/component/usageCredits/queries.d.ts.map +1 -1
  197. package/dist/component/usageCredits/queries.js +6 -0
  198. package/dist/component/usageCredits/queries.js.map +1 -1
  199. package/dist/component/usageCredits/schema.d.ts +5 -5
  200. package/dist/component/usageCredits/schema.d.ts.map +1 -1
  201. package/dist/component/usageCredits/schema.js +1 -1
  202. package/dist/component/usageCredits/schema.js.map +1 -1
  203. package/dist/component/usageDelivery/fields.d.ts +2 -2
  204. package/dist/component/usageDelivery/fields.d.ts.map +1 -1
  205. package/dist/component/usageDelivery/fields.js +1 -1
  206. package/dist/component/usageDelivery/fields.js.map +1 -1
  207. package/dist/component/usageDelivery/helpers.d.ts +7 -6
  208. package/dist/component/usageDelivery/helpers.d.ts.map +1 -1
  209. package/dist/component/usageDelivery/mutations.d.ts +6 -6
  210. package/dist/component/usageDelivery/mutations.d.ts.map +1 -1
  211. package/dist/component/usageDelivery/mutations.js +9 -1
  212. package/dist/component/usageDelivery/mutations.js.map +1 -1
  213. package/dist/component/usageDelivery/queries.d.ts +8 -6
  214. package/dist/component/usageDelivery/queries.d.ts.map +1 -1
  215. package/dist/component/usageDelivery/schema.d.ts +4 -4
  216. package/dist/component/usageDelivery/steps.d.ts +2 -2
  217. package/dist/component/usageDelivery/steps.js +1 -1
  218. package/dist/component/usageDelivery/steps.js.map +1 -1
  219. package/dist/component/usageObservations/queries.d.ts.map +1 -1
  220. package/dist/component/usageObservations/queries.js +4 -2
  221. package/dist/component/usageObservations/queries.js.map +1 -1
  222. package/dist/component/usageSubscriptions/retirement.d.ts.map +1 -1
  223. package/dist/component/usageSubscriptions/retirement.js +24 -2
  224. package/dist/component/usageSubscriptions/retirement.js.map +1 -1
  225. package/docs/README.md +4 -0
  226. package/docs/settlement.md +4 -0
  227. package/docs/usage-corrections.md +249 -0
  228. package/docs/usage-limits.md +1 -1
  229. package/docs/usage-settlement.md +162 -0
  230. package/package.json +3 -1
  231. package/src/client/index.ts +9 -0
  232. package/src/client/paymentSource/resolver.fixtures.ts +216 -0
  233. package/src/client/paymentSource/resolver.test.ts +11 -207
  234. package/src/client/paymentSource/resolver.ts +54 -2
  235. package/src/client/settlement/execution.ts +24 -0
  236. package/src/client/usage/catalogPrices.ts +4 -2
  237. package/src/client/usage/client.ts +2 -2
  238. package/src/client/usage/correctionClient.test.ts +153 -0
  239. package/src/client/usage/correctionClient.ts +62 -0
  240. package/src/client/usage/correctionCredits.test.ts +156 -0
  241. package/src/client/usage/correctionEligibility.ts +14 -0
  242. package/src/client/usage/correctionInvoice.test.ts +127 -0
  243. package/src/client/usage/correctionInvoice.ts +269 -0
  244. package/src/client/usage/correctionInvoiceProof.ts +40 -0
  245. package/src/client/usage/correctionProofs.ts +40 -0
  246. package/src/client/usage/correctionProvider.ts +326 -0
  247. package/src/client/usage/correctionRead.ts +73 -0
  248. package/src/client/usage/correctionRecovery.test.ts +113 -0
  249. package/src/client/usage/correctionTerms.ts +98 -0
  250. package/src/client/usage/correctionTransport.fixtures.ts +372 -0
  251. package/src/client/usage/creditRevenue.test.ts +105 -0
  252. package/src/client/usage/creditRevenue.ts +163 -0
  253. package/src/client/usage/creditSettlement.fixtures.ts +70 -0
  254. package/src/client/usage/creditSettlement.test.ts +66 -0
  255. package/src/client/usage/creditSettlement.ts +94 -0
  256. package/src/client/usage/creditSettlementRecovery.test.ts +173 -0
  257. package/src/client/usage/creditTransport.fixtures.ts +29 -4
  258. package/src/client/usage/index.ts +20 -0
  259. package/src/client/usage/invoiceSale.fixtures.ts +103 -0
  260. package/src/client/usage/invoiceSale.test.ts +184 -0
  261. package/src/client/usage/invoiceSale.ts +155 -0
  262. package/src/client/usage/observationClient.ts +20 -6
  263. package/src/client/usage/records.ts +7 -1
  264. package/src/client/usage/settlement.test.ts +179 -0
  265. package/src/client/usage/settlement.ts +81 -0
  266. package/src/client/usage/settlementClient.ts +84 -0
  267. package/src/client/usage/summary.ts +12 -4
  268. package/src/client/usageExports.ts +11 -0
  269. package/src/component/_generated/api.ts +12 -0
  270. package/src/component/_generated/component.ts +440 -2
  271. package/src/component/accountClosure/mutations.ts +17 -0
  272. package/src/component/financialObservations/settlementHelpers.ts +2 -0
  273. package/src/component/schema.ts +8 -0
  274. package/src/component/settlement/mutations.ts +10 -1
  275. package/src/component/settlement/schema.ts +26 -0
  276. package/src/component/settlement/settlement-claims.test.ts +54 -0
  277. package/src/component/usage/schema.ts +2 -0
  278. package/src/component/usageAllowance/queries.ts +8 -1
  279. package/src/component/usageAllowance/schema.ts +1 -0
  280. package/src/component/usageCorrections/accounting.ts +79 -0
  281. package/src/component/usageCorrections/cancellation.ts +32 -0
  282. package/src/component/usageCorrections/corrections.test.ts +389 -0
  283. package/src/component/usageCorrections/helpers.ts +57 -0
  284. package/src/component/usageCorrections/invoice.ts +103 -0
  285. package/src/component/usageCorrections/mutations.ts +278 -0
  286. package/src/component/usageCorrections/queries.ts +94 -0
  287. package/src/component/usageCorrections/schema.ts +90 -0
  288. package/src/component/usageCredits/queries.ts +4 -0
  289. package/src/component/usageCredits/schema.ts +1 -0
  290. package/src/component/usageDelivery/fields.ts +1 -0
  291. package/src/component/usageDelivery/mutations.ts +8 -3
  292. package/src/component/usageDelivery/steps.ts +1 -1
  293. package/src/component/usageObservations/queries.ts +5 -2
  294. package/src/component/usageSubscriptions/retirement.ts +31 -2
@@ -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
+ }
@@ -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
  );