@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,326 @@
1
+ import { locallyCancelable } from "./correctionEligibility.js";
2
+ import Stripe from "stripe";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import type { PreparedUsageRecord } from "./records.js";
8
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
9
+ import type { StripeApiVersion } from "../stripe-types.js";
10
+ import { verifyRealm, verifyMeter } from "./catalogTypes.js";
11
+ import { verifyCreditDelivery } from "./creditDelivery.js";
12
+ import { subscriptionSnapshot } from "../../component/usage/helpers.js";
13
+ import {
14
+ correctionRequest,
15
+ correctionView,
16
+ type UsageCorrectionOptions,
17
+ } from "./correctionTerms.js";
18
+ import type { correctionOutcome } from "./correctionProofs.js";
19
+ import type { z } from "zod";
20
+ type Outcome = z.infer<typeof correctionOutcome>;
21
+ const customerId = (customer: string | { id: string } | null) =>
22
+ typeof customer === "string" ? customer : customer?.id;
23
+ async function finalizedInvoice(
24
+ stripe: Stripe,
25
+ record: PreparedUsageRecord,
26
+ subscriptionId: string,
27
+ receivedAt: number,
28
+ ) {
29
+ const invoices = await stripe.invoices.list({
30
+ subscription: subscriptionId,
31
+ limit: 100,
32
+ });
33
+ if (invoices.has_more !== false) return { held: true as const };
34
+ for (const invoice of invoices.data) {
35
+ if (
36
+ !/^in_[a-zA-Z0-9]+$/.test(invoice.id) ||
37
+ invoice.currency !== record.binding.plan.rate.currency ||
38
+ invoice.parent?.type !== "subscription_details" ||
39
+ (typeof invoice.parent.subscription_details?.subscription === "string"
40
+ ? invoice.parent.subscription_details.subscription
41
+ : invoice.parent.subscription_details?.subscription?.id) !==
42
+ subscriptionId ||
43
+ invoice.livemode !== record.scope.livemode ||
44
+ invoice.customer_account !== record.scope.customerAccount ||
45
+ customerId(invoice.customer) !== record.binding.stripeCustomerId
46
+ )
47
+ return { held: true as const };
48
+ if (invoice.status === "draft") continue;
49
+ const finalizedAt = invoice.status_transitions?.finalized_at;
50
+ if (
51
+ !["open", "paid", "void", "uncollectible"].includes(
52
+ invoice.status ?? "",
53
+ ) ||
54
+ !Number.isSafeInteger(finalizedAt) ||
55
+ finalizedAt! < 0
56
+ )
57
+ return { held: true as const };
58
+ if (finalizedAt! < receivedAt) continue;
59
+ if (invoice.lines.has_more !== false) return { held: true as const };
60
+ for (const line of invoice.lines.data) {
61
+ const priceId = line.pricing?.price_details?.price;
62
+ if (!priceId) return { held: true as const };
63
+ if (priceId !== record.binding.stripePriceId) continue;
64
+ if (
65
+ !Number.isSafeInteger(line.period?.start) ||
66
+ !Number.isSafeInteger(line.period?.end) ||
67
+ line.period.end <= line.period.start
68
+ )
69
+ return { held: true as const };
70
+ if (
71
+ line.period.start > record.occurredAt ||
72
+ line.period.end <= record.occurredAt
73
+ )
74
+ continue;
75
+ const quantity =
76
+ line.quantity_decimal != null
77
+ ? line.quantity_decimal.toString()
78
+ : typeof line.quantity === "number" &&
79
+ Number.isSafeInteger(line.quantity) &&
80
+ line.quantity >= 0
81
+ ? String(line.quantity)
82
+ : null;
83
+ if (
84
+ quantity === null ||
85
+ quantity.length > 64 ||
86
+ !/^(0|[1-9]\d*)(\.\d+)?$/.test(quantity)
87
+ )
88
+ return { held: true as const };
89
+ if (!/^0(?:\.0+)?$/.test(quantity))
90
+ return { held: false as const, invoiceId: invoice.id };
91
+ }
92
+ }
93
+ return { held: false as const };
94
+ }
95
+ /** All native context comes from the immutable component event, never browser claims. */
96
+ export async function requestUsageCorrection(
97
+ component: Component,
98
+ ctx: RunCtx,
99
+ input: UsageCorrectionOptions,
100
+ options: UsageDeliveryProviderOptions = {},
101
+ ) {
102
+ const request = correctionRequest.parse(input);
103
+ let row = (await runMutationOrThrow(
104
+ ctx,
105
+ componentRef(component, "usageCorrections/mutations/prepare"),
106
+ { inputJson: JSON.stringify(request) },
107
+ )) as Doc<"usageCorrections">;
108
+ const claimed = (await runMutationOrThrow(
109
+ ctx,
110
+ componentRef(component, "usageCorrections/mutations/claim"),
111
+ { key: row.key },
112
+ )) as { kind: "ready" | "done" | "busy"; attempt: number };
113
+ const read = async () =>
114
+ (await ctx.runQuery(
115
+ componentRef(component, "usageCorrections/queries/get"),
116
+ {
117
+ scope: request.scope,
118
+ eventId: request.eventId,
119
+ correctionId: request.correctionId,
120
+ },
121
+ )) as Doc<"usageCorrections">;
122
+ if (claimed.kind !== "ready") return correctionView(await read());
123
+ const save = async (outcome: Outcome) => {
124
+ row = (await runMutationOrThrow(
125
+ ctx,
126
+ componentRef(component, "usageCorrections/mutations/save"),
127
+ {
128
+ key: row.key,
129
+ attempt: claimed.attempt,
130
+ outcomeJson: JSON.stringify(outcome),
131
+ },
132
+ )) as Doc<"usageCorrections">;
133
+ return correctionView(row);
134
+ };
135
+ if (!options.stripeSecretKey)
136
+ return save({ status: "held", reason: "provider_unavailable" });
137
+ const record = JSON.parse(row.recordJson) as PreparedUsageRecord,
138
+ subscription = subscriptionSnapshot(row.subscriptionJson);
139
+ const stripe = new Stripe(options.stripeSecretKey, {
140
+ apiVersion: record.binding.apiVersion as StripeApiVersion,
141
+ maxNetworkRetries: 0,
142
+ timeout: 15000,
143
+ ...(options.httpClient ? { httpClient: options.httpClient } : {}),
144
+ });
145
+ let writing = false,
146
+ outcome: Outcome;
147
+ try {
148
+ await verifyRealm(stripe, {
149
+ stripeAccountId: record.scope.stripeAccountId,
150
+ livemode: record.scope.livemode,
151
+ });
152
+ const customer = await stripe.customers.retrieve(
153
+ record.scope.customerAccount,
154
+ );
155
+ if (
156
+ customer.deleted ||
157
+ customer.id !== record.binding.stripeCustomerId ||
158
+ customer.customer_account !== record.scope.customerAccount ||
159
+ customer.livemode !== record.scope.livemode
160
+ )
161
+ throw new Error("Native correction payer mismatch");
162
+ const saved = (await ctx.runQuery(
163
+ componentRef(component, "usageDelivery/queries/snapshot"),
164
+ { scope: request.scope, eventId: request.eventId },
165
+ )) as { event: Doc<"usageEvents">; outbox: Doc<"usageOutbox"> };
166
+ if (saved.outbox.correctionKey !== row.key)
167
+ throw new Error("Native correction intent mismatch");
168
+ const unsent = locallyCancelable(saved.outbox);
169
+ if (unsent) {
170
+ await verifyCreditDelivery(stripe, component, ctx, saved.event, record);
171
+ return save({ status: "local_complete", creditBackingVerified: true });
172
+ }
173
+ if (
174
+ !saved.outbox.receipt ||
175
+ saved.outbox.state === "sending" ||
176
+ saved.outbox.state === "unknown"
177
+ )
178
+ return save({ status: "held", reason: "original_delivery_unresolved" });
179
+ const now = Date.now() / 1000;
180
+ if (now - saved.outbox.receipt.created >= 23 * 3600)
181
+ return save({
182
+ status: "invoice_adjustment_required",
183
+ reason: "native_cancellation_expired",
184
+ });
185
+ if (now + 15 >= subscription.period.end - 60)
186
+ return save({
187
+ status: "invoice_adjustment_required",
188
+ reason: "billing_period_closed",
189
+ });
190
+ const [meter, native] = await Promise.all([
191
+ stripe.billing.meters.retrieve(record.scope.meterId),
192
+ stripe.subscriptions.retrieve(subscription.subscriptionId),
193
+ ]);
194
+ if (meter.id !== record.scope.meterId)
195
+ throw new Error("Native correction meter identity mismatch");
196
+ verifyMeter(meter, {
197
+ scope: record.scope,
198
+ plan: record.binding.plan,
199
+ eventName: record.binding.eventName,
200
+ displayName: meter.display_name,
201
+ });
202
+ const item = native.items.data.find(
203
+ (item) => item.id === subscription.subscriptionItemId,
204
+ );
205
+ if (
206
+ native.id !== subscription.subscriptionId ||
207
+ native.livemode !== record.scope.livemode ||
208
+ native.customer_account !== record.scope.customerAccount ||
209
+ customerId(native.customer) !== record.binding.stripeCustomerId ||
210
+ native.status !== "active" ||
211
+ native.items.has_more ||
212
+ !item ||
213
+ item.price.id !== record.binding.stripePriceId ||
214
+ item.current_period_start !== subscription.period.start ||
215
+ item.current_period_end !== subscription.period.end ||
216
+ native.billing_thresholds
217
+ )
218
+ throw new Error("Original native correction period mismatch");
219
+ const invoice = await finalizedInvoice(
220
+ stripe,
221
+ record,
222
+ subscription.subscriptionId,
223
+ saved.outbox.receipt.created,
224
+ );
225
+ if (invoice.held)
226
+ return save({
227
+ status: "held",
228
+ reason: "native_invoice_history_incomplete",
229
+ });
230
+ if (invoice.invoiceId)
231
+ return save({
232
+ status: "invoice_adjustment_required",
233
+ reason: "native_invoice_finalized",
234
+ invoiceId: invoice.invoiceId,
235
+ });
236
+ const current = await read();
237
+ const sendAt = Date.now() / 1000;
238
+ if (
239
+ current.attempt !== claimed.attempt ||
240
+ [
241
+ "confirmed",
242
+ "unsupported",
243
+ "provider_accepted",
244
+ "invoice_adjustment_required",
245
+ ].includes(current.state) ||
246
+ (current.leaseUntil ?? 0) <= sendAt + 60
247
+ )
248
+ return correctionView(current);
249
+ if (sendAt + 15 >= subscription.period.end - 60)
250
+ return save({
251
+ status: "invoice_adjustment_required",
252
+ reason: "billing_period_closed",
253
+ });
254
+ if (
255
+ sendAt - saved.outbox.receipt.created >= 23 * 3600 ||
256
+ sendAt - (current.attemptedAt ?? current.firstAttemptAt) >= 23 * 3600
257
+ )
258
+ return save({
259
+ status: "invoice_adjustment_required",
260
+ reason: "native_cancellation_expired",
261
+ });
262
+ writing = true;
263
+ const response = await stripe.billing.meterEventAdjustments.create(
264
+ {
265
+ event_name: record.binding.eventName,
266
+ type: "cancel",
267
+ cancel: { identifier: saved.outbox.providerIdentifier },
268
+ },
269
+ { idempotencyKey: `bs_usage_correction_${row.key}` },
270
+ );
271
+ if (
272
+ response.object !== "billing.meter_event_adjustment" ||
273
+ response.type !== "cancel" ||
274
+ response.event_name !== record.binding.eventName ||
275
+ response.cancel?.identifier !== saved.outbox.providerIdentifier ||
276
+ response.livemode !== record.scope.livemode ||
277
+ !["pending", "complete"].includes(response.status)
278
+ )
279
+ throw new Error("Native correction response mismatch");
280
+ let creditBackingVerified = record.binding.plan.model !== "prepaid";
281
+ let billingSafe =
282
+ response.status === "complete" &&
283
+ Date.now() / 1000 + 15 < subscription.period.end - 60;
284
+ let invoiceId: string | undefined;
285
+ if (response.status === "complete") {
286
+ const after = await finalizedInvoice(
287
+ stripe,
288
+ record,
289
+ subscription.subscriptionId,
290
+ saved.outbox.receipt.created,
291
+ );
292
+ invoiceId = after.invoiceId;
293
+ billingSafe = billingSafe && !after.held && !invoiceId;
294
+ if (record.binding.plan.model === "prepaid") {
295
+ try {
296
+ await verifyCreditDelivery(
297
+ stripe,
298
+ component,
299
+ ctx,
300
+ saved.event,
301
+ record,
302
+ );
303
+ creditBackingVerified = true;
304
+ } catch {
305
+ creditBackingVerified = false;
306
+ }
307
+ }
308
+ }
309
+ outcome = {
310
+ status: response.status as "pending" | "complete",
311
+ eventName: response.event_name,
312
+ identifier: response.cancel.identifier!,
313
+ livemode: response.livemode,
314
+ nativeAdjustmentId: null,
315
+ creditBackingVerified,
316
+ billingSafe,
317
+ ...(invoiceId ? { invoiceId } : {}),
318
+ };
319
+ } catch {
320
+ outcome = {
321
+ status: "held",
322
+ reason: writing ? "provider_outcome_unknown" : "provider_unavailable",
323
+ };
324
+ }
325
+ return save(outcome);
326
+ }
@@ -0,0 +1,73 @@
1
+ import type { PreparedUsageRecord } from "./records.js";
2
+ import type { UsageSubscriptionBinding } from "./boundaries.js";
3
+ import { subscriptionSnapshot } from "../../component/usage/helpers.js";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import type { Doc } from "../../component/_generated/dataModel.js";
7
+ import { validateUsagePageRequest, type UsagePeriod } from "./boundaries.js";
8
+ import { scopeSchema, type UsageScope } from "./records.js";
9
+ import { z } from "zod";
10
+ export type UsageCorrectionHistoryRecord = Doc<"usageCorrectionHistory"> & {
11
+ record: PreparedUsageRecord;
12
+ subscription: UsageSubscriptionBinding;
13
+ evidence: unknown;
14
+ recordedAt: number;
15
+ };
16
+ export type UsageCorrectionHistoryPage = {
17
+ records: UsageCorrectionHistoryRecord[];
18
+ cursor: string | null;
19
+ isDone: boolean;
20
+ coverage: "recorded" | "not_recorded";
21
+ legacyHistoryMissing: boolean;
22
+ };
23
+ export async function readCorrectionEvidence(
24
+ component: Component,
25
+ ctx: RunCtx,
26
+ input: {
27
+ scope: UsageScope;
28
+ eventId?: string;
29
+ period?: UsagePeriod;
30
+ limit: number;
31
+ cursor: string | null;
32
+ },
33
+ ): Promise<UsageCorrectionHistoryPage> {
34
+ const page = validateUsagePageRequest({
35
+ period: input.period ?? { start: 0, end: 1 },
36
+ limit: input.limit,
37
+ cursor: input.cursor,
38
+ });
39
+ const scope = scopeSchema.parse(input.scope);
40
+ const result = (await ctx.runQuery(
41
+ componentRef(
42
+ component,
43
+ input.eventId
44
+ ? "usageCorrections/queries/readHistory"
45
+ : "usageCorrections/queries/periodHistory",
46
+ ),
47
+ {
48
+ scope,
49
+ ...(input.eventId
50
+ ? { eventId: z.string().min(1).max(100).parse(input.eventId) }
51
+ : { period: page.period }),
52
+ paginationOpts: { numItems: page.limit, cursor: page.cursor },
53
+ },
54
+ )) as {
55
+ page: Doc<"usageCorrectionHistory">[];
56
+ continueCursor: string;
57
+ isDone: boolean;
58
+ legacyHistoryMissing?: boolean;
59
+ };
60
+ return {
61
+ records: result.page.map((row) => ({
62
+ ...row,
63
+ record: JSON.parse(row.recordJson) as PreparedUsageRecord,
64
+ subscription: subscriptionSnapshot(row.subscriptionJson),
65
+ evidence: JSON.parse(row.evidenceJson) as unknown,
66
+ recordedAt: row.at,
67
+ })),
68
+ cursor: result.isDone ? null : result.continueCursor,
69
+ isDone: result.isDone,
70
+ coverage: result.page.length ? "recorded" : "not_recorded",
71
+ legacyHistoryMissing: result.legacyHistoryMissing ?? false,
72
+ };
73
+ }
@@ -0,0 +1,113 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import type { RunCtx } from "../helpers.js";
3
+ import { setupCorrection } from "./correctionTransport.fixtures.js";
4
+ afterEach(() => vi.useRealTimers());
5
+ it("retains unknown native outcomes and retries the same operation identity without leaking provider error bodies", async () => {
6
+ const { f, client, options, correction, state, calls } =
7
+ await setupCorrection();
8
+ state.failFirstAdjustment = true;
9
+ const unknown = await f.t.action((ctx) =>
10
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
11
+ );
12
+ expect(unknown).toMatchObject({
13
+ state: "held",
14
+ reason: "provider_outcome_unknown",
15
+ restoredQuantity: "0",
16
+ });
17
+ expect(JSON.stringify(unknown)).not.toContain("sk_test_private");
18
+ expect(
19
+ await f.t.action((ctx) =>
20
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
21
+ ),
22
+ ).toMatchObject({ state: "provider_accepted", nativeStatus: "pending" });
23
+ expect(calls).toHaveLength(2);
24
+ expect(calls[0].key).toBe(calls[1].key);
25
+ expect(calls[0].body.toString()).toBe(calls[1].body.toString());
26
+ });
27
+ it("recovers provider success followed by receipt-storage failure with the same native key after the lease", async () => {
28
+ const { f, client, options, correction, calls } = await setupCorrection(
29
+ false,
30
+ 100000,
31
+ );
32
+ let failed = false;
33
+ await expect(
34
+ f.t.action((ctx) =>
35
+ client.usage.requestCorrection(
36
+ {
37
+ ...ctx,
38
+ runMutation: async (ref, ...args) => {
39
+ if (
40
+ !failed &&
41
+ String(
42
+ ref[Symbol.for("toReferencePath") as keyof typeof ref],
43
+ ).endsWith("/usageCorrections/mutations/save")
44
+ ) {
45
+ failed = true;
46
+ throw new Error("Receipt storage unavailable");
47
+ }
48
+ return ctx.runMutation(ref, ...args);
49
+ },
50
+ } as RunCtx,
51
+ correction,
52
+ options,
53
+ ),
54
+ ),
55
+ ).rejects.toThrow(/receipt storage/i);
56
+ vi.advanceTimersByTime(901000);
57
+ expect(
58
+ await f.t.action((ctx) =>
59
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
60
+ ),
61
+ ).toMatchObject({ state: "provider_accepted", restoredQuantity: "0" });
62
+ expect(calls).toHaveLength(2);
63
+ expect(calls[0].key).toBe(calls[1].key);
64
+ });
65
+ it("requires invoice adjustment outside the conservative native cancellation window", async () => {
66
+ const { f, client, options, correction, calls } = await setupCorrection(
67
+ false,
68
+ 100000,
69
+ );
70
+ vi.setSystemTime((700 + 23 * 3600) * 1000);
71
+ expect(
72
+ await f.t.action((ctx) =>
73
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
74
+ ),
75
+ ).toMatchObject({
76
+ state: "invoice_adjustment_required",
77
+ reason: "native_cancellation_expired",
78
+ restoredQuantity: "0",
79
+ });
80
+ expect(calls).toHaveLength(0);
81
+ });
82
+
83
+ it("does not send a native cancellation if billing closes during provider preflight", async () => {
84
+ const { f, client, options, correction, state, calls } =
85
+ await setupCorrection();
86
+ state.advanceAtInvoiceRead = 500000;
87
+ expect(
88
+ await f.t.action((ctx) =>
89
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
90
+ ),
91
+ ).toMatchObject({
92
+ state: "invoice_adjustment_required",
93
+ restoredQuantity: "0",
94
+ });
95
+ expect(calls).toHaveLength(0);
96
+ });
97
+
98
+ it("holds native cancellation when a potentially finalized usage line has no quantity evidence", async () => {
99
+ const { f, client, options, correction, state, calls } =
100
+ await setupCorrection();
101
+ state.finalized = true;
102
+ state.missingEvidence = true;
103
+ expect(
104
+ await f.t.action((ctx) =>
105
+ client.usage.requestCorrection(ctx as RunCtx, correction, options),
106
+ ),
107
+ ).toMatchObject({
108
+ state: "held",
109
+ reason: "native_invoice_history_incomplete",
110
+ restoredQuantity: "0",
111
+ });
112
+ expect(calls).toHaveLength(0);
113
+ });
@@ -0,0 +1,98 @@
1
+ import { invoiceCorrectionProof } from "./correctionInvoiceProof.js";
2
+ import { z } from "zod";
3
+ import { scopeSchema } from "./records.js";
4
+ export const correctionRequest = z.strictObject({
5
+ scope: scopeSchema,
6
+ eventId: z.string().min(1).max(100),
7
+ correctionId: z.string().min(1).max(100),
8
+ actor: z.string().min(1).max(200),
9
+ reason: z.string().min(1).max(500),
10
+ operation: z.literal("cancel"),
11
+ quantity: z.string().optional(),
12
+ });
13
+ export type UsageCorrectionOptions = z.infer<typeof correctionRequest>;
14
+ export const correctionState = z.enum([
15
+ "requested",
16
+ "provider_accepted",
17
+ "confirmed",
18
+ "held",
19
+ "unsupported",
20
+ "invoice_adjustment_required",
21
+ ]);
22
+ export type UsageInvoiceCorrectionEvidence = z.infer<
23
+ typeof invoiceCorrectionProof
24
+ >;
25
+ export type UsageCorrectionView = {
26
+ cashCollection: "none";
27
+ invoiceAdjustment: UsageInvoiceCorrectionEvidence | null;
28
+ observedAt: number;
29
+ nativeCreditNoteStatus: "issued" | "void" | null;
30
+ resolution: "event_cancellation" | "invoice_credit";
31
+ correctionId: string;
32
+ eventId: string;
33
+ sourceEventId: string;
34
+ state: z.infer<typeof correctionState>;
35
+ reason: string;
36
+ actor: string;
37
+ requestedReason: string;
38
+ quantity: string;
39
+ nativeAdjustmentId: string | null;
40
+ nativeStatus: "pending" | "complete" | null;
41
+ invoiceId: string | null;
42
+ creditNoteId: string | null;
43
+ refundId: string | null;
44
+ cashConsequence:
45
+ "none" | "operator_resolution_required" | "verified_external_adjustment";
46
+ restoredQuantity: string;
47
+ };
48
+
49
+ export function correctionView(
50
+ row: import("../../component/_generated/dataModel.js").Doc<"usageCorrections">,
51
+ ): UsageCorrectionView {
52
+ const request = correctionRequest.parse(JSON.parse(row.inputJson));
53
+ const invoiceAdjustment = row.adjustmentJson
54
+ ? invoiceCorrectionProof.parse(JSON.parse(row.adjustmentJson))
55
+ : null;
56
+ if (invoiceAdjustment && row.nativeCreditNoteStatus)
57
+ invoiceAdjustment.creditNoteStatus = row.nativeCreditNoteStatus;
58
+ return {
59
+ cashCollection: "none",
60
+ invoiceAdjustment,
61
+ observedAt: row.observedAt ?? row.firstAttemptAt,
62
+ nativeCreditNoteStatus: row.nativeCreditNoteStatus ?? null,
63
+ resolution: row.resolution ?? "event_cancellation",
64
+ correctionId: row.correctionId,
65
+ eventId: row.eventId,
66
+ sourceEventId: JSON.parse(row.recordJson).sourceEventId,
67
+ state: row.state,
68
+ reason: row.reason,
69
+ actor: request.actor,
70
+ requestedReason: request.reason,
71
+ quantity: row.quantity,
72
+ nativeAdjustmentId: row.nativeAdjustmentId ?? null,
73
+ nativeStatus: row.nativeStatus ?? null,
74
+ invoiceId: row.invoiceId ?? null,
75
+ creditNoteId: row.creditNoteId ?? null,
76
+ refundId: row.refundId ?? null,
77
+ cashConsequence: row.cashConsequence,
78
+ restoredQuantity: row.restoredQuantity,
79
+ };
80
+ }
81
+
82
+ export const invoiceCorrectionOptions = z.strictObject({
83
+ scope: scopeSchema,
84
+ eventId: z.string().min(1).max(100),
85
+ correctionId: z.string().min(1).max(100),
86
+ invoiceId: z
87
+ .string()
88
+ .regex(/^in_[a-zA-Z0-9]+$/)
89
+ .max(100),
90
+ creditNoteId: z
91
+ .string()
92
+ .regex(/^cn_[a-zA-Z0-9]+$/)
93
+ .max(100),
94
+ amount: z.number().int().positive().max(99999999),
95
+ });
96
+ export type UsageInvoiceCorrectionOptions = z.infer<
97
+ typeof invoiceCorrectionOptions
98
+ >;