@fantastic.dev/better-stripe 0.23.2 → 0.25.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 (358) hide show
  1. package/CHANGELOG.md +27 -2
  2. package/README.md +46 -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/billing/checkout.d.ts +3 -43
  32. package/dist/client/billing/checkout.d.ts.map +1 -1
  33. package/dist/client/billing/checkout.js +5 -260
  34. package/dist/client/billing/checkout.js.map +1 -1
  35. package/dist/client/billing/checkoutRequest.d.ts +129 -0
  36. package/dist/client/billing/checkoutRequest.d.ts.map +1 -0
  37. package/dist/client/billing/checkoutRequest.js +263 -0
  38. package/dist/client/billing/checkoutRequest.js.map +1 -0
  39. package/dist/client/billing/preparedCheckout.d.ts +22 -0
  40. package/dist/client/billing/preparedCheckout.d.ts.map +1 -0
  41. package/dist/client/billing/preparedCheckout.js +86 -0
  42. package/dist/client/billing/preparedCheckout.js.map +1 -0
  43. package/dist/client/checkoutRequests.d.ts +80 -0
  44. package/dist/client/checkoutRequests.d.ts.map +1 -0
  45. package/dist/client/checkoutRequests.js +28 -0
  46. package/dist/client/checkoutRequests.js.map +1 -0
  47. package/dist/client/connect/commissionReceipts.d.ts +4 -0
  48. package/dist/client/connect/commissionReceipts.d.ts.map +1 -0
  49. package/dist/client/connect/commissionReceipts.js +17 -0
  50. package/dist/client/connect/commissionReceipts.js.map +1 -0
  51. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +958 -2
  52. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  53. package/dist/client/connect/payoutCollection.d.ts +21 -0
  54. package/dist/client/connect/payoutCollection.d.ts.map +1 -0
  55. package/dist/client/connect/payoutCollection.js +47 -0
  56. package/dist/client/connect/payoutCollection.js.map +1 -0
  57. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +1805 -0
  58. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -0
  59. package/dist/client/connect/payoutExecutionTestHelpers.js +194 -0
  60. package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -0
  61. package/dist/client/connect/payoutSyncTestHelpers.d.ts +479 -1
  62. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  63. package/dist/client/connect/payoutWorker.d.ts +48 -0
  64. package/dist/client/connect/payoutWorker.d.ts.map +1 -0
  65. package/dist/client/connect/payoutWorker.js +78 -0
  66. package/dist/client/connect/payoutWorker.js.map +1 -0
  67. package/dist/client/connect/payouts.d.ts +3 -1
  68. package/dist/client/connect/payouts.d.ts.map +1 -1
  69. package/dist/client/connect/payouts.js +45 -12
  70. package/dist/client/connect/payouts.js.map +1 -1
  71. package/dist/client/connect/refundPrincipal.d.ts +4 -0
  72. package/dist/client/connect/refundPrincipal.d.ts.map +1 -0
  73. package/dist/client/connect/refundPrincipal.js +21 -0
  74. package/dist/client/connect/refundPrincipal.js.map +1 -0
  75. package/dist/client/connect/reversalExecution.d.ts +47 -0
  76. package/dist/client/connect/reversalExecution.d.ts.map +1 -0
  77. package/dist/client/connect/reversalExecution.js +84 -0
  78. package/dist/client/connect/reversalExecution.js.map +1 -0
  79. package/dist/client/connect/transfers.d.ts +8 -4
  80. package/dist/client/connect/transfers.d.ts.map +1 -1
  81. package/dist/client/connect/transfers.js +52 -57
  82. package/dist/client/connect/transfers.js.map +1 -1
  83. package/dist/client/index.d.ts +7 -11
  84. package/dist/client/index.d.ts.map +1 -1
  85. package/dist/client/index.js +10 -10
  86. package/dist/client/index.js.map +1 -1
  87. package/dist/client/payoutPolicy.d.ts +67 -0
  88. package/dist/client/payoutPolicy.d.ts.map +1 -1
  89. package/dist/client/payoutPolicy.js +10 -0
  90. package/dist/client/payoutPolicy.js.map +1 -1
  91. package/dist/client/readContracts.d.ts +11 -1
  92. package/dist/client/readContracts.d.ts.map +1 -1
  93. package/dist/client/readContracts.js +10 -0
  94. package/dist/client/readContracts.js.map +1 -1
  95. package/dist/client/settlement/execution.d.ts.map +1 -1
  96. package/dist/client/settlement/execution.js +30 -3
  97. package/dist/client/settlement/execution.js.map +1 -1
  98. package/dist/client/settlement/reconciliation.d.ts.map +1 -1
  99. package/dist/client/settlement/reconciliation.js +16 -2
  100. package/dist/client/settlement/reconciliation.js.map +1 -1
  101. package/dist/client/webhooks/disputeRecovery.d.ts +4 -0
  102. package/dist/client/webhooks/disputeRecovery.d.ts.map +1 -0
  103. package/dist/client/webhooks/disputeRecovery.js +40 -0
  104. package/dist/client/webhooks/disputeRecovery.js.map +1 -0
  105. package/dist/client/webhooks/processors.d.ts.map +1 -1
  106. package/dist/client/webhooks/processors.js +14 -29
  107. package/dist/client/webhooks/processors.js.map +1 -1
  108. package/dist/component/_generated/component.d.ts +784 -0
  109. package/dist/component/_generated/component.d.ts.map +1 -1
  110. package/dist/component/affiliateEarnings/mutations.d.ts +22 -0
  111. package/dist/component/affiliateEarnings/mutations.d.ts.map +1 -0
  112. package/dist/component/affiliateEarnings/mutations.js +160 -0
  113. package/dist/component/affiliateEarnings/mutations.js.map +1 -0
  114. package/dist/component/affiliatePayouts/mutations.d.ts +25 -0
  115. package/dist/component/affiliatePayouts/mutations.d.ts.map +1 -0
  116. package/dist/component/affiliatePayouts/mutations.js +104 -0
  117. package/dist/component/affiliatePayouts/mutations.js.map +1 -0
  118. package/dist/component/affiliatePayouts/queries.d.ts +23 -0
  119. package/dist/component/affiliatePayouts/queries.d.ts.map +1 -0
  120. package/dist/component/affiliatePayouts/queries.js +23 -0
  121. package/dist/component/affiliatePayouts/queries.js.map +1 -0
  122. package/dist/component/affiliatePayouts/recipientGuard.d.ts +12 -0
  123. package/dist/component/affiliatePayouts/recipientGuard.d.ts.map +1 -0
  124. package/dist/component/affiliatePayouts/recipientGuard.js +26 -0
  125. package/dist/component/affiliatePayouts/recipientGuard.js.map +1 -0
  126. package/dist/component/affiliateRecovery/accounting.d.ts +28 -0
  127. package/dist/component/affiliateRecovery/accounting.d.ts.map +1 -0
  128. package/dist/component/affiliateRecovery/accounting.js +71 -0
  129. package/dist/component/affiliateRecovery/accounting.js.map +1 -0
  130. package/dist/component/affiliateRecovery/mutations.d.ts +65 -0
  131. package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -0
  132. package/dist/component/affiliateRecovery/mutations.js +250 -0
  133. package/dist/component/affiliateRecovery/mutations.js.map +1 -0
  134. package/dist/component/affiliateRecovery/queries.d.ts +305 -0
  135. package/dist/component/affiliateRecovery/queries.d.ts.map +1 -0
  136. package/dist/component/affiliateRecovery/queries.js +113 -0
  137. package/dist/component/affiliateRecovery/queries.js.map +1 -0
  138. package/dist/component/affiliateRecovery/schema.d.ts +171 -0
  139. package/dist/component/affiliateRecovery/schema.d.ts.map +1 -0
  140. package/dist/component/affiliateRecovery/schema.js +71 -0
  141. package/dist/component/affiliateRecovery/schema.js.map +1 -0
  142. package/dist/component/connect/mutations.d.ts +36 -23
  143. package/dist/component/connect/mutations.d.ts.map +1 -1
  144. package/dist/component/connect/mutations.js +7 -124
  145. package/dist/component/connect/mutations.js.map +1 -1
  146. package/dist/component/connect/queries.d.ts +10 -0
  147. package/dist/component/connect/queries.d.ts.map +1 -1
  148. package/dist/component/connect/queries.js +3 -40
  149. package/dist/component/connect/queries.js.map +1 -1
  150. package/dist/component/connect/reversalClaims.d.ts +169 -0
  151. package/dist/component/connect/reversalClaims.d.ts.map +1 -0
  152. package/dist/component/connect/reversalClaims.js +176 -0
  153. package/dist/component/connect/reversalClaims.js.map +1 -0
  154. package/dist/component/connect/reversalDiagnostics.d.ts +59 -0
  155. package/dist/component/connect/reversalDiagnostics.d.ts.map +1 -0
  156. package/dist/component/connect/reversalDiagnostics.js +50 -0
  157. package/dist/component/connect/reversalDiagnostics.js.map +1 -0
  158. package/dist/component/connect/reversalReceipts.d.ts +27 -0
  159. package/dist/component/connect/reversalReceipts.d.ts.map +1 -0
  160. package/dist/component/connect/reversalReceipts.js +85 -0
  161. package/dist/component/connect/reversalReceipts.js.map +1 -0
  162. package/dist/component/connect/schema.d.ts +31 -1
  163. package/dist/component/connect/schema.d.ts.map +1 -1
  164. package/dist/component/connect/schema.js +3 -1
  165. package/dist/component/connect/schema.js.map +1 -1
  166. package/dist/component/connect/validators.d.ts +49 -1
  167. package/dist/component/connect/validators.d.ts.map +1 -1
  168. package/dist/component/connect/validators.js +2 -0
  169. package/dist/component/connect/validators.js.map +1 -1
  170. package/dist/component/core/mutations.d.ts.map +1 -1
  171. package/dist/component/core/mutations.js +2 -0
  172. package/dist/component/core/mutations.js.map +1 -1
  173. package/dist/component/core/resetSafety.d.ts +4 -0
  174. package/dist/component/core/resetSafety.d.ts.map +1 -0
  175. package/dist/component/core/resetSafety.js +54 -0
  176. package/dist/component/core/resetSafety.js.map +1 -0
  177. package/dist/component/earnings/triggers.d.ts +828 -2
  178. package/dist/component/earnings/triggers.d.ts.map +1 -1
  179. package/dist/component/earnings/triggers.js +2 -0
  180. package/dist/component/earnings/triggers.js.map +1 -1
  181. package/dist/component/payoutPolicy/schema.d.ts +2 -0
  182. package/dist/component/payoutPolicy/schema.d.ts.map +1 -1
  183. package/dist/component/payoutPolicy/schema.js +3 -1
  184. package/dist/component/payoutPolicy/schema.js.map +1 -1
  185. package/dist/component/payoutRelease/mutations.d.ts.map +1 -1
  186. package/dist/component/payoutRelease/mutations.js +7 -1
  187. package/dist/component/payoutRelease/mutations.js.map +1 -1
  188. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  189. package/dist/component/payoutRelease/queries.js +3 -1
  190. package/dist/component/payoutRelease/queries.js.map +1 -1
  191. package/dist/component/payoutRelease/schema.d.ts +1 -0
  192. package/dist/component/payoutRelease/schema.d.ts.map +1 -1
  193. package/dist/component/payoutRelease/schema.js +1 -0
  194. package/dist/component/payoutRelease/schema.js.map +1 -1
  195. package/dist/component/payoutSnapshots/localState.d.ts +89 -0
  196. package/dist/component/payoutSnapshots/localState.d.ts.map +1 -0
  197. package/dist/component/payoutSnapshots/localState.js +186 -0
  198. package/dist/component/payoutSnapshots/localState.js.map +1 -0
  199. package/dist/component/payoutSnapshots/mutations.d.ts +108 -0
  200. package/dist/component/payoutSnapshots/mutations.d.ts.map +1 -0
  201. package/dist/component/payoutSnapshots/mutations.js +263 -0
  202. package/dist/component/payoutSnapshots/mutations.js.map +1 -0
  203. package/dist/component/payoutSnapshots/revisions.d.ts +12 -0
  204. package/dist/component/payoutSnapshots/revisions.d.ts.map +1 -0
  205. package/dist/component/payoutSnapshots/revisions.js +173 -0
  206. package/dist/component/payoutSnapshots/revisions.js.map +1 -0
  207. package/dist/component/payoutSnapshots/schema.d.ts +285 -0
  208. package/dist/component/payoutSnapshots/schema.d.ts.map +1 -0
  209. package/dist/component/payoutSnapshots/schema.js +108 -0
  210. package/dist/component/payoutSnapshots/schema.js.map +1 -0
  211. package/dist/component/payoutSnapshots/scope.d.ts +7 -0
  212. package/dist/component/payoutSnapshots/scope.d.ts.map +1 -0
  213. package/dist/component/payoutSnapshots/scope.js +8 -0
  214. package/dist/component/payoutSnapshots/scope.js.map +1 -0
  215. package/dist/component/payoutWorker/helpers.d.ts +30 -0
  216. package/dist/component/payoutWorker/helpers.d.ts.map +1 -0
  217. package/dist/component/payoutWorker/helpers.js +21 -0
  218. package/dist/component/payoutWorker/helpers.js.map +1 -0
  219. package/dist/component/payoutWorker/mutations.d.ts +68 -0
  220. package/dist/component/payoutWorker/mutations.d.ts.map +1 -0
  221. package/dist/component/payoutWorker/mutations.js +161 -0
  222. package/dist/component/payoutWorker/mutations.js.map +1 -0
  223. package/dist/component/payoutWorker/queries.d.ts +123 -0
  224. package/dist/component/payoutWorker/queries.d.ts.map +1 -0
  225. package/dist/component/payoutWorker/queries.js +61 -0
  226. package/dist/component/payoutWorker/queries.js.map +1 -0
  227. package/dist/component/payoutWorker/schema.d.ts +91 -0
  228. package/dist/component/payoutWorker/schema.d.ts.map +1 -0
  229. package/dist/component/payoutWorker/schema.js +27 -0
  230. package/dist/component/payoutWorker/schema.js.map +1 -0
  231. package/dist/component/schema.d.ts +479 -1
  232. package/dist/component/schema.js +19 -0
  233. package/dist/component/schema.js.map +1 -1
  234. package/dist/component/settlement/clawbackSchema.d.ts +161 -0
  235. package/dist/component/settlement/clawbackSchema.d.ts.map +1 -0
  236. package/dist/component/settlement/clawbackSchema.js +73 -0
  237. package/dist/component/settlement/clawbackSchema.js.map +1 -0
  238. package/dist/component/settlement/clawbacks.d.ts +55 -0
  239. package/dist/component/settlement/clawbacks.d.ts.map +1 -0
  240. package/dist/component/settlement/clawbacks.js +146 -0
  241. package/dist/component/settlement/clawbacks.js.map +1 -0
  242. package/dist/component/settlement/mutations.d.ts +16 -0
  243. package/dist/component/settlement/mutations.d.ts.map +1 -1
  244. package/dist/component/settlement/mutations.js +48 -0
  245. package/dist/component/settlement/mutations.js.map +1 -1
  246. package/dist/component/settlement/queries.d.ts +53 -0
  247. package/dist/component/settlement/queries.d.ts.map +1 -1
  248. package/dist/component/settlement/queries.js +26 -0
  249. package/dist/component/settlement/queries.js.map +1 -1
  250. package/dist/react/workflows/AffiliateRecovery.d.ts +46 -0
  251. package/dist/react/workflows/AffiliateRecovery.d.ts.map +1 -0
  252. package/dist/react/workflows/AffiliateRecovery.js +84 -0
  253. package/dist/react/workflows/AffiliateRecovery.js.map +1 -0
  254. package/dist/react/workflows/index.d.ts +2 -0
  255. package/dist/react/workflows/index.d.ts.map +1 -1
  256. package/dist/react/workflows/index.js +1 -0
  257. package/dist/react/workflows/index.js.map +1 -1
  258. package/dist/testing/affiliate-recovery.d.ts +10 -0
  259. package/dist/testing/affiliate-recovery.d.ts.map +1 -0
  260. package/dist/testing/affiliate-recovery.js +126 -0
  261. package/dist/testing/affiliate-recovery.js.map +1 -0
  262. package/dist/testing/index.d.ts +2 -0
  263. package/dist/testing/index.d.ts.map +1 -1
  264. package/dist/testing/index.js +1 -0
  265. package/dist/testing/index.js.map +1 -1
  266. package/docs/affiliate-clawbacks.md +306 -0
  267. package/docs/read-contracts.md +48 -0
  268. package/docs/settlement.md +145 -1
  269. package/package.json +2 -1
  270. package/src/client/affiliateRecovery/disputes.ts +62 -0
  271. package/src/client/affiliateRecovery/engine.ts +196 -0
  272. package/src/client/affiliateRecovery/payoutGate.ts +65 -0
  273. package/src/client/affiliateRecovery/provider.ts +127 -0
  274. package/src/client/affiliateRecovery/review.ts +117 -0
  275. package/src/client/affiliateRecovery/validators.ts +38 -0
  276. package/src/client/affiliateRecovery.ts +173 -0
  277. package/src/client/billing/checkout.ts +11 -359
  278. package/src/client/billing/checkoutRequest.ts +362 -0
  279. package/src/client/billing/prepared-checkout.test.ts +430 -0
  280. package/src/client/billing/preparedCheckout.ts +143 -0
  281. package/src/client/checkoutRequests.ts +40 -0
  282. package/src/client/connect/commissionReceipts.test.ts +157 -0
  283. package/src/client/connect/commissionReceipts.ts +23 -0
  284. package/src/client/connect/payoutCollection.test.ts +74 -0
  285. package/src/client/connect/payoutCollection.ts +82 -0
  286. package/src/client/connect/payoutExecution.test.ts +1 -211
  287. package/src/client/connect/payoutExecutionTestHelpers.ts +213 -0
  288. package/src/client/connect/payoutWorker.test.ts +145 -0
  289. package/src/client/connect/payoutWorker.ts +144 -0
  290. package/src/client/connect/payouts.ts +75 -15
  291. package/src/client/connect/refundPrincipal.test.ts +46 -0
  292. package/src/client/connect/refundPrincipal.ts +26 -0
  293. package/src/client/connect/reversalExecution.ts +130 -0
  294. package/src/client/connect/transfers.test.ts +3 -3
  295. package/src/client/connect/transfers.ts +93 -92
  296. package/src/client/index.ts +16 -28
  297. package/src/client/payoutPolicy.ts +26 -1
  298. package/src/client/readContracts.ts +23 -0
  299. package/src/client/settlement/execution.test.ts +5 -0
  300. package/src/client/settlement/execution.ts +50 -3
  301. package/src/client/settlement/reconciliation.ts +20 -2
  302. package/src/client/webhooks/disputeRecovery.ts +74 -0
  303. package/src/client/webhooks/processors.test.ts +36 -53
  304. package/src/client/webhooks/processors.ts +18 -31
  305. package/src/component/_generated/api.ts +40 -0
  306. package/src/component/_generated/component.ts +975 -1
  307. package/src/component/affiliate-clawbacks.test.ts +370 -0
  308. package/src/component/affiliate-component-pagination.test.ts +83 -0
  309. package/src/component/affiliate-direct-payout.test.ts +160 -0
  310. package/src/component/affiliate-recovery-lifecycle.test.ts +587 -0
  311. package/src/component/affiliateEarnings/mutations.ts +196 -0
  312. package/src/component/affiliatePayouts/mutations.ts +121 -0
  313. package/src/component/affiliatePayouts/queries.ts +28 -0
  314. package/src/component/affiliatePayouts/recipientGuard.ts +42 -0
  315. package/src/component/affiliateRecovery/accounting.ts +111 -0
  316. package/src/component/affiliateRecovery/mutations.ts +275 -0
  317. package/src/component/affiliateRecovery/queries.ts +138 -0
  318. package/src/component/affiliateRecovery/schema.ts +86 -0
  319. package/src/component/connect/mutations.ts +9 -160
  320. package/src/component/connect/queries.ts +4 -47
  321. package/src/component/connect/reversalClaims.ts +232 -0
  322. package/src/component/connect/reversalDiagnostics.ts +61 -0
  323. package/src/component/connect/reversalReceipts.ts +147 -0
  324. package/src/component/connect/schema.ts +3 -3
  325. package/src/component/connect/validators.ts +2 -0
  326. package/src/component/core/mutations.ts +2 -0
  327. package/src/component/core/resetSafety.ts +67 -0
  328. package/src/component/earnings/triggers.ts +2 -0
  329. package/src/component/payout-recovery-integration.test.ts +172 -0
  330. package/src/component/payout-reset-safety.test.ts +148 -0
  331. package/src/component/payout-revisions.test.ts +125 -0
  332. package/src/component/payout-snapshots.test.ts +395 -0
  333. package/src/component/payout-worker.test.ts +165 -0
  334. package/src/component/payoutPolicy/schema.ts +3 -1
  335. package/src/component/payoutRelease/mutations.ts +10 -1
  336. package/src/component/payoutRelease/queries.ts +3 -1
  337. package/src/component/payoutRelease/schema.ts +1 -0
  338. package/src/component/payoutSnapshots/localState.ts +238 -0
  339. package/src/component/payoutSnapshots/mutations.ts +275 -0
  340. package/src/component/payoutSnapshots/revisions.ts +247 -0
  341. package/src/component/payoutSnapshots/schema.ts +125 -0
  342. package/src/component/payoutSnapshots/scope.ts +7 -0
  343. package/src/component/payoutWorker/helpers.ts +30 -0
  344. package/src/component/payoutWorker/mutations.ts +181 -0
  345. package/src/component/payoutWorker/queries.ts +64 -0
  346. package/src/component/payoutWorker/schema.ts +26 -0
  347. package/src/component/public.test.ts +2 -2
  348. package/src/component/schema.ts +36 -0
  349. package/src/component/settlement/clawbackSchema.ts +78 -0
  350. package/src/component/settlement/clawbacks.ts +233 -0
  351. package/src/component/settlement/mutations.ts +54 -0
  352. package/src/component/settlement/queries.ts +35 -0
  353. package/src/component/summary-arithmetic.test.ts +9 -4
  354. package/src/react/workflows/AffiliateRecovery.test.tsx +106 -0
  355. package/src/react/workflows/AffiliateRecovery.tsx +273 -0
  356. package/src/react/workflows/index.ts +9 -0
  357. package/src/testing/affiliate-recovery.ts +137 -0
  358. package/src/testing/index.ts +2 -0
@@ -0,0 +1,213 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { vi } from "vitest";
5
+ import type Stripe from "stripe";
6
+ import schema from "../../component/schema.js";
7
+ import type { Component, RunCtx } from "../helpers.js";
8
+ import { releaseRecipientPayout } from "./payoutExecution.js";
9
+ const modules = import.meta.glob("../../component/**/*.*s");
10
+ const symbol = Symbol.for("toReferencePath");
11
+ export const component = {
12
+ payoutPolicy: {
13
+ queries: { get: { [symbol]: "betterStripe/payoutPolicy/queries/get" } },
14
+ },
15
+ } as unknown as Component;
16
+ export const scope = {
17
+ accountId: "acct_recipient",
18
+ ownerKey: "owner",
19
+ operationKey: "release-1",
20
+ currency: "usd",
21
+ independentLiabilities: 0,
22
+ };
23
+ export async function setup(amounts = [600, 400]) {
24
+ const t = convexTest(schema, modules);
25
+ await t.run(async (ctx) => {
26
+ await ctx.db.insert("payoutPolicies", {
27
+ accountId: scope.accountId,
28
+ ownerKey: scope.ownerKey,
29
+ mode: "custom",
30
+ status: "ready",
31
+ revision: 0,
32
+ operationKey: "enable",
33
+ country: "US",
34
+ thresholds: [{ currency: "usd", amount: 1000 }],
35
+ holdDeadline: Date.now() + 86400000,
36
+ });
37
+ for (let i = 0; i < amounts.length; i++)
38
+ await ctx.db.insert("transfers", {
39
+ stripeTransferId: `tr_${i}`,
40
+ destinationAccountId: scope.accountId,
41
+ sourceChargeId: `ch_${i}`,
42
+ amount: amounts[i],
43
+ currency: "usd",
44
+ status: "paid",
45
+ role: i % 2 ? "affiliate" : "store",
46
+ });
47
+ });
48
+ const path = (ref: Record<symbol, string>) =>
49
+ ref[symbol].replace("betterStripe/", "").replace(/\/(\w+)$/, ":$1");
50
+ const ctx = {
51
+ runQuery: (ref: Record<symbol, string>, args: never) =>
52
+ t.query(makeFunctionReference<"query">(path(ref)), args),
53
+ runMutation: (ref: Record<symbol, string>, args: never) =>
54
+ t.mutation(makeFunctionReference<"mutation">(path(ref)), args),
55
+ } as unknown as RunCtx;
56
+ let transactions = amounts.map((amount, i) => ({
57
+ id: `txn_${i}`,
58
+ source: `py_${i}`,
59
+ amount,
60
+ fee: 0,
61
+ net: amount,
62
+ currency: "usd",
63
+ created: 100,
64
+ available_on: 200,
65
+ status: "available",
66
+ type: "payment",
67
+ exchange_rate: null,
68
+ }));
69
+ let payout: Record<string, unknown> | undefined;
70
+ const provider = {
71
+ accounts: {
72
+ listExternalAccounts: vi.fn(async () => ({
73
+ data: [
74
+ {
75
+ id: "ba_one",
76
+ object: "bank_account",
77
+ currency: "usd",
78
+ default_for_currency: true,
79
+ },
80
+ ],
81
+ has_more: false,
82
+ })),
83
+ },
84
+ transfers: {
85
+ retrieve: vi.fn(async (id: string) => {
86
+ const i = Number(id.slice(3));
87
+ return {
88
+ id,
89
+ destination: scope.accountId,
90
+ destination_payment: `py_${i}`,
91
+ source_transaction: `ch_${i}`,
92
+ amount: amounts[i],
93
+ currency: "usd",
94
+ amount_reversed: 0,
95
+ };
96
+ }),
97
+ listReversals: vi.fn(async () => ({ data: [], has_more: false })),
98
+ },
99
+ charges: {
100
+ retrieve: vi.fn(async (id: string) => {
101
+ const i = Number(id.slice(3));
102
+ return {
103
+ id,
104
+ source_transfer: `tr_${i}`,
105
+ amount: amounts[i],
106
+ currency: "usd",
107
+ paid: true,
108
+ status: "succeeded",
109
+ balance_transaction: `txn_${i}`,
110
+ };
111
+ }),
112
+ },
113
+ balanceTransactions: {
114
+ list: vi.fn(async (params: { source?: string; limit?: number }) => ({
115
+ data: params.source
116
+ ? transactions.filter((t) => t.source === params.source)
117
+ : transactions.slice(0, params.limit),
118
+ has_more: false,
119
+ })),
120
+ retrieve: vi.fn(async (id: string) =>
121
+ transactions.find((t) => t.id === id),
122
+ ),
123
+ },
124
+ balance: {
125
+ retrieve: vi.fn(async () => ({
126
+ available: [
127
+ {
128
+ currency: "usd",
129
+ amount: transactions
130
+ .filter((t) => t.status === "available")
131
+ .reduce((a, t) => a + t.net, 0),
132
+ source_types: {
133
+ card: transactions
134
+ .filter((t) => t.status === "available")
135
+ .reduce((a, t) => a + t.net, 0),
136
+ },
137
+ },
138
+ ],
139
+ pending: [],
140
+ })),
141
+ },
142
+ payouts: {
143
+ list: vi.fn(async () => ({
144
+ data: payout ? [payout] : [],
145
+ has_more: false,
146
+ })),
147
+ retrieve: vi.fn(async () => payout),
148
+ create: vi.fn(
149
+ async (params: {
150
+ amount: number;
151
+ currency: string;
152
+ metadata: object;
153
+ }) => {
154
+ payout = {
155
+ id: "po_one",
156
+ ...params,
157
+ status: "paid",
158
+ automatic: false,
159
+ method: "standard",
160
+ type: "bank_account",
161
+ source_type: "card",
162
+ destination: "ba_one",
163
+ created: Math.floor(Date.now() / 1000),
164
+ arrival_date: Math.floor(Date.now() / 1000),
165
+ balance_transaction: "txn_debit",
166
+ failure_balance_transaction: null,
167
+ reversed_by: null,
168
+ };
169
+ transactions = [
170
+ {
171
+ id: "txn_debit",
172
+ source: "po_one",
173
+ amount: -params.amount,
174
+ fee: 0,
175
+ net: -params.amount,
176
+ currency: "usd",
177
+ created: Math.floor(Date.now() / 1000),
178
+ available_on: Math.floor(Date.now() / 1000),
179
+ status: "available",
180
+ type: "payout",
181
+ exchange_rate: null,
182
+ },
183
+ ...transactions,
184
+ ];
185
+ return payout;
186
+ },
187
+ ),
188
+ },
189
+ };
190
+ const verify = vi.fn(async () => ({
191
+ status: "verified" as const,
192
+ policy: (await t.run((ctx) => ctx.db.query("payoutPolicies").first()))!,
193
+ }));
194
+ const run = (extra = {}) =>
195
+ releaseRecipientPayout(
196
+ provider as unknown as Stripe,
197
+ component,
198
+ ctx,
199
+ { ...scope, ...extra },
200
+ verify,
201
+ );
202
+ return {
203
+ t,
204
+ ctx,
205
+ provider,
206
+ verify,
207
+ run,
208
+ setTransactions: (rows: typeof transactions) => {
209
+ transactions = rows;
210
+ },
211
+ transactions: () => transactions,
212
+ };
213
+ }
@@ -0,0 +1,145 @@
1
+ // @vitest-environment edge-runtime
2
+ import { afterEach, expect, it, vi } from "vitest";
3
+ import type Stripe from "stripe";
4
+ import { setup, scope, component } from "./payoutExecutionTestHelpers.js";
5
+ import { reconcileRecipientPayout } from "./payoutReconciliation.js";
6
+ import { PayoutWorkerClient } from "./payoutWorker.js";
7
+ import { changeBalance } from "../../component/affiliateRecovery/accounting.js";
8
+ afterEach(() => vi.useRealTimers());
9
+ async function worker(amounts?: number[]) {
10
+ const s = await setup(amounts);
11
+ const client = new PayoutWorkerClient(
12
+ component,
13
+ (_ctx, opts) => s.run(opts),
14
+ (_ctx, opts) =>
15
+ reconcileRecipientPayout(
16
+ s.provider as unknown as Stripe,
17
+ component,
18
+ s.ctx,
19
+ opts,
20
+ ),
21
+ );
22
+ const run = () => client.run(s.ctx, scope);
23
+ return { ...s, client, run };
24
+ }
25
+ it("the recurring worker releases combined money once, records its result and waits for the next attempt", async () => {
26
+ const s = await worker();
27
+ expect(await s.run()).toMatchObject({
28
+ status: "completed",
29
+ job: { lastReason: "paid", hasOperation: false },
30
+ payout: { claim: { amount: 1000, status: "paid" } },
31
+ });
32
+ expect(await s.run()).toMatchObject({ status: "held", reason: "not_due" });
33
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
34
+ const state = await s.client.get(s.ctx, scope);
35
+ expect(state?.nextAttemptAt).toBeGreaterThan(Date.now());
36
+ });
37
+ it("the next recurring attempt carries below-minimum balances and pays when new funding qualifies", async () => {
38
+ vi.useFakeTimers();
39
+ const amounts = [599, 400];
40
+ const s = await worker(amounts);
41
+ expect(await s.run()).toMatchObject({
42
+ payout: { status: "held", reason: "below_threshold", matureUnpaid: 999 },
43
+ });
44
+ vi.advanceTimersByTime(300000);
45
+ expect(await s.run()).toMatchObject({
46
+ payout: { reason: "below_threshold" },
47
+ });
48
+ expect(s.provider.payouts.create).not.toHaveBeenCalled();
49
+ amounts.push(1);
50
+ await s.t.run((ctx) =>
51
+ ctx.db.insert("transfers", {
52
+ stripeTransferId: "tr_2",
53
+ destinationAccountId: scope.accountId,
54
+ sourceChargeId: "ch_2",
55
+ amount: 1,
56
+ currency: "usd",
57
+ status: "paid",
58
+ role: "affiliate",
59
+ }),
60
+ );
61
+ s.setTransactions([
62
+ ...s.transactions(),
63
+ {
64
+ ...s.transactions()[0],
65
+ id: "txn_2",
66
+ source: "py_2",
67
+ amount: 1,
68
+ net: 1,
69
+ },
70
+ ]);
71
+ vi.advanceTimersByTime(300000);
72
+ expect(await s.run()).toMatchObject({
73
+ payout: { claim: { status: "paid", amount: 1000 } },
74
+ });
75
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
76
+ });
77
+ it("unknown provider outcomes keep the same durable attempt and never blindly recreate", async () => {
78
+ vi.useFakeTimers();
79
+ const s = await worker();
80
+ s.provider.payouts.create.mockRejectedValueOnce(
81
+ new Error("network outcome unknown"),
82
+ );
83
+ await expect(s.run()).rejects.toThrow("network outcome unknown");
84
+ const first = await s.client.get(s.ctx, scope);
85
+ expect(first).toMatchObject({
86
+ hasOperation: true,
87
+ lastReason: "worker_error",
88
+ });
89
+ vi.advanceTimersByTime(300000);
90
+ expect(await s.run()).toMatchObject({
91
+ payout: { status: "held", reason: "payout_unidentified" },
92
+ });
93
+ expect((await s.client.get(s.ctx, scope))?.operationKey).toBe(
94
+ first?.operationKey,
95
+ );
96
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
97
+ });
98
+ it("concurrent recurring workers share the lease instead of canceling each other's unattempted claim", async () => {
99
+ const s = await worker();
100
+ const results = await Promise.all([s.run(), s.run()]);
101
+ expect(results.map((r) => r.status).sort()).toEqual(["completed", "held"]);
102
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
103
+ });
104
+ it("a successful payout with a lost response is recovered after opting out without another create", async () => {
105
+ vi.useFakeTimers();
106
+ const s = await worker();
107
+ const create = s.provider.payouts.create.getMockImplementation()!;
108
+ s.provider.payouts.create.mockImplementationOnce(async (params) => {
109
+ await create(params);
110
+ throw new Error("response lost after provider accepted");
111
+ });
112
+ await expect(s.run()).rejects.toThrow(/response lost/);
113
+ await s.t.run((ctx) =>
114
+ changeBalance(ctx, scope.accountId, "usd", { outstandingDebt: 100 }),
115
+ );
116
+ await s.t.run(async (ctx) => {
117
+ const policy = await ctx.db.query("payoutPolicies").first();
118
+ await ctx.db.patch("payoutPolicies", policy!._id, {
119
+ mode: "stripe_managed",
120
+ thresholds: [],
121
+ revision: 1,
122
+ });
123
+ });
124
+ vi.advanceTimersByTime(300000);
125
+ expect(await s.run()).toMatchObject({
126
+ payout: { claim: { status: "paid", amount: 1000 } },
127
+ job: { hasOperation: false },
128
+ });
129
+ expect(s.provider.payouts.create).toHaveBeenCalledTimes(1);
130
+ });
131
+ it("reports affiliate recovery holds before a fresh attempt without creating a payout", async () => {
132
+ const s = await worker();
133
+ await s.t.run((ctx) =>
134
+ changeBalance(ctx, scope.accountId, "usd", { outstandingDebt: 100 }),
135
+ );
136
+ expect(await s.run()).toMatchObject({
137
+ status: "held",
138
+ reason: "affiliate_recovery_pending",
139
+ });
140
+ expect(await s.client.get(s.ctx, scope)).toMatchObject({
141
+ lastReason: "affiliate_recovery_pending",
142
+ hasOperation: false,
143
+ });
144
+ expect(s.provider.payouts.create).not.toHaveBeenCalled();
145
+ });
@@ -0,0 +1,144 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { jobDoc } from "../../component/payoutWorker/schema.js";
3
+ import type { policyDoc } from "../../component/payoutPolicy/schema.js";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { runMutationOrThrow } from "../helpers.js";
6
+ import { componentRef } from "../webhooks/helpers.js";
7
+ import type {
8
+ PayoutReleaseOptions,
9
+ PayoutReleaseResult,
10
+ } from "./payoutExecution.js";
11
+ import type {
12
+ PayoutReconciliationOptions,
13
+ PayoutReconciliation,
14
+ } from "./payoutReconciliation.js";
15
+ export type PayoutWorkerJob = Infer<typeof jobDoc>;
16
+ export type PayoutWorkerScope = {
17
+ accountId: string;
18
+ ownerKey: string;
19
+ currency: string;
20
+ };
21
+ export type PayoutWorkerOptions = Omit<PayoutReleaseOptions, "operationKey"> & {
22
+ cadenceMs?: number;
23
+ };
24
+ type PageOptions = { cursor: string | null; numItems: number };
25
+ type Page<T> = { page: T[]; continueCursor: string; isDone: boolean };
26
+ type Held = { status: "held"; reason: string; nextAttemptAt?: number };
27
+ export type PayoutWorkerResult =
28
+ | Held
29
+ | { status: "completed"; job: PayoutWorkerJob; payout: PayoutReleaseResult };
30
+ /** Host cron only. No method on this worker represents a customer withdrawal request. */
31
+ export class PayoutWorkerClient {
32
+ constructor(
33
+ private readonly component: Component,
34
+ private readonly release: (
35
+ ctx: RunCtx,
36
+ opts: PayoutReleaseOptions,
37
+ ) => Promise<PayoutReleaseResult>,
38
+ private readonly reconcile: (
39
+ ctx: RunCtx,
40
+ opts: PayoutReconciliationOptions,
41
+ ) => Promise<PayoutReconciliation>,
42
+ ) {}
43
+ get(ctx: RunCtx, scope: PayoutWorkerScope): Promise<PayoutWorkerJob | null> {
44
+ return ctx.runQuery(
45
+ componentRef(this.component, "payoutWorker/queries/get"),
46
+ {
47
+ accountId: scope.accountId,
48
+ ownerKey: scope.ownerKey,
49
+ currency: scope.currency,
50
+ },
51
+ );
52
+ }
53
+ policies(
54
+ ctx: RunCtx,
55
+ paginationOpts: PageOptions,
56
+ ): Promise<Page<Infer<typeof policyDoc>>> {
57
+ return ctx.runQuery(
58
+ componentRef(this.component, "payoutWorker/queries/policies"),
59
+ { paginationOpts },
60
+ );
61
+ }
62
+ recovering(
63
+ ctx: RunCtx,
64
+ paginationOpts: PageOptions,
65
+ ): Promise<Page<PayoutWorkerJob>> {
66
+ return ctx.runQuery(
67
+ componentRef(this.component, "payoutWorker/queries/recovering"),
68
+ { paginationOpts },
69
+ );
70
+ }
71
+ changing(
72
+ ctx: RunCtx,
73
+ paginationOpts: PageOptions,
74
+ ): Promise<Page<Infer<typeof policyDoc>>> {
75
+ return ctx.runQuery(
76
+ componentRef(this.component, "payoutWorker/queries/changing"),
77
+ { paginationOpts },
78
+ );
79
+ }
80
+ async run(
81
+ ctx: RunCtx,
82
+ opts: PayoutWorkerOptions,
83
+ ): Promise<PayoutWorkerResult> {
84
+ if (
85
+ !Number.isSafeInteger(opts.independentLiabilities) ||
86
+ opts.independentLiabilities < 0 ||
87
+ (opts.maxPages !== undefined &&
88
+ (!Number.isInteger(opts.maxPages) ||
89
+ opts.maxPages < 1 ||
90
+ opts.maxPages > 100))
91
+ )
92
+ throw new Error("Invalid automatic payout liabilities or page budget.");
93
+ const scope = {
94
+ accountId: opts.accountId,
95
+ ownerKey: opts.ownerKey,
96
+ currency: opts.currency,
97
+ };
98
+ const started = (await runMutationOrThrow(
99
+ ctx,
100
+ componentRef(this.component, "payoutWorker/mutations/begin"),
101
+ {
102
+ ...scope,
103
+ cadenceMs: opts.cadenceMs ?? 300000,
104
+ },
105
+ )) as
106
+ Held | { status: "run"; job: PayoutWorkerJob; reconcileOnly: boolean };
107
+ if (started.status === "held") return started;
108
+ const operationKey = started.job.operationKey!;
109
+ const finish = (reason: string) =>
110
+ runMutationOrThrow(
111
+ ctx,
112
+ componentRef(this.component, "payoutWorker/mutations/finish"),
113
+ { ...scope, operationKey, generation: started.job.generation, reason },
114
+ ) as Promise<PayoutWorkerJob>;
115
+ let payout: PayoutReleaseResult;
116
+ try {
117
+ payout = started.reconcileOnly
118
+ ? await this.reconcile(ctx, {
119
+ ...scope,
120
+ operationKey,
121
+ maxPages: opts.maxPages,
122
+ })
123
+ : await this.release(ctx, {
124
+ ...scope,
125
+ operationKey,
126
+ independentLiabilities: opts.independentLiabilities,
127
+ maxPages: opts.maxPages,
128
+ });
129
+ } catch (error) {
130
+ try {
131
+ await finish("worker_error");
132
+ } catch (completionError) {
133
+ throw new AggregateError(
134
+ [error, completionError],
135
+ "Payout worker outcome requires reconciliation.",
136
+ );
137
+ }
138
+ throw error;
139
+ }
140
+ const reason =
141
+ payout.status === "held" ? payout.reason : payout.claim.status;
142
+ return { status: "completed", job: await finish(reason), payout };
143
+ }
144
+ }
@@ -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
+ }