@fantastic.dev/better-stripe 0.41.0 → 0.43.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 (209) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +1 -1
  3. package/dist/client/balanceFundingWorkflow/client.d.ts +172 -0
  4. package/dist/client/balanceFundingWorkflow/client.d.ts.map +1 -0
  5. package/dist/client/balanceFundingWorkflow/client.js +289 -0
  6. package/dist/client/balanceFundingWorkflow/client.js.map +1 -0
  7. package/dist/client/billing/balanceFunding.d.ts +5 -0
  8. package/dist/client/billing/balanceFunding.d.ts.map +1 -1
  9. package/dist/client/billing/balanceFunding.js +30 -0
  10. package/dist/client/billing/balanceFunding.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +1388 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +710 -17
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +1420 -34
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +694 -1
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/costRecovery-invoices.d.ts +3 -2
  20. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  21. package/dist/client/costRecovery-invoices.js +10 -5
  22. package/dist/client/costRecovery-invoices.js.map +1 -1
  23. package/dist/client/costRecovery.d.ts +4 -2
  24. package/dist/client/costRecovery.d.ts.map +1 -1
  25. package/dist/client/costRecovery.js +2 -2
  26. package/dist/client/costRecovery.js.map +1 -1
  27. package/dist/client/index.d.ts +3 -0
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js +4 -0
  30. package/dist/client/index.js.map +1 -1
  31. package/dist/client/processingCostReconciliation/client.d.ts +14 -0
  32. package/dist/client/processingCostReconciliation/client.d.ts.map +1 -0
  33. package/dist/client/processingCostReconciliation/client.js +35 -0
  34. package/dist/client/processingCostReconciliation/client.js.map +1 -0
  35. package/dist/client/processingCostReconciliation/contracts.d.ts +172 -0
  36. package/dist/client/processingCostReconciliation/contracts.d.ts.map +1 -0
  37. package/dist/client/processingCostReconciliation/contracts.js +55 -0
  38. package/dist/client/processingCostReconciliation/contracts.js.map +1 -0
  39. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts +15 -0
  40. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts.map +1 -0
  41. package/dist/client/processingCostReconciliation/invoiceFunding.js +195 -0
  42. package/dist/client/processingCostReconciliation/invoiceFunding.js.map +1 -0
  43. package/dist/client/processingCostReconciliation/provider.d.ts +9 -0
  44. package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -0
  45. package/dist/client/processingCostReconciliation/provider.js +148 -0
  46. package/dist/client/processingCostReconciliation/provider.js.map +1 -0
  47. package/dist/client/settlement/processingCostHistory.d.ts +12 -0
  48. package/dist/client/settlement/processingCostHistory.d.ts.map +1 -0
  49. package/dist/client/settlement/processingCostHistory.js +20 -0
  50. package/dist/client/settlement/processingCostHistory.js.map +1 -0
  51. package/dist/client/settlement/processingCosts.d.ts +3 -0
  52. package/dist/client/settlement/processingCosts.d.ts.map +1 -1
  53. package/dist/client/settlement/processingCosts.js +27 -7
  54. package/dist/client/settlement/processingCosts.js.map +1 -1
  55. package/dist/component/_generated/api.d.ts +36 -0
  56. package/dist/component/_generated/api.d.ts.map +1 -1
  57. package/dist/component/_generated/api.js.map +1 -1
  58. package/dist/component/_generated/component.d.ts +988 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  61. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  62. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  63. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/internal/actions.js +80 -0
  65. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  66. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  67. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  68. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  69. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  70. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  71. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  72. package/dist/component/balanceFunding/internal/queries.js +35 -0
  73. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  74. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  75. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  76. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  77. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  78. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  79. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  80. package/dist/component/balanceFunding/mutations.d.ts +419 -16
  81. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  82. package/dist/component/balanceFunding/mutations.js +24 -0
  83. package/dist/component/balanceFunding/mutations.js.map +1 -1
  84. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  85. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  86. package/dist/component/balanceFunding/queries.d.ts +78 -0
  87. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  88. package/dist/component/balanceFunding/queries.js +35 -0
  89. package/dist/component/balanceFunding/queries.js.map +1 -1
  90. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  91. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  92. package/dist/component/balanceFunding/receipt.js +37 -0
  93. package/dist/component/balanceFunding/receipt.js.map +1 -0
  94. package/dist/component/balanceFunding/schema.d.ts +506 -2
  95. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  96. package/dist/component/balanceFunding/schema.js +2 -0
  97. package/dist/component/balanceFunding/schema.js.map +1 -1
  98. package/dist/component/balanceFunding/stateHandlers.d.ts +42 -0
  99. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  100. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  101. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  102. package/dist/component/balanceFunding/workflowControl.js +149 -0
  103. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  104. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  105. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  106. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  107. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  108. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  109. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  110. package/dist/component/balanceFunding/workflowState.js +194 -0
  111. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  112. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  113. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  114. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  115. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  116. package/dist/component/earnings/triggers.d.ts +388 -2
  117. package/dist/component/earnings/triggers.d.ts.map +1 -1
  118. package/dist/component/payoutRelease/queries.d.ts +2 -2
  119. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  120. package/dist/component/processingCostReconciliation/adoption.d.ts +29 -0
  121. package/dist/component/processingCostReconciliation/adoption.d.ts.map +1 -0
  122. package/dist/component/processingCostReconciliation/adoption.js +58 -0
  123. package/dist/component/processingCostReconciliation/adoption.js.map +1 -0
  124. package/dist/component/processingCostReconciliation/bridge.d.ts +45 -0
  125. package/dist/component/processingCostReconciliation/bridge.d.ts.map +1 -0
  126. package/dist/component/processingCostReconciliation/bridge.js +41 -0
  127. package/dist/component/processingCostReconciliation/bridge.js.map +1 -0
  128. package/dist/component/processingCostReconciliation/helpers.d.ts +327 -0
  129. package/dist/component/processingCostReconciliation/helpers.d.ts.map +1 -0
  130. package/dist/component/processingCostReconciliation/helpers.js +39 -0
  131. package/dist/component/processingCostReconciliation/helpers.js.map +1 -0
  132. package/dist/component/processingCostReconciliation/mutations.d.ts +303 -0
  133. package/dist/component/processingCostReconciliation/mutations.d.ts.map +1 -0
  134. package/dist/component/processingCostReconciliation/mutations.js +121 -0
  135. package/dist/component/processingCostReconciliation/mutations.js.map +1 -0
  136. package/dist/component/processingCostReconciliation/queries.d.ts +422 -0
  137. package/dist/component/processingCostReconciliation/queries.d.ts.map +1 -0
  138. package/dist/component/processingCostReconciliation/queries.js +19 -0
  139. package/dist/component/processingCostReconciliation/queries.js.map +1 -0
  140. package/dist/component/processingCostReconciliation/rollback.d.ts +21 -0
  141. package/dist/component/processingCostReconciliation/rollback.d.ts.map +1 -0
  142. package/dist/component/processingCostReconciliation/rollback.js +54 -0
  143. package/dist/component/processingCostReconciliation/rollback.js.map +1 -0
  144. package/dist/component/processingCostReconciliation/schema.d.ts +2460 -0
  145. package/dist/component/processingCostReconciliation/schema.d.ts.map +1 -0
  146. package/dist/component/processingCostReconciliation/schema.js +137 -0
  147. package/dist/component/processingCostReconciliation/schema.js.map +1 -0
  148. package/dist/component/processingCostReconciliation/steps.d.ts +306 -0
  149. package/dist/component/processingCostReconciliation/steps.d.ts.map +1 -0
  150. package/dist/component/processingCostReconciliation/steps.js +149 -0
  151. package/dist/component/processingCostReconciliation/steps.js.map +1 -0
  152. package/dist/component/processingCostReconciliation/validation.d.ts +13 -0
  153. package/dist/component/processingCostReconciliation/validation.d.ts.map +1 -0
  154. package/dist/component/processingCostReconciliation/validation.js +61 -0
  155. package/dist/component/processingCostReconciliation/validation.js.map +1 -0
  156. package/dist/component/processingCostReconciliation/workflow.d.ts +105 -0
  157. package/dist/component/processingCostReconciliation/workflow.d.ts.map +1 -0
  158. package/dist/component/processingCostReconciliation/workflow.js +33 -0
  159. package/dist/component/processingCostReconciliation/workflow.js.map +1 -0
  160. package/dist/component/schema.d.ts +694 -1
  161. package/dist/component/schema.js +2 -0
  162. package/dist/component/schema.js.map +1 -1
  163. package/package.json +1 -1
  164. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  165. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  166. package/src/client/billing/balanceFunding.ts +50 -0
  167. package/src/client/costRecovery-invoices.ts +19 -4
  168. package/src/client/costRecovery.ts +4 -2
  169. package/src/client/index.ts +15 -0
  170. package/src/client/processingCostReconciliation/client.ts +75 -0
  171. package/src/client/processingCostReconciliation/contracts.ts +176 -0
  172. package/src/client/processingCostReconciliation/invoiceFunding.ts +270 -0
  173. package/src/client/processingCostReconciliation/invoiceProvider.test.ts +353 -0
  174. package/src/client/processingCostReconciliation/provider.test.ts +324 -0
  175. package/src/client/processingCostReconciliation/provider.ts +178 -0
  176. package/src/client/settlement/processingCostHistory.ts +31 -0
  177. package/src/client/settlement/processingCosts.ts +50 -15
  178. package/src/component/_generated/api.ts +36 -0
  179. package/src/component/_generated/component.ts +1094 -0
  180. package/src/component/balanceFunding/internal/actions.ts +107 -0
  181. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  182. package/src/component/balanceFunding/internal/queries.ts +34 -0
  183. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  184. package/src/component/balanceFunding/mutations.ts +34 -0
  185. package/src/component/balanceFunding/queries.ts +38 -0
  186. package/src/component/balanceFunding/receipt.ts +48 -0
  187. package/src/component/balanceFunding/schema.ts +2 -0
  188. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  189. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  190. package/src/component/balanceFunding/workflow.test.ts +552 -0
  191. package/src/component/balanceFunding/workflowControl.ts +198 -0
  192. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  193. package/src/component/balanceFunding/workflowState.ts +285 -0
  194. package/src/component/balanceFunding/workflowValidators.ts +40 -0
  195. package/src/component/processingCostReconciliation/adoption.test.ts +206 -0
  196. package/src/component/processingCostReconciliation/adoption.ts +77 -0
  197. package/src/component/processingCostReconciliation/bridge.ts +50 -0
  198. package/src/component/processingCostReconciliation/helpers.ts +55 -0
  199. package/src/component/processingCostReconciliation/invoice.test.ts +152 -0
  200. package/src/component/processingCostReconciliation/mutations.ts +148 -0
  201. package/src/component/processingCostReconciliation/queries.ts +18 -0
  202. package/src/component/processingCostReconciliation/rollback.ts +72 -0
  203. package/src/component/processingCostReconciliation/schema.ts +191 -0
  204. package/src/component/processingCostReconciliation/state.test.ts +407 -0
  205. package/src/component/processingCostReconciliation/steps.ts +168 -0
  206. package/src/component/processingCostReconciliation/validation.ts +79 -0
  207. package/src/component/processingCostReconciliation/workflow.test.ts +329 -0
  208. package/src/component/processingCostReconciliation/workflow.ts +50 -0
  209. package/src/component/schema.ts +2 -0
@@ -0,0 +1,353 @@
1
+ import Stripe from "stripe";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import {
4
+ componentsGeneric,
5
+ mutationGeneric,
6
+ type FunctionReference,
7
+ } from "convex/server";
8
+ import { v } from "convex/values";
9
+ import { expect, it } from "vitest";
10
+ import { initConvexTest } from "../setup.test.js";
11
+ import schema from "../../component/schema.js";
12
+ import { CostRecoveryClient } from "../costRecovery.js";
13
+ import type { Component, RunCtx } from "../helpers.js";
14
+ import type { ProcessingCostProviderRequest } from "./contracts.js";
15
+ const modules = import.meta.glob("../../component/**/*.ts");
16
+ const nested = componentsGeneric();
17
+ const scope = { accountId: "acct_owner", scopeKey: "store", currency: "usd" };
18
+ async function fixture() {
19
+ const t = initConvexTest();
20
+ t.registerComponent("betterStripe", schema, {
21
+ ...modules,
22
+ "../../component/fixture.ts": async () => ({
23
+ seed: mutationGeneric({
24
+ args: {},
25
+ returns: v.any(),
26
+ handler: async (ctx) => {
27
+ const id = await ctx.db.insert("recoveryGroups", {
28
+ ...scope,
29
+ groupKey: "old-invoice",
30
+ sourceKind: "invoice",
31
+ sourceId: "in_original",
32
+ invoiceItemId: "ii_original",
33
+ amount: 80,
34
+ maxDebit: 100,
35
+ maxCredit: 0,
36
+ pendingOperations: 0,
37
+ status: "collected",
38
+ });
39
+ return ctx.db.get(id);
40
+ },
41
+ }),
42
+ }),
43
+ });
44
+ workflowTest.register(t, "betterStripe/workflow");
45
+ const group = await t.mutation(nested.betterStripe.fixture.seed, {});
46
+ const op = await t.mutation(
47
+ nested.betterStripe.processingCostReconciliation.mutations.start,
48
+ {
49
+ ...scope,
50
+ claimKey: "cost:pi_a",
51
+ requestKey: "invoice-refund",
52
+ expectedRevision: -1,
53
+ source: {
54
+ kind: "invoice_recovery",
55
+ paymentIntentId: "pi_a",
56
+ gross: 1000,
57
+ groupKey: "old-invoice",
58
+ },
59
+ rollback: { groupKey: "old-invoice", expectedRevision: -1 },
60
+ policy: {
61
+ sellingFee: 100,
62
+ liability: { processingCosts: "uncovered", disputeCosts: "all" },
63
+ rounding: "nearest",
64
+ },
65
+ provider: "function://fixture/provider",
66
+ providerApiVersion: "2026-09-30.endive",
67
+ definitionVersion: 1,
68
+ maxAttempts: 3,
69
+ retryDelayMs: 1,
70
+ },
71
+ );
72
+ const request: ProcessingCostProviderRequest = {
73
+ ...scope,
74
+ operationId: op.operationId,
75
+ version: op.version,
76
+ providerApiVersion: "2026-09-30.endive",
77
+ definitionVersion: 1,
78
+ };
79
+ let writes = 0;
80
+ const ctx = {
81
+ runQuery: (
82
+ ref: FunctionReference<"query">,
83
+ args: Record<string, unknown>,
84
+ ) => t.query(ref, args),
85
+ runMutation: (
86
+ ref: FunctionReference<"mutation">,
87
+ args: Record<string, unknown>,
88
+ ) => {
89
+ writes++;
90
+ return t.mutation(ref, args);
91
+ },
92
+ } as unknown as RunCtx;
93
+ const client = new CostRecoveryClient(
94
+ nested.betterStripe as unknown as Component,
95
+ );
96
+ const tx = (id: string, source: string, amount: number, fee: number) => ({
97
+ id,
98
+ object: "balance_transaction",
99
+ source,
100
+ amount,
101
+ fee,
102
+ net: amount - fee,
103
+ currency: "usd",
104
+ created: 1,
105
+ fee_details: [],
106
+ });
107
+ const payment = {
108
+ id: "pi_a",
109
+ object: "payment_intent",
110
+ status: "succeeded",
111
+ amount: 1000,
112
+ amount_received: 1000,
113
+ currency: "usd",
114
+ customer_account: scope.accountId,
115
+ livemode: false,
116
+ metadata: {},
117
+ latest_charge: {
118
+ id: "ch_a",
119
+ object: "charge",
120
+ payment_intent: "pi_a",
121
+ amount: 1000,
122
+ amount_captured: 1000,
123
+ currency: "usd",
124
+ paid: true,
125
+ captured: true,
126
+ status: "succeeded",
127
+ amount_refunded: 500,
128
+ disputed: false,
129
+ livemode: false,
130
+ balance_transaction: tx("txn_charge", "ch_a", 1000, 30),
131
+ },
132
+ };
133
+ const invoice = {
134
+ id: "in_original",
135
+ object: "invoice",
136
+ status: "paid",
137
+ currency: "usd",
138
+ amount_paid: 1000,
139
+ amount_due: 1000,
140
+ total: 1000,
141
+ amount_remaining: 0,
142
+ amount_overpaid: 0,
143
+ customer_account: scope.accountId,
144
+ livemode: false,
145
+ };
146
+ const item = {
147
+ id: "ii_original",
148
+ object: "invoiceitem",
149
+ invoice: "in_original",
150
+ customer_account: scope.accountId,
151
+ currency: "usd",
152
+ amount: 80,
153
+ discountable: false,
154
+ metadata: { bsRecoveryGroup: group._id },
155
+ };
156
+ const funding = {
157
+ id: "inpay_original",
158
+ object: "invoice_payment",
159
+ invoice: "in_original",
160
+ status: "paid",
161
+ currency: "usd",
162
+ amount_paid: 1000,
163
+ amount_requested: 1000,
164
+ livemode: false,
165
+ payment: { type: "payment_intent", payment_intent: "pi_a" },
166
+ };
167
+ const refund = {
168
+ id: "re_a",
169
+ object: "refund",
170
+ amount: 500,
171
+ status: "succeeded",
172
+ currency: "usd",
173
+ charge: "ch_a",
174
+ payment_intent: "pi_a",
175
+ balance_transaction: tx("txn_refund", "re_a", -500, 0),
176
+ failure_balance_transaction: null,
177
+ };
178
+ const pages = new Map<string, unknown>();
179
+ const requests: {
180
+ path: string;
181
+ method: string;
182
+ authorized: boolean;
183
+ version: string | null;
184
+ }[] = [];
185
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
186
+ const u = new URL(String(url));
187
+ const h = new Headers(init?.headers);
188
+ const phase = u.pathname.endsWith("/invoice_payments")
189
+ ? u.searchParams.has("invoice")
190
+ ? "forward"
191
+ : "inverse"
192
+ : u.pathname;
193
+ requests.push({
194
+ path: u.pathname,
195
+ method: init?.method ?? "GET",
196
+ authorized: h.get("Authorization") === "Bearer sk_test_runtime_only",
197
+ version: h.get("Stripe-Version"),
198
+ });
199
+ const data =
200
+ pages.get(phase) ??
201
+ (u.pathname.includes("/payment_intents/")
202
+ ? payment
203
+ : u.pathname.includes("/invoices/")
204
+ ? invoice
205
+ : u.pathname.endsWith("/invoiceitems")
206
+ ? { object: "list", data: [item], has_more: false }
207
+ : u.pathname.endsWith("/invoice_payments")
208
+ ? { object: "list", data: [funding], has_more: false }
209
+ : u.pathname.endsWith("/refunds")
210
+ ? { object: "list", data: [refund], has_more: false }
211
+ : { object: "list", data: [], has_more: false });
212
+ return new Response(JSON.stringify(data), {
213
+ status: 200,
214
+ headers: { "content-type": "application/json" },
215
+ });
216
+ });
217
+ return {
218
+ t,
219
+ ctx,
220
+ client,
221
+ request,
222
+ httpClient,
223
+ pages,
224
+ requests,
225
+ group,
226
+ payment,
227
+ invoice,
228
+ item,
229
+ funding,
230
+ refund,
231
+ writes: () => writes,
232
+ };
233
+ }
234
+ it("verifies collected group/item and full original funding independently of price metadata", async () => {
235
+ const f = await fixture();
236
+ const receipt = await f.client.observeProcessingCosts(f.ctx, f.request, {
237
+ stripeSecretKey: "sk_test_runtime_only",
238
+ httpClient: f.httpClient,
239
+ });
240
+ expect(receipt).toMatchObject({
241
+ outcome: {
242
+ status: "ready",
243
+ value: {
244
+ sourceChargeId: "ch_a",
245
+ gross: 1000,
246
+ originalProcessingFee: 30,
247
+ principalReturned: 500,
248
+ provenance: {
249
+ invoiceId: "in_original",
250
+ invoicePaymentId: "inpay_original",
251
+ customerAccountId: scope.accountId,
252
+ recoveryInvoiceItemId: "ii_original",
253
+ },
254
+ },
255
+ },
256
+ });
257
+ expect(JSON.stringify(receipt)).not.toContain("stripePriceId");
258
+ expect(f.writes()).toBe(0);
259
+ expect(
260
+ f.requests.every(
261
+ (r) =>
262
+ r.method === "GET" &&
263
+ r.authorized &&
264
+ r.version === f.request.providerApiVersion,
265
+ ),
266
+ ).toBe(true);
267
+ expect(
268
+ (
269
+ await f.t.query(nested.betterStripe.costRecovery.queries.group, {
270
+ groupKey: "old-invoice",
271
+ })
272
+ ).invoiceFunding,
273
+ ).toBeUndefined();
274
+ if (receipt.outcome.status !== "ready")
275
+ throw new Error("Expected verified observation.");
276
+ expect(
277
+ await f.t.mutation(
278
+ nested.betterStripe.processingCostReconciliation.steps.apply,
279
+ {
280
+ ...scope,
281
+ operationId: f.request.operationId,
282
+ version: f.request.version,
283
+ observation: receipt.outcome.value,
284
+ },
285
+ ),
286
+ ).toMatchObject({
287
+ status: "completed",
288
+ result: { rollbackClaim: { amountDue: 40, revision: 0 } },
289
+ });
290
+ });
291
+ it.each(["forward", "inverse", "/v1/invoiceitems", "/v1/refunds"])(
292
+ "holds incomplete %s before any financial write",
293
+ async (phase) => {
294
+ const f = await fixture();
295
+ f.pages.set(phase, { object: "list", data: [], has_more: true });
296
+ expect(
297
+ await f.client.observeProcessingCosts(f.ctx, f.request, {
298
+ stripeSecretKey: "sk_test_runtime_only",
299
+ httpClient: f.httpClient,
300
+ }),
301
+ ).toMatchObject({
302
+ outcome: {
303
+ status: "unknown",
304
+ reason: "history_incomplete",
305
+ retryable: false,
306
+ },
307
+ });
308
+ expect(f.writes()).toBe(0);
309
+ },
310
+ );
311
+ it("rejects partial or ambiguous funding even when the invoice is marked paid", async () => {
312
+ const f = await fixture();
313
+ for (const data of [
314
+ [{ ...f.funding, amount_paid: 500 }],
315
+ [
316
+ { ...f.funding, amount_paid: 500 },
317
+ { ...f.funding, id: "inpay_other", amount_paid: 500 },
318
+ ],
319
+ ]) {
320
+ f.pages.set("forward", { object: "list", data, has_more: false });
321
+ expect(
322
+ await f.client.observeProcessingCosts(f.ctx, f.request, {
323
+ stripeSecretKey: "sk_test_runtime_only",
324
+ httpClient: f.httpClient,
325
+ }),
326
+ ).toMatchObject({
327
+ outcome: { status: "rejected", reason: "unsupported_source" },
328
+ });
329
+ }
330
+ expect(f.writes()).toBe(0);
331
+ });
332
+ it("rejects a different original funding payment without binding or rolling back", async () => {
333
+ const f = await fixture();
334
+ f.pages.set("forward", {
335
+ object: "list",
336
+ data: [
337
+ {
338
+ ...f.funding,
339
+ payment: { type: "payment_intent", payment_intent: "pi_foreign" },
340
+ },
341
+ ],
342
+ has_more: false,
343
+ });
344
+ expect(
345
+ await f.client.observeProcessingCosts(f.ctx, f.request, {
346
+ stripeSecretKey: "sk_test_runtime_only",
347
+ httpClient: f.httpClient,
348
+ }),
349
+ ).toMatchObject({
350
+ outcome: { status: "conflict", reason: "identity_changed" },
351
+ });
352
+ expect(f.writes()).toBe(0);
353
+ });
@@ -0,0 +1,324 @@
1
+ import Stripe from "stripe";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import { componentsGeneric, type FunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { initConvexTest } from "../setup.test.js";
6
+ import schema from "../../component/schema.js";
7
+ import { CostRecoveryClient } from "../costRecovery.js";
8
+ import type { Component, RunCtx } from "../helpers.js";
9
+ import type { ProcessingCostProviderRequest } from "./contracts.js";
10
+ const modules = import.meta.glob("../../component/**/*.ts");
11
+ const nested = componentsGeneric();
12
+ const scope = { accountId: "acct_seller", scopeKey: "store", currency: "usd" };
13
+ async function fixture() {
14
+ const t = initConvexTest();
15
+ t.registerComponent("betterStripe", schema, modules);
16
+ workflowTest.register(t, "betterStripe/workflow");
17
+ const client = new CostRecoveryClient(
18
+ nested.betterStripe as unknown as Component,
19
+ );
20
+ let writes = 0;
21
+ const ctx = {
22
+ runQuery: (
23
+ ref: FunctionReference<"query">,
24
+ args: Record<string, unknown>,
25
+ ) => t.query(ref, args),
26
+ runMutation: (
27
+ ref: FunctionReference<"mutation">,
28
+ args: Record<string, unknown>,
29
+ ) => {
30
+ writes++;
31
+ return t.mutation(ref, args);
32
+ },
33
+ } as unknown as RunCtx;
34
+ const op = await t.mutation(
35
+ nested.betterStripe.processingCostReconciliation.mutations.start,
36
+ {
37
+ ...scope,
38
+ claimKey: "cost:pi_a",
39
+ requestKey: "provider-refund",
40
+ expectedRevision: -1,
41
+ source: {
42
+ kind: "sale",
43
+ paymentIntentId: "pi_a",
44
+ gross: 1000,
45
+ customerAccountId: "acct_buyer",
46
+ invoiceId: "in_a",
47
+ stripeAccountId: "acct_connected",
48
+ },
49
+ policy: {
50
+ sellingFee: 100,
51
+ liability: { processingCosts: "uncovered", disputeCosts: "all" },
52
+ rounding: "nearest",
53
+ },
54
+ provider: "function://fixture/provider",
55
+ providerApiVersion: "2026-09-30.endive",
56
+ definitionVersion: 1,
57
+ maxAttempts: 3,
58
+ retryDelayMs: 1,
59
+ },
60
+ );
61
+ const request: ProcessingCostProviderRequest = {
62
+ ...scope,
63
+ operationId: op.operationId,
64
+ version: op.version,
65
+ providerApiVersion: "2026-09-30.endive",
66
+ definitionVersion: 1,
67
+ };
68
+ const tx = (id: string, source: string, amount: number, fee: number) => ({
69
+ id,
70
+ object: "balance_transaction",
71
+ source,
72
+ amount,
73
+ fee,
74
+ net: amount - fee,
75
+ currency: "usd",
76
+ created: 1,
77
+ fee_details: [],
78
+ });
79
+ const payment = {
80
+ id: "pi_a",
81
+ object: "payment_intent",
82
+ status: "succeeded",
83
+ amount: 1000,
84
+ amount_received: 1000,
85
+ currency: "usd",
86
+ customer_account: "acct_buyer",
87
+ livemode: false,
88
+ metadata: { stripePriceId: "price_current", private: "sk_test_PRIVATE" },
89
+ latest_charge: {
90
+ id: "ch_a",
91
+ object: "charge",
92
+ payment_intent: "pi_a",
93
+ amount: 1000,
94
+ amount_captured: 1000,
95
+ currency: "usd",
96
+ paid: true,
97
+ captured: true,
98
+ status: "succeeded",
99
+ amount_refunded: 500,
100
+ disputed: true,
101
+ livemode: false,
102
+ balance_transaction: tx("txn_charge", "ch_a", 1000, 30),
103
+ },
104
+ };
105
+ const invoice = {
106
+ id: "in_a",
107
+ object: "invoice",
108
+ status: "paid",
109
+ currency: "usd",
110
+ amount_paid: 1000,
111
+ amount_due: 1000,
112
+ amount_remaining: 0,
113
+ total: 1000,
114
+ amount_overpaid: 0,
115
+ customer_account: "acct_buyer",
116
+ livemode: false,
117
+ };
118
+ const funding = {
119
+ id: "inpay_a",
120
+ object: "invoice_payment",
121
+ invoice: "in_a",
122
+ status: "paid",
123
+ currency: "usd",
124
+ amount_paid: 1000,
125
+ amount_requested: 1000,
126
+ livemode: false,
127
+ payment: { type: "payment_intent", payment_intent: "pi_a" },
128
+ };
129
+ const line = {
130
+ id: "il_a",
131
+ object: "line_item",
132
+ invoice: "in_a",
133
+ currency: "usd",
134
+ amount: 1000,
135
+ quantity: 1,
136
+ livemode: false,
137
+ parent: {
138
+ type: "invoice_item_details",
139
+ invoice_item_details: { proration: false },
140
+ },
141
+ pricing: {
142
+ type: "price_details",
143
+ price_details: { price: "price_original", product: "prod_original" },
144
+ },
145
+ };
146
+ const refund = {
147
+ id: "re_a",
148
+ object: "refund",
149
+ amount: 500,
150
+ status: "succeeded",
151
+ currency: "usd",
152
+ charge: "ch_a",
153
+ payment_intent: "pi_a",
154
+ balance_transaction: tx("txn_refund", "re_a", -500, -5),
155
+ failure_balance_transaction: null,
156
+ };
157
+ const dispute = {
158
+ id: "dp_a",
159
+ object: "dispute",
160
+ amount: 600,
161
+ status: "lost",
162
+ currency: "usd",
163
+ charge: "ch_a",
164
+ payment_intent: "pi_a",
165
+ balance_transactions: [tx("txn_dispute", "dp_a", -600, 15)],
166
+ };
167
+ const pages = new Map<string, unknown>();
168
+ const requests: {
169
+ path: string;
170
+ method: string;
171
+ authenticated: boolean;
172
+ version: string | null;
173
+ account: string | null;
174
+ }[] = [];
175
+ const httpClient = Stripe.createFetchHttpClient(async (url, init) => {
176
+ const u = new URL(String(url));
177
+ const h = new Headers(init?.headers);
178
+ requests.push({
179
+ path: u.pathname,
180
+ method: init?.method ?? "GET",
181
+ authenticated: h.get("Authorization") === "Bearer sk_test_runtime_only",
182
+ version: h.get("Stripe-Version"),
183
+ account: h.get("Stripe-Account"),
184
+ });
185
+ const data =
186
+ pages.get(u.pathname) ??
187
+ (u.pathname.includes("/payment_intents/")
188
+ ? payment
189
+ : u.pathname.endsWith("/lines")
190
+ ? { object: "list", data: [line], has_more: false }
191
+ : u.pathname.includes("/invoices/")
192
+ ? invoice
193
+ : u.pathname.endsWith("/invoice_payments")
194
+ ? { object: "list", data: [funding], has_more: false }
195
+ : u.pathname.endsWith("/refunds")
196
+ ? { object: "list", data: [refund], has_more: false }
197
+ : { object: "list", data: [dispute], has_more: false });
198
+ return new Response(JSON.stringify(data), {
199
+ status: 200,
200
+ headers: { "content-type": "application/json" },
201
+ });
202
+ });
203
+ return {
204
+ t,
205
+ client,
206
+ ctx,
207
+ request,
208
+ httpClient,
209
+ requests,
210
+ pages,
211
+ payment,
212
+ refund,
213
+ dispute,
214
+ writes: () => writes,
215
+ };
216
+ }
217
+ it("uses real Stripe transport, original provenance and signed refunds/disputes without provider or ledger writes", async () => {
218
+ const f = await fixture();
219
+ const receipt = await f.client.observeProcessingCosts(f.ctx, f.request, {
220
+ stripeSecretKey: "sk_test_runtime_only",
221
+ httpClient: f.httpClient,
222
+ });
223
+ expect(receipt).toMatchObject({
224
+ outcome: {
225
+ status: "ready",
226
+ value: {
227
+ sourceChargeId: "ch_a",
228
+ gross: 1000,
229
+ originalProcessingFee: 30,
230
+ processingFee: 25,
231
+ disputeFees: 15,
232
+ principalReturned: 1000,
233
+ provenance: {
234
+ invoiceId: "in_a",
235
+ invoicePaymentId: "inpay_a",
236
+ stripePriceId: "price_original",
237
+ stripeProductId: "prod_original",
238
+ },
239
+ },
240
+ },
241
+ });
242
+ expect(JSON.stringify(receipt)).not.toContain("sk_test_PRIVATE");
243
+ expect(JSON.stringify(receipt)).not.toContain("price_current");
244
+ expect(
245
+ f.requests.every(
246
+ (r) =>
247
+ r.method === "GET" &&
248
+ r.authenticated &&
249
+ r.version === f.request.providerApiVersion &&
250
+ r.account === "acct_connected",
251
+ ),
252
+ ).toBe(true);
253
+ expect(f.writes()).toBe(0);
254
+ });
255
+ it.each(["/v1/refunds", "/v1/disputes"])(
256
+ "holds malformed or incomplete %s history without inventing zero costs",
257
+ async (path) => {
258
+ const f = await fixture();
259
+ f.pages.set(path, { object: "list", data: [], has_more: true });
260
+ expect(
261
+ await f.client.observeProcessingCosts(f.ctx, f.request, {
262
+ stripeSecretKey: "sk_test_runtime_only",
263
+ httpClient: f.httpClient,
264
+ }),
265
+ ).toMatchObject({
266
+ outcome: {
267
+ status: "unknown",
268
+ reason: "history_incomplete",
269
+ retryable: false,
270
+ },
271
+ });
272
+ expect(f.writes()).toBe(0);
273
+ },
274
+ );
275
+ it("never contacts the provider for a changed pinned API version", async () => {
276
+ const f = await fixture();
277
+ expect(
278
+ await f.client.observeProcessingCosts(
279
+ f.ctx,
280
+ { ...f.request, providerApiVersion: "2026-01-01.changed" },
281
+ { stripeSecretKey: "sk_test_runtime_only", httpClient: f.httpClient },
282
+ ),
283
+ ).toMatchObject({
284
+ outcome: { status: "conflict", reason: "identity_changed" },
285
+ });
286
+ expect(f.requests).toEqual([]);
287
+ });
288
+
289
+ it.each(["refund_source", "dispute_source", "refund_object", "requested_id"])(
290
+ "rejects unrelated balance transaction evidence: %s",
291
+ async (mode) => {
292
+ const f = await fixture();
293
+ if (mode === "refund_source")
294
+ f.refund.balance_transaction.source = "re_foreign";
295
+ if (mode === "dispute_source")
296
+ f.dispute.balance_transactions[0]!.source = "dp_foreign";
297
+ if (mode === "refund_object")
298
+ f.refund.balance_transaction.object = "foreign_object";
299
+ if (mode === "requested_id") {
300
+ const original = f.refund.balance_transaction;
301
+ (
302
+ f.refund as unknown as { balance_transaction: string }
303
+ ).balance_transaction = "txn_requested";
304
+ f.pages.set("/v1/balance_transactions/txn_requested", {
305
+ ...original,
306
+ id: "txn_other",
307
+ });
308
+ }
309
+ const receipt = await f.client.observeProcessingCosts(f.ctx, f.request, {
310
+ stripeSecretKey: "sk_test_runtime_only",
311
+ httpClient: f.httpClient,
312
+ });
313
+ expect(receipt.outcome).toMatchObject({
314
+ status: "unknown",
315
+ retryable: false,
316
+ });
317
+ expect(f.writes()).toBe(0);
318
+ expect(
319
+ await f.t.query(nested.betterStripe.costRecovery.queries.claim, {
320
+ claimKey: "cost:pi_a",
321
+ }),
322
+ ).toBeNull();
323
+ },
324
+ );