@fantastic.dev/better-stripe 0.28.6 → 0.30.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 (222) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/MIGRATION.md +14 -0
  3. package/README.md +7 -1
  4. package/dist/client/connect/payoutActivationProof.d.ts.map +1 -1
  5. package/dist/client/connect/payoutActivationProof.js +88 -42
  6. package/dist/client/connect/payoutActivationProof.js.map +1 -1
  7. package/dist/client/connect/payoutAdoption.d.ts +3 -0
  8. package/dist/client/connect/payoutAdoption.d.ts.map +1 -1
  9. package/dist/client/connect/payoutAdoption.js +218 -183
  10. package/dist/client/connect/payoutAdoption.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionCollection.d.ts +21 -0
  12. package/dist/client/connect/payoutAdoptionCollection.d.ts.map +1 -0
  13. package/dist/client/connect/payoutAdoptionCollection.js +44 -0
  14. package/dist/client/connect/payoutAdoptionCollection.js.map +1 -0
  15. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +54 -14
  16. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutCollectedInput.d.ts +110 -0
  18. package/dist/client/connect/payoutCollectedInput.d.ts.map +1 -0
  19. package/dist/client/connect/payoutCollectedInput.js +70 -0
  20. package/dist/client/connect/payoutCollectedInput.js.map +1 -0
  21. package/dist/client/connect/payoutExecution.d.ts +1 -0
  22. package/dist/client/connect/payoutExecution.d.ts.map +1 -1
  23. package/dist/client/connect/payoutExecution.js +94 -67
  24. package/dist/client/connect/payoutExecution.js.map +1 -1
  25. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +29 -7
  26. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  27. package/dist/client/connect/payoutExecutionTestHelpers.js +9 -6
  28. package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -1
  29. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +3745 -0
  30. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -0
  31. package/dist/client/connect/payoutLargeAdoptionTestHelpers.js +55 -0
  32. package/dist/client/connect/payoutLargeAdoptionTestHelpers.js.map +1 -0
  33. package/dist/client/connect/payoutOutcomeBatches.d.ts +5 -0
  34. package/dist/client/connect/payoutOutcomeBatches.d.ts.map +1 -0
  35. package/dist/client/connect/payoutOutcomeBatches.js +21 -0
  36. package/dist/client/connect/payoutOutcomeBatches.js.map +1 -0
  37. package/dist/client/connect/payoutPolicyState.d.ts +14 -0
  38. package/dist/client/connect/payoutPolicyState.d.ts.map +1 -0
  39. package/dist/client/connect/payoutPolicyState.js +19 -0
  40. package/dist/client/connect/payoutPolicyState.js.map +1 -0
  41. package/dist/client/connect/payoutPreview.d.ts +1 -0
  42. package/dist/client/connect/payoutPreview.d.ts.map +1 -1
  43. package/dist/client/connect/payoutPreview.js +31 -19
  44. package/dist/client/connect/payoutPreview.js.map +1 -1
  45. package/dist/client/connect/payoutQualification.d.ts +7 -1
  46. package/dist/client/connect/payoutQualification.d.ts.map +1 -1
  47. package/dist/client/connect/payoutQualification.js +34 -19
  48. package/dist/client/connect/payoutQualification.js.map +1 -1
  49. package/dist/client/connect/payoutReconciliation.d.ts +11 -6
  50. package/dist/client/connect/payoutReconciliation.d.ts.map +1 -1
  51. package/dist/client/connect/payoutReconciliation.js +62 -16
  52. package/dist/client/connect/payoutReconciliation.js.map +1 -1
  53. package/dist/client/connect/payoutResumableProof.d.ts +17 -0
  54. package/dist/client/connect/payoutResumableProof.d.ts.map +1 -0
  55. package/dist/client/connect/payoutResumableProof.js +25 -0
  56. package/dist/client/connect/payoutResumableProof.js.map +1 -0
  57. package/dist/client/connect/payoutSyncTestHelpers.d.ts +27 -7
  58. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  59. package/dist/client/connect/payoutWorker.d.ts.map +1 -1
  60. package/dist/client/connect/payoutWorker.js +4 -1
  61. package/dist/client/connect/payoutWorker.js.map +1 -1
  62. package/dist/client/connect/transferReceipt.d.ts +6 -2
  63. package/dist/client/connect/transferReceipt.d.ts.map +1 -1
  64. package/dist/client/connect/transferReceipt.js +3 -3
  65. package/dist/client/connect/transferReceipt.js.map +1 -1
  66. package/dist/client/costRecovery.d.ts +5 -0
  67. package/dist/client/costRecovery.d.ts.map +1 -1
  68. package/dist/client/costRecovery.js +5 -0
  69. package/dist/client/costRecovery.js.map +1 -1
  70. package/dist/client/payoutPolicy.d.ts +4 -0
  71. package/dist/client/payoutPolicy.d.ts.map +1 -1
  72. package/dist/client/payoutPolicy.js +24 -14
  73. package/dist/client/payoutPolicy.js.map +1 -1
  74. package/dist/component/_generated/component.d.ts +247 -0
  75. package/dist/component/_generated/component.d.ts.map +1 -1
  76. package/dist/component/costRecovery/mutations.js +1 -1
  77. package/dist/component/costRecovery/queries.d.ts +9 -0
  78. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  79. package/dist/component/costRecovery/queries.js +20 -0
  80. package/dist/component/costRecovery/queries.js.map +1 -1
  81. package/dist/component/earnings/triggers.d.ts +28 -10
  82. package/dist/component/earnings/triggers.d.ts.map +1 -1
  83. package/dist/component/payoutPolicy/adoption.d.ts.map +1 -1
  84. package/dist/component/payoutPolicy/adoption.js +12 -7
  85. package/dist/component/payoutPolicy/adoption.js.map +1 -1
  86. package/dist/component/payoutPolicy/mutations.d.ts +12 -0
  87. package/dist/component/payoutPolicy/mutations.d.ts.map +1 -1
  88. package/dist/component/payoutPolicy/queries.d.ts +2 -0
  89. package/dist/component/payoutPolicy/queries.d.ts.map +1 -1
  90. package/dist/component/payoutPolicy/schema.d.ts +31 -7
  91. package/dist/component/payoutPolicy/schema.d.ts.map +1 -1
  92. package/dist/component/payoutPolicy/schema.js +2 -0
  93. package/dist/component/payoutPolicy/schema.js.map +1 -1
  94. package/dist/component/payoutRelease/adoption.d.ts +9 -1
  95. package/dist/component/payoutRelease/adoption.d.ts.map +1 -1
  96. package/dist/component/payoutRelease/adoption.js +33 -16
  97. package/dist/component/payoutRelease/adoption.js.map +1 -1
  98. package/dist/component/payoutRelease/fees.d.ts.map +1 -1
  99. package/dist/component/payoutRelease/fees.js +7 -0
  100. package/dist/component/payoutRelease/fees.js.map +1 -1
  101. package/dist/component/payoutRelease/helpers.d.ts +4 -1
  102. package/dist/component/payoutRelease/helpers.d.ts.map +1 -1
  103. package/dist/component/payoutRelease/helpers.js +17 -10
  104. package/dist/component/payoutRelease/helpers.js.map +1 -1
  105. package/dist/component/payoutRelease/mutations.d.ts +79 -0
  106. package/dist/component/payoutRelease/mutations.d.ts.map +1 -1
  107. package/dist/component/payoutRelease/mutations.js +38 -81
  108. package/dist/component/payoutRelease/mutations.js.map +1 -1
  109. package/dist/component/payoutRelease/outcome.d.ts +69 -0
  110. package/dist/component/payoutRelease/outcome.d.ts.map +1 -0
  111. package/dist/component/payoutRelease/outcome.js +94 -0
  112. package/dist/component/payoutRelease/outcome.js.map +1 -0
  113. package/dist/component/payoutRelease/planning.d.ts +4 -0
  114. package/dist/component/payoutRelease/planning.d.ts.map +1 -1
  115. package/dist/component/payoutRelease/planning.js +8 -3
  116. package/dist/component/payoutRelease/planning.js.map +1 -1
  117. package/dist/component/payoutRelease/preview.d.ts +2 -0
  118. package/dist/component/payoutRelease/preview.d.ts.map +1 -1
  119. package/dist/component/payoutRelease/preview.js +2 -0
  120. package/dist/component/payoutRelease/preview.js.map +1 -1
  121. package/dist/component/payoutRelease/queries.d.ts +13 -2
  122. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  123. package/dist/component/payoutRelease/queries.js +2 -0
  124. package/dist/component/payoutRelease/queries.js.map +1 -1
  125. package/dist/component/payoutRelease/schema.d.ts +17 -2
  126. package/dist/component/payoutRelease/schema.d.ts.map +1 -1
  127. package/dist/component/payoutRelease/schema.js +3 -0
  128. package/dist/component/payoutRelease/schema.js.map +1 -1
  129. package/dist/component/payoutSnapshots/adoption.d.ts +88 -0
  130. package/dist/component/payoutSnapshots/adoption.d.ts.map +1 -0
  131. package/dist/component/payoutSnapshots/adoption.js +49 -0
  132. package/dist/component/payoutSnapshots/adoption.js.map +1 -0
  133. package/dist/component/payoutSnapshots/financial.d.ts +47 -0
  134. package/dist/component/payoutSnapshots/financial.d.ts.map +1 -0
  135. package/dist/component/payoutSnapshots/financial.js +103 -0
  136. package/dist/component/payoutSnapshots/financial.js.map +1 -0
  137. package/dist/component/payoutSnapshots/liabilities.d.ts +7 -0
  138. package/dist/component/payoutSnapshots/liabilities.d.ts.map +1 -0
  139. package/dist/component/payoutSnapshots/liabilities.js +18 -0
  140. package/dist/component/payoutSnapshots/liabilities.js.map +1 -0
  141. package/dist/component/payoutSnapshots/localState.d.ts +22 -16
  142. package/dist/component/payoutSnapshots/localState.d.ts.map +1 -1
  143. package/dist/component/payoutSnapshots/localState.js +19 -7
  144. package/dist/component/payoutSnapshots/localState.js.map +1 -1
  145. package/dist/component/payoutSnapshots/mutations.d.ts +6 -0
  146. package/dist/component/payoutSnapshots/mutations.d.ts.map +1 -1
  147. package/dist/component/payoutSnapshots/mutations.js +3 -1
  148. package/dist/component/payoutSnapshots/mutations.js.map +1 -1
  149. package/dist/component/payoutSnapshots/queries.d.ts +133 -0
  150. package/dist/component/payoutSnapshots/queries.d.ts.map +1 -0
  151. package/dist/component/payoutSnapshots/queries.js +86 -0
  152. package/dist/component/payoutSnapshots/queries.js.map +1 -0
  153. package/dist/component/payoutSnapshots/revisions.d.ts.map +1 -1
  154. package/dist/component/payoutSnapshots/revisions.js +19 -0
  155. package/dist/component/payoutSnapshots/revisions.js.map +1 -1
  156. package/dist/component/payoutSnapshots/schema.d.ts +20 -6
  157. package/dist/component/payoutSnapshots/schema.d.ts.map +1 -1
  158. package/dist/component/payoutSnapshots/schema.js +5 -1
  159. package/dist/component/payoutSnapshots/schema.js.map +1 -1
  160. package/dist/component/payoutWorker/mutations.d.ts.map +1 -1
  161. package/dist/component/payoutWorker/mutations.js +3 -1
  162. package/dist/component/payoutWorker/mutations.js.map +1 -1
  163. package/dist/component/schema.d.ts +27 -7
  164. package/dist/react/workflows/payout-attempt-state.d.ts.map +1 -1
  165. package/dist/react/workflows/payout-attempt-state.js +3 -0
  166. package/dist/react/workflows/payout-attempt-state.js.map +1 -1
  167. package/dist/react/workflows/payout-progress-state.d.ts.map +1 -1
  168. package/dist/react/workflows/payout-progress-state.js +3 -0
  169. package/dist/react/workflows/payout-progress-state.js.map +1 -1
  170. package/docs/settlement.md +136 -24
  171. package/package.json +1 -1
  172. package/src/client/connect/payoutActivationProof.ts +123 -53
  173. package/src/client/connect/payoutAdoption.ts +299 -215
  174. package/src/client/connect/payoutAdoptionCollection.ts +78 -0
  175. package/src/client/connect/payoutAdoptionConcurrency.test.ts +266 -0
  176. package/src/client/connect/payoutCacheIdentity.test.ts +93 -0
  177. package/src/client/connect/payoutCollectedInput.ts +120 -0
  178. package/src/client/connect/payoutExecution.ts +116 -84
  179. package/src/client/connect/payoutExecutionTestHelpers.ts +19 -6
  180. package/src/client/connect/payoutLargeAdoption.test.ts +541 -0
  181. package/src/client/connect/payoutLargeAdoptionTestHelpers.ts +74 -0
  182. package/src/client/connect/payoutLargeHistory.test.ts +222 -0
  183. package/src/client/connect/payoutLiabilityVersion.test.ts +221 -0
  184. package/src/client/connect/payoutOutcomeBatches.test.ts +40 -0
  185. package/src/client/connect/payoutOutcomeBatches.ts +24 -0
  186. package/src/client/connect/payoutPolicyState.ts +36 -0
  187. package/src/client/connect/payoutPreview.ts +42 -24
  188. package/src/client/connect/payoutQualification.ts +68 -21
  189. package/src/client/connect/payoutReconciliation.ts +86 -7
  190. package/src/client/connect/payoutResumableProof.ts +41 -0
  191. package/src/client/connect/payoutWorker.ts +4 -1
  192. package/src/client/connect/transferReceipt.ts +3 -2
  193. package/src/client/connect/transferReceiptBaseline.test.ts +55 -0
  194. package/src/client/costRecovery.ts +8 -0
  195. package/src/client/payoutPolicy.ts +37 -23
  196. package/src/component/_generated/api.ts +10 -0
  197. package/src/component/_generated/component.ts +288 -0
  198. package/src/component/costRecovery/mutations.ts +1 -1
  199. package/src/component/costRecovery/queries.ts +21 -0
  200. package/src/component/payout-snapshots.test.ts +45 -1
  201. package/src/component/payoutPolicy/adoption.ts +20 -7
  202. package/src/component/payoutPolicy/schema.ts +2 -0
  203. package/src/component/payoutRelease/adoption.ts +57 -27
  204. package/src/component/payoutRelease/fees.ts +9 -0
  205. package/src/component/payoutRelease/helpers.ts +19 -11
  206. package/src/component/payoutRelease/mutations.ts +43 -96
  207. package/src/component/payoutRelease/outcome.ts +119 -0
  208. package/src/component/payoutRelease/planning.ts +11 -2
  209. package/src/component/payoutRelease/preview.ts +2 -0
  210. package/src/component/payoutRelease/queries.ts +2 -0
  211. package/src/component/payoutRelease/schema.ts +3 -0
  212. package/src/component/payoutSnapshots/adoption.ts +73 -0
  213. package/src/component/payoutSnapshots/financial.ts +134 -0
  214. package/src/component/payoutSnapshots/liabilities.ts +25 -0
  215. package/src/component/payoutSnapshots/localState.ts +24 -6
  216. package/src/component/payoutSnapshots/mutations.ts +10 -1
  217. package/src/component/payoutSnapshots/queries.ts +104 -0
  218. package/src/component/payoutSnapshots/revisions.ts +26 -0
  219. package/src/component/payoutSnapshots/schema.ts +5 -0
  220. package/src/component/payoutWorker/mutations.ts +3 -1
  221. package/src/react/workflows/payout-attempt-state.ts +6 -0
  222. package/src/react/workflows/payout-progress-state.ts +6 -0
@@ -1,3 +1,8 @@
1
+ import {
2
+ collectLargePayoutInput,
3
+ type CollectionRef,
4
+ type PayoutInput,
5
+ } from "./payoutCollectedInput.js";
1
6
  import type Stripe from "stripe";
2
7
  import type { Infer } from "convex/values";
3
8
  import type { Component, RunCtx } from "../helpers.js";
@@ -30,6 +35,8 @@ export type PayoutProofScope = {
30
35
  accountId: string;
31
36
  ownerKey: string;
32
37
  currency: string;
38
+ operationKey?: string;
39
+ liabilityRevision?: number;
33
40
  };
34
41
  /** Shared provider qualification. It can reconcile existing receipts, but never creates a bank payout. */
35
42
  export async function collectPayoutQualification(
@@ -39,20 +46,45 @@ export async function collectPayoutQualification(
39
46
  opts: PayoutProofScope,
40
47
  maxPages: number,
41
48
  ): Promise<
42
- | Held
49
+ | (Held & { collection?: CollectionRef })
43
50
  | {
44
51
  status: "verified";
52
+ collection?: CollectionRef;
45
53
  observations: Infer<typeof observation>[];
46
54
  destinationId: string;
47
55
  providerAvailable: number;
48
56
  observedAt: number;
49
57
  }
50
58
  > {
51
- const snapshot = (await ctx.runQuery(
59
+ let snapshot = (await ctx.runQuery(
52
60
  componentRef(component, "payoutRelease/queries/snapshot"),
53
61
  { accountId: opts.accountId, ownerKey: opts.ownerKey },
54
62
  )) as Snapshot;
55
- if (snapshot.status !== "ready") return snapshot;
63
+ let collection: CollectionRef | undefined;
64
+ if (snapshot.status !== "ready" || opts.liabilityRevision !== undefined) {
65
+ const large = await collectLargePayoutInput(component, ctx, opts, maxPages);
66
+ if (large.status !== "ready") return large;
67
+ collection = large.collection;
68
+ snapshot = large;
69
+ }
70
+ const result = await qualifyInput(
71
+ stripe,
72
+ component,
73
+ ctx,
74
+ opts,
75
+ maxPages,
76
+ snapshot,
77
+ );
78
+ return { ...result, ...(collection ? { collection } : {}) };
79
+ }
80
+ async function qualifyInput(
81
+ stripe: Stripe,
82
+ component: Component,
83
+ ctx: RunCtx,
84
+ opts: PayoutProofScope,
85
+ maxPages: number,
86
+ snapshot: PayoutInput,
87
+ ): Promise<Awaited<ReturnType<typeof collectPayoutQualification>>> {
56
88
  const banks: string[] = [];
57
89
  let bankCursor: string | undefined;
58
90
  for (let page = 0; ; page++) {
@@ -109,24 +141,39 @@ export async function collectPayoutQualification(
109
141
  transactions.push({ ...t, sourceId: result.receipt.stripePayoutId });
110
142
  }
111
143
  const observations = [];
112
- for (const row of snapshot.transfers) {
113
- const receipt = await getTransferFundingReceipt(stripe, component, ctx, {
114
- accountId: opts.accountId,
115
- stripeTransferId: row.stripeTransferId,
116
- });
117
- if (receipt.status !== "ready")
118
- return { status: "held", reason: receipt.reason };
119
- observations.push({
120
- stripeTransferId: row.stripeTransferId,
121
- currency: receipt.settlementCurrency,
122
- matureNet: receipt.matureNet,
123
- pendingCredits: receipt.pendingCredits,
124
- ledgerFingerprint: transferFingerprint(row),
125
- observedAt: receipt.observedAt,
126
- transactionIds: receipt.transactions.map((t) => t.id),
127
- });
128
- if (receipt.settlementCurrency === opts.currency)
129
- transactions.push(...receipt.transactions);
144
+ for (let i = 0; i < snapshot.transfers.length; i += 5) {
145
+ const batch = snapshot.transfers.slice(i, i + 5);
146
+ const receipts = await Promise.all(
147
+ batch.map((row) =>
148
+ getTransferFundingReceipt(
149
+ stripe,
150
+ component,
151
+ ctx,
152
+ {
153
+ accountId: opts.accountId,
154
+ stripeTransferId: row.stripeTransferId,
155
+ },
156
+ row,
157
+ ),
158
+ ),
159
+ );
160
+ for (let j = 0; j < batch.length; j++) {
161
+ const row = batch[j],
162
+ receipt = receipts[j];
163
+ if (receipt.status !== "ready")
164
+ return { status: "held", reason: receipt.reason };
165
+ observations.push({
166
+ stripeTransferId: row.stripeTransferId,
167
+ currency: receipt.settlementCurrency,
168
+ matureNet: receipt.matureNet,
169
+ pendingCredits: receipt.pendingCredits,
170
+ ledgerFingerprint: transferFingerprint(row),
171
+ observedAt: receipt.observedAt,
172
+ transactionIds: receipt.transactions.map((t) => t.id),
173
+ });
174
+ if (receipt.settlementCurrency === opts.currency)
175
+ transactions.push(...receipt.transactions);
176
+ }
130
177
  }
131
178
  const history = await verifyPayoutHistory(stripe, {
132
179
  accountId: opts.accountId,
@@ -1,3 +1,5 @@
1
+ import { payoutOutcomeBatches } from "./payoutOutcomeBatches.js";
2
+ import type { outcomeArgs } from "../../component/payoutRelease/outcome.js";
1
3
  import type Stripe from "stripe";
2
4
  import type { Infer } from "convex/values";
3
5
  import type { claimDoc } from "../../component/payoutRelease/schema.js";
@@ -87,12 +89,20 @@ async function discover(
87
89
  * receipts is required for adoption; no match never proves money did not move.
88
90
  * Fees and principal are persisted together in the component transaction.
89
91
  */
90
- export async function reconcileRecipientPayout(
92
+ async function prepareRecipientPayout(
91
93
  stripe: Stripe,
92
94
  component: Component,
93
95
  ctx: RunCtx,
94
96
  options: PayoutReconciliationOptions,
95
- ): Promise<PayoutReconciliation> {
97
+ ): Promise<
98
+ | Exclude<PayoutReconciliation, { status: "updated" }>
99
+ | {
100
+ status: "prepared";
101
+ allocationCount: number;
102
+ outcome: Infer<typeof outcomeArgs>;
103
+ receipt: Extract<RecipientPayoutReceipt, { status: "ready" }>;
104
+ }
105
+ > {
96
106
  validateIdentity(options);
97
107
  const maxPages = options.maxPages ?? 10;
98
108
  if (!Number.isInteger(maxPages) || maxPages < 1 || maxPages > 100)
@@ -159,10 +169,11 @@ export async function reconcileRecipientPayout(
159
169
  return { status: "held", reason: "source_allocation_required" };
160
170
  const fee = addSummaryAmounts(receipt.debit.fee, receipt.credit?.fee ?? 0);
161
171
  if (fee < 0) return { status: "held", reason: "fee_allocation_required" };
162
- const saved = (await runMutationOrThrow(
163
- ctx,
164
- componentRef(component, "payoutRelease/mutations/recordOutcome"),
165
- {
172
+ return {
173
+ status: "prepared",
174
+ allocationCount: claim.allocations.length,
175
+ receipt,
176
+ outcome: {
166
177
  ...identity,
167
178
  stripePayoutId: receipt.stripePayoutId,
168
179
  amount: receipt.amount,
@@ -177,6 +188,74 @@ export async function reconcileRecipientPayout(
177
188
  }
178
189
  : {}),
179
190
  },
191
+ };
192
+ }
193
+ export async function reconcileRecipientPayout(
194
+ stripe: Stripe,
195
+ component: Component,
196
+ ctx: RunCtx,
197
+ options: PayoutReconciliationOptions,
198
+ ): Promise<PayoutReconciliation> {
199
+ const result = await prepareRecipientPayout(stripe, component, ctx, options);
200
+ if (result.status !== "prepared") return result;
201
+ const saved = (await runMutationOrThrow(
202
+ ctx,
203
+ componentRef(component, "payoutRelease/mutations/recordOutcome"),
204
+ result.outcome,
180
205
  )) as Claim;
181
- return { status: "updated", claim: saved, receipt };
206
+ return { status: "updated", claim: saved, receipt: result.receipt };
207
+ }
208
+ /** Bound provider reads and outcome transactions without truncating known history. */
209
+ export async function reconcileRecipientPayouts(
210
+ stripe: Stripe,
211
+ component: Component,
212
+ ctx: RunCtx,
213
+ scope: { accountId: string; ownerKey: string },
214
+ options: PayoutReconciliationOptions[],
215
+ ): Promise<
216
+ { status: "updated"; claims: Claim[] } | { status: "held"; reason: string }
217
+ > {
218
+ const claims: Claim[] = [];
219
+ for (let start = 0; start < options.length; start += 25) {
220
+ const batch = options.slice(start, start + 25);
221
+ const outcomes: {
222
+ outcome: Infer<typeof outcomeArgs>;
223
+ allocationCount: number;
224
+ }[] = [];
225
+ for (let i = 0; i < batch.length; i += 5) {
226
+ const prepared = await Promise.all(
227
+ batch.slice(i, i + 5).map((opts) => {
228
+ if (
229
+ opts.accountId !== scope.accountId ||
230
+ opts.ownerKey !== scope.ownerKey
231
+ )
232
+ throw new Error("Payout reconciliation batch ownership changed.");
233
+ return prepareRecipientPayout(stripe, component, ctx, opts);
234
+ }),
235
+ );
236
+ for (const result of prepared) {
237
+ if (result.status !== "prepared")
238
+ return {
239
+ status: "held",
240
+ reason:
241
+ result.status === "held"
242
+ ? result.reason
243
+ : "historical_claim_terminal",
244
+ };
245
+ outcomes.push({
246
+ outcome: result.outcome,
247
+ allocationCount: result.allocationCount,
248
+ });
249
+ }
250
+ }
251
+ for (const group of payoutOutcomeBatches(outcomes)) {
252
+ const saved = (await runMutationOrThrow(
253
+ ctx,
254
+ componentRef(component, "payoutRelease/mutations/recordOutcomes"),
255
+ { ...scope, outcomes: group.map((row) => row.outcome) },
256
+ )) as Claim[];
257
+ claims.push(...saved);
258
+ }
259
+ }
260
+ return { status: "updated", claims };
182
261
  }
@@ -0,0 +1,41 @@
1
+ import type Stripe from "stripe";
2
+ import type { Component, RunCtx } from "../helpers.js";
3
+ import { readPayoutOperation } from "./payoutPolicyState.js";
4
+ import { collectAdoptionProof } from "./payoutActivationProof.js";
5
+ /** A competing identical caller may consume and remove the shared proof cache. */
6
+ export async function collectResumableAdoptionProof(
7
+ stripe: Stripe,
8
+ component: Component,
9
+ ctx: RunCtx,
10
+ scope: { accountId: string; ownerKey: string; operationKey: string },
11
+ expectedRevision: number,
12
+ currencies: string[],
13
+ phase: "prepare" | "apply",
14
+ ) {
15
+ const changed = async () => {
16
+ const operation = await readPayoutOperation(component, ctx, scope);
17
+ return (
18
+ !!operation &&
19
+ (phase === "prepare" ||
20
+ operation.attempted ||
21
+ operation.status === "complete" ||
22
+ operation.status === "canceled")
23
+ );
24
+ };
25
+ try {
26
+ const result = await collectAdoptionProof(
27
+ stripe,
28
+ component,
29
+ ctx,
30
+ scope,
31
+ expectedRevision,
32
+ currencies,
33
+ );
34
+ if (result.status === "held" && (await changed()))
35
+ return { status: "operation_changed" as const };
36
+ return result;
37
+ } catch (error) {
38
+ if (await changed()) return { status: "operation_changed" as const };
39
+ throw error;
40
+ }
41
+ }
@@ -127,6 +127,9 @@ export class PayoutWorkerClient {
127
127
  ...scope,
128
128
  operationKey,
129
129
  independentLiabilities: opts.independentLiabilities,
130
+ ...(opts.liabilityRevision === undefined
131
+ ? {}
132
+ : { liabilityRevision: opts.liabilityRevision }),
130
133
  maxPages: opts.maxPages,
131
134
  });
132
135
  } catch (error) {
@@ -163,7 +166,7 @@ export function payoutAttemptStatus(
163
166
  : (job.lastReason ?? "pending_claim");
164
167
  const status = running
165
168
  ? "running"
166
- : job.hasOperation
169
+ : job.hasOperation && reason !== "collection_pending"
167
170
  ? "reconciling"
168
171
  : ["balance_insufficient", "amount_too_small", "rejected"].includes(
169
172
  reason,
@@ -83,12 +83,13 @@ function fingerprint(t: Stripe.Transfer) {
83
83
  t.metadata?.bsReinstateOf,
84
84
  ]);
85
85
  }
86
- /** Recipient-scoped received credit. Previous payouts are deliberately not allocated here. */
86
+ /** Recipient-scoped credit. An optional already-read baseline never replaces the final live ledger check. */
87
87
  export async function getTransferFundingReceipt(
88
88
  stripe: Stripe,
89
89
  component: Component,
90
90
  ctx: RunCtx,
91
91
  opts: TransferReceiptOptions,
92
+ baseline?: LedgerTransfer,
92
93
  ): Promise<TransferFundingReceipt> {
93
94
  const max = opts.maxRequests ?? 20;
94
95
  if (!Number.isInteger(max) || max < 1 || max > 100)
@@ -107,7 +108,7 @@ export async function getTransferFundingReceipt(
107
108
  componentRef(component, "connect/queries/getTransferByStripeId"),
108
109
  { stripeTransferId: opts.stripeTransferId },
109
110
  ) as Promise<LedgerTransfer | null>;
110
- const ledger = await read();
111
+ const ledger = baseline ?? (await read());
111
112
  if (!ledger)
112
113
  return { status: "not_ready", ...scope, reason: "not_in_ledger" };
113
114
  if (
@@ -0,0 +1,55 @@
1
+ // @vitest-environment edge-runtime
2
+ import type Stripe from "stripe";
3
+ import { expect, it } from "vitest";
4
+ import { setup, component, scope } from "./payoutAdoptionTestHelpers.js";
5
+ import { getTransferFundingReceipt } from "./transferReceipt.js";
6
+ it("reuses an already read baseline while still rereading the current ledger", async () => {
7
+ const s = await setup([100]);
8
+ const row = await s.t.run((ctx) => ctx.db.query("transfers").first());
9
+ if (!row) throw Error("Missing source");
10
+ let reads = 0;
11
+ const runQuery = s.ctx.runQuery;
12
+ const ctx = {
13
+ ...s.ctx,
14
+ runQuery: ((ref, ...args) => {
15
+ if (
16
+ (ref as Record<symbol, string>)[Symbol.for("toReferencePath")].endsWith(
17
+ "getTransferByStripeId",
18
+ )
19
+ )
20
+ reads++;
21
+ return runQuery(ref, ...args);
22
+ }) as typeof runQuery,
23
+ };
24
+ expect(
25
+ await getTransferFundingReceipt(
26
+ s.provider as unknown as Stripe,
27
+ component,
28
+ ctx,
29
+ { accountId: scope.accountId, stripeTransferId: row.stripeTransferId },
30
+ row,
31
+ ),
32
+ ).toMatchObject({ status: "ready" });
33
+ expect(reads).toBe(1);
34
+ });
35
+ it("rejects a ledger change after an already read baseline", async () => {
36
+ const s = await setup([100]);
37
+ const row = await s.t.run((ctx) => ctx.db.query("transfers").first());
38
+ if (!row) throw Error("Missing source");
39
+ const retrieve = s.provider.transfers.retrieve.getMockImplementation()!;
40
+ s.provider.transfers.retrieve.mockImplementation(async (id) => {
41
+ await s.t.run((ctx) =>
42
+ ctx.db.patch("transfers", row._id, { role: "other" }),
43
+ );
44
+ return retrieve(id);
45
+ });
46
+ expect(
47
+ await getTransferFundingReceipt(
48
+ s.provider as unknown as Stripe,
49
+ component,
50
+ s.ctx,
51
+ { accountId: scope.accountId, stripeTransferId: row.stripeTransferId },
52
+ row,
53
+ ),
54
+ ).toMatchObject({ status: "not_ready", reason: "ledger_changed" });
55
+ });
@@ -241,6 +241,14 @@ export class CostRecoveryClient {
241
241
  ) {
242
242
  return this.mutate<RecoveryClaim>(ctx, "mutations/rollback", opts);
243
243
  }
244
+ /** Host authorizes the recovery scope; pass this atomic quote unchanged to payout qualification. */
245
+ payoutQuote(ctx: RunCtx, opts: RecoveryScope) {
246
+ const { accountId, scopeKey, currency } = opts;
247
+ return this.query<{
248
+ independentLiabilities: number;
249
+ liabilityRevision: number;
250
+ }>(ctx, "payoutQuote", { accountId, scopeKey, currency });
251
+ }
244
252
  balance(ctx: RunCtx, opts: RecoveryScope) {
245
253
  return this.query<RecoveryBalance>(ctx, "balance", opts);
246
254
  }
@@ -1,3 +1,11 @@
1
+ import {
2
+ readPayoutOperation,
3
+ readPayoutPolicy,
4
+ } from "./connect/payoutPolicyState.js";
5
+ import {
6
+ runAdoptionMutation,
7
+ discardAdoptionProof,
8
+ } from "./connect/payoutAdoptionCollection.js";
1
9
  export { payoutAttemptStatus } from "./connect/payoutWorker.js";
2
10
  export { attemptStatus as payoutAttemptValidator } from "../component/payoutWorker/schema.js";
3
11
  export { holdingExpiry as payoutHoldingExpiryValidator } from "../component/payoutPolicy/schema.js";
@@ -17,7 +25,7 @@ import {
17
25
  type PayoutCollectionScope,
18
26
  } from "./connect/payoutCollection.js";
19
27
  export type * from "./connect/payoutCollection.js";
20
- import { collectAdoptionProof } from "./connect/payoutActivationProof.js";
28
+ import { collectResumableAdoptionProof as collectAdoptionProof } from "./connect/payoutResumableProof.js";
21
29
  import {
22
30
  adoptRecipientPayouts,
23
31
  type PayoutAdoptionOptions,
@@ -175,25 +183,13 @@ export class PayoutPolicyClient {
175
183
  ctx: RunCtx,
176
184
  scope: PayoutPolicyScope,
177
185
  ): Promise<PayoutPolicy | null> {
178
- validateScope(scope);
179
- return ctx.runQuery(
180
- componentRef(this.component, "payoutPolicy/queries/get"),
181
- { accountId: scope.accountId, ownerKey: scope.ownerKey },
182
- );
186
+ return readPayoutPolicy(this.component, ctx, scope);
183
187
  }
184
188
  async operation(
185
189
  ctx: RunCtx,
186
190
  args: PayoutPolicyScope & { operationKey: string },
187
191
  ): Promise<PayoutPolicyOperation | null> {
188
- validateScope(args);
189
- return ctx.runQuery(
190
- componentRef(this.component, "payoutPolicy/queries/operation"),
191
- {
192
- accountId: args.accountId,
193
- ownerKey: args.ownerKey,
194
- operationKey: args.operationKey,
195
- },
196
- );
192
+ return readPayoutOperation(this.component, ctx, args);
197
193
  }
198
194
  async due(
199
195
  ctx: RunCtx,
@@ -357,7 +353,10 @@ export class PayoutPolicyClient {
357
353
  opts,
358
354
  policy!.revision,
359
355
  thresholds.map((t) => t.currency),
356
+ "prepare",
360
357
  );
358
+ if (proof.status === "operation_changed")
359
+ return this.prepare(ctx, opts);
361
360
  if (proof.status !== "verified")
362
361
  return {
363
362
  status: "migration_required",
@@ -369,20 +368,23 @@ export class PayoutPolicyClient {
369
368
  adoption.oldestHeldAt !== undefined &&
370
369
  adoption.oldestHeldAt + holdingDays(controls.country) * 86400000 <=
371
370
  Date.now()
372
- )
371
+ ) {
372
+ await discardAdoptionProof(this.component, ctx, opts, adoption);
373
373
  return {
374
374
  status: "migration_required",
375
375
  reason: "existing_balance",
376
376
  adoptionReason: "holding_deadline_expired",
377
377
  };
378
+ }
378
379
  } else {
379
380
  const migration = await this.migrationPreflight(opts);
380
381
  if (migration) return migration;
381
382
  }
382
383
  }
383
- const operation = (await runMutationOrThrow(
384
+ const operation = (await runAdoptionMutation(
385
+ this.component,
384
386
  ctx,
385
- componentRef(this.component, "payoutPolicy/mutations/prepare"),
387
+ "prepare",
386
388
  {
387
389
  accountId: opts.accountId,
388
390
  ownerKey: opts.ownerKey,
@@ -468,8 +470,11 @@ export class PayoutPolicyClient {
468
470
  args,
469
471
  policy.revision,
470
472
  operation.thresholds.map((t) => t.currency),
473
+ "apply",
471
474
  )
472
475
  : null;
476
+ if (result?.status === "operation_changed")
477
+ return this.apply(ctx, args);
473
478
  if (result?.status === "verified") freshAdoption = result.proof;
474
479
  const ageExpired =
475
480
  result?.status === "verified" &&
@@ -493,6 +498,7 @@ export class PayoutPolicyClient {
493
498
  ? null
494
499
  : await this.migrationPreflight(args);
495
500
  if (migration) {
501
+ await discardAdoptionProof(this.component, ctx, args, freshAdoption);
496
502
  await runMutationOrThrow(
497
503
  ctx,
498
504
  componentRef(
@@ -504,11 +510,19 @@ export class PayoutPolicyClient {
504
510
  return migration;
505
511
  }
506
512
  }
507
- await runMutationOrThrow(
508
- ctx,
509
- componentRef(this.component, "payoutPolicy/mutations/beginAttempt"),
510
- { ...args, ...(freshAdoption ? { adoption: freshAdoption } : {}) },
511
- );
513
+ if (!operation.attempted) {
514
+ const attempt = await runAdoptionMutation(
515
+ this.component,
516
+ ctx,
517
+ "beginAttempt",
518
+ {
519
+ ...args,
520
+ ...(freshAdoption ? { adoption: freshAdoption } : {}),
521
+ },
522
+ );
523
+ if (attempt.status === "operation_changed")
524
+ return this.apply(ctx, args);
525
+ }
512
526
  try {
513
527
  await this.provider().balanceSettings.update(
514
528
  {
@@ -59,12 +59,17 @@ import type * as payoutRelease_fees from "../payoutRelease/fees.js";
59
59
  import type * as payoutRelease_helpers from "../payoutRelease/helpers.js";
60
60
  import type * as payoutRelease_mutations from "../payoutRelease/mutations.js";
61
61
  import type * as payoutRelease_observation from "../payoutRelease/observation.js";
62
+ import type * as payoutRelease_outcome from "../payoutRelease/outcome.js";
62
63
  import type * as payoutRelease_planning from "../payoutRelease/planning.js";
63
64
  import type * as payoutRelease_preview from "../payoutRelease/preview.js";
64
65
  import type * as payoutRelease_progress from "../payoutRelease/progress.js";
65
66
  import type * as payoutRelease_queries from "../payoutRelease/queries.js";
67
+ import type * as payoutSnapshots_adoption from "../payoutSnapshots/adoption.js";
68
+ import type * as payoutSnapshots_financial from "../payoutSnapshots/financial.js";
69
+ import type * as payoutSnapshots_liabilities from "../payoutSnapshots/liabilities.js";
66
70
  import type * as payoutSnapshots_localState from "../payoutSnapshots/localState.js";
67
71
  import type * as payoutSnapshots_mutations from "../payoutSnapshots/mutations.js";
72
+ import type * as payoutSnapshots_queries from "../payoutSnapshots/queries.js";
68
73
  import type * as payoutSnapshots_revisions from "../payoutSnapshots/revisions.js";
69
74
  import type * as payoutSnapshots_scope from "../payoutSnapshots/scope.js";
70
75
  import type * as payoutSync_helpers from "../payoutSync/helpers.js";
@@ -145,12 +150,17 @@ const fullApi: ApiFromModules<{
145
150
  "payoutRelease/helpers": typeof payoutRelease_helpers;
146
151
  "payoutRelease/mutations": typeof payoutRelease_mutations;
147
152
  "payoutRelease/observation": typeof payoutRelease_observation;
153
+ "payoutRelease/outcome": typeof payoutRelease_outcome;
148
154
  "payoutRelease/planning": typeof payoutRelease_planning;
149
155
  "payoutRelease/preview": typeof payoutRelease_preview;
150
156
  "payoutRelease/progress": typeof payoutRelease_progress;
151
157
  "payoutRelease/queries": typeof payoutRelease_queries;
158
+ "payoutSnapshots/adoption": typeof payoutSnapshots_adoption;
159
+ "payoutSnapshots/financial": typeof payoutSnapshots_financial;
160
+ "payoutSnapshots/liabilities": typeof payoutSnapshots_liabilities;
152
161
  "payoutSnapshots/localState": typeof payoutSnapshots_localState;
153
162
  "payoutSnapshots/mutations": typeof payoutSnapshots_mutations;
163
+ "payoutSnapshots/queries": typeof payoutSnapshots_queries;
154
164
  "payoutSnapshots/revisions": typeof payoutSnapshots_revisions;
155
165
  "payoutSnapshots/scope": typeof payoutSnapshots_scope;
156
166
  "payoutSync/helpers": typeof payoutSync_helpers;