@fantastic.dev/better-stripe 0.23.1 → 0.24.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 (287) hide show
  1. package/CHANGELOG.md +26 -2
  2. package/README.md +40 -5
  3. package/dist/client/affiliateRecovery/disputes.d.ts +18 -0
  4. package/dist/client/affiliateRecovery/disputes.d.ts.map +1 -0
  5. package/dist/client/affiliateRecovery/disputes.js +33 -0
  6. package/dist/client/affiliateRecovery/disputes.js.map +1 -0
  7. package/dist/client/affiliateRecovery/engine.d.ts +29 -0
  8. package/dist/client/affiliateRecovery/engine.d.ts.map +1 -0
  9. package/dist/client/affiliateRecovery/engine.js +116 -0
  10. package/dist/client/affiliateRecovery/engine.js.map +1 -0
  11. package/dist/client/affiliateRecovery/payoutGate.d.ts +24 -0
  12. package/dist/client/affiliateRecovery/payoutGate.d.ts.map +1 -0
  13. package/dist/client/affiliateRecovery/payoutGate.js +30 -0
  14. package/dist/client/affiliateRecovery/payoutGate.js.map +1 -0
  15. package/dist/client/affiliateRecovery/provider.d.ts +14 -0
  16. package/dist/client/affiliateRecovery/provider.d.ts.map +1 -0
  17. package/dist/client/affiliateRecovery/provider.js +96 -0
  18. package/dist/client/affiliateRecovery/provider.js.map +1 -0
  19. package/dist/client/affiliateRecovery/review.d.ts +28 -0
  20. package/dist/client/affiliateRecovery/review.d.ts.map +1 -0
  21. package/dist/client/affiliateRecovery/review.js +86 -0
  22. package/dist/client/affiliateRecovery/review.js.map +1 -0
  23. package/dist/client/affiliateRecovery/validators.d.ts +402 -0
  24. package/dist/client/affiliateRecovery/validators.d.ts.map +1 -0
  25. package/dist/client/affiliateRecovery/validators.js +27 -0
  26. package/dist/client/affiliateRecovery/validators.js.map +1 -0
  27. package/dist/client/affiliateRecovery.d.ts +131 -0
  28. package/dist/client/affiliateRecovery.d.ts.map +1 -0
  29. package/dist/client/affiliateRecovery.js +69 -0
  30. package/dist/client/affiliateRecovery.js.map +1 -0
  31. package/dist/client/connect/commissionReceipts.d.ts +4 -0
  32. package/dist/client/connect/commissionReceipts.d.ts.map +1 -0
  33. package/dist/client/connect/commissionReceipts.js +17 -0
  34. package/dist/client/connect/commissionReceipts.js.map +1 -0
  35. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +536 -2
  36. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  37. package/dist/client/connect/payoutSync.d.ts +32 -0
  38. package/dist/client/connect/payoutSync.d.ts.map +1 -0
  39. package/dist/client/connect/payoutSync.js +48 -0
  40. package/dist/client/connect/payoutSync.js.map +1 -0
  41. package/dist/client/connect/payoutSyncTestHelpers.d.ts +1509 -0
  42. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -0
  43. package/dist/client/connect/payoutSyncTestHelpers.js +62 -0
  44. package/dist/client/connect/payoutSyncTestHelpers.js.map +1 -0
  45. package/dist/client/connect/payoutSyncValidation.d.ts +16 -0
  46. package/dist/client/connect/payoutSyncValidation.d.ts.map +1 -0
  47. package/dist/client/connect/payoutSyncValidation.js +54 -0
  48. package/dist/client/connect/payoutSyncValidation.js.map +1 -0
  49. package/dist/client/connect/payouts.d.ts +3 -1
  50. package/dist/client/connect/payouts.d.ts.map +1 -1
  51. package/dist/client/connect/payouts.js +45 -12
  52. package/dist/client/connect/payouts.js.map +1 -1
  53. package/dist/client/connect/refundPrincipal.d.ts +4 -0
  54. package/dist/client/connect/refundPrincipal.d.ts.map +1 -0
  55. package/dist/client/connect/refundPrincipal.js +21 -0
  56. package/dist/client/connect/refundPrincipal.js.map +1 -0
  57. package/dist/client/connect/reversalExecution.d.ts +47 -0
  58. package/dist/client/connect/reversalExecution.d.ts.map +1 -0
  59. package/dist/client/connect/reversalExecution.js +84 -0
  60. package/dist/client/connect/reversalExecution.js.map +1 -0
  61. package/dist/client/connect/transfers.d.ts +8 -4
  62. package/dist/client/connect/transfers.d.ts.map +1 -1
  63. package/dist/client/connect/transfers.js +52 -57
  64. package/dist/client/connect/transfers.js.map +1 -1
  65. package/dist/client/index.d.ts +29 -9
  66. package/dist/client/index.d.ts.map +1 -1
  67. package/dist/client/index.js +9 -6
  68. package/dist/client/index.js.map +1 -1
  69. package/dist/client/readContracts.d.ts +8 -0
  70. package/dist/client/readContracts.d.ts.map +1 -1
  71. package/dist/client/readContracts.js +7 -0
  72. package/dist/client/readContracts.js.map +1 -1
  73. package/dist/client/settlement/execution.d.ts.map +1 -1
  74. package/dist/client/settlement/execution.js +30 -3
  75. package/dist/client/settlement/execution.js.map +1 -1
  76. package/dist/client/settlement/reconciliation.d.ts.map +1 -1
  77. package/dist/client/settlement/reconciliation.js +16 -2
  78. package/dist/client/settlement/reconciliation.js.map +1 -1
  79. package/dist/client/webhooks/disputeRecovery.d.ts +4 -0
  80. package/dist/client/webhooks/disputeRecovery.d.ts.map +1 -0
  81. package/dist/client/webhooks/disputeRecovery.js +40 -0
  82. package/dist/client/webhooks/disputeRecovery.js.map +1 -0
  83. package/dist/client/webhooks/processors.d.ts.map +1 -1
  84. package/dist/client/webhooks/processors.js +14 -29
  85. package/dist/client/webhooks/processors.js.map +1 -1
  86. package/dist/component/_generated/component.d.ts +560 -0
  87. package/dist/component/_generated/component.d.ts.map +1 -1
  88. package/dist/component/affiliateEarnings/mutations.d.ts +22 -0
  89. package/dist/component/affiliateEarnings/mutations.d.ts.map +1 -0
  90. package/dist/component/affiliateEarnings/mutations.js +160 -0
  91. package/dist/component/affiliateEarnings/mutations.js.map +1 -0
  92. package/dist/component/affiliatePayouts/mutations.d.ts +25 -0
  93. package/dist/component/affiliatePayouts/mutations.d.ts.map +1 -0
  94. package/dist/component/affiliatePayouts/mutations.js +104 -0
  95. package/dist/component/affiliatePayouts/mutations.js.map +1 -0
  96. package/dist/component/affiliatePayouts/queries.d.ts +23 -0
  97. package/dist/component/affiliatePayouts/queries.d.ts.map +1 -0
  98. package/dist/component/affiliatePayouts/queries.js +23 -0
  99. package/dist/component/affiliatePayouts/queries.js.map +1 -0
  100. package/dist/component/affiliatePayouts/recipientGuard.d.ts +12 -0
  101. package/dist/component/affiliatePayouts/recipientGuard.d.ts.map +1 -0
  102. package/dist/component/affiliatePayouts/recipientGuard.js +26 -0
  103. package/dist/component/affiliatePayouts/recipientGuard.js.map +1 -0
  104. package/dist/component/affiliateRecovery/accounting.d.ts +28 -0
  105. package/dist/component/affiliateRecovery/accounting.d.ts.map +1 -0
  106. package/dist/component/affiliateRecovery/accounting.js +71 -0
  107. package/dist/component/affiliateRecovery/accounting.js.map +1 -0
  108. package/dist/component/affiliateRecovery/mutations.d.ts +65 -0
  109. package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -0
  110. package/dist/component/affiliateRecovery/mutations.js +250 -0
  111. package/dist/component/affiliateRecovery/mutations.js.map +1 -0
  112. package/dist/component/affiliateRecovery/queries.d.ts +305 -0
  113. package/dist/component/affiliateRecovery/queries.d.ts.map +1 -0
  114. package/dist/component/affiliateRecovery/queries.js +113 -0
  115. package/dist/component/affiliateRecovery/queries.js.map +1 -0
  116. package/dist/component/affiliateRecovery/schema.d.ts +171 -0
  117. package/dist/component/affiliateRecovery/schema.d.ts.map +1 -0
  118. package/dist/component/affiliateRecovery/schema.js +71 -0
  119. package/dist/component/affiliateRecovery/schema.js.map +1 -0
  120. package/dist/component/connect/mutations.d.ts +36 -23
  121. package/dist/component/connect/mutations.d.ts.map +1 -1
  122. package/dist/component/connect/mutations.js +11 -151
  123. package/dist/component/connect/mutations.js.map +1 -1
  124. package/dist/component/connect/payoutWrites.d.ts +21 -0
  125. package/dist/component/connect/payoutWrites.d.ts.map +1 -0
  126. package/dist/component/connect/payoutWrites.js +19 -0
  127. package/dist/component/connect/payoutWrites.js.map +1 -0
  128. package/dist/component/connect/queries.d.ts +10 -0
  129. package/dist/component/connect/queries.d.ts.map +1 -1
  130. package/dist/component/connect/queries.js +3 -40
  131. package/dist/component/connect/queries.js.map +1 -1
  132. package/dist/component/connect/reversalClaims.d.ts +169 -0
  133. package/dist/component/connect/reversalClaims.d.ts.map +1 -0
  134. package/dist/component/connect/reversalClaims.js +176 -0
  135. package/dist/component/connect/reversalClaims.js.map +1 -0
  136. package/dist/component/connect/reversalDiagnostics.d.ts +59 -0
  137. package/dist/component/connect/reversalDiagnostics.d.ts.map +1 -0
  138. package/dist/component/connect/reversalDiagnostics.js +50 -0
  139. package/dist/component/connect/reversalDiagnostics.js.map +1 -0
  140. package/dist/component/connect/reversalReceipts.d.ts +27 -0
  141. package/dist/component/connect/reversalReceipts.d.ts.map +1 -0
  142. package/dist/component/connect/reversalReceipts.js +85 -0
  143. package/dist/component/connect/reversalReceipts.js.map +1 -0
  144. package/dist/component/connect/schema.d.ts +31 -1
  145. package/dist/component/connect/schema.d.ts.map +1 -1
  146. package/dist/component/connect/schema.js +3 -1
  147. package/dist/component/connect/schema.js.map +1 -1
  148. package/dist/component/connect/validators.d.ts +49 -1
  149. package/dist/component/connect/validators.d.ts.map +1 -1
  150. package/dist/component/connect/validators.js +2 -0
  151. package/dist/component/connect/validators.js.map +1 -1
  152. package/dist/component/earnings/triggers.d.ts +454 -2
  153. package/dist/component/earnings/triggers.d.ts.map +1 -1
  154. package/dist/component/payoutRelease/mutations.d.ts.map +1 -1
  155. package/dist/component/payoutRelease/mutations.js +6 -0
  156. package/dist/component/payoutRelease/mutations.js.map +1 -1
  157. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  158. package/dist/component/payoutRelease/queries.js +3 -1
  159. package/dist/component/payoutRelease/queries.js.map +1 -1
  160. package/dist/component/payoutSync/helpers.d.ts +44 -0
  161. package/dist/component/payoutSync/helpers.d.ts.map +1 -0
  162. package/dist/component/payoutSync/helpers.js +60 -0
  163. package/dist/component/payoutSync/helpers.js.map +1 -0
  164. package/dist/component/payoutSync/mutations.d.ts +51 -0
  165. package/dist/component/payoutSync/mutations.d.ts.map +1 -0
  166. package/dist/component/payoutSync/mutations.js +88 -0
  167. package/dist/component/payoutSync/mutations.js.map +1 -0
  168. package/dist/component/payoutSync/queries.d.ts +16 -0
  169. package/dist/component/payoutSync/queries.d.ts.map +1 -0
  170. package/dist/component/payoutSync/queries.js +11 -0
  171. package/dist/component/payoutSync/queries.js.map +1 -0
  172. package/dist/component/payoutSync/schema.d.ts +46 -0
  173. package/dist/component/payoutSync/schema.d.ts.map +1 -0
  174. package/dist/component/payoutSync/schema.js +22 -0
  175. package/dist/component/payoutSync/schema.js.map +1 -0
  176. package/dist/component/payoutSync/validators.d.ts +137 -0
  177. package/dist/component/payoutSync/validators.d.ts.map +1 -0
  178. package/dist/component/payoutSync/validators.js +19 -0
  179. package/dist/component/payoutSync/validators.js.map +1 -0
  180. package/dist/component/schema.d.ts +268 -1
  181. package/dist/component/schema.js +11 -0
  182. package/dist/component/schema.js.map +1 -1
  183. package/dist/component/settlement/clawbackSchema.d.ts +161 -0
  184. package/dist/component/settlement/clawbackSchema.d.ts.map +1 -0
  185. package/dist/component/settlement/clawbackSchema.js +73 -0
  186. package/dist/component/settlement/clawbackSchema.js.map +1 -0
  187. package/dist/component/settlement/clawbacks.d.ts +55 -0
  188. package/dist/component/settlement/clawbacks.d.ts.map +1 -0
  189. package/dist/component/settlement/clawbacks.js +146 -0
  190. package/dist/component/settlement/clawbacks.js.map +1 -0
  191. package/dist/component/settlement/mutations.d.ts +16 -0
  192. package/dist/component/settlement/mutations.d.ts.map +1 -1
  193. package/dist/component/settlement/mutations.js +48 -0
  194. package/dist/component/settlement/mutations.js.map +1 -1
  195. package/dist/component/settlement/queries.d.ts +53 -0
  196. package/dist/component/settlement/queries.d.ts.map +1 -1
  197. package/dist/component/settlement/queries.js +26 -0
  198. package/dist/component/settlement/queries.js.map +1 -1
  199. package/dist/react/workflows/AffiliateRecovery.d.ts +46 -0
  200. package/dist/react/workflows/AffiliateRecovery.d.ts.map +1 -0
  201. package/dist/react/workflows/AffiliateRecovery.js +84 -0
  202. package/dist/react/workflows/AffiliateRecovery.js.map +1 -0
  203. package/dist/react/workflows/index.d.ts +2 -0
  204. package/dist/react/workflows/index.d.ts.map +1 -1
  205. package/dist/react/workflows/index.js +1 -0
  206. package/dist/react/workflows/index.js.map +1 -1
  207. package/dist/testing/affiliate-recovery.d.ts +10 -0
  208. package/dist/testing/affiliate-recovery.d.ts.map +1 -0
  209. package/dist/testing/affiliate-recovery.js +126 -0
  210. package/dist/testing/affiliate-recovery.js.map +1 -0
  211. package/dist/testing/index.d.ts +2 -0
  212. package/dist/testing/index.d.ts.map +1 -1
  213. package/dist/testing/index.js +1 -0
  214. package/dist/testing/index.js.map +1 -1
  215. package/docs/affiliate-clawbacks.md +306 -0
  216. package/docs/read-contracts.md +40 -5
  217. package/docs/settlement.md +17 -0
  218. package/package.json +2 -1
  219. package/src/client/affiliateRecovery/disputes.ts +62 -0
  220. package/src/client/affiliateRecovery/engine.ts +196 -0
  221. package/src/client/affiliateRecovery/payoutGate.ts +65 -0
  222. package/src/client/affiliateRecovery/provider.ts +127 -0
  223. package/src/client/affiliateRecovery/review.ts +117 -0
  224. package/src/client/affiliateRecovery/validators.ts +38 -0
  225. package/src/client/affiliateRecovery.ts +173 -0
  226. package/src/client/connect/commissionReceipts.test.ts +157 -0
  227. package/src/client/connect/commissionReceipts.ts +23 -0
  228. package/src/client/connect/payoutSync.test.ts +313 -0
  229. package/src/client/connect/payoutSync.ts +93 -0
  230. package/src/client/connect/payoutSyncTestHelpers.ts +82 -0
  231. package/src/client/connect/payoutSyncValidation.ts +74 -0
  232. package/src/client/connect/payouts.ts +75 -15
  233. package/src/client/connect/refundPrincipal.test.ts +46 -0
  234. package/src/client/connect/refundPrincipal.ts +26 -0
  235. package/src/client/connect/reversalExecution.ts +130 -0
  236. package/src/client/connect/transfers.test.ts +3 -3
  237. package/src/client/connect/transfers.ts +93 -92
  238. package/src/client/index.ts +20 -18
  239. package/src/client/readContracts.ts +12 -0
  240. package/src/client/settlement/execution.test.ts +5 -0
  241. package/src/client/settlement/execution.ts +50 -3
  242. package/src/client/settlement/reconciliation.ts +20 -2
  243. package/src/client/webhooks/disputeRecovery.ts +74 -0
  244. package/src/client/webhooks/processors.test.ts +36 -53
  245. package/src/client/webhooks/processors.ts +18 -31
  246. package/src/component/_generated/api.ts +34 -0
  247. package/src/component/_generated/component.ts +696 -1
  248. package/src/component/affiliate-clawbacks.test.ts +370 -0
  249. package/src/component/affiliate-component-pagination.test.ts +83 -0
  250. package/src/component/affiliate-direct-payout.test.ts +160 -0
  251. package/src/component/affiliate-recovery-lifecycle.test.ts +587 -0
  252. package/src/component/affiliateEarnings/mutations.ts +196 -0
  253. package/src/component/affiliatePayouts/mutations.ts +121 -0
  254. package/src/component/affiliatePayouts/queries.ts +28 -0
  255. package/src/component/affiliatePayouts/recipientGuard.ts +42 -0
  256. package/src/component/affiliateRecovery/accounting.ts +111 -0
  257. package/src/component/affiliateRecovery/mutations.ts +275 -0
  258. package/src/component/affiliateRecovery/queries.ts +138 -0
  259. package/src/component/affiliateRecovery/schema.ts +86 -0
  260. package/src/component/connect/mutations.ts +13 -190
  261. package/src/component/connect/payoutWrites.ts +25 -0
  262. package/src/component/connect/queries.ts +4 -47
  263. package/src/component/connect/reversalClaims.ts +232 -0
  264. package/src/component/connect/reversalDiagnostics.ts +61 -0
  265. package/src/component/connect/reversalReceipts.ts +147 -0
  266. package/src/component/connect/schema.ts +3 -3
  267. package/src/component/connect/validators.ts +2 -0
  268. package/src/component/payout-recovery-integration.test.ts +172 -0
  269. package/src/component/payout-sync.test.ts +117 -0
  270. package/src/component/payoutRelease/mutations.ts +9 -0
  271. package/src/component/payoutRelease/queries.ts +3 -1
  272. package/src/component/payoutSync/helpers.ts +86 -0
  273. package/src/component/payoutSync/mutations.ts +102 -0
  274. package/src/component/payoutSync/queries.ts +10 -0
  275. package/src/component/payoutSync/schema.ts +25 -0
  276. package/src/component/payoutSync/validators.ts +21 -0
  277. package/src/component/schema.ts +20 -0
  278. package/src/component/settlement/clawbackSchema.ts +78 -0
  279. package/src/component/settlement/clawbacks.ts +233 -0
  280. package/src/component/settlement/mutations.ts +54 -0
  281. package/src/component/settlement/queries.ts +35 -0
  282. package/src/component/summary-arithmetic.test.ts +9 -4
  283. package/src/react/workflows/AffiliateRecovery.test.tsx +106 -0
  284. package/src/react/workflows/AffiliateRecovery.tsx +273 -0
  285. package/src/react/workflows/index.ts +9 -0
  286. package/src/testing/affiliate-recovery.ts +137 -0
  287. package/src/testing/index.ts +2 -0
@@ -0,0 +1,93 @@
1
+ import type Stripe from "stripe";
2
+ import type { Infer } from "convex/values";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import { runMutationOrThrow } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+ import { validateIdentity } from "../../component/payoutSync/helpers.js";
7
+ import type { result } from "../../component/payoutSync/validators.js";
8
+ import {
9
+ payoutAccount,
10
+ payoutSnapshot,
11
+ type PayoutSyncScope,
12
+ } from "./payoutSyncValidation.js";
13
+ export type PayoutSyncOptions = {
14
+ stripePayoutId: string;
15
+ scope: PayoutSyncScope;
16
+ };
17
+ export type PayoutSyncResult = Infer<typeof result>;
18
+ export type PreparedPayoutSync = Awaited<ReturnType<typeof preparePayoutSync>>;
19
+ async function markUnknown(
20
+ component: Component,
21
+ ctx: RunCtx,
22
+ observation: {
23
+ stripePayoutId: string;
24
+ accountId: string;
25
+ generation: number;
26
+ },
27
+ ) {
28
+ await runMutationOrThrow(
29
+ ctx,
30
+ componentRef(component, "payoutSync/mutations/markUnknown"),
31
+ observation,
32
+ );
33
+ }
34
+ /** Package-internal preparation for transactional host webhook dispatch. No financial record write. */
35
+ export async function preparePayoutSync(
36
+ stripe: Stripe,
37
+ component: Component,
38
+ ctx: RunCtx,
39
+ opts: PayoutSyncOptions,
40
+ ) {
41
+ const identity = {
42
+ stripePayoutId: opts.stripePayoutId,
43
+ accountId: payoutAccount(opts.scope),
44
+ };
45
+ validateIdentity(identity);
46
+ if (!ctx.runMutation)
47
+ throw new Error("Payout synchronization requires runMutation.");
48
+ const generation = (await runMutationOrThrow(
49
+ ctx,
50
+ componentRef(component, "payoutSync/mutations/begin"),
51
+ identity,
52
+ )) as number;
53
+ try {
54
+ const payout = await stripe.payouts.retrieve(
55
+ identity.stripePayoutId,
56
+ {},
57
+ identity.accountId === "platform"
58
+ ? {}
59
+ : { stripeAccount: identity.accountId },
60
+ );
61
+ return {
62
+ ...identity,
63
+ generation,
64
+ payout: payoutSnapshot(payout, identity),
65
+ };
66
+ } catch (error) {
67
+ await markUnknown(component, ctx, { ...identity, generation });
68
+ throw error;
69
+ }
70
+ }
71
+ /** Host must authorize scope. This only reads Stripe and synchronizes the existing financial record. */
72
+ export async function syncPayoutFromStripe(
73
+ stripe: Stripe,
74
+ component: Component,
75
+ ctx: RunCtx,
76
+ opts: PayoutSyncOptions,
77
+ ): Promise<PayoutSyncResult> {
78
+ const observation = await preparePayoutSync(stripe, component, ctx, opts);
79
+ try {
80
+ return (await runMutationOrThrow(
81
+ ctx,
82
+ componentRef(component, "payoutSync/mutations/finish"),
83
+ observation,
84
+ )) as PayoutSyncResult;
85
+ } catch (error) {
86
+ await markUnknown(component, ctx, {
87
+ stripePayoutId: observation.stripePayoutId,
88
+ accountId: observation.accountId,
89
+ generation: observation.generation,
90
+ });
91
+ throw error;
92
+ }
93
+ }
@@ -0,0 +1,82 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, vi } from "vitest";
5
+ import type Stripe from "stripe";
6
+ import type { Component, RunCtx } from "../helpers.js";
7
+ import schema from "../../component/schema.js";
8
+ const modules = import.meta.glob("../../component/**/*.*s");
9
+ const symbol = Symbol.for("toReferencePath");
10
+ export const component = {
11
+ payoutPolicy: {
12
+ queries: { get: { [symbol]: "betterStripe/payoutPolicy/queries/get" } },
13
+ },
14
+ } as unknown as Component;
15
+ export type Scope =
16
+ { type: "connected"; accountId: string } | { type: "platform" };
17
+ type Sync = (
18
+ stripe: Stripe,
19
+ component: Component,
20
+ ctx: RunCtx,
21
+ opts: { stripePayoutId: string; scope: Scope },
22
+ ) => Promise<unknown>;
23
+ export async function operation() {
24
+ const path = "./payoutSync.js";
25
+ const mod = (await import(path).catch(() => ({}))) as {
26
+ syncPayoutFromStripe?: Sync;
27
+ };
28
+ expect(
29
+ mod.syncPayoutFromStripe,
30
+ "authoritative payout synchronization is missing",
31
+ ).toBeTypeOf("function");
32
+ return mod.syncPayoutFromStripe!;
33
+ }
34
+ export async function setup(
35
+ scope: Scope = { type: "connected", accountId: "acct_owner" },
36
+ ) {
37
+ const t = convexTest(schema, modules);
38
+ const path = (ref: Record<symbol, string>) =>
39
+ ref[symbol].replace("betterStripe/", "").replace(/\/(\w+)$/, ":$1");
40
+ const mutate = (ref: Record<symbol, string>, args: never) =>
41
+ t.mutation(makeFunctionReference<"mutation">(path(ref)), args);
42
+ const ctx = {
43
+ runQuery: (ref: Record<symbol, string>, args: never) =>
44
+ t.query(makeFunctionReference<"query">(path(ref)), args),
45
+ runMutation: mutate,
46
+ } as unknown as RunCtx;
47
+ let payout = {
48
+ id: "po_one",
49
+ amount: 500,
50
+ currency: "jpy",
51
+ status: "paid",
52
+ arrival_date: 200,
53
+ created: 100,
54
+ automatic: true,
55
+ method: "standard",
56
+ type: "bank_account",
57
+ source_type: "card",
58
+ destination: "ba_one",
59
+ balance_transaction: "txn_pending",
60
+ failure_code: null,
61
+ failure_message: null,
62
+ metadata: { accountId: "acct_metadata_is_not_authority" },
63
+ } as unknown as Stripe.Payout;
64
+ const retrieve = vi.fn(async () => ({ ...payout }));
65
+ const provider = { payouts: { retrieve } } as unknown as Stripe;
66
+ const sync = await operation();
67
+ return {
68
+ t,
69
+ ctx,
70
+ mutate,
71
+ retrieve,
72
+ provider,
73
+ scope,
74
+ set: (patch: Partial<Stripe.Payout>) => {
75
+ payout = { ...payout, ...patch };
76
+ },
77
+ read: () => ({ ...payout }),
78
+ run: () =>
79
+ sync(provider, component, ctx, { stripePayoutId: "po_one", scope }),
80
+ row: () => t.run((ctx) => ctx.db.query("payouts").unique()),
81
+ };
82
+ }
@@ -0,0 +1,74 @@
1
+ import type Stripe from "stripe";
2
+ import type { Infer } from "convex/values";
3
+ import type { snapshot } from "../../component/payoutSync/validators.js";
4
+ import {
5
+ validateIdentity,
6
+ validateSnapshot,
7
+ } from "../../component/payoutSync/helpers.js";
8
+ export type PayoutSyncScope =
9
+ { type: "connected"; accountId: string } | { type: "platform" };
10
+ export function payoutAccount(scope: PayoutSyncScope) {
11
+ if (scope?.type === "platform" && Object.keys(scope).length === 1)
12
+ return "platform";
13
+ if (
14
+ scope?.type === "connected" &&
15
+ Object.keys(scope).length === 2 &&
16
+ typeof scope.accountId === "string" &&
17
+ /^acct_[A-Za-z0-9_]+$/.test(scope.accountId)
18
+ )
19
+ return scope.accountId;
20
+ throw new Error("Payout synchronization scope must be explicit.");
21
+ }
22
+ /** Status observations do not establish funding maturity or payout eligibility. */
23
+ export function payoutSnapshot(
24
+ p: Stripe.Payout,
25
+ args: { stripePayoutId: string; accountId: string },
26
+ ): Infer<typeof snapshot> {
27
+ validateIdentity(args);
28
+ if (!p || typeof p !== "object")
29
+ throw new Error("Provider payout response is unavailable.");
30
+ if (p.id !== args.stripePayoutId)
31
+ throw new Error("Provider payout identity does not match.");
32
+ if (
33
+ (p.status !== "pending" &&
34
+ p.status !== "paid" &&
35
+ p.status !== "failed" &&
36
+ p.status !== "canceled" &&
37
+ p.status !== "in_transit") ||
38
+ typeof p.automatic !== "boolean" ||
39
+ !["standard", "instant"].includes(p.method)
40
+ )
41
+ throw new Error("Provider payout status or method is unsupported.");
42
+ if (
43
+ !Number.isSafeInteger(p.arrival_date) ||
44
+ p.arrival_date < 0 ||
45
+ !Number.isSafeInteger(p.arrival_date * 1000) ||
46
+ p.arrival_date * 1000 > 8640000000000000
47
+ )
48
+ throw new Error("Invalid provider payout arrival date.");
49
+ if (
50
+ (p.failure_code != null && typeof p.failure_code !== "string") ||
51
+ (p.failure_message != null && typeof p.failure_message !== "string")
52
+ )
53
+ throw new Error("Invalid provider payout failure detail.");
54
+ const metadata = p.metadata ?? {};
55
+ if (
56
+ typeof metadata !== "object" ||
57
+ Array.isArray(metadata) ||
58
+ Object.values(metadata).some((v) => typeof v !== "string")
59
+ )
60
+ throw new Error("Invalid provider payout metadata.");
61
+ const result: Infer<typeof snapshot> = {
62
+ ...args,
63
+ amount: p.amount,
64
+ currency: p.currency,
65
+ status: p.status,
66
+ arrivalDate: new Date(p.arrival_date * 1000).toISOString(),
67
+ method: p.method,
68
+ failureCode: p.failure_code ?? undefined,
69
+ failureMessage: p.failure_message ?? undefined,
70
+ metadata,
71
+ };
72
+ validateSnapshot(result);
73
+ return result;
74
+ }
@@ -1,3 +1,9 @@
1
+ import {
2
+ reserveAffiliatePayout,
3
+ completeAffiliatePayout,
4
+ reconcileAffiliatePayout,
5
+ } from "../affiliateRecovery/payoutGate.js";
6
+ import { classifyRecoveryError } from "../affiliateRecovery/provider.js";
1
7
  import type Stripe from "stripe";
2
8
 
3
9
  import type { PayoutStatus } from "../../component/connect/validators.js";
@@ -54,6 +60,8 @@ export async function getAccountBalance(
54
60
  }
55
61
 
56
62
  export type CreatePayoutOptions = {
63
+ /** Host-authorized minimum in the payout currency. */
64
+ minimumAmount?: number;
57
65
  stripeAccountId: string;
58
66
  amount: number;
59
67
  currency?: string;
@@ -64,23 +72,75 @@ export type CreatePayoutOptions = {
64
72
 
65
73
  export async function createPayout(
66
74
  stripe: Stripe,
67
- _ctx: RunCtx,
75
+ ctx: RunCtx,
68
76
  opts: CreatePayoutOptions,
77
+ component?: Component,
69
78
  ) {
70
- const payout = await stripe.payouts.create(
71
- {
72
- amount: opts.amount,
73
- currency: opts.currency ?? "usd",
74
- metadata: opts.metadata ?? undefined,
75
- },
76
- {
77
- stripeAccount: opts.stripeAccountId,
78
- ...(opts.idempotencyKey !== undefined
79
- ? { idempotencyKey: opts.idempotencyKey }
80
- : {}),
81
- },
82
- );
83
- return { stripePayoutId: payout.id };
79
+ const release = component
80
+ ? await reserveAffiliatePayout(component, ctx, opts)
81
+ : null;
82
+ if (release?.state === "submitted")
83
+ return { stripePayoutId: release.stripePayoutId! };
84
+ if (release?.state === "failed")
85
+ throw new Error(
86
+ "Affiliate payout failed; use a new authorized operation key.",
87
+ );
88
+ try {
89
+ if (release) {
90
+ const receiptId = await reconcileAffiliatePayout(stripe, release);
91
+ if (receiptId) {
92
+ await completeAffiliatePayout(
93
+ component!,
94
+ ctx,
95
+ release.operationKey,
96
+ "submitted",
97
+ receiptId,
98
+ );
99
+ return { stripePayoutId: receiptId };
100
+ }
101
+ }
102
+ if (release) {
103
+ if (Date.now() - release.createdAt >= 23 * 60 * 60 * 1000)
104
+ throw new Error(
105
+ "Affiliate payout idempotency window expired; reconcile the provider receipt before retrying.",
106
+ );
107
+ // Receipt lookup may yield while a refund records new debt.
108
+ await reserveAffiliatePayout(component!, ctx, opts);
109
+ }
110
+ const payout = await stripe.payouts.create(
111
+ {
112
+ amount: opts.amount,
113
+ currency: opts.currency ?? "usd",
114
+ metadata: release
115
+ ? { ...opts.metadata, bsAffiliatePayout: release._id }
116
+ : (opts.metadata ?? undefined),
117
+ },
118
+ {
119
+ stripeAccount: opts.stripeAccountId,
120
+ ...(opts.idempotencyKey !== undefined
121
+ ? { idempotencyKey: opts.idempotencyKey }
122
+ : {}),
123
+ },
124
+ );
125
+ if (release)
126
+ await completeAffiliatePayout(
127
+ component!,
128
+ ctx,
129
+ release.operationKey,
130
+ "submitted",
131
+ payout.id,
132
+ );
133
+ return { stripePayoutId: payout.id };
134
+ } catch (error) {
135
+ if (release)
136
+ await completeAffiliatePayout(
137
+ component!,
138
+ ctx,
139
+ release.operationKey,
140
+ classifyRecoveryError(error).state === "unknown" ? "unknown" : "failed",
141
+ );
142
+ throw error;
143
+ }
84
144
  }
85
145
 
86
146
  export async function getPayout(
@@ -0,0 +1,46 @@
1
+ import type Stripe from "stripe";
2
+ import { expect, it } from "vitest";
3
+ import { successfulRefundPrincipal } from "./refundPrincipal.js";
4
+ const provider = (refunds: { amount: number; status: string }[]) =>
5
+ ({
6
+ refunds: {
7
+ list: () =>
8
+ (async function* () {
9
+ yield* refunds;
10
+ })(),
11
+ },
12
+ }) as unknown as Stripe;
13
+ it("excludes pending, failed and canceled refunds from the finalized cumulative principal", async () => {
14
+ expect(
15
+ await successfulRefundPrincipal(
16
+ provider([
17
+ { amount: 100, status: "succeeded" },
18
+ { amount: 200, status: "pending" },
19
+ { amount: 300, status: "failed" },
20
+ { amount: 400, status: "canceled" },
21
+ { amount: 500, status: "succeeded" },
22
+ { amount: 600, status: "requires_action" },
23
+ ]),
24
+ "ch_1",
25
+ ),
26
+ ).toBe(600);
27
+ });
28
+ it("fails closed on invalid money and a refund history beyond the supported bound", async () => {
29
+ await expect(
30
+ successfulRefundPrincipal(
31
+ provider([{ amount: -1, status: "succeeded" }]),
32
+ "ch_1",
33
+ ),
34
+ ).rejects.toThrow("Invalid");
35
+ await expect(
36
+ successfulRefundPrincipal(
37
+ provider(
38
+ Array.from({ length: 1001 }, () => ({
39
+ amount: 1,
40
+ status: "succeeded",
41
+ })),
42
+ ),
43
+ "ch_1",
44
+ ),
45
+ ).rejects.toThrow("limit exceeded");
46
+ });
@@ -0,0 +1,26 @@
1
+ import type Stripe from "stripe";
2
+
3
+ /** Charge.amount_refunded also includes pending refunds; only success is final. */
4
+ export async function successfulRefundPrincipal(
5
+ stripe: Stripe,
6
+ chargeId: string,
7
+ ) {
8
+ let principal = 0;
9
+ let count = 0;
10
+ for await (const refund of stripe.refunds.list({
11
+ charge: chargeId,
12
+ limit: 100,
13
+ })) {
14
+ if (++count > 1000)
15
+ throw new Error("Successful refund lookup limit exceeded.");
16
+ if (refund.status !== "succeeded") continue;
17
+ if (
18
+ !Number.isSafeInteger(refund.amount) ||
19
+ refund.amount < 0 ||
20
+ !Number.isSafeInteger(principal + refund.amount)
21
+ )
22
+ throw new Error("Invalid successful refund principal.");
23
+ principal += refund.amount;
24
+ }
25
+ return principal;
26
+ }
@@ -0,0 +1,130 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { runMutationOrThrow } from "../helpers.js";
4
+ import { componentRef } from "../webhooks/helpers.js";
5
+ import { findCommissionReversal } from "./commissionReceipts.js";
6
+
7
+ export type ClaimedSlice = {
8
+ stripeTransferId: string;
9
+ /** Cumulative reversed amount this slice starts from. */
10
+ from: number;
11
+ /** Cumulative reversed amount this slice raises the leg to. */
12
+ to: number;
13
+ /** The leg's confirmed `reversedAmount` at claim time. */
14
+ confirmed: number;
15
+ commissionTracked?: boolean;
16
+ };
17
+
18
+ export type ReversalClaim = { replay: boolean; slices: ClaimedSlice[] };
19
+
20
+ /**
21
+ * Execute the slices an operation claimed via `claimReversalSlices` (BTS-63).
22
+ * The claim already reserved this money atomically, so all that's left is
23
+ * moving it: one `bs_rev_<operationId>_<transferId>` reversal per slice, then
24
+ * confirming the new cumulative total in the ledger. A replayed claim always
25
+ * re-sends byte-identical params under the same key, which Stripe answers
26
+ * from its idempotency cache without moving money twice.
27
+ *
28
+ * Because Stripe prunes idempotency keys after ~24h (and a crash can land
29
+ * between the Stripe call and the ledger confirm), a replay first checks the
30
+ * transfer's live `amount_reversed`: if the slice's money already moved, it
31
+ * just confirms the ledger instead of re-sending the reversal.
32
+ *
33
+ * A slice only executes once every predecessor slice on its leg is confirmed
34
+ * (`confirmed ≥ from`). Without that gate, a sibling operation landing behind
35
+ * a transiently-failed claim would execute and confirm PAST the hole; the
36
+ * failed operation's retry would then see `confirmed ≥ to` and silently skip
37
+ * — its money would never move while the ledger says it did. Throwing instead
38
+ * fails this operation's webhook event, and at-least-once delivery retries
39
+ * both operations until the predecessor fills its hole and each claimed slice
40
+ * has actually moved. The ledger's `reversedAmount` therefore always covers a
41
+ * solid, hole-free prefix of the reversed axis — which is exactly what makes
42
+ * the `confirmed`/`amount_reversed` checks above sound.
43
+ */
44
+ export async function executeClaimedSlices(
45
+ stripe: Stripe,
46
+ component: Component,
47
+ ctx: RunCtx,
48
+ operationId: string,
49
+ claim: ReversalClaim,
50
+ ): Promise<{ reversals: { stripeTransferId: string; amount: number }[] }> {
51
+ const reversals: { stripeTransferId: string; amount: number }[] = [];
52
+ for (const slice of claim.slices) {
53
+ const receiptAmount = slice.to - slice.from;
54
+ if (slice.commissionTracked && claim.replay) {
55
+ const receipt = await findCommissionReversal(
56
+ stripe,
57
+ slice.stripeTransferId,
58
+ operationId,
59
+ receiptAmount,
60
+ );
61
+ if (receipt) {
62
+ await runMutationOrThrow(
63
+ ctx,
64
+ componentRef(component, "connect/mutations/recordTransferReversal"),
65
+ {
66
+ stripeTransferId: slice.stripeTransferId,
67
+ reversedAmount: slice.to,
68
+ receipt: {
69
+ stripeReversalId: receipt.id,
70
+ operationId,
71
+ amount: receiptAmount,
72
+ },
73
+ },
74
+ );
75
+ continue;
76
+ }
77
+ if (slice.confirmed >= slice.to)
78
+ throw new Error("Commission reversal requires receipt reconciliation.");
79
+ }
80
+ if (slice.confirmed >= slice.to) continue; // executed and recorded already
81
+
82
+ if (slice.confirmed < slice.from) {
83
+ throw new Error(
84
+ `reversal slice [${slice.from},${slice.to}) on ${slice.stripeTransferId} ` +
85
+ `blocked: predecessor claim unexecuted (confirmed=${slice.confirmed})`,
86
+ );
87
+ }
88
+
89
+ if (claim.replay && !slice.commissionTracked) {
90
+ const transfer = await stripe.transfers.retrieve(slice.stripeTransferId);
91
+ if ((transfer.amount_reversed ?? 0) >= slice.to) {
92
+ // The money moved on a previous attempt that died before confirming.
93
+ await runMutationOrThrow(
94
+ ctx,
95
+ componentRef(component, "connect/mutations/recordTransferReversal"),
96
+ {
97
+ stripeTransferId: slice.stripeTransferId,
98
+ reversedAmount: slice.to,
99
+ },
100
+ );
101
+ continue;
102
+ }
103
+ }
104
+
105
+ const amount = slice.to - slice.from;
106
+ const receipt = await stripe.transfers.createReversal(
107
+ slice.stripeTransferId,
108
+ {
109
+ amount,
110
+ ...(slice.commissionTracked
111
+ ? { metadata: { bsReversalOperation: operationId } }
112
+ : {}),
113
+ },
114
+ { idempotencyKey: `bs_rev_${operationId}_${slice.stripeTransferId}` },
115
+ );
116
+ await runMutationOrThrow(
117
+ ctx,
118
+ componentRef(component, "connect/mutations/recordTransferReversal"),
119
+ {
120
+ stripeTransferId: slice.stripeTransferId,
121
+ reversedAmount: slice.to,
122
+ ...(slice.commissionTracked
123
+ ? { receipt: { stripeReversalId: receipt.id, operationId, amount } }
124
+ : {}),
125
+ },
126
+ );
127
+ reversals.push({ stripeTransferId: slice.stripeTransferId, amount });
128
+ }
129
+ return { reversals };
130
+ }
@@ -350,8 +350,8 @@ describe("createSplitTransfers engine (BTS-22)", () => {
350
350
  destination: "acct_aff",
351
351
  });
352
352
  // ledger rows
353
- expect(ctx.runMutation).toHaveBeenCalledTimes(3);
354
- expect(ctx.runMutation.mock.calls[1][1]).toMatchObject({
353
+ expect(ctx.runMutation).toHaveBeenCalledTimes(4);
354
+ expect(ctx.runMutation.mock.calls[2][1]).toMatchObject({
355
355
  sourceChargeId: "ch_1",
356
356
  destinationAccountId: "acct_store",
357
357
  amount: 8000,
@@ -380,7 +380,7 @@ describe("createSplitTransfers engine (BTS-22)", () => {
380
380
  });
381
381
 
382
382
  expect(stripe.transfers.create).toHaveBeenCalledTimes(3);
383
- expect(ctx.runMutation).toHaveBeenCalledTimes(4);
383
+ expect(ctx.runMutation).toHaveBeenCalledTimes(5);
384
384
  });
385
385
 
386
386
  it("skips zero-amount transfers", async () => {