@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
@@ -9,6 +9,32 @@ export const allocationFields = {
9
9
  sourceChargeId: v.string(),
10
10
  paymentIntentId: v.optional(v.string()),
11
11
  sourceInvoiceId: v.optional(v.string()),
12
+ usageSource: v.optional(
13
+ v.object({
14
+ stripeAccountId: v.string(),
15
+ customerAccount: v.string(),
16
+ livemode: v.boolean(),
17
+ meterId: v.string(),
18
+ stripePriceId: v.string(),
19
+ stripeProductId: v.string(),
20
+ subscriptionId: v.string(),
21
+ subscriptionItemId: v.string(),
22
+ invoicePaymentId: v.string(),
23
+ period: v.object({ start: v.number(), end: v.number() }),
24
+ model: v.union(v.literal("pay_as_you_go"), v.literal("included_overage")),
25
+ }),
26
+ ),
27
+ creditSource: v.optional(
28
+ v.object({
29
+ stripeAccountId: v.string(),
30
+ customerAccount: v.string(),
31
+ livemode: v.boolean(),
32
+ purchaseId: v.string(),
33
+ creditGrantId: v.string(),
34
+ stripePriceId: v.string(),
35
+ stripeProductId: v.string(),
36
+ }),
37
+ ),
12
38
  gross: v.number(),
13
39
  currency: v.string(),
14
40
  processingFee: v.number(),
@@ -74,3 +74,57 @@ it("persists the term, identity and earliest invoice despite replay and term cha
74
74
  }),
75
75
  ).rejects.toThrow();
76
76
  });
77
+
78
+ it("pins original native metering provenance and refuses replay against another meter or invoice payment", async () => {
79
+ const t = convexTest(schema, modules);
80
+ const opts = {
81
+ sourceChargeId: "ch_meter",
82
+ paymentIntentId: "pi_meter",
83
+ sourceInvoiceId: "in_meter",
84
+ gross: 100,
85
+ currency: "usd",
86
+ processingFee: 3,
87
+ platformNet: 7,
88
+ transfers: [
89
+ {
90
+ destinationAccountId: "acct_seller",
91
+ amount: 90,
92
+ role: "store" as const,
93
+ },
94
+ ],
95
+ usageSource: {
96
+ stripeAccountId: "acct_platform",
97
+ customerAccount: "acct_buyer",
98
+ livemode: false,
99
+ meterId: "mtr_calls",
100
+ stripePriceId: "price_calls",
101
+ stripeProductId: "prod_calls",
102
+ subscriptionId: "sub_calls",
103
+ subscriptionItemId: "si_calls",
104
+ invoicePaymentId: "inpay_meter",
105
+ period: { start: 600, end: 1200 },
106
+ model: "pay_as_you_go" as const,
107
+ },
108
+ };
109
+ const first = await t.mutation(
110
+ api.settlement.mutations.reserveSettlementAllocation,
111
+ opts,
112
+ );
113
+ expect(first).toMatchObject({ usageSource: opts.usageSource });
114
+ for (const changed of [
115
+ { meterId: "mtr_other" },
116
+ { invoicePaymentId: "inpay_other" },
117
+ ])
118
+ await expect(
119
+ t.mutation(api.settlement.mutations.reserveSettlementAllocation, {
120
+ ...opts,
121
+ usageSource: { ...opts.usageSource, ...changed },
122
+ }),
123
+ ).rejects.toThrow(/source identity/i);
124
+ await expect(
125
+ t.mutation(api.settlement.mutations.reserveSettlementAllocation, {
126
+ ...opts,
127
+ usageSource: undefined,
128
+ }),
129
+ ).rejects.toThrow(/source identity/i);
130
+ });
@@ -10,6 +10,7 @@ export const scopeValidator = v.object({
10
10
  });
11
11
  export const deliveryValidator = v.union(
12
12
  v.literal("queued"),
13
+ v.literal("canceled"),
13
14
  v.literal("sending"),
14
15
  v.literal("provider_accepted"),
15
16
  v.literal("rejected"),
@@ -41,6 +42,7 @@ export const usageEventsTable = defineTable(eventFields)
41
42
  ])
42
43
  .index("by_scope_time", ["scopeKey", "occurredAt"]);
43
44
  export const outboxFields = {
45
+ correctionKey: v.optional(v.string()),
44
46
  ...deliveryFields,
45
47
  eventId: v.id("usageEvents"),
46
48
  scopeKey: v.string(),
@@ -1,3 +1,4 @@
1
+ import { verifiedCancellation } from "../usageCorrections/cancellation.js";
1
2
  import { paginationOptsValidator } from "convex/server";
2
3
  import { v } from "convex/values";
3
4
  import { query } from "../_generated/server.js";
@@ -109,7 +110,13 @@ export const reconciliation = query({
109
110
  reservation.scaledQuantity !== record.scaledQuantity
110
111
  )
111
112
  complete = false;
112
- accepted += BigInt(record.scaledQuantity);
113
+ const outbox = await ctx.db
114
+ .query("usageOutbox")
115
+ .withIndex("by_event", (q) => q.eq("eventId", event._id))
116
+ .unique();
117
+ const canceled = await verifiedCancellation(ctx, event, outbox);
118
+ if (canceled === "unverified") complete = false;
119
+ if (canceled !== "confirmed") accepted += BigInt(record.scaledQuantity);
113
120
  }
114
121
  for (const reservation of reservations)
115
122
  reserved += BigInt(reservation.scaledQuantity);
@@ -24,6 +24,7 @@ export const historyFields = {
24
24
  v.literal("reservation"),
25
25
  v.literal("commit"),
26
26
  v.literal("release"),
27
+ v.literal("correction"),
27
28
  ),
28
29
  evidenceJson: v.string(),
29
30
  at: v.number(),
@@ -0,0 +1,79 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ import { creditAllocations } from "../usageCredits/reservations.js";
4
+ import { account, history as creditHistory } from "../usageCredits/helpers.js";
5
+ import {
6
+ policyRow,
7
+ history as allowanceHistory,
8
+ } from "../usageAllowance/helpers.js";
9
+ /** Called only for a full proven cancellation, in the same transaction as the terminal receipt. */
10
+ export async function restore(
11
+ ctx: MutationCtx,
12
+ correction: Doc<"usageCorrections">,
13
+ event: Doc<"usageEvents">,
14
+ ) {
15
+ if (!event.reservationId) return;
16
+ const reservation = await ctx.db.get(
17
+ "usageReservations",
18
+ event.reservationId,
19
+ );
20
+ if (
21
+ !reservation ||
22
+ reservation.state !== "committed" ||
23
+ reservation.eventId !== event._id ||
24
+ reservation.scopeKey !== correction.scopeKey ||
25
+ reservation.scaledQuantity !== correction.scaledQuantity
26
+ )
27
+ throw new Error("Correction reservation provenance mismatch");
28
+ if (reservation.accountingKind === "allowance") {
29
+ const policy = await policyRow(ctx, reservation.accountKey!);
30
+ if (!policy || BigInt(policy.consumed) < BigInt(correction.scaledQuantity))
31
+ throw new Error("Correction allowance backing unavailable");
32
+ await ctx.db.patch("usageAllowancePolicies", policy._id, {
33
+ consumed: (
34
+ BigInt(policy.consumed) - BigInt(correction.scaledQuantity)
35
+ ).toString(),
36
+ });
37
+ await allowanceHistory(ctx, policy, "correction", {
38
+ correctionKey: correction.key,
39
+ eventId: event._id,
40
+ scaledQuantity: correction.scaledQuantity,
41
+ cashCollection: "none",
42
+ });
43
+ } else if (reservation.accountingKind === "prepaid") {
44
+ const ledger = await account(ctx, reservation.accountKey!);
45
+ if (ledger.closed || ledger.frozenReason)
46
+ throw new Error("Correction credit account requires reconciliation");
47
+ const allocations = creditAllocations.parse(
48
+ JSON.parse(reservation.allocationsJson!),
49
+ );
50
+ for (const allocation of allocations) {
51
+ const grant = await ctx.db.get(
52
+ "usageCreditGrants",
53
+ allocation.grantId as import("../_generated/dataModel.js").Id<"usageCreditGrants">,
54
+ );
55
+ if (
56
+ !grant ||
57
+ grant.accountKey !== ledger.key ||
58
+ grant.frozen ||
59
+ grant.nativeExpired ||
60
+ (grant.expiresAt !== null && grant.expiresAt <= Date.now() / 1000) ||
61
+ BigInt(grant.consumed) < BigInt(allocation.quantity)
62
+ )
63
+ throw new Error("Correction original credit backing unavailable");
64
+ await ctx.db.patch("usageCreditGrants", grant._id, {
65
+ consumed: (
66
+ BigInt(grant.consumed) - BigInt(allocation.quantity)
67
+ ).toString(),
68
+ available: (
69
+ BigInt(grant.available) + BigInt(allocation.quantity)
70
+ ).toString(),
71
+ });
72
+ }
73
+ await creditHistory(ctx, ledger.key, "correction", correction.key, {
74
+ eventId: event._id,
75
+ allocations,
76
+ cashCollection: "none",
77
+ });
78
+ }
79
+ }
@@ -0,0 +1,32 @@
1
+ import type { QueryCtx } from "../_generated/server.js";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ /** Never treat an unproven terminal projection as canceled billable quantity. */
4
+ export async function verifiedCancellation(
5
+ ctx: QueryCtx,
6
+ event: Doc<"usageEvents">,
7
+ outbox: Doc<"usageOutbox"> | null,
8
+ ) {
9
+ if (outbox?.state !== "canceled") return "none" as const;
10
+ if (!outbox.correctionKey) return "unverified" as const;
11
+ const correction = await ctx.db
12
+ .query("usageCorrections")
13
+ .withIndex("by_key", (q) => q.eq("key", outbox.correctionKey!))
14
+ .unique();
15
+ const record = JSON.parse(event.recordJson);
16
+ return correction?.state === "confirmed" &&
17
+ correction.resolution !== "invoice_credit" &&
18
+ correction.eventId === event._id &&
19
+ correction.scopeKey === event.scopeKey &&
20
+ correction.recordJson === event.recordJson &&
21
+ correction.subscriptionJson === event.subscriptionJson &&
22
+ correction.scaledQuantity === record.scaledQuantity &&
23
+ correction.restoredQuantity === record.quantity
24
+ ? ("confirmed" as const)
25
+ : ("unverified" as const);
26
+ }
27
+ export const unresolvedCorrectionStates = [
28
+ "requested",
29
+ "provider_accepted",
30
+ "held",
31
+ "invoice_adjustment_required",
32
+ ] as const;
@@ -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
+ }