@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,372 @@
1
+ import type { UsageDeliveryProviderOptions } from "./deliveryProvider.js";
2
+ import type { UsageCorrectionOptions } from "./correctionTerms.js";
3
+ import type { UsageReceipt } from "./boundaries.js";
4
+ import type { UsageSubscriptionView } from "./subscriptionTerms.js";
5
+ import { internalMutationGeneric } from "convex/server";
6
+ import { v } from "convex/values";
7
+ import { schema, modules } from "../../test.js";
8
+ import { vi } from "vitest";
9
+ import { BetterStripe } from "../index.js";
10
+ import type { RunCtx } from "../helpers.js";
11
+ import { componentRef } from "../webhooks/helpers.js";
12
+ import { fixture } from "./subscriptionTransport.fixtures.js";
13
+ import { request } from "./subscription.fixtures.js";
14
+ const response = (value: unknown) =>
15
+ new Response(JSON.stringify(value), {
16
+ headers: { "content-type": "application/json" },
17
+ });
18
+ type CorrectionState = {
19
+ status: string;
20
+ missingEvidence: boolean;
21
+ advanceAtInvoiceRead: number;
22
+ failFirstAdjustment: boolean;
23
+ invalidCash: boolean;
24
+ paidAdjustment: boolean;
25
+ refundSucceeded: boolean;
26
+ voidedNote: boolean;
27
+ truncatedNote: boolean;
28
+ foreignLine: boolean;
29
+ finalizeOnAdjust: boolean;
30
+ finalized: boolean;
31
+ creditNoteAmount: number;
32
+ foreignNote: boolean;
33
+ };
34
+ export async function setupCorrection(
35
+ withAllowance = false,
36
+ periodEnd = 1200,
37
+ ): Promise<{
38
+ f: ReturnType<typeof fixture>;
39
+ client: BetterStripe;
40
+ options: UsageDeliveryProviderOptions;
41
+ correction: UsageCorrectionOptions;
42
+ receipt: UsageReceipt;
43
+ calls: Array<{ body: URLSearchParams; key: string | null }>;
44
+ state: CorrectionState;
45
+ original: UsageSubscriptionView["bindings"][number];
46
+ }> {
47
+ vi.useFakeTimers();
48
+ vi.setSystemTime(700000);
49
+ const state: CorrectionState = {
50
+ advanceAtInvoiceRead: 0,
51
+ status: "pending",
52
+ missingEvidence: false,
53
+ failFirstAdjustment: false,
54
+ invalidCash: false,
55
+ paidAdjustment: false,
56
+ refundSucceeded: true,
57
+ voidedNote: false,
58
+ truncatedNote: false,
59
+ foreignLine: false,
60
+ finalizeOnAdjust: false,
61
+ finalized: false,
62
+ creditNoteAmount: 4,
63
+ foreignNote: false,
64
+ };
65
+ const calls: Array<{ body: URLSearchParams; key: string | null }> = [];
66
+ const f = fixture(false, false, async (input, init) => {
67
+ const path = new URL(input).pathname;
68
+ if (path === "/v1/credit_notes/cn_fix")
69
+ return response({
70
+ id: "cn_fix",
71
+ object: "credit_note",
72
+ livemode: false,
73
+ customer_account: state.foreignNote ? "acct_other" : "acct_buyer",
74
+ customer: "cus_buyer",
75
+ invoice: "in_usage",
76
+ currency: "usd",
77
+ status: state.voidedNote ? "void" : "issued",
78
+ amount: state.creditNoteAmount,
79
+ total: state.creditNoteAmount,
80
+ subtotal: state.creditNoteAmount,
81
+ discount_amount: 0,
82
+ amount_shipping: 0,
83
+ total_taxes: state.missingEvidence ? undefined : [],
84
+ pre_payment_amount: state.paidAdjustment ? 0 : state.creditNoteAmount,
85
+ post_payment_amount: state.paidAdjustment ? state.creditNoteAmount : 0,
86
+ customer_balance_transaction: null,
87
+ out_of_band_amount: 0,
88
+ refunds: state.paidAdjustment
89
+ ? [
90
+ {
91
+ type: "refund",
92
+ refund: "re_fix",
93
+ amount_refunded: state.creditNoteAmount,
94
+ },
95
+ ]
96
+ : [],
97
+ pretax_credit_amounts: [],
98
+ lines: {
99
+ has_more: state.truncatedNote,
100
+ data: [
101
+ {
102
+ id: "cnli_fix",
103
+ type: "invoice_line_item",
104
+ invoice_line_item: "il_usage",
105
+ amount: state.creditNoteAmount,
106
+ livemode: false,
107
+ discount_amount: 0,
108
+ taxes: [],
109
+ pretax_credit_amounts: [],
110
+ },
111
+ ],
112
+ },
113
+ });
114
+ if (path === "/v1/invoices/in_usage")
115
+ return response({
116
+ id: "in_usage",
117
+ object: "invoice",
118
+ livemode: false,
119
+ customer_account: "acct_buyer",
120
+ customer: "cus_buyer",
121
+ currency: "usd",
122
+ status: state.paidAdjustment ? "paid" : "open",
123
+ status_transitions: { finalized_at: 701 },
124
+ parent: {
125
+ type: "subscription_details",
126
+ subscription_details: { subscription: "sub_calls" },
127
+ },
128
+ lines: {
129
+ has_more: false,
130
+ data: [
131
+ {
132
+ id: "il_usage",
133
+ amount: 12,
134
+ currency: "usd",
135
+ pricing: {
136
+ price_details: {
137
+ price: state.foreignLine ? "price_other" : "price_calls",
138
+ },
139
+ },
140
+ period: { start: 600, end: periodEnd },
141
+ parent: {
142
+ subscription_item_details: {
143
+ subscription_item: "si_calls",
144
+ subscription: "sub_calls",
145
+ proration: false,
146
+ },
147
+ },
148
+ quantity_decimal: state.missingEvidence ? undefined : "6",
149
+ pretax_credit_amounts: [],
150
+ discount_amounts: [],
151
+ taxes: [],
152
+ },
153
+ ],
154
+ },
155
+ });
156
+ if (path === "/v1/refunds/re_fix")
157
+ return response({
158
+ id: "re_fix",
159
+ object: "refund",
160
+ status: state.refundSucceeded ? "succeeded" : "pending",
161
+ amount: state.creditNoteAmount,
162
+ currency: "usd",
163
+ payment_intent: "pi_invoice",
164
+ charge: "ch_invoice",
165
+ });
166
+ if (path === "/v1/payment_intents/pi_invoice")
167
+ return response({
168
+ id: "pi_invoice",
169
+ object: "payment_intent",
170
+ livemode: false,
171
+ customer_account: "acct_buyer",
172
+ customer: "cus_buyer",
173
+ status: "succeeded",
174
+ currency: "usd",
175
+ amount: 12,
176
+ amount_received: 12,
177
+ latest_charge: "ch_invoice",
178
+ });
179
+ if (path === "/v1/charges/ch_invoice")
180
+ return response({
181
+ id: "ch_invoice",
182
+ object: "charge",
183
+ payment_intent: "pi_invoice",
184
+ livemode: false,
185
+ customer: "cus_buyer",
186
+ currency: "usd",
187
+ paid: true,
188
+ captured: true,
189
+ status: "succeeded",
190
+ disputed: false,
191
+ amount: 12,
192
+ amount_captured: state.invalidCash ? 12.5 : 12,
193
+ amount_refunded: state.creditNoteAmount,
194
+ });
195
+ if (path === "/v1/invoice_payments")
196
+ return response({
197
+ has_more: false,
198
+ data: [
199
+ {
200
+ id: "inpay_usage",
201
+ object: "invoice_payment",
202
+ amount_requested: 12,
203
+ invoice: "in_usage",
204
+ status: "paid",
205
+ currency: "usd",
206
+ amount_paid: 12,
207
+ payment: { type: "payment_intent", payment_intent: "pi_invoice" },
208
+ },
209
+ ],
210
+ });
211
+ if (path === "/v1/invoices") {
212
+ if (state.advanceAtInvoiceRead) {
213
+ vi.advanceTimersByTime(state.advanceAtInvoiceRead);
214
+ state.advanceAtInvoiceRead = 0;
215
+ }
216
+ return response({
217
+ data: state.finalized
218
+ ? [
219
+ {
220
+ id: "in_usage",
221
+ livemode: false,
222
+ customer_account: "acct_buyer",
223
+ customer: "cus_buyer",
224
+ status: "open",
225
+ currency: "usd",
226
+ parent: {
227
+ type: "subscription_details",
228
+ subscription_details: { subscription: "sub_calls" },
229
+ },
230
+ status_transitions: { finalized_at: 701 },
231
+ lines: {
232
+ has_more: false,
233
+ data: [
234
+ {
235
+ pricing: { price_details: { price: "price_calls" } },
236
+ period: { start: 600, end: periodEnd },
237
+ quantity_decimal: state.missingEvidence ? undefined : "6",
238
+ },
239
+ ],
240
+ },
241
+ },
242
+ ]
243
+ : [],
244
+ has_more: false,
245
+ });
246
+ }
247
+ if (path === "/v1/billing/meter_event_adjustments") {
248
+ if (state.finalizeOnAdjust) state.finalized = true;
249
+ const body = new URLSearchParams(String(init?.body));
250
+ calls.push({
251
+ body,
252
+ key: new Headers(init?.headers).get("idempotency-key"),
253
+ });
254
+ if (state.failFirstAdjustment) {
255
+ state.failFirstAdjustment = false;
256
+ throw new Error("private provider response sk_test_private");
257
+ }
258
+ return response({
259
+ object: "billing.meter_event_adjustment",
260
+ livemode: false,
261
+ status: state.status,
262
+ event_name: "calls",
263
+ type: "cancel",
264
+ cancel: { identifier: body.get("cancel[identifier]") },
265
+ });
266
+ }
267
+ return undefined;
268
+ });
269
+ f.t.registerComponent("betterStripe", schema, {
270
+ ...modules,
271
+ "./component/testSetup.ts": () =>
272
+ Promise.resolve({
273
+ delivered: internalMutationGeneric({
274
+ args: { eventId: v.id("usageEvents") },
275
+ returns: v.null(),
276
+ handler: async (ctx, args) => {
277
+ const row = await ctx.db
278
+ .query("usageOutbox")
279
+ .withIndex("by_event", (q) => q.eq("eventId", args.eventId))
280
+ .unique();
281
+ await ctx.db.patch(row!._id, {
282
+ state: "provider_accepted",
283
+ attempts: 1,
284
+ firstSendAt: 700,
285
+ definitionVersion: 1,
286
+ receipt: { identifier: row!.providerIdentifier, created: 700 },
287
+ });
288
+ return null;
289
+ },
290
+ }),
291
+ }),
292
+ });
293
+ const client = new BetterStripe(f.component),
294
+ options = {
295
+ stripeSecretKey: "sk_test_subscription",
296
+ httpClient: f.httpClient,
297
+ };
298
+ let managed = await f.t.action((ctx) =>
299
+ client.usage.ensureSubscription(ctx as RunCtx, request, options),
300
+ );
301
+ if (periodEnd !== 1200) {
302
+ for (const item of f.state.native!.items.data)
303
+ item.current_period_end = periodEnd;
304
+ managed = await f.t.action((ctx) =>
305
+ client.usage.observeSubscription(
306
+ ctx as RunCtx,
307
+ {
308
+ scope: {
309
+ stripeAccountId: "acct_platform",
310
+ customerAccount: "acct_buyer",
311
+ livemode: false,
312
+ },
313
+ requestId: request.requestId,
314
+ },
315
+ options,
316
+ ),
317
+ );
318
+ }
319
+ const original = managed.bindings[0];
320
+ if (withAllowance)
321
+ await f.t.action((ctx) =>
322
+ client.usage.configureAllowance(ctx as RunCtx, {
323
+ ...original,
324
+ expectedRevision: 0,
325
+ policy: {
326
+ reset: "billing_period",
327
+ rollover: "none",
328
+ entitled: true,
329
+ overage: "allow",
330
+ limit: { mode: "hard", quantity: "12" },
331
+ },
332
+ }),
333
+ );
334
+ const event = {
335
+ scope: original.scope,
336
+ binding: original.binding,
337
+ sourceEventId: "work1",
338
+ quantity: "6",
339
+ occurredAt: 700,
340
+ };
341
+ const reservation = withAllowance
342
+ ? await f.t.action((ctx) =>
343
+ client.usage.reserveAllowance(ctx as RunCtx, {
344
+ event,
345
+ subscription: original.subscription,
346
+ }),
347
+ )
348
+ : null;
349
+ const receipt = await f.t.action((ctx) =>
350
+ client.usage.record(ctx as RunCtx, {
351
+ event,
352
+ subscription: original.subscription,
353
+ ...(reservation && reservation.state !== "denied"
354
+ ? { reservationId: reservation.reservationId }
355
+ : {}),
356
+ }),
357
+ );
358
+ await f.t.action((ctx) =>
359
+ ctx.runMutation(componentRef(f.component, "testSetup/delivered"), {
360
+ eventId: receipt.eventId,
361
+ }),
362
+ );
363
+ const correction = {
364
+ scope: original.scope,
365
+ eventId: receipt.eventId,
366
+ correctionId: "fix1",
367
+ actor: "operator1",
368
+ reason: "duplicate activity",
369
+ operation: "cancel",
370
+ } as const;
371
+ return { f, client, options, correction, receipt, calls, state, original };
372
+ }
@@ -0,0 +1,105 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { creditFixture } from "./creditTransport.fixtures.js";
5
+ afterEach(() => vi.useRealTimers());
6
+ it("recognizes only the original verified paid credit purchase, without creating a second sale as units are consumed", async () => {
7
+ const f = creditFixture(),
8
+ client = new BetterStripe(f.component),
9
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
10
+ const view = await f.ready();
11
+ await f.t.action((ctx) =>
12
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
13
+ );
14
+ f.state.paid = true;
15
+ await f.t.action((ctx) =>
16
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
17
+ );
18
+ const read = () =>
19
+ f.t.action((ctx) =>
20
+ client.usage.getCreditPurchaseRevenue(ctx as RunCtx, f.purchase, options),
21
+ );
22
+ const first = await read();
23
+ expect(first).toMatchObject({
24
+ status: "ready",
25
+ value: {
26
+ paymentIntentId: "pi_topup1",
27
+ chargeId: "ch_topup1",
28
+ creditGrantId: "credgr_topup1",
29
+ gross: 20,
30
+ processingFee: 1,
31
+ ownership: "issuer",
32
+ stripePriceId: "price_calls",
33
+ stripeProductId: "prod_calls",
34
+ },
35
+ });
36
+ const event = {
37
+ ...f.purchase,
38
+ sourceEventId: "consume1",
39
+ quantity: "6",
40
+ occurredAt: 700,
41
+ };
42
+ const {
43
+ ownership: _ownership,
44
+ purchaseId: _purchase,
45
+ rollover: _rollover,
46
+ ...usage
47
+ } = event;
48
+ const subscription = view.bindings[0].subscription;
49
+ const reservation = await f.t.action((ctx) =>
50
+ client.usage.reserveCredits(ctx as RunCtx, { event: usage, subscription }),
51
+ );
52
+ await f.t.action((ctx) =>
53
+ client.usage.record(ctx as RunCtx, {
54
+ event: usage,
55
+ subscription,
56
+ reservationId: reservation.reservationId,
57
+ }),
58
+ );
59
+ expect(await read()).toEqual(first);
60
+ f.state.refunded = true;
61
+ expect(await read()).toMatchObject({
62
+ status: "rejected",
63
+ reason: "payment_not_payable",
64
+ });
65
+ expect(
66
+ f.calls.filter(
67
+ (c) => c.path === "/v1/payment_intents" && c.method === "POST",
68
+ ),
69
+ ).toHaveLength(1);
70
+ });
71
+
72
+ it("holds foreign mapped native customers and missing processing fees", async () => {
73
+ for (const condition of [
74
+ "payment_customer",
75
+ "charge_customer",
76
+ "fee_pending",
77
+ "dispute",
78
+ ]) {
79
+ const f = creditFixture(),
80
+ client = new BetterStripe(f.component),
81
+ options = { stripeSecretKey: "sk_test_credit", httpClient: f.httpClient };
82
+ await f.ready();
83
+ await f.t.action((ctx) =>
84
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
85
+ );
86
+ f.state.paid = true;
87
+ await f.t.action((ctx) =>
88
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
89
+ );
90
+ if (condition === "payment_customer") f.state.paymentCustomer = "cus_other";
91
+ if (condition === "charge_customer") f.state.chargeCustomer = "cus_other";
92
+ if (condition === "fee_pending") f.state.feePending = true;
93
+ if (condition === "dispute") f.state.disputed = true;
94
+ const result = await f.t.action((ctx) =>
95
+ client.usage.getCreditPurchaseRevenue(ctx as RunCtx, f.purchase, options),
96
+ );
97
+ expect(result.status, condition).not.toBe("ready");
98
+ if (condition === "fee_pending")
99
+ expect(result).toMatchObject({
100
+ status: "not_ready",
101
+ reason: "fee_pending",
102
+ retryable: true,
103
+ });
104
+ }
105
+ });
@@ -0,0 +1,163 @@
1
+ import { verifyPinnedUsagePrice } from "./catalogPrices.js";
2
+ import type Stripe from "stripe";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import type { FinancialOutcome } from "../financialOutcomes/contracts.js";
5
+ import type { UsageCreditPurchaseOptions } from "./creditTerms.js";
6
+ import { UsageCreditRecoveryError } from "./creditTerms.js";
7
+ import { findCreditPurchase } from "./creditRead.js";
8
+ import {
9
+ verifyCreditRealm,
10
+ paymentIdentity,
11
+ verifiedCreditPayment,
12
+ } from "./creditNative.js";
13
+ import { paymentCreditProof } from "./creditProofs.js";
14
+ import { saleAmountFailure } from "../paymentSource/economics.js";
15
+ export type UsageCreditRevenue = {
16
+ purchaseId: string;
17
+ paymentIntentId: string;
18
+ chargeId: string;
19
+ creditGrantId: string;
20
+ stripeAccountId: string;
21
+ customerAccount: string;
22
+ livemode: boolean;
23
+ stripePriceId: string;
24
+ stripeProductId: string;
25
+ gross: number;
26
+ processingFee: number;
27
+ currency: string;
28
+ ownership: "issuer";
29
+ };
30
+ /** Original issuer-service revenue only. Credit consumption never creates a second sale. */
31
+ export async function getCreditPurchaseRevenue(
32
+ stripe: Stripe,
33
+ component: Component,
34
+ ctx: RunCtx,
35
+ input: UsageCreditPurchaseOptions,
36
+ ): Promise<FinancialOutcome<UsageCreditRevenue>> {
37
+ try {
38
+ const { row, terms } = await findCreditPurchase(component, ctx, input);
39
+ if (row.state === "frozen" || row.state === "canceled")
40
+ return {
41
+ status: "rejected",
42
+ reason: "payment_not_payable",
43
+ retryable: false,
44
+ };
45
+ if (
46
+ row.state !== "ready" ||
47
+ !row.paymentIntentId ||
48
+ !row.paymentProofJson ||
49
+ !row.creditGrantId
50
+ )
51
+ return {
52
+ status: "not_ready",
53
+ reason: "provider_pending",
54
+ retryable: true,
55
+ };
56
+ await verifyCreditRealm(stripe, terms, false);
57
+ const [payment, price] = await Promise.all([
58
+ stripe.paymentIntents.retrieve(row.paymentIntentId, {
59
+ expand: ["latest_charge.balance_transaction"],
60
+ }),
61
+ stripe.prices.retrieve(terms.binding.stripePriceId, {
62
+ expand: ["tiers"],
63
+ }),
64
+ ]);
65
+ paymentIdentity(payment, terms, row.key, row.paymentIntentId);
66
+ const proof = verifiedCreditPayment(payment, terms),
67
+ retained = paymentCreditProof.parse(JSON.parse(row.paymentProofJson));
68
+ if (
69
+ !proof ||
70
+ proof.chargeId !== retained.chargeId ||
71
+ price.id !== terms.binding.stripePriceId
72
+ )
73
+ return {
74
+ status: "conflict",
75
+ reason: "identity_changed",
76
+ retryable: false,
77
+ };
78
+ verifyPinnedUsagePrice(
79
+ price,
80
+ {
81
+ stripeAccountId: terms.scope.stripeAccountId,
82
+ livemode: terms.scope.livemode,
83
+ },
84
+ terms.binding.plan,
85
+ terms.scope.meterId,
86
+ false,
87
+ );
88
+ const charge = payment.latest_charge;
89
+ if (!charge || typeof charge === "string")
90
+ return {
91
+ status: "not_ready",
92
+ reason: "provider_pending",
93
+ retryable: true,
94
+ };
95
+ const customerId = (value: string | { id: string } | null | undefined) =>
96
+ typeof value === "string" ? value : value?.id;
97
+ if (
98
+ customerId(payment.customer) !== terms.binding.stripeCustomerId ||
99
+ customerId(charge.customer) !== terms.binding.stripeCustomerId ||
100
+ charge.transfer
101
+ )
102
+ return {
103
+ status: "conflict",
104
+ reason: "identity_changed",
105
+ retryable: false,
106
+ };
107
+ const balanceRef = charge.balance_transaction;
108
+ if (!balanceRef)
109
+ return { status: "not_ready", reason: "fee_pending", retryable: true };
110
+ const balance =
111
+ typeof balanceRef === "string"
112
+ ? await stripe.balanceTransactions.retrieve(balanceRef)
113
+ : balanceRef;
114
+ const sourceId =
115
+ typeof balance.source === "string" ? balance.source : balance.source?.id;
116
+ if (
117
+ (typeof balanceRef === "string" && balance.id !== balanceRef) ||
118
+ balance.object !== "balance_transaction" ||
119
+ sourceId !== charge.id ||
120
+ saleAmountFailure(payment, charge, balance) ||
121
+ balance.amount !== terms.amount ||
122
+ balance.net !== balance.amount - balance.fee ||
123
+ !Number.isSafeInteger(balance.amount) ||
124
+ !Number.isSafeInteger(balance.net)
125
+ )
126
+ return {
127
+ status: "rejected",
128
+ reason: "unsupported_source",
129
+ retryable: false,
130
+ };
131
+ return {
132
+ status: "ready",
133
+ value: {
134
+ purchaseId: terms.purchaseId,
135
+ paymentIntentId: proof.paymentIntentId,
136
+ chargeId: proof.chargeId,
137
+ creditGrantId: row.creditGrantId,
138
+ stripeAccountId: terms.scope.stripeAccountId,
139
+ customerAccount: terms.scope.customerAccount,
140
+ livemode: terms.scope.livemode,
141
+ stripePriceId: price.id,
142
+ stripeProductId:
143
+ typeof price.product === "string" ? price.product : price.product.id,
144
+ gross: terms.amount,
145
+ processingFee: balance.fee,
146
+ currency: payment.currency,
147
+ ownership: "issuer",
148
+ },
149
+ };
150
+ } catch (error) {
151
+ if (error instanceof UsageCreditRecoveryError)
152
+ return {
153
+ status: "rejected",
154
+ reason: "payment_not_payable",
155
+ retryable: false,
156
+ };
157
+ return {
158
+ status: "unknown",
159
+ reason: "provider_outcome_unknown",
160
+ retryable: false,
161
+ };
162
+ }
163
+ }
@@ -0,0 +1,70 @@
1
+ import type { SourceHttpClient } from "../paymentSource/resolver.fixtures.js";
2
+ import { BetterStripe } from "../index.js";
3
+ import type { RunCtx } from "../helpers.js";
4
+ import { creditFixture } from "./creditTransport.fixtures.js";
5
+ export async function fixture(
6
+ affiliate: { basisPoints?: number; fixedAmount?: number } = {
7
+ basisPoints: 1000,
8
+ },
9
+ ) {
10
+ const native: Record<string, unknown>[] = [];
11
+ const response = (data: unknown) =>
12
+ new Response(JSON.stringify(data), {
13
+ headers: { "content-type": "application/json" },
14
+ });
15
+ const f = creditFixture(async (input, init) => {
16
+ const path = new URL(input).pathname;
17
+ if (path === "/v1/charges/ch_topup1")
18
+ return response({ id: "ch_topup1", created: 700 });
19
+ if (path !== "/v1/transfers") return;
20
+ if ((init?.method ?? "GET") === "GET")
21
+ return response({ object: "list", data: native, has_more: false });
22
+ const body = new URLSearchParams(String(init?.body ?? ""));
23
+ const transfer = {
24
+ id: `tr_${native.length}`,
25
+ amount: Number(body.get("amount")),
26
+ currency: body.get("currency"),
27
+ destination: body.get("destination"),
28
+ source_transaction: body.get("source_transaction"),
29
+ metadata: {
30
+ bsRole: body.get("metadata[bsRole]"),
31
+ bsSourceCharge: body.get("metadata[bsSourceCharge]"),
32
+ },
33
+ };
34
+ native.push(transfer);
35
+ return response(transfer);
36
+ });
37
+ const client = new BetterStripe(f.component),
38
+ options = {
39
+ stripeSecretKey: "sk_test_credit",
40
+ httpClient: f.httpClient as SourceHttpClient,
41
+ };
42
+ const view = await f.ready();
43
+ await f.t.action((ctx) =>
44
+ client.usage.purchaseCredits(ctx as RunCtx, f.purchase, options),
45
+ );
46
+ f.state.paid = true;
47
+ await f.t.action((ctx) =>
48
+ client.usage.observeCreditPurchase(ctx as RunCtx, f.purchase, options),
49
+ );
50
+ const input = {
51
+ ...f.purchase,
52
+ policy: {
53
+ affiliate: { destinationAccountId: "acct_affiliate", ...affiliate },
54
+ },
55
+ };
56
+ const settle = () =>
57
+ f.t.action((ctx) =>
58
+ client.usage.settleCreditPurchase(ctx as RunCtx, input, options),
59
+ );
60
+ return {
61
+ ...f,
62
+ httpClient: f.httpClient as SourceHttpClient,
63
+ native,
64
+ client,
65
+ options,
66
+ view,
67
+ input,
68
+ settle,
69
+ };
70
+ }