@fantastic.dev/better-stripe 0.29.0 → 0.30.1

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 (158) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/MIGRATION.md +8 -0
  3. package/README.md +10 -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/dist/react/index.d.ts +1 -0
  111. package/dist/react/index.d.ts.map +1 -1
  112. package/dist/react/index.js +1 -0
  113. package/dist/react/index.js.map +1 -1
  114. package/dist/react/lib/payout-format.d.ts +5 -0
  115. package/dist/react/lib/payout-format.d.ts.map +1 -0
  116. package/dist/react/lib/payout-format.js +13 -0
  117. package/dist/react/lib/payout-format.js.map +1 -0
  118. package/dist/react/workflows/Payouts.js +4 -4
  119. package/dist/react/workflows/Payouts.js.map +1 -1
  120. package/docs/react-workflows.md +9 -4
  121. package/docs/settlement.md +61 -8
  122. package/package.json +1 -1
  123. package/src/client/connect/payoutActivationProof.ts +123 -53
  124. package/src/client/connect/payoutAdoption.ts +299 -215
  125. package/src/client/connect/payoutAdoptionCollection.ts +78 -0
  126. package/src/client/connect/payoutAdoptionConcurrency.test.ts +266 -0
  127. package/src/client/connect/payoutCacheIdentity.test.ts +93 -0
  128. package/src/client/connect/payoutLargeAdoption.test.ts +541 -0
  129. package/src/client/connect/payoutLargeAdoptionTestHelpers.ts +74 -0
  130. package/src/client/connect/payoutOutcomeBatches.test.ts +40 -0
  131. package/src/client/connect/payoutOutcomeBatches.ts +24 -0
  132. package/src/client/connect/payoutPolicyState.ts +36 -0
  133. package/src/client/connect/payoutQualification.ts +10 -4
  134. package/src/client/connect/payoutReconciliation.ts +86 -7
  135. package/src/client/connect/payoutResumableProof.ts +41 -0
  136. package/src/client/connect/transferReceipt.ts +3 -2
  137. package/src/client/connect/transferReceiptBaseline.test.ts +55 -0
  138. package/src/client/payoutPolicy.ts +37 -23
  139. package/src/component/_generated/api.ts +4 -0
  140. package/src/component/_generated/component.ts +85 -0
  141. package/src/component/payout-snapshots.test.ts +45 -1
  142. package/src/component/payoutPolicy/adoption.ts +20 -7
  143. package/src/component/payoutPolicy/schema.ts +2 -0
  144. package/src/component/payoutRelease/adoption.ts +57 -27
  145. package/src/component/payoutRelease/fees.ts +9 -0
  146. package/src/component/payoutRelease/mutations.ts +26 -96
  147. package/src/component/payoutRelease/outcome.ts +119 -0
  148. package/src/component/payoutRelease/planning.ts +5 -2
  149. package/src/component/payoutRelease/queries.ts +2 -0
  150. package/src/component/payoutSnapshots/adoption.ts +73 -0
  151. package/src/component/payoutSnapshots/financial.ts +33 -20
  152. package/src/component/payoutSnapshots/localState.ts +17 -3
  153. package/src/component/payoutSnapshots/mutations.ts +8 -1
  154. package/src/component/payoutSnapshots/queries.ts +8 -6
  155. package/src/component/payoutSnapshots/schema.ts +2 -0
  156. package/src/react/index.ts +1 -0
  157. package/src/react/lib/payout-format.ts +16 -0
  158. package/src/react/workflows/Payouts.tsx +7 -5
@@ -0,0 +1,36 @@
1
+ import type { Infer } from "convex/values";
2
+ import type {
3
+ operationDoc,
4
+ policyDoc,
5
+ } from "../../component/payoutPolicy/schema.js";
6
+ import type { Component, RunCtx } from "../helpers.js";
7
+ import { validateScope } from "../../component/payoutPolicy/helpers.js";
8
+ import { componentRef } from "../webhooks/helpers.js";
9
+ /** Re-read the same durable operation; callers must still authorize the recipient scope. */
10
+ export function readPayoutOperation(
11
+ component: Component,
12
+ ctx: RunCtx,
13
+ args: { accountId: string; ownerKey: string; operationKey: string },
14
+ ): Promise<Infer<typeof operationDoc> | null> {
15
+ validateScope(args);
16
+ return ctx.runQuery(
17
+ componentRef(component, "payoutPolicy/queries/operation"),
18
+ {
19
+ accountId: args.accountId,
20
+ ownerKey: args.ownerKey,
21
+ operationKey: args.operationKey,
22
+ },
23
+ );
24
+ }
25
+
26
+ export function readPayoutPolicy(
27
+ component: Component,
28
+ ctx: RunCtx,
29
+ scope: { accountId: string; ownerKey: string },
30
+ ): Promise<Infer<typeof policyDoc> | null> {
31
+ validateScope(scope);
32
+ return ctx.runQuery(componentRef(component, "payoutPolicy/queries/get"), {
33
+ accountId: scope.accountId,
34
+ ownerKey: scope.ownerKey,
35
+ });
36
+ }
@@ -145,10 +145,16 @@ async function qualifyInput(
145
145
  const batch = snapshot.transfers.slice(i, i + 5);
146
146
  const receipts = await Promise.all(
147
147
  batch.map((row) =>
148
- getTransferFundingReceipt(stripe, component, ctx, {
149
- accountId: opts.accountId,
150
- stripeTransferId: row.stripeTransferId,
151
- }),
148
+ getTransferFundingReceipt(
149
+ stripe,
150
+ component,
151
+ ctx,
152
+ {
153
+ accountId: opts.accountId,
154
+ stripeTransferId: row.stripeTransferId,
155
+ },
156
+ row,
157
+ ),
152
158
  ),
153
159
  );
154
160
  for (let j = 0; j < batch.length; j++) {
@@ -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
+ }
@@ -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
+ });
@@ -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,10 +59,12 @@ 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";
66
68
  import type * as payoutSnapshots_financial from "../payoutSnapshots/financial.js";
67
69
  import type * as payoutSnapshots_liabilities from "../payoutSnapshots/liabilities.js";
68
70
  import type * as payoutSnapshots_localState from "../payoutSnapshots/localState.js";
@@ -148,10 +150,12 @@ const fullApi: ApiFromModules<{
148
150
  "payoutRelease/helpers": typeof payoutRelease_helpers;
149
151
  "payoutRelease/mutations": typeof payoutRelease_mutations;
150
152
  "payoutRelease/observation": typeof payoutRelease_observation;
153
+ "payoutRelease/outcome": typeof payoutRelease_outcome;
151
154
  "payoutRelease/planning": typeof payoutRelease_planning;
152
155
  "payoutRelease/preview": typeof payoutRelease_preview;
153
156
  "payoutRelease/progress": typeof payoutRelease_progress;
154
157
  "payoutRelease/queries": typeof payoutRelease_queries;
158
+ "payoutSnapshots/adoption": typeof payoutSnapshots_adoption;
155
159
  "payoutSnapshots/financial": typeof payoutSnapshots_financial;
156
160
  "payoutSnapshots/liabilities": typeof payoutSnapshots_liabilities;
157
161
  "payoutSnapshots/localState": typeof payoutSnapshots_localState;
@@ -2738,6 +2738,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2738
2738
  accountId: string;
2739
2739
  adoption?: {
2740
2740
  claims: Array<{ fingerprint: string; operationKey: string }>;
2741
+ collectionKey?: string;
2741
2742
  observations: Array<{
2742
2743
  currency: string;
2743
2744
  ledgerFingerprint: string;
@@ -2748,6 +2749,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2748
2749
  transactionIds: Array<string>;
2749
2750
  }>;
2750
2751
  oldestHeldAt?: number;
2752
+ snapshotId?: string;
2751
2753
  };
2752
2754
  operationKey: string;
2753
2755
  ownerKey: string;
@@ -2758,6 +2760,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2758
2760
  accountId: string;
2759
2761
  adoption?: {
2760
2762
  claims: Array<{ fingerprint: string; operationKey: string }>;
2763
+ collectionKey?: string;
2761
2764
  observations: Array<{
2762
2765
  currency: string;
2763
2766
  ledgerFingerprint: string;
@@ -2768,6 +2771,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2768
2771
  transactionIds: Array<string>;
2769
2772
  }>;
2770
2773
  oldestHeldAt?: number;
2774
+ snapshotId?: string;
2771
2775
  };
2772
2776
  attempted?: boolean;
2773
2777
  country: string;
@@ -2854,6 +2858,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2854
2858
  accountId: string;
2855
2859
  adoption?: {
2856
2860
  claims: Array<{ fingerprint: string; operationKey: string }>;
2861
+ collectionKey?: string;
2857
2862
  observations: Array<{
2858
2863
  currency: string;
2859
2864
  ledgerFingerprint: string;
@@ -2864,6 +2869,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2864
2869
  transactionIds: Array<string>;
2865
2870
  }>;
2866
2871
  oldestHeldAt?: number;
2872
+ snapshotId?: string;
2867
2873
  };
2868
2874
  attempted?: boolean;
2869
2875
  country: string;
@@ -2912,6 +2918,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2912
2918
  accountId: string;
2913
2919
  adoption?: {
2914
2920
  claims: Array<{ fingerprint: string; operationKey: string }>;
2921
+ collectionKey?: string;
2915
2922
  observations: Array<{
2916
2923
  currency: string;
2917
2924
  ledgerFingerprint: string;
@@ -2922,6 +2929,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2922
2929
  transactionIds: Array<string>;
2923
2930
  }>;
2924
2931
  oldestHeldAt?: number;
2932
+ snapshotId?: string;
2925
2933
  };
2926
2934
  attempted?: boolean;
2927
2935
  country: string;
@@ -3007,6 +3015,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3007
3015
  accountId: string;
3008
3016
  adoption?: {
3009
3017
  claims: Array<{ fingerprint: string; operationKey: string }>;
3018
+ collectionKey?: string;
3010
3019
  observations: Array<{
3011
3020
  currency: string;
3012
3021
  ledgerFingerprint: string;
@@ -3017,6 +3026,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3017
3026
  transactionIds: Array<string>;
3018
3027
  }>;
3019
3028
  oldestHeldAt?: number;
3029
+ snapshotId?: string;
3020
3030
  };
3021
3031
  country: string;
3022
3032
  expectedRevision: number;
@@ -3037,6 +3047,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3037
3047
  accountId: string;
3038
3048
  adoption?: {
3039
3049
  claims: Array<{ fingerprint: string; operationKey: string }>;
3050
+ collectionKey?: string;
3040
3051
  observations: Array<{
3041
3052
  currency: string;
3042
3053
  ledgerFingerprint: string;
@@ -3047,6 +3058,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3047
3058
  transactionIds: Array<string>;
3048
3059
  }>;
3049
3060
  oldestHeldAt?: number;
3061
+ snapshotId?: string;
3050
3062
  };
3051
3063
  attempted?: boolean;
3052
3064
  country: string;
@@ -3178,6 +3190,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3178
3190
  accountId: string;
3179
3191
  adoption?: {
3180
3192
  claims: Array<{ fingerprint: string; operationKey: string }>;
3193
+ collectionKey?: string;
3181
3194
  observations: Array<{
3182
3195
  currency: string;
3183
3196
  ledgerFingerprint: string;
@@ -3188,6 +3201,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3188
3201
  transactionIds: Array<string>;
3189
3202
  }>;
3190
3203
  oldestHeldAt?: number;
3204
+ snapshotId?: string;
3191
3205
  };
3192
3206
  attempted?: boolean;
3193
3207
  country: string;
@@ -3260,6 +3274,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3260
3274
  stripePayoutId: string;
3261
3275
  };
3262
3276
  }>;
3277
+ snapshotId?: string;
3263
3278
  },
3264
3279
  {
3265
3280
  claims: Array<{
@@ -3567,6 +3582,76 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3567
3582
  },
3568
3583
  Name
3569
3584
  >;
3585
+ recordOutcomes: FunctionReference<
3586
+ "mutation",
3587
+ "internal",
3588
+ {
3589
+ accountId: string;
3590
+ outcomes: Array<{
3591
+ accountId: string;
3592
+ amount: number;
3593
+ currency: string;
3594
+ debitFee?: number;
3595
+ debitTransactionId?: string;
3596
+ operationKey: string;
3597
+ ownerKey: string;
3598
+ providerStatus:
3599
+ "pending" | "in_transit" | "paid" | "failed" | "canceled";
3600
+ returnFee?: number;
3601
+ returnTransactionId?: string;
3602
+ stripePayoutId: string;
3603
+ }>;
3604
+ ownerKey: string;
3605
+ },
3606
+ Array<{
3607
+ _creationTime: number;
3608
+ _id: string;
3609
+ accountId: string;
3610
+ allocations: Array<{
3611
+ amount: number;
3612
+ role?: "store" | "affiliate" | "other";
3613
+ stripeTransferId: string;
3614
+ }>;
3615
+ amount: number;
3616
+ attemptedAt?: number;
3617
+ currency: string;
3618
+ debitFee?: number;
3619
+ debitTransactionId?: string;
3620
+ destinationId?: string;
3621
+ expectedRevision: number;
3622
+ feeRevision?: number;
3623
+ historical?: boolean;
3624
+ independentLiabilities?: number;
3625
+ liabilityRevision?: number;
3626
+ observations: Array<{
3627
+ currency: string;
3628
+ ledgerFingerprint: string;
3629
+ matureNet: number;
3630
+ observedAt: number;
3631
+ pendingCredits: number;
3632
+ stripeTransferId: string;
3633
+ transactionIds: Array<string>;
3634
+ }>;
3635
+ operationKey: string;
3636
+ ownerKey: string;
3637
+ providerFee?: number;
3638
+ rejection?: {
3639
+ code: "balance_insufficient" | "amount_too_small";
3640
+ requestId: string;
3641
+ };
3642
+ returnTransactionId?: string;
3643
+ snapshotId?: string;
3644
+ status:
3645
+ | "reserved"
3646
+ | "submitted"
3647
+ | "paid"
3648
+ | "returned"
3649
+ | "canceled"
3650
+ | "rejected";
3651
+ stripePayoutId?: string;
3652
+ }>,
3653
+ Name
3654
+ >;
3570
3655
  recordRejection: FunctionReference<
3571
3656
  "mutation",
3572
3657
  "internal",