@fantastic.dev/better-stripe 0.29.0 → 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 (144) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/MIGRATION.md +8 -0
  3. package/README.md +3 -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 +26 -6
  16. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +13 -3
  18. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  19. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +3745 -0
  20. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -0
  21. package/dist/client/connect/payoutLargeAdoptionTestHelpers.js +55 -0
  22. package/dist/client/connect/payoutLargeAdoptionTestHelpers.js.map +1 -0
  23. package/dist/client/connect/payoutOutcomeBatches.d.ts +5 -0
  24. package/dist/client/connect/payoutOutcomeBatches.d.ts.map +1 -0
  25. package/dist/client/connect/payoutOutcomeBatches.js +21 -0
  26. package/dist/client/connect/payoutOutcomeBatches.js.map +1 -0
  27. package/dist/client/connect/payoutPolicyState.d.ts +14 -0
  28. package/dist/client/connect/payoutPolicyState.d.ts.map +1 -0
  29. package/dist/client/connect/payoutPolicyState.js +19 -0
  30. package/dist/client/connect/payoutPolicyState.js.map +1 -0
  31. package/dist/client/connect/payoutQualification.js +1 -1
  32. package/dist/client/connect/payoutQualification.js.map +1 -1
  33. package/dist/client/connect/payoutReconciliation.d.ts +11 -6
  34. package/dist/client/connect/payoutReconciliation.d.ts.map +1 -1
  35. package/dist/client/connect/payoutReconciliation.js +62 -16
  36. package/dist/client/connect/payoutReconciliation.js.map +1 -1
  37. package/dist/client/connect/payoutResumableProof.d.ts +17 -0
  38. package/dist/client/connect/payoutResumableProof.d.ts.map +1 -0
  39. package/dist/client/connect/payoutResumableProof.js +25 -0
  40. package/dist/client/connect/payoutResumableProof.js.map +1 -0
  41. package/dist/client/connect/payoutSyncTestHelpers.d.ts +13 -3
  42. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  43. package/dist/client/connect/transferReceipt.d.ts +6 -2
  44. package/dist/client/connect/transferReceipt.d.ts.map +1 -1
  45. package/dist/client/connect/transferReceipt.js +3 -3
  46. package/dist/client/connect/transferReceipt.js.map +1 -1
  47. package/dist/client/payoutPolicy.d.ts.map +1 -1
  48. package/dist/client/payoutPolicy.js +24 -14
  49. package/dist/client/payoutPolicy.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +72 -0
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/earnings/triggers.d.ts +12 -4
  53. package/dist/component/earnings/triggers.d.ts.map +1 -1
  54. package/dist/component/payoutPolicy/adoption.d.ts.map +1 -1
  55. package/dist/component/payoutPolicy/adoption.js +12 -7
  56. package/dist/component/payoutPolicy/adoption.js.map +1 -1
  57. package/dist/component/payoutPolicy/mutations.d.ts +12 -0
  58. package/dist/component/payoutPolicy/mutations.d.ts.map +1 -1
  59. package/dist/component/payoutPolicy/queries.d.ts +2 -0
  60. package/dist/component/payoutPolicy/queries.d.ts.map +1 -1
  61. package/dist/component/payoutPolicy/schema.d.ts +31 -7
  62. package/dist/component/payoutPolicy/schema.d.ts.map +1 -1
  63. package/dist/component/payoutPolicy/schema.js +2 -0
  64. package/dist/component/payoutPolicy/schema.js.map +1 -1
  65. package/dist/component/payoutRelease/adoption.d.ts +3 -1
  66. package/dist/component/payoutRelease/adoption.d.ts.map +1 -1
  67. package/dist/component/payoutRelease/adoption.js +33 -16
  68. package/dist/component/payoutRelease/adoption.js.map +1 -1
  69. package/dist/component/payoutRelease/fees.d.ts.map +1 -1
  70. package/dist/component/payoutRelease/fees.js +7 -0
  71. package/dist/component/payoutRelease/fees.js.map +1 -1
  72. package/dist/component/payoutRelease/mutations.d.ts +59 -0
  73. package/dist/component/payoutRelease/mutations.d.ts.map +1 -1
  74. package/dist/component/payoutRelease/mutations.js +25 -80
  75. package/dist/component/payoutRelease/mutations.js.map +1 -1
  76. package/dist/component/payoutRelease/outcome.d.ts +69 -0
  77. package/dist/component/payoutRelease/outcome.d.ts.map +1 -0
  78. package/dist/component/payoutRelease/outcome.js +94 -0
  79. package/dist/component/payoutRelease/outcome.js.map +1 -0
  80. package/dist/component/payoutRelease/planning.d.ts.map +1 -1
  81. package/dist/component/payoutRelease/planning.js +5 -2
  82. package/dist/component/payoutRelease/planning.js.map +1 -1
  83. package/dist/component/payoutRelease/queries.d.ts +2 -2
  84. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  85. package/dist/component/payoutRelease/queries.js +2 -0
  86. package/dist/component/payoutRelease/queries.js.map +1 -1
  87. package/dist/component/payoutSnapshots/adoption.d.ts +88 -0
  88. package/dist/component/payoutSnapshots/adoption.d.ts.map +1 -0
  89. package/dist/component/payoutSnapshots/adoption.js +49 -0
  90. package/dist/component/payoutSnapshots/adoption.js.map +1 -0
  91. package/dist/component/payoutSnapshots/financial.d.ts +31 -19
  92. package/dist/component/payoutSnapshots/financial.d.ts.map +1 -1
  93. package/dist/component/payoutSnapshots/financial.js +28 -14
  94. package/dist/component/payoutSnapshots/financial.js.map +1 -1
  95. package/dist/component/payoutSnapshots/localState.d.ts +20 -16
  96. package/dist/component/payoutSnapshots/localState.d.ts.map +1 -1
  97. package/dist/component/payoutSnapshots/localState.js +13 -4
  98. package/dist/component/payoutSnapshots/localState.js.map +1 -1
  99. package/dist/component/payoutSnapshots/mutations.d.ts.map +1 -1
  100. package/dist/component/payoutSnapshots/mutations.js +1 -1
  101. package/dist/component/payoutSnapshots/mutations.js.map +1 -1
  102. package/dist/component/payoutSnapshots/queries.d.ts.map +1 -1
  103. package/dist/component/payoutSnapshots/queries.js +6 -4
  104. package/dist/component/payoutSnapshots/queries.js.map +1 -1
  105. package/dist/component/payoutSnapshots/schema.d.ts +5 -1
  106. package/dist/component/payoutSnapshots/schema.d.ts.map +1 -1
  107. package/dist/component/payoutSnapshots/schema.js +2 -0
  108. package/dist/component/payoutSnapshots/schema.js.map +1 -1
  109. package/dist/component/schema.d.ts +13 -3
  110. package/docs/settlement.md +61 -8
  111. package/package.json +1 -1
  112. package/src/client/connect/payoutActivationProof.ts +123 -53
  113. package/src/client/connect/payoutAdoption.ts +299 -215
  114. package/src/client/connect/payoutAdoptionCollection.ts +78 -0
  115. package/src/client/connect/payoutAdoptionConcurrency.test.ts +266 -0
  116. package/src/client/connect/payoutCacheIdentity.test.ts +93 -0
  117. package/src/client/connect/payoutLargeAdoption.test.ts +541 -0
  118. package/src/client/connect/payoutLargeAdoptionTestHelpers.ts +74 -0
  119. package/src/client/connect/payoutOutcomeBatches.test.ts +40 -0
  120. package/src/client/connect/payoutOutcomeBatches.ts +24 -0
  121. package/src/client/connect/payoutPolicyState.ts +36 -0
  122. package/src/client/connect/payoutQualification.ts +10 -4
  123. package/src/client/connect/payoutReconciliation.ts +86 -7
  124. package/src/client/connect/payoutResumableProof.ts +41 -0
  125. package/src/client/connect/transferReceipt.ts +3 -2
  126. package/src/client/connect/transferReceiptBaseline.test.ts +55 -0
  127. package/src/client/payoutPolicy.ts +37 -23
  128. package/src/component/_generated/api.ts +4 -0
  129. package/src/component/_generated/component.ts +85 -0
  130. package/src/component/payout-snapshots.test.ts +45 -1
  131. package/src/component/payoutPolicy/adoption.ts +20 -7
  132. package/src/component/payoutPolicy/schema.ts +2 -0
  133. package/src/component/payoutRelease/adoption.ts +57 -27
  134. package/src/component/payoutRelease/fees.ts +9 -0
  135. package/src/component/payoutRelease/mutations.ts +26 -96
  136. package/src/component/payoutRelease/outcome.ts +119 -0
  137. package/src/component/payoutRelease/planning.ts +5 -2
  138. package/src/component/payoutRelease/queries.ts +2 -0
  139. package/src/component/payoutSnapshots/adoption.ts +73 -0
  140. package/src/component/payoutSnapshots/financial.ts +33 -20
  141. package/src/component/payoutSnapshots/localState.ts +17 -3
  142. package/src/component/payoutSnapshots/mutations.ts +8 -1
  143. package/src/component/payoutSnapshots/queries.ts +8 -6
  144. package/src/component/payoutSnapshots/schema.ts +2 -0
@@ -1,3 +1,9 @@
1
+ import { adoptionCollectionKey } from "./payoutAdoptionCollection.js";
2
+ import {
3
+ collectLargePayoutInput,
4
+ discardQualificationInput,
5
+ type CollectionRef,
6
+ } from "./payoutCollectedInput.js";
1
7
  import { oldestUnpaidFunding } from "./payoutAdoptionAge.js";
2
8
  import { addSummaryAmounts as add } from "../../component/earnings/arithmetic.js";
3
9
  import type Stripe from "stripe";
@@ -27,7 +33,7 @@ import {
27
33
  type HistoricalFundingSource,
28
34
  type HistoricalFundingPayout,
29
35
  } from "./payoutAdoptionAllocation.js";
30
- import { reconcileRecipientPayout } from "./payoutReconciliation.js";
36
+ import { reconcileRecipientPayouts } from "./payoutReconciliation.js";
31
37
  type Claim = Infer<typeof claimDoc>;
32
38
  export type PayoutAdoptionOptions = {
33
39
  accountId: string;
@@ -49,6 +55,8 @@ export type PayoutAdoptionResult =
49
55
  observations: Infer<typeof observation>[];
50
56
  oldestHeldAt?: number;
51
57
  historyCurrencies: string[];
58
+ /** Internal handoff to funded-activation proof collection only. */
59
+ collection?: CollectionRef;
52
60
  }
53
61
  | { status: "held"; reason: string };
54
62
  /** Import verified terminal historical payouts. Does not change payout schedules or authorize activation. */
@@ -95,7 +103,7 @@ export async function adoptRecipientPayouts(
95
103
  throw new Error(
96
104
  "Historical adoption requires an owned automatic policy at this revision.",
97
105
  );
98
- const snapshot = (await ctx.runQuery(
106
+ let snapshot = (await ctx.runQuery(
99
107
  componentRef(component, "payoutRelease/queries/snapshot"),
100
108
  scope,
101
109
  )) as
@@ -105,227 +113,303 @@ export async function adoptRecipientPayouts(
105
113
  claims: Claim[];
106
114
  }
107
115
  | { status: "held"; reason: string };
108
- if (snapshot.status !== "ready") return snapshot;
109
- const known = new Map(
110
- snapshot.claims
111
- .filter((c) => c.stripePayoutId)
112
- .map((c) => [c.stripePayoutId!, c]),
113
- );
114
- const historyCurrencies = new Set<string>();
115
- const payouts: Stripe.Payout[] = [];
116
- let cursor: string | undefined,
117
- head: string | undefined,
118
- complete = false;
119
- for (let page = 0; page < max; page++) {
120
- const batch = await stripe.payouts.list(
121
- { limit: 100, ...(cursor ? { starting_after: cursor } : {}) },
122
- { stripeAccount: opts.accountId },
116
+ let collection: CollectionRef | undefined;
117
+ if (
118
+ snapshot.status !== "ready" ||
119
+ opts.payouts.length + snapshot.claims.length > 100
120
+ ) {
121
+ const large = await collectLargePayoutInput(
122
+ component,
123
+ ctx,
124
+ {
125
+ ...scope,
126
+ operationKey: await adoptionCollectionKey(
127
+ scope,
128
+ policy.operationKey,
129
+ `import:${opts.currency}`,
130
+ ),
131
+ },
132
+ max,
123
133
  );
124
- if (page === 0) head = batch.data[0]?.id;
125
- for (const p of batch.data) historyCurrencies.add(p.currency);
126
- payouts.push(...batch.data.filter((p) => p.currency === opts.currency));
127
- if (!batch.has_more) {
128
- complete = true;
129
- break;
134
+ collection = large.collection;
135
+ if (large.status !== "ready") {
136
+ await discardQualificationInput(
137
+ component,
138
+ ctx,
139
+ collection,
140
+ large.reason === "collection_pending",
141
+ );
142
+ return { status: "held", reason: large.reason };
130
143
  }
131
- const next = batch.data[batch.data.length - 1]?.id;
132
- if (!next || next === cursor)
133
- return { status: "held", reason: "history_incomplete" };
134
- cursor = next;
144
+ snapshot = large;
135
145
  }
136
- if (!complete) return { status: "held", reason: "history_incomplete" };
137
- if (new Set(payouts.map((p) => p.id)).size !== payouts.length)
138
- return { status: "held", reason: "history_incomplete" };
139
- if ([...mappings.keys()].some((id) => !payouts.some((p) => p.id === id)))
140
- return { status: "held", reason: "historical_history_changed" };
141
- const proofPayouts: HistoricalFundingPayout[] = [];
142
- const transactions: TransferReceiptTransaction[] = [];
143
- const imports = [];
144
- for (const p of payouts) {
145
- const old = known.get(p.id),
146
- supplied = mappings.get(p.id);
147
- const allocations = old?.allocations ?? supplied;
148
- if (!allocations)
149
- return { status: "held", reason: "historical_allocation_required" };
150
- const canonical = (a: typeof allocations) =>
151
- JSON.stringify(
152
- a
153
- .map((x) => [x.stripeTransferId, x.amount])
154
- .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
146
+ let retainCollection = false;
147
+ try {
148
+ const known = new Map(
149
+ snapshot.claims
150
+ .filter((c) => c.stripePayoutId)
151
+ .map((c) => [c.stripePayoutId!, c]),
152
+ );
153
+ const historyCurrencies = new Set<string>();
154
+ const payouts: Stripe.Payout[] = [];
155
+ let cursor: string | undefined,
156
+ head: string | undefined,
157
+ complete = false;
158
+ for (let page = 0; page < max; page++) {
159
+ const batch = await stripe.payouts.list(
160
+ { limit: 100, ...(cursor ? { starting_after: cursor } : {}) },
161
+ { stripeAccount: opts.accountId },
162
+ );
163
+ if (page === 0) head = batch.data[0]?.id;
164
+ for (const p of batch.data) historyCurrencies.add(p.currency);
165
+ payouts.push(...batch.data.filter((p) => p.currency === opts.currency));
166
+ if (!batch.has_more) {
167
+ complete = true;
168
+ break;
169
+ }
170
+ const next = batch.data[batch.data.length - 1]?.id;
171
+ if (!next || next === cursor)
172
+ return { status: "held", reason: "history_incomplete" };
173
+ cursor = next;
174
+ }
175
+ if (!complete) return { status: "held", reason: "history_incomplete" };
176
+ if (new Set(payouts.map((p) => p.id)).size !== payouts.length)
177
+ return { status: "held", reason: "history_incomplete" };
178
+ if ([...mappings.keys()].some((id) => !payouts.some((p) => p.id === id)))
179
+ return { status: "held", reason: "historical_history_changed" };
180
+ const proofPayouts: HistoricalFundingPayout[] = [];
181
+ const transactions: TransferReceiptTransaction[] = [];
182
+ const imports = [];
183
+ for (let start = 0; start < payouts.length; start += 5) {
184
+ const batch = payouts.slice(start, start + 5);
185
+ const receipts = await Promise.all(
186
+ batch.map((p) =>
187
+ getRecipientPayoutReceipt(stripe, {
188
+ accountId: opts.accountId,
189
+ stripePayoutId: p.id,
190
+ }),
191
+ ),
155
192
  );
156
- if (old && supplied && canonical(old.allocations) !== canonical(supplied))
157
- throw new Error(
158
- "Historical payout source allocations cannot be changed.",
193
+ for (let index = 0; index < batch.length; index++) {
194
+ const p = batch[index];
195
+
196
+ const old = known.get(p.id),
197
+ supplied = mappings.get(p.id);
198
+ const allocations = old?.allocations ?? supplied;
199
+ if (!allocations)
200
+ return { status: "held", reason: "historical_allocation_required" };
201
+ const canonical = (a: typeof allocations) =>
202
+ JSON.stringify(
203
+ a
204
+ .map((x) => [x.stripeTransferId, x.amount])
205
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0]))),
206
+ );
207
+ if (
208
+ old &&
209
+ supplied &&
210
+ canonical(old.allocations) !== canonical(supplied)
211
+ )
212
+ throw new Error(
213
+ "Historical payout source allocations cannot be changed.",
214
+ );
215
+ const receipt = receipts[index];
216
+ if (receipt.status !== "ready")
217
+ return { status: "held", reason: receipt.reason };
218
+ if (
219
+ receipt.sourceType !== "card" ||
220
+ receipt.method !== "standard" ||
221
+ receipt.type !== "bank_account"
222
+ )
223
+ return { status: "held", reason: "source_allocation_required" };
224
+ if (!["paid", "failed", "canceled"].includes(receipt.providerStatus))
225
+ return { status: "held", reason: "historical_payout_pending" };
226
+ const returned = receipt.providerStatus !== "paid";
227
+ if (returned && !receipt.credit)
228
+ return { status: "held", reason: "return_unavailable" };
229
+ if (receipt.debit.fee + (receipt.credit?.fee ?? 0) < 0)
230
+ return { status: "held", reason: "fee_allocation_required" };
231
+ proofPayouts.push({
232
+ stripePayoutId: p.id,
233
+ currency: receipt.currency,
234
+ amount: receipt.amount,
235
+ created: receipt.created,
236
+ allocations,
237
+ ...(returned
238
+ ? {
239
+ returnedAt: Math.max(
240
+ receipt.credit!.created,
241
+ receipt.credit!.availableOn,
242
+ ),
243
+ }
244
+ : {}),
245
+ });
246
+ transactions.push({ ...receipt.debit, sourceId: p.id });
247
+ if (receipt.credit)
248
+ transactions.push({ ...receipt.credit, sourceId: p.id });
249
+ imports.push({
250
+ old,
251
+ allocations,
252
+ payout: {
253
+ stripePayoutId: p.id,
254
+ amount: receipt.amount,
255
+ currency: receipt.currency,
256
+ created: receipt.created,
257
+ destinationId: receipt.destinationId,
258
+ status: returned ? ("returned" as const) : ("paid" as const),
259
+ debitTransactionId: receipt.debit.id,
260
+ debitFee: receipt.debit.fee,
261
+ ...(returned
262
+ ? {
263
+ returnTransactionId: receipt.credit!.id,
264
+ returnFee: receipt.credit!.fee,
265
+ }
266
+ : {}),
267
+ },
268
+ });
269
+ }
270
+ }
271
+ const observations: Infer<typeof observation>[] = [];
272
+ const sources: HistoricalFundingSource[] = [];
273
+ for (let i = 0; i < snapshot.transfers.length; i += 5) {
274
+ const batch = snapshot.transfers.slice(i, i + 5);
275
+ const receipts = await Promise.all(
276
+ batch.map((row) =>
277
+ getTransferFundingReceipt(
278
+ stripe,
279
+ component,
280
+ ctx,
281
+ {
282
+ accountId: opts.accountId,
283
+ stripeTransferId: row.stripeTransferId,
284
+ },
285
+ row,
286
+ ),
287
+ ),
159
288
  );
160
- const receipt = await getRecipientPayoutReceipt(stripe, {
161
- accountId: opts.accountId,
162
- stripePayoutId: p.id,
163
- });
164
- if (receipt.status !== "ready")
165
- return { status: "held", reason: receipt.reason };
166
- if (
167
- receipt.sourceType !== "card" ||
168
- receipt.method !== "standard" ||
169
- receipt.type !== "bank_account"
170
- )
171
- return { status: "held", reason: "source_allocation_required" };
172
- if (!["paid", "failed", "canceled"].includes(receipt.providerStatus))
173
- return { status: "held", reason: "historical_payout_pending" };
174
- const returned = receipt.providerStatus !== "paid";
175
- if (returned && !receipt.credit)
176
- return { status: "held", reason: "return_unavailable" };
177
- if (receipt.debit.fee + (receipt.credit?.fee ?? 0) < 0)
178
- return { status: "held", reason: "fee_allocation_required" };
179
- proofPayouts.push({
180
- stripePayoutId: p.id,
181
- currency: receipt.currency,
182
- amount: receipt.amount,
183
- created: receipt.created,
184
- allocations,
185
- ...(returned
186
- ? {
187
- returnedAt: Math.max(
188
- receipt.credit!.created,
189
- receipt.credit!.availableOn,
190
- ),
191
- }
192
- : {}),
193
- });
194
- transactions.push({ ...receipt.debit, sourceId: p.id });
195
- if (receipt.credit)
196
- transactions.push({ ...receipt.credit, sourceId: p.id });
197
- imports.push({
198
- old,
199
- allocations,
200
- payout: {
201
- stripePayoutId: p.id,
202
- amount: receipt.amount,
203
- currency: receipt.currency,
204
- created: receipt.created,
205
- destinationId: receipt.destinationId,
206
- status: returned ? ("returned" as const) : ("paid" as const),
207
- debitTransactionId: receipt.debit.id,
208
- debitFee: receipt.debit.fee,
209
- ...(returned
210
- ? {
211
- returnTransactionId: receipt.credit!.id,
212
- returnFee: receipt.credit!.fee,
213
- }
214
- : {}),
215
- },
216
- });
217
- }
218
- const observations: Infer<typeof observation>[] = [];
219
- const sources: HistoricalFundingSource[] = [];
220
- for (const row of snapshot.transfers) {
221
- const receipt = await getTransferFundingReceipt(stripe, component, ctx, {
289
+ for (let j = 0; j < batch.length; j++) {
290
+ const row = batch[j],
291
+ receipt = receipts[j];
292
+ if (receipt.status !== "ready")
293
+ return { status: "held", reason: receipt.reason };
294
+ historyCurrencies.add(receipt.settlementCurrency);
295
+ sources.push({
296
+ stripeTransferId: row.stripeTransferId,
297
+ currency: receipt.settlementCurrency,
298
+ transactions: receipt.transactions,
299
+ });
300
+ observations.push({
301
+ stripeTransferId: row.stripeTransferId,
302
+ currency: receipt.settlementCurrency,
303
+ matureNet: receipt.matureNet,
304
+ pendingCredits: receipt.pendingCredits,
305
+ ledgerFingerprint: transferFingerprint(row),
306
+ observedAt: receipt.observedAt,
307
+ transactionIds: receipt.transactions.map((t) => t.id),
308
+ });
309
+ if (receipt.settlementCurrency === opts.currency)
310
+ transactions.push(...receipt.transactions);
311
+ }
312
+ }
313
+ validateHistoricalFunding(sources, proofPayouts);
314
+ const claims: Claim[] = [];
315
+ const reconciled = await reconcileRecipientPayouts(
316
+ stripe,
317
+ component,
318
+ ctx,
319
+ scope,
320
+ imports
321
+ .filter((i) => i.old)
322
+ .map((item) => ({
323
+ ...scope,
324
+ operationKey: item.old!.operationKey,
325
+ stripePayoutId: item.payout.stripePayoutId,
326
+ maxPages: max,
327
+ })),
328
+ );
329
+ if (reconciled.status !== "updated") return reconciled;
330
+ claims.push(...reconciled.claims);
331
+ const history = await verifyPayoutHistory(stripe, {
222
332
  accountId: opts.accountId,
223
- stripeTransferId: row.stripeTransferId,
224
- });
225
- if (receipt.status !== "ready")
226
- return { status: "held", reason: receipt.reason };
227
- historyCurrencies.add(receipt.settlementCurrency);
228
- sources.push({
229
- stripeTransferId: row.stripeTransferId,
230
- currency: receipt.settlementCurrency,
231
- transactions: receipt.transactions,
232
- });
233
- observations.push({
234
- stripeTransferId: row.stripeTransferId,
235
- currency: receipt.settlementCurrency,
236
- matureNet: receipt.matureNet,
237
- pendingCredits: receipt.pendingCredits,
238
- ledgerFingerprint: transferFingerprint(row),
239
- observedAt: receipt.observedAt,
240
- transactionIds: receipt.transactions.map((t) => t.id),
241
- });
242
- if (receipt.settlementCurrency === opts.currency)
243
- transactions.push(...receipt.transactions);
244
- }
245
- validateHistoricalFunding(sources, proofPayouts);
246
- const history = await verifyPayoutHistory(stripe, {
247
- accountId: opts.accountId,
248
- currency: opts.currency,
249
- transactions,
250
- maxPages: max,
251
- });
252
- if (history.status !== "verified") return history;
253
- const latest = await stripe.payouts.list(
254
- { limit: 1 },
255
- { stripeAccount: opts.accountId },
256
- );
257
- if (latest.data[0]?.id !== head)
258
- return { status: "held", reason: "provider_changed" };
259
- const claims: Claim[] = [];
260
- for (const item of imports.filter((i) => i.old)) {
261
- const result = await reconcileRecipientPayout(stripe, component, ctx, {
262
- ...scope,
263
- operationKey: item.old!.operationKey,
264
- stripePayoutId: item.payout.stripePayoutId,
333
+ currency: opts.currency,
334
+ transactions,
265
335
  maxPages: max,
266
336
  });
267
- if (result.status !== "updated")
268
- return {
269
- status: "held",
270
- reason:
271
- result.status === "held"
272
- ? result.reason
273
- : "historical_claim_terminal",
274
- };
275
- claims.push(result.claim);
276
- }
277
- const unknown = imports.filter((i) => !i.old);
278
- if (unknown.length && verifyOnly)
279
- return { status: "held", reason: "historical_allocation_required" };
280
- if (unknown.length) {
281
- const fresh = (await ctx.runQuery(
282
- componentRef(component, "payoutRelease/queries/snapshot"),
283
- scope,
284
- )) as
285
- { status: "ready"; claims: Claim[] } | { status: "held"; reason: string };
286
- if (fresh.status !== "ready") return fresh;
287
- const result = (await runMutationOrThrow(
337
+ if (history.status !== "verified") return history;
338
+ const latest = await stripe.payouts.list(
339
+ { limit: 1 },
340
+ { stripeAccount: opts.accountId },
341
+ );
342
+ if (latest.data[0]?.id !== head)
343
+ return { status: "held", reason: "provider_changed" };
344
+ // Complete currency history now matches every receipt after reconciliation.
345
+ for (const o of observations)
346
+ if (o.currency === opts.currency) o.observedAt = history.observedAt;
347
+ const unknown = imports.filter((i) => !i.old);
348
+ if (unknown.length && verifyOnly)
349
+ return { status: "held", reason: "historical_allocation_required" };
350
+ if (unknown.length) {
351
+ const fresh = collection
352
+ ? snapshot
353
+ : ((await ctx.runQuery(
354
+ componentRef(component, "payoutRelease/queries/snapshot"),
355
+ scope,
356
+ )) as
357
+ | { status: "ready"; claims: Claim[] }
358
+ | { status: "held"; reason: string });
359
+ if (fresh.status !== "ready") return fresh;
360
+ const result = (await runMutationOrThrow(
361
+ ctx,
362
+ componentRef(component, "payoutRelease/mutations/adoptHistoricalBatch"),
363
+ {
364
+ ...scope,
365
+ expectedRevision: opts.expectedRevision,
366
+ ...(collection ? { snapshotId: collection.snapshotId } : {}),
367
+ observations,
368
+ expectedClaims: fresh.claims.map((c) => ({
369
+ operationKey: c.operationKey,
370
+ fingerprint: payoutClaimFingerprint(c),
371
+ })),
372
+ payouts: unknown.map((i) => ({
373
+ payout: i.payout,
374
+ allocations: i.allocations,
375
+ })),
376
+ },
377
+ )) as { claims: Claim[] };
378
+ claims.push(...result.claims);
379
+ }
380
+ // Returned cash gets a fresh holding age after consuming its original principal.
381
+ const originalPaid = claims
382
+ .filter((c) => c.status === "paid" || c.status === "returned")
383
+ .flatMap((c) => c.allocations);
384
+ const fees = claims.reduce((total, c) => add(total, c.providerFee ?? 0), 0);
385
+ const returned = proofPayouts
386
+ .filter((p) => p.returnedAt !== undefined)
387
+ .flatMap((p) =>
388
+ p.allocations.map((a) => ({ ...a, created: p.returnedAt! })),
389
+ );
390
+ const oldestHeldAt = oldestUnpaidFunding(
391
+ opts.currency,
392
+ sources,
393
+ originalPaid,
394
+ fees,
395
+ returned,
396
+ );
397
+ retainCollection = verifyOnly;
398
+ return {
399
+ status: "adopted",
400
+ ...(verifyOnly && collection ? { collection } : {}),
401
+ claims,
402
+ observations,
403
+ historyCurrencies: [...historyCurrencies],
404
+ ...(oldestHeldAt !== undefined ? { oldestHeldAt } : {}),
405
+ observedAt: Date.now(),
406
+ };
407
+ } finally {
408
+ await discardQualificationInput(
409
+ component,
288
410
  ctx,
289
- componentRef(component, "payoutRelease/mutations/adoptHistoricalBatch"),
290
- {
291
- ...scope,
292
- expectedRevision: opts.expectedRevision,
293
- observations,
294
- expectedClaims: fresh.claims.map((c) => ({
295
- operationKey: c.operationKey,
296
- fingerprint: payoutClaimFingerprint(c),
297
- })),
298
- payouts: unknown.map((i) => ({
299
- payout: i.payout,
300
- allocations: i.allocations,
301
- })),
302
- },
303
- )) as { claims: Claim[] };
304
- claims.push(...result.claims);
305
- }
306
- // Returned cash gets a fresh holding age after consuming its original principal.
307
- const originalPaid = claims
308
- .filter((c) => c.status === "paid" || c.status === "returned")
309
- .flatMap((c) => c.allocations);
310
- const fees = claims.reduce((total, c) => add(total, c.providerFee ?? 0), 0);
311
- const returned = proofPayouts
312
- .filter((p) => p.returnedAt !== undefined)
313
- .flatMap((p) =>
314
- p.allocations.map((a) => ({ ...a, created: p.returnedAt! })),
411
+ collection,
412
+ retainCollection,
315
413
  );
316
- const oldestHeldAt = oldestUnpaidFunding(
317
- opts.currency,
318
- sources,
319
- originalPaid,
320
- fees,
321
- returned,
322
- );
323
- return {
324
- status: "adopted",
325
- claims,
326
- observations,
327
- historyCurrencies: [...historyCurrencies],
328
- ...(oldestHeldAt !== undefined ? { oldestHeldAt } : {}),
329
- observedAt: Date.now(),
330
- };
414
+ }
331
415
  }
@@ -0,0 +1,78 @@
1
+ import { readPayoutOperation } from "./payoutPolicyState.js";
2
+ import type { Infer } from "convex/values";
3
+ import type {
4
+ adoptionProof,
5
+ operationDoc,
6
+ } from "../../component/payoutPolicy/schema.js";
7
+ import type { Component, RunCtx } from "../helpers.js";
8
+ import { runMutationOrThrow } from "../helpers.js";
9
+ import { componentRef } from "../webhooks/helpers.js";
10
+ import { discardQualificationInput } from "./payoutCollectedInput.js";
11
+ export async function adoptionCollectionKey(
12
+ scope: { accountId: string; ownerKey: string },
13
+ operationKey: string,
14
+ purpose: string,
15
+ ) {
16
+ const bytes = new TextEncoder().encode(
17
+ JSON.stringify([scope.accountId, scope.ownerKey, operationKey, purpose]),
18
+ );
19
+ const digest = await crypto.subtle.digest("SHA-256", bytes);
20
+ return (
21
+ "bs:adopt:" +
22
+ Array.from(new Uint8Array(digest), (b) =>
23
+ b.toString(16).padStart(2, "0"),
24
+ ).join("")
25
+ );
26
+ }
27
+ export async function discardAdoptionProof(
28
+ component: Component,
29
+ ctx: RunCtx,
30
+ scope: { accountId: string; ownerKey: string },
31
+ proof?: Pick<Infer<typeof adoptionProof>, "snapshotId" | "collectionKey">,
32
+ ) {
33
+ if (proof?.snapshotId && proof.collectionKey)
34
+ await discardQualificationInput(component, ctx, {
35
+ accountId: scope.accountId,
36
+ ownerKey: scope.ownerKey,
37
+ snapshotId: proof.snapshotId,
38
+ operationKey: proof.collectionKey,
39
+ });
40
+ }
41
+ /** Only disposable read-only proof caches are cleaned; policy/restoration operations remain durable. */
42
+ export async function runAdoptionMutation(
43
+ component: Component,
44
+ ctx: RunCtx,
45
+ kind: "prepare" | "beginAttempt",
46
+ args: {
47
+ accountId: string;
48
+ ownerKey: string;
49
+ adoption?: Infer<typeof adoptionProof>;
50
+ [key: string]: unknown;
51
+ },
52
+ ): Promise<Infer<typeof operationDoc> | { status: "operation_changed" }> {
53
+ try {
54
+ return (await runMutationOrThrow(
55
+ ctx,
56
+ componentRef(component, `payoutPolicy/mutations/${kind}`),
57
+ args,
58
+ )) as Infer<typeof operationDoc>;
59
+ } catch (error) {
60
+ if (kind === "beginAttempt" && typeof args.operationKey === "string") {
61
+ const operation = await readPayoutOperation(component, ctx, {
62
+ accountId: args.accountId,
63
+ ownerKey: args.ownerKey,
64
+ operationKey: args.operationKey,
65
+ });
66
+ if (
67
+ operation &&
68
+ (operation.attempted ||
69
+ operation.status === "complete" ||
70
+ operation.status === "canceled")
71
+ )
72
+ return { status: "operation_changed" };
73
+ }
74
+ throw error;
75
+ } finally {
76
+ await discardAdoptionProof(component, ctx, args, args.adoption);
77
+ }
78
+ }