@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,184 @@
1
+ import { BetterStripe } from "../index.js";
2
+ import { componentsGeneric } from "convex/server";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { expect, it } from "vitest";
5
+ import { fixture } from "./invoiceSale.fixtures.js";
6
+ import { getUsageInvoiceSale } from "./invoiceSale.js";
7
+ it("resolves original metered invoice funding and actual costs even after current subscription prices change", async () => {
8
+ const f = fixture();
9
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
10
+ status: "ready",
11
+ value: {
12
+ meterId: "mtr_calls",
13
+ stripePriceId: "price_original",
14
+ stripeProductId: "prod_original",
15
+ invoicePaymentId: "inpay_source",
16
+ gross: 1000,
17
+ processingFee: 50,
18
+ period: { start: 600, end: 1200 },
19
+ },
20
+ });
21
+ expect(
22
+ f.requests.every((r) => r.method === "GET" && r.account === "undefined"),
23
+ ).toBe(true);
24
+ });
25
+
26
+ it("verifies included-overage cash against its original graduated price", async () => {
27
+ const f = fixture();
28
+ const plan = {
29
+ ...f.input.binding.plan,
30
+ model: "included_overage" as const,
31
+ includedQuantity: "10",
32
+ reset: "billing_period" as const,
33
+ };
34
+ Object.assign(f.price, {
35
+ billing_scheme: "tiered",
36
+ tiers_mode: "graduated",
37
+ unit_amount_decimal: null,
38
+ tiers: [
39
+ { up_to: 10, unit_amount_decimal: "0", flat_amount: null },
40
+ { up_to: null, unit_amount_decimal: "2", flat_amount: null },
41
+ ],
42
+ });
43
+ expect(
44
+ await getUsageInvoiceSale(f.sdk, {
45
+ ...f.input,
46
+ binding: { ...f.input.binding, plan },
47
+ }),
48
+ ).toMatchObject({
49
+ status: "ready",
50
+ value: { model: "included_overage", gross: 1000 },
51
+ });
52
+ });
53
+ it("does not recognize zero invoices, credit consumption, refunds, disputes or incomplete funding as a new sale", async () => {
54
+ for (const condition of [
55
+ "zero",
56
+ "prepaid",
57
+ "refund",
58
+ "dispute",
59
+ "incomplete",
60
+ "automatic_transfer",
61
+ ]) {
62
+ const f = fixture();
63
+ if (condition === "zero") f.invoice.amount_paid = 0;
64
+ if (condition === "refund") f.payment.latest_charge.amount_refunded = 100;
65
+ if (condition === "dispute") f.payment.latest_charge.disputed = true;
66
+ if (condition === "incomplete")
67
+ f.pages.set("funding:", { data: [f.funding], has_more: true });
68
+ if (condition === "automatic_transfer")
69
+ Object.assign(f.payment, {
70
+ transfer_data: { destination: "acct_seller" },
71
+ });
72
+ const input =
73
+ condition === "prepaid"
74
+ ? {
75
+ ...f.input,
76
+ binding: {
77
+ ...f.input.binding,
78
+ plan: {
79
+ ...f.input.binding.plan,
80
+ model: "prepaid" as const,
81
+ insufficientBalance: "reject" as const,
82
+ },
83
+ },
84
+ }
85
+ : f.input;
86
+ expect((await getUsageInvoiceSale(f.sdk, input)).status).not.toBe("ready");
87
+ expect(f.requests.every((r) => r.method === "GET")).toBe(true);
88
+ }
89
+ });
90
+ it("rejects foreign original bindings, periods and mapped payer identities", async () => {
91
+ for (const condition of [
92
+ "realm",
93
+ "mode",
94
+ "payer",
95
+ "customer",
96
+ "meter",
97
+ "price_meter",
98
+ "product",
99
+ "period",
100
+ "item",
101
+ "proration",
102
+ ]) {
103
+ const f = fixture();
104
+ if (condition === "realm")
105
+ f.extra.set("/v1/account", { id: "acct_foreign" });
106
+ if (condition === "mode") f.payment.livemode = true;
107
+ if (condition === "payer") f.invoice.customer_account = "acct_other";
108
+ if (condition === "customer")
109
+ Object.assign(f.payment.latest_charge, { customer: "cus_other" });
110
+ if (condition === "meter") f.meter.id = "mtr_other";
111
+ if (condition === "price_meter") f.price.recurring.meter = "mtr_other";
112
+ if (condition === "product")
113
+ f.line.pricing.price_details.product = "prod_other";
114
+ if (condition === "period")
115
+ Object.assign(f.line, { period: { start: 1200, end: 1800 } });
116
+ if (condition === "item")
117
+ f.line.parent.subscription_item_details.subscription_item = "si_other";
118
+ if (condition === "proration")
119
+ f.line.parent.subscription_item_details.proration = true;
120
+ expect(
121
+ (await getUsageInvoiceSale(f.sdk, f.input)).status,
122
+ condition,
123
+ ).not.toBe("ready");
124
+ }
125
+ });
126
+
127
+ it("can settle original paid invoices after their immutable price is archived", async () => {
128
+ const f = fixture();
129
+ f.price.active = false;
130
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toMatchObject({
131
+ status: "ready",
132
+ value: { stripePriceId: "price_original" },
133
+ });
134
+ });
135
+
136
+ it("requires the complete original invoice-line read to retain the same item and billing period", async () => {
137
+ for (const change of ["item", "period", "id"]) {
138
+ const f = fixture();
139
+ const line = structuredClone(f.line);
140
+ if (change === "item")
141
+ line.parent.subscription_item_details.subscription_item = "si_other";
142
+ if (change === "period")
143
+ Object.assign(line, { period: { start: 1200, end: 1800 } });
144
+ if (change === "id") line.id = "il_other";
145
+ f.extra.set("/v1/invoices/in_source/lines", {
146
+ object: "list",
147
+ data: [line],
148
+ has_more: false,
149
+ });
150
+ expect((await getUsageInvoiceSale(f.sdk, f.input)).status, change).not.toBe(
151
+ "ready",
152
+ );
153
+ }
154
+ });
155
+
156
+ it("keeps an unpaid invoice pending until native payment is verified", async () => {
157
+ const f = fixture();
158
+ f.invoice.status = "open";
159
+ f.invoice.amount_paid = 0;
160
+ expect(await getUsageInvoiceSale(f.sdk, f.input)).toEqual({
161
+ status: "not_ready",
162
+ reason: "provider_pending",
163
+ retryable: true,
164
+ });
165
+ });
166
+
167
+ it("exposes the scoped reader through stripe.usage with runtime-only credentials and the original API version", async () => {
168
+ const f = fixture(),
169
+ client = new BetterStripe(
170
+ componentsGeneric().betterStripe as unknown as Component,
171
+ );
172
+ expect(
173
+ await client.usage.getInvoiceSale({} as RunCtx, f.input, {
174
+ stripeSecretKey: "sk_test_usage_sale",
175
+ httpClient: f.httpClient,
176
+ }),
177
+ ).toMatchObject({ status: "ready" });
178
+ expect(
179
+ f.requests.every(
180
+ (r) =>
181
+ r.version === f.input.binding.apiVersion && r.account === "undefined",
182
+ ),
183
+ ).toBe(true);
184
+ });
@@ -0,0 +1,155 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import type {
4
+ FinancialOutcome,
5
+ FinancialUnavailable,
6
+ } from "../financialOutcomes/contracts.js";
7
+ import { resolveVerifiedPaymentSource } from "../paymentSource/resolver.js";
8
+ import type { VerifiedPaymentSource } from "../paymentSource/contracts.js";
9
+ import {
10
+ observationOptions,
11
+ type UsageObservationOptions,
12
+ } from "./observationTypes.js";
13
+ import { observeUsageInvoice } from "./invoiceObservation.js";
14
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
15
+ export type UsageInvoiceSaleOptions = UsageObservationOptions & {
16
+ invoiceId: string;
17
+ paymentIntentId: string;
18
+ gross: number;
19
+ };
20
+ export type VerifiedUsageInvoiceSale = VerifiedPaymentSource & {
21
+ stripeAccountId: string;
22
+ meterId: string;
23
+ subscriptionItemId: string;
24
+ period: { start: number; end: number };
25
+ model: "pay_as_you_go" | "included_overage";
26
+ };
27
+ const unsupported = (): FinancialUnavailable => ({
28
+ status: "rejected",
29
+ reason: "unsupported_source",
30
+ retryable: false,
31
+ });
32
+ /** Native invoice/payment provenance only. Host authorizes original seller/product policy. */
33
+ export async function getUsageInvoiceSale(
34
+ stripe: Stripe,
35
+ input: UsageInvoiceSaleOptions,
36
+ ): Promise<FinancialOutcome<VerifiedUsageInvoiceSale>> {
37
+ try {
38
+ const opts = observationOptions(input);
39
+ z.string()
40
+ .regex(/^pi_[a-zA-Z0-9]+$/)
41
+ .max(100)
42
+ .parse(input.paymentIntentId);
43
+ if (opts.binding.plan.model === "prepaid") return unsupported();
44
+ const invoice = await observeUsageInvoice(stripe, opts, input.invoiceId);
45
+ if (invoice.status !== "available") return unsupported();
46
+ const value = invoice.value;
47
+ if (value.status === "draft" || value.status === "open")
48
+ return {
49
+ status: "not_ready",
50
+ reason: "provider_pending",
51
+ retryable: true,
52
+ };
53
+ if (
54
+ value.status !== "paid" ||
55
+ !value.finalized ||
56
+ BigInt(value.amountPaid) <= 0n
57
+ )
58
+ return {
59
+ status: "rejected",
60
+ reason: "payment_not_payable",
61
+ retryable: false,
62
+ };
63
+ const line = value.lines[0];
64
+ if (
65
+ !value.linesComplete ||
66
+ value.meterAmount.status !== "available" ||
67
+ value.lines.length !== 1 ||
68
+ !line ||
69
+ line.proration ||
70
+ line.creditAppliedAmount !== "0" ||
71
+ line.nativePeriod.start !== opts.subscription.period.start ||
72
+ line.nativePeriod.end !== opts.subscription.period.end ||
73
+ opts.period.start !== opts.subscription.period.start ||
74
+ opts.period.end !== opts.subscription.period.end
75
+ )
76
+ return unsupported();
77
+ const [price, customer] = await Promise.all([
78
+ stripe.prices.retrieve(opts.binding.stripePriceId, { expand: ["tiers"] }),
79
+ stripe.customers.retrieve(opts.scope.customerAccount),
80
+ ]);
81
+ if (
82
+ price.id !== opts.binding.stripePriceId ||
83
+ customer.deleted ||
84
+ customer.id !== opts.binding.stripeCustomerId ||
85
+ customer.customer_account !== opts.scope.customerAccount ||
86
+ customer.livemode !== opts.scope.livemode
87
+ )
88
+ return {
89
+ status: "conflict",
90
+ reason: "identity_changed",
91
+ retryable: false,
92
+ };
93
+ verifyPinnedUsagePrice(
94
+ price,
95
+ {
96
+ stripeAccountId: opts.scope.stripeAccountId,
97
+ livemode: opts.scope.livemode,
98
+ },
99
+ opts.binding.plan,
100
+ opts.scope.meterId,
101
+ false,
102
+ );
103
+ const source = await resolveVerifiedPaymentSource(
104
+ stripe,
105
+ {
106
+ paymentIntentId: input.paymentIntentId,
107
+ invoiceId: input.invoiceId,
108
+ subscriptionId: opts.subscription.subscriptionId,
109
+ customerAccountId: opts.scope.customerAccount,
110
+ gross: input.gross,
111
+ currency: opts.binding.plan.rate.currency,
112
+ },
113
+ {
114
+ requirePayable: true,
115
+ customerId: opts.binding.stripeCustomerId,
116
+ invoiceLine: {
117
+ id: line.lineId,
118
+ subscriptionItemId: opts.subscription.subscriptionItemId,
119
+ period: opts.subscription.period,
120
+ },
121
+ },
122
+ );
123
+ if (source.status !== "ready") return source;
124
+ const productId =
125
+ typeof price.product === "string" ? price.product : price.product.id;
126
+ if (
127
+ source.value.stripePriceId !== opts.binding.stripePriceId ||
128
+ source.value.stripeProductId !== productId ||
129
+ source.value.livemode !== opts.scope.livemode ||
130
+ String(source.value.gross) !== value.amountPaid
131
+ )
132
+ return {
133
+ status: "conflict",
134
+ reason: "identity_changed",
135
+ retryable: false,
136
+ };
137
+ return {
138
+ status: "ready",
139
+ value: {
140
+ ...source.value,
141
+ stripeAccountId: opts.scope.stripeAccountId,
142
+ meterId: opts.scope.meterId,
143
+ subscriptionItemId: opts.subscription.subscriptionItemId,
144
+ period: opts.subscription.period,
145
+ model: opts.binding.plan.model,
146
+ },
147
+ };
148
+ } catch {
149
+ return {
150
+ status: "unknown",
151
+ reason: "provider_outcome_unknown",
152
+ retryable: false,
153
+ };
154
+ }
155
+ }
@@ -1,3 +1,4 @@
1
+ import { readCorrectionEvidence } from "./correctionRead.js";
1
2
  import type { Doc } from "../../component/_generated/dataModel.js";
2
3
  import type { UsageDeliveryRef } from "./deliveryClient.js";
3
4
  import { observeUsageInvoice } from "./invoiceObservation.js";
@@ -198,13 +199,19 @@ export class UsageObservationClient extends UsageDeliveryClient {
198
199
  }
199
200
  async getReconciliation(ctx: RunCtx, input: UsageReconciliationOptions) {
200
201
  const opts = observationOptions(input);
201
- const [local, aggregate] = await Promise.all([
202
+ const [local, aggregate, corrections] = await Promise.all([
202
203
  this.getSummary(ctx, {
203
204
  scope: opts.scope,
204
205
  period: opts.period,
205
206
  maxRecords: input.maxRecords,
206
207
  }),
207
208
  this.getProviderUsage(ctx, input),
209
+ readCorrectionEvidence(this.component, ctx, {
210
+ scope: opts.scope,
211
+ period: opts.period,
212
+ limit: 100,
213
+ cursor: null,
214
+ }),
208
215
  ]);
209
216
  return {
210
217
  local,
@@ -215,11 +222,18 @@ export class UsageObservationClient extends UsageDeliveryClient {
215
222
  reason: "invoice_not_observed",
216
223
  retryable: true,
217
224
  },
218
- correctionHistory: {
219
- status: "unsupported" as const,
220
- reason: "corrections_not_configured",
221
- retryable: false,
222
- },
225
+ correctionHistory: corrections.records.length
226
+ ? {
227
+ status: "available" as const,
228
+ observedAt: Math.floor(Date.now() / 1000),
229
+ value: corrections,
230
+ }
231
+ : {
232
+ status: "unsupported" as const,
233
+ reason: "corrections_not_configured",
234
+ retryable: false,
235
+ legacyHistoryMissing: corrections.legacyHistoryMissing,
236
+ },
223
237
  };
224
238
  }
225
239
  async reconcile(
@@ -44,7 +44,13 @@ export type PreparedUsageRecord = Omit<
44
44
  };
45
45
  };
46
46
  export type UsageDeliveryState =
47
- "queued" | "sending" | "provider_accepted" | "rejected" | "unknown" | "held";
47
+ | "canceled"
48
+ | "queued"
49
+ | "sending"
50
+ | "provider_accepted"
51
+ | "rejected"
52
+ | "unknown"
53
+ | "held";
48
54
 
49
55
  /**
50
56
  * Validate and snapshot a record before acceptance. This pure helper does not
@@ -0,0 +1,179 @@
1
+ import { expect, it } from "vitest";
2
+ import { componentsGeneric } from "convex/server";
3
+ import { initConvexTest } from "../setup.test.js";
4
+ import { schema, modules } from "../../test.js";
5
+ import type { Component, RunCtx } from "../helpers.js";
6
+ import { fixture } from "./invoiceSale.fixtures.js";
7
+ import { settleUsageInvoice } from "./settlement.js";
8
+ function setup() {
9
+ const f = fixture(),
10
+ t = initConvexTest();
11
+ t.registerComponent("betterStripe", schema, modules);
12
+ const component = componentsGeneric().betterStripe as unknown as Component;
13
+ const native: Record<string, unknown>[] = [];
14
+ f.extra.set("/v1/charges/ch_source", {
15
+ ...f.payment.latest_charge,
16
+ created: 1200,
17
+ });
18
+ f.extra.set("/v1/transfers", (method: string, raw: string) => {
19
+ if (method === "GET")
20
+ return { object: "list", data: native, has_more: false };
21
+ const body = new URLSearchParams(raw);
22
+ const transfer = {
23
+ id: `tr_${native.length}`,
24
+ object: "transfer",
25
+ amount: Number(body.get("amount")),
26
+ currency: body.get("currency"),
27
+ destination: body.get("destination"),
28
+ source_transaction: body.get("source_transaction"),
29
+ transfer_group: body.get("transfer_group"),
30
+ metadata: {
31
+ bsRole: body.get("metadata[bsRole]"),
32
+ bsSourceCharge: body.get("metadata[bsSourceCharge]"),
33
+ },
34
+ };
35
+ native.push(transfer);
36
+ return transfer;
37
+ });
38
+ const input = {
39
+ ...f.input,
40
+ policy: { creatorAccountId: "acct_seller", feeBasisPoints: 900 },
41
+ };
42
+ return { ...f, t, component, native, input };
43
+ }
44
+ it("settles actual paid metered proceeds once using the existing immutable allocation and transfer ledger", async () => {
45
+ const f = setup();
46
+ const first = await f.t.action((ctx) =>
47
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, f.input),
48
+ );
49
+ expect(first).toMatchObject({
50
+ status: "settled",
51
+ gross: 1000,
52
+ processingFee: 50,
53
+ platformNet: 40,
54
+ usageSource: {
55
+ meterId: "mtr_calls",
56
+ invoicePaymentId: "inpay_source",
57
+ stripeProductId: "prod_original",
58
+ },
59
+ transfers: [
60
+ { destinationAccountId: "acct_seller", amount: 910, role: "store" },
61
+ ],
62
+ });
63
+ expect(
64
+ await f.t.action((ctx) =>
65
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, {
66
+ ...f.input,
67
+ policy: { ...f.input.policy, feeBasisPoints: 9900 },
68
+ }),
69
+ ),
70
+ ).toEqual(first);
71
+ expect(f.native).toHaveLength(1);
72
+ });
73
+ it("never creates transfers from a zero invoice or a prepaid consumption invoice", async () => {
74
+ for (const prepaid of [false, true]) {
75
+ const f = setup();
76
+ if (!prepaid) f.invoice.amount_paid = 0;
77
+ const input = prepaid
78
+ ? {
79
+ ...f.input,
80
+ binding: {
81
+ ...f.input.binding,
82
+ plan: {
83
+ ...f.input.binding.plan,
84
+ model: "prepaid" as const,
85
+ insufficientBalance: "reject" as const,
86
+ },
87
+ },
88
+ }
89
+ : f.input;
90
+ expect(
91
+ await f.t.action((ctx) =>
92
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, input),
93
+ ),
94
+ ).toMatchObject({ status: "rejected" });
95
+ expect(f.native).toHaveLength(0);
96
+ }
97
+ });
98
+
99
+ it("keeps a zero initial metered invoice from consuming the one-time affiliate commission", async () => {
100
+ const f = setup();
101
+ const paid = {
102
+ ...f.invoice,
103
+ created: 1200,
104
+ status_transitions: { finalized_at: 1200, paid_at: 1250 },
105
+ };
106
+ f.extra.set("/v1/invoices", {
107
+ object: "list",
108
+ has_more: false,
109
+ data: [
110
+ {
111
+ ...paid,
112
+ id: "in_zero",
113
+ created: 600,
114
+ amount_paid: 0,
115
+ status_transitions: { finalized_at: 600, paid_at: 600 },
116
+ },
117
+ paid,
118
+ ],
119
+ });
120
+ const result = await f.t.action((ctx) =>
121
+ settleUsageInvoice(f.sdk, f.component, ctx as RunCtx, {
122
+ ...f.input,
123
+ policy: {
124
+ ...f.input.policy,
125
+ commissionTerm: "one_time",
126
+ affiliate: {
127
+ destinationAccountId: "acct_affiliate",
128
+ basisPoints: 2000,
129
+ },
130
+ },
131
+ }),
132
+ );
133
+ expect(result).toMatchObject({
134
+ status: "settled",
135
+ transfers: [
136
+ { destinationAccountId: "acct_seller", role: "store", amount: 728 },
137
+ {
138
+ destinationAccountId: "acct_affiliate",
139
+ role: "affiliate",
140
+ amount: 182,
141
+ },
142
+ ],
143
+ });
144
+ expect(f.native).toHaveLength(2);
145
+ });
146
+ it("recovers a native transfer whose ledger write failed without paying the metered invoice twice", async () => {
147
+ const f = setup();
148
+ let fail = true;
149
+ const settle = () =>
150
+ f.t.action((ctx) =>
151
+ settleUsageInvoice(
152
+ f.sdk,
153
+ f.component,
154
+ {
155
+ ...ctx,
156
+ runMutation: async (ref, args) => {
157
+ if (
158
+ fail &&
159
+ String(
160
+ ref[Symbol.for("toReferencePath") as keyof typeof ref],
161
+ ).includes("upsertTransfer")
162
+ ) {
163
+ fail = false;
164
+ throw new Error("receipt storage unavailable");
165
+ }
166
+ return ctx.runMutation(ref, args);
167
+ },
168
+ } as RunCtx,
169
+ f.input,
170
+ ),
171
+ );
172
+ await expect(settle()).rejects.toThrow("receipt storage unavailable");
173
+ expect(f.native).toHaveLength(1);
174
+ expect(await settle()).toMatchObject({
175
+ status: "settled",
176
+ usageSource: { invoicePaymentId: "inpay_source" },
177
+ });
178
+ expect(f.native).toHaveLength(1);
179
+ });
@@ -0,0 +1,81 @@
1
+ import { getUsageInvoiceSale } from "./invoiceSale.js";
2
+ import { allocateSale } from "../settlement/allocation.js";
3
+ import { selectCommissionInvoice } from "../settlement/commissions.js";
4
+ import {
5
+ executeResolvedTransfers,
6
+ type ResolvedSettlement,
7
+ } from "../settlement/execution.js";
8
+ import { componentRef } from "../webhooks/helpers.js";
9
+ import type Stripe from "stripe";
10
+ import type { Component, RunCtx } from "../helpers.js";
11
+ import type { SaleAllocationOptions } from "../settlement/allocation.js";
12
+ import type { CommissionTerm } from "../settlement/commissions.js";
13
+ import type { UsageInvoiceSaleOptions } from "./invoiceSale.js";
14
+ export type UsageInvoiceSettlementOptions = UsageInvoiceSaleOptions & {
15
+ policy: Omit<SaleAllocationOptions, "gross" | "processingFee"> & {
16
+ commissionTerm?: CommissionTerm;
17
+ };
18
+ };
19
+ export async function settleUsageInvoice(
20
+ stripe: Stripe,
21
+ component: Component,
22
+ ctx: RunCtx,
23
+ input: UsageInvoiceSettlementOptions,
24
+ ) {
25
+ const sale = await getUsageInvoiceSale(stripe, input);
26
+ if (sale.status !== "ready") return sale;
27
+ const source = sale.value;
28
+ const prior = (await ctx.runQuery(
29
+ componentRef(component, "settlement/queries/getSettlementAllocation"),
30
+ { sourceChargeId: source.chargeId },
31
+ )) as ResolvedSettlement | null;
32
+ if (
33
+ prior &&
34
+ (prior.gross !== source.gross ||
35
+ prior.processingFee !== source.processingFee ||
36
+ prior.currency !== source.currency)
37
+ )
38
+ throw new Error(
39
+ "Retained allocation conflicts with verified invoice proceeds",
40
+ );
41
+ let affiliate = input.policy.affiliate;
42
+ if (affiliate) {
43
+ const commission = await selectCommissionInvoice(stripe, component, ctx, {
44
+ subscriptionId: input.subscription.subscriptionId,
45
+ invoiceId: source.invoiceId,
46
+ affiliateAccountId: affiliate.destinationAccountId,
47
+ term: input.policy.commissionTerm ?? "forever",
48
+ });
49
+ if (commission.status !== "ready") return commission;
50
+ if (!commission.eligible) affiliate = undefined;
51
+ }
52
+ const allocation = allocateSale({
53
+ ...input.policy,
54
+ affiliate,
55
+ gross: source.gross,
56
+ processingFee: source.processingFee,
57
+ });
58
+ return executeResolvedTransfers(stripe, component, ctx, {
59
+ sourceChargeId: source.chargeId,
60
+ paymentIntentId: source.paymentIntentId,
61
+ sourceInvoiceId: source.invoiceId,
62
+ usageSource: {
63
+ stripeAccountId: input.scope.stripeAccountId,
64
+ customerAccount: source.customerAccountId,
65
+ livemode: source.livemode,
66
+ meterId: source.meterId,
67
+ stripePriceId: source.stripePriceId,
68
+ stripeProductId: source.stripeProductId,
69
+ subscriptionId: input.subscription.subscriptionId,
70
+ subscriptionItemId: source.subscriptionItemId,
71
+ invoicePaymentId: source.invoicePaymentId,
72
+ period: source.period,
73
+ model: source.model,
74
+ },
75
+ gross: source.gross,
76
+ currency: source.currency,
77
+ processingFee: source.processingFee,
78
+ platformNet: allocation.platformNet,
79
+ transfers: allocation.transfers,
80
+ });
81
+ }