@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,9 +1,10 @@
1
1
  // @vitest-environment edge-runtime
2
2
  import { convexTest } from "convex-test";
3
3
  import { makeFunctionReference } from "convex/server";
4
- import { expect, it } from "vitest";
4
+ import { expect, it, vi } from "vitest";
5
5
  import type { Doc } from "./_generated/dataModel.js";
6
6
  import schema from "./schema.js";
7
+ import { cacheSource } from "./payoutSnapshots/localState.js";
7
8
  import { transferFingerprint } from "./payoutRelease/helpers.js";
8
9
  const modules = import.meta.glob("./**/*.*s");
9
10
  const m = (name: string) =>
@@ -393,3 +394,46 @@ it("retains a risk-journal continuation when changes exceed one page", async ()
393
394
  sourceCount: 1,
394
395
  });
395
396
  });
397
+
398
+ it("retains immutable primary source IDs in the disposable verification cache", async () => {
399
+ const s = await setup(2);
400
+ await s.finish(await s.begin());
401
+ const rows = await s.t.run(async (ctx) => ({
402
+ sources: await ctx.db.query("transfers").collect(),
403
+ cache: await ctx.db.query("payoutSnapshotSources").collect(),
404
+ }));
405
+ expect(rows.cache).toHaveLength(2);
406
+ for (const cached of rows.cache)
407
+ expect(
408
+ (cached as typeof cached & { transferDocId?: string }).transferDocId,
409
+ ).toBe(
410
+ rows.sources.find(
411
+ (row) => row.stripeTransferId === cached.stripeTransferId,
412
+ )!._id,
413
+ );
414
+ });
415
+
416
+ it("does not rewrite an unchanged source already cached in the same collection", async () => {
417
+ const s = await setup(2);
418
+ const started = await s.begin();
419
+ const h = await s.step(started.step);
420
+ await s.t.run(async (ctx) => {
421
+ const transfer = await ctx.db.query("transfers").first();
422
+ if (!transfer) throw Error("Missing source");
423
+ const patch = vi.spyOn(ctx.db, "patch");
424
+ await cacheSource(
425
+ ctx,
426
+ h,
427
+ transfer.stripeTransferId,
428
+ {
429
+ sourceCount: h.sourceCount,
430
+ allocationCount: h.allocationCount,
431
+ claimCount: h.claimCount,
432
+ feeCount: h.feeCount,
433
+ },
434
+ transfer,
435
+ );
436
+ expect(patch).not.toHaveBeenCalled();
437
+ patch.mockRestore();
438
+ });
439
+ });
@@ -1,3 +1,4 @@
1
+ import { adoptionCollection } from "../payoutSnapshots/adoption.js";
1
2
  import type { Infer } from "convex/values";
2
3
  import type { MutationCtx } from "../_generated/server.js";
3
4
  import type { adoptionProof } from "./schema.js";
@@ -14,16 +15,26 @@ export async function validateAdoption(
14
15
  scope: { accountId: string; ownerKey: string },
15
16
  proof: Infer<typeof adoptionProof>,
16
17
  ) {
17
- await checkSnapshot(ctx, scope.accountId, proof.observations, true);
18
- const rows = await ctx.db
19
- .query("payoutReleaseClaims")
20
- .withIndex("by_account_status", (q) => q.eq("accountId", scope.accountId))
21
- .take(101);
18
+ const collected = await adoptionCollection(ctx, scope, proof);
19
+ await checkSnapshot(
20
+ ctx,
21
+ scope.accountId,
22
+ proof.observations,
23
+ true,
24
+ undefined,
25
+ collected?.sources,
26
+ );
27
+ const rows =
28
+ collected?.claims ??
29
+ (await ctx.db
30
+ .query("payoutReleaseClaims")
31
+ .withIndex("by_account_status", (q) => q.eq("accountId", scope.accountId))
32
+ .take(101));
22
33
  const expected = new Map(
23
34
  proof.claims.map((c) => [c.operationKey, c.fingerprint]),
24
35
  );
25
36
  if (
26
- rows.length > 100 ||
37
+ (!collected && rows.length > 100) ||
27
38
  expected.size !== proof.claims.length ||
28
39
  rows.length !== expected.size ||
29
40
  rows.some(
@@ -39,7 +50,9 @@ export async function validateAdoption(
39
50
  );
40
51
  const owed = new Map<string, number>();
41
52
  for (const o of proof.observations) {
42
- const source = await sourceById(ctx, o.stripeTransferId);
53
+ const source = collected?.allocations?.has(o.stripeTransferId)
54
+ ? collected.allocations.get(o.stripeTransferId)
55
+ : await sourceById(ctx, o.stripeTransferId);
43
56
  if (
44
57
  source &&
45
58
  (source.accountId !== scope.accountId ||
@@ -17,6 +17,8 @@ export const thresholds = v.array(
17
17
  v.object({ currency: v.string(), amount: v.number() }),
18
18
  );
19
19
  export const adoptionProof = v.object({
20
+ snapshotId: v.optional(v.id("payoutSnapshots")),
21
+ collectionKey: v.optional(v.string()),
20
22
  observations: v.array(observation),
21
23
  claims: v.array(
22
24
  v.object({ operationKey: v.string(), fingerprint: v.string() }),
@@ -1,3 +1,5 @@
1
+ import type { Doc } from "../_generated/dataModel.js";
2
+ import { adoptionCollection } from "../payoutSnapshots/adoption.js";
1
3
  import { v, type Infer } from "convex/values";
2
4
  import type { MutationCtx } from "../_generated/server.js";
3
5
  import { scopeFields } from "../payoutPolicy/schema.js";
@@ -32,7 +34,11 @@ type Args = {
32
34
  [K in keyof typeof historicalArgs]: Infer<(typeof historicalArgs)[K]>;
33
35
  };
34
36
  /** Trusted package observations only. Provider history and historical maturity are verified upstream. */
35
- export async function adoptHistoricalPayout(ctx: MutationCtx, args: Args) {
37
+ export async function adoptHistoricalPayout(
38
+ ctx: MutationCtx,
39
+ args: Args,
40
+ collected?: Map<string, Doc<"transfers">>,
41
+ ) {
36
42
  const policy = await readPolicy(ctx, args);
37
43
  if (!policy || policy.revision !== args.expectedRevision)
38
44
  throw new Error("Historical payout policy revision changed.");
@@ -61,12 +67,9 @@ export async function adoptHistoricalPayout(ctx: MutationCtx, args: Args) {
61
67
  : p.returnTransactionId !== undefined || p.returnFee !== undefined)
62
68
  )
63
69
  throw new Error("Invalid historical payout receipt.");
64
- const rows = await checkSnapshot(
65
- ctx,
66
- args.accountId,
67
- args.observations,
68
- true,
69
- );
70
+ const rows =
71
+ collected ??
72
+ (await checkSnapshot(ctx, args.accountId, args.observations, true));
70
73
  const byObservation = new Map(
71
74
  args.observations.map((o) => [o.stripeTransferId, o]),
72
75
  );
@@ -142,12 +145,14 @@ export async function adoptHistoricalPayout(ctx: MutationCtx, args: Args) {
142
145
  "Resolve existing payout attempts before historical adoption.",
143
146
  );
144
147
  }
145
- const history = await ctx.db
146
- .query("payoutReleaseClaims")
147
- .withIndex("by_account_status", (q) => q.eq("accountId", args.accountId))
148
- .take(100);
149
- if (history.length >= 100)
150
- throw new Error("Historical payout snapshot limit exceeded.");
148
+ if (!collected) {
149
+ const history = await ctx.db
150
+ .query("payoutReleaseClaims")
151
+ .withIndex("by_account_status", (q) => q.eq("accountId", args.accountId))
152
+ .take(100);
153
+ if (history.length >= 100)
154
+ throw new Error("Historical payout snapshot limit exceeded.");
155
+ }
151
156
  for (const a of allocations) {
152
157
  const source = await sourceById(ctx, a.stripeTransferId);
153
158
  if (
@@ -185,7 +190,10 @@ export async function adoptHistoricalPayout(ctx: MutationCtx, args: Args) {
185
190
  amount: p.amount,
186
191
  destinationId: p.destinationId,
187
192
  allocations,
188
- observations: args.observations,
193
+ // Complete batch membership is validated above. Keep the immutable receipt
194
+ // evidence for every source allocated to this historical payout, rather than
195
+ // duplicating unrelated source proofs on every imported claim.
196
+ observations: args.observations.filter((o) => seen.has(o.stripeTransferId)),
189
197
  status: p.status,
190
198
  attemptedAt: p.created * 1000,
191
199
  stripePayoutId: p.stripePayoutId,
@@ -208,6 +216,7 @@ export async function adoptHistoricalPayout(ctx: MutationCtx, args: Args) {
208
216
  }
209
217
 
210
218
  export const historicalBatchArgs = {
219
+ snapshotId: v.optional(v.id("payoutSnapshots")),
211
220
  ...scopeFields,
212
221
  expectedRevision: v.number(),
213
222
  observations: v.array(observation),
@@ -227,17 +236,34 @@ type BatchArgs = {
227
236
  >;
228
237
  };
229
238
  export async function adoptHistoricalBatch(ctx: MutationCtx, args: BatchArgs) {
230
- if (!args.payouts.length || args.payouts.length > 100)
239
+ if (!args.payouts.length || (!args.snapshotId && args.payouts.length > 100))
231
240
  throw new Error("Invalid historical payout batch size.");
232
- const rows = await ctx.db
233
- .query("payoutReleaseClaims")
234
- .withIndex("by_account_status", (q) => q.eq("accountId", args.accountId))
235
- .take(101);
241
+ const collected = await adoptionCollection(ctx, args, {
242
+ snapshotId: args.snapshotId,
243
+ observations: args.observations,
244
+ claims: args.expectedClaims,
245
+ });
246
+ const validated = collected
247
+ ? await checkSnapshot(
248
+ ctx,
249
+ args.accountId,
250
+ args.observations,
251
+ true,
252
+ undefined,
253
+ collected.sources,
254
+ )
255
+ : undefined;
256
+ const rows =
257
+ collected?.claims ??
258
+ (await ctx.db
259
+ .query("payoutReleaseClaims")
260
+ .withIndex("by_account_status", (q) => q.eq("accountId", args.accountId))
261
+ .take(101));
236
262
  const expected = new Map(
237
263
  args.expectedClaims.map((c) => [c.operationKey, c.fingerprint]),
238
264
  );
239
265
  if (
240
- rows.length > 100 ||
266
+ (!collected && rows.length > 100) ||
241
267
  expected.size !== args.expectedClaims.length ||
242
268
  rows.length !== expected.size ||
243
269
  rows.some(
@@ -250,13 +276,17 @@ export async function adoptHistoricalBatch(ctx: MutationCtx, args: BatchArgs) {
250
276
  const claims = [];
251
277
  for (const p of args.payouts)
252
278
  claims.push(
253
- await adoptHistoricalPayout(ctx, {
254
- accountId: args.accountId,
255
- ownerKey: args.ownerKey,
256
- expectedRevision: args.expectedRevision,
257
- observations: args.observations,
258
- ...p,
259
- }),
279
+ await adoptHistoricalPayout(
280
+ ctx,
281
+ {
282
+ accountId: args.accountId,
283
+ ownerKey: args.ownerKey,
284
+ expectedRevision: args.expectedRevision,
285
+ observations: args.observations,
286
+ ...p,
287
+ },
288
+ validated,
289
+ ),
260
290
  );
261
291
  return { claims };
262
292
  }
@@ -66,6 +66,15 @@ export async function recordFees(
66
66
  )
67
67
  throw new Error("Verified payout return fee receipt changed.");
68
68
  const delta = add(fee, -(claim.providerFee ?? 0));
69
+ // Idempotent paid-history reads must not rewrite an already verified claim.
70
+ // Receipt identity, signed fee arithmetic and uniqueness were checked above.
71
+ if (
72
+ delta === 0 &&
73
+ claim.debitTransactionId === proof.debitTransactionId &&
74
+ claim.debitFee === proof.debitFee &&
75
+ claim.providerFee === fee
76
+ )
77
+ return;
69
78
  if (delta !== 0) {
70
79
  const balance = await readFees(ctx, claim);
71
80
  const amount = add(balance?.amount ?? 0, delta);
@@ -1,3 +1,4 @@
1
+ import { outcomeArgs, recordPayoutOutcome } from "./outcome.js";
1
2
  import {
2
3
  collectedSources,
3
4
  bindCollection,
@@ -11,7 +12,7 @@ import {
11
12
  historicalBatchArgs,
12
13
  adoptHistoricalBatch as importHistoricalBatch,
13
14
  } from "./adoption.js";
14
- import { readFees, recordFees } from "./fees.js";
15
+ import { readFees } from "./fees.js";
15
16
  import { v } from "convex/values";
16
17
  import { mutation } from "../earnings/triggers.js";
17
18
  import { identity, observation, claimDoc } from "./schema.js";
@@ -144,7 +145,7 @@ export const beginAttempt = mutation({
144
145
  claim.observations,
145
146
  true,
146
147
  claim.currency,
147
- await collectedSources(ctx, claim, claim.observations),
148
+ (await collectedSources(ctx, claim, claim.observations))?.transfers,
148
149
  );
149
150
  await reserveRecoveryGuard(ctx, claim, claim.amount);
150
151
  await ctx.db.patch("payoutReleaseClaims", claim._id, {
@@ -176,107 +177,36 @@ export const cancelUnattempted = mutation({
176
177
  },
177
178
  });
178
179
  export const recordOutcome = mutation({
180
+ args: outcomeArgs,
181
+ returns: claimDoc,
182
+ handler: recordPayoutOutcome,
183
+ });
184
+ /** Bounded atomic reconciliation; every row retains the single-outcome validation. */
185
+ export const recordOutcomes = mutation({
179
186
  args: {
180
- ...identity,
181
- stripePayoutId: v.string(),
182
- amount: v.number(),
183
- currency: v.string(),
184
- providerStatus: v.union(
185
- v.literal("pending"),
186
- v.literal("in_transit"),
187
- v.literal("paid"),
188
- v.literal("failed"),
189
- v.literal("canceled"),
190
- ),
191
- returnTransactionId: v.optional(v.string()),
192
- debitTransactionId: v.optional(v.string()),
193
- debitFee: v.optional(v.number()),
194
- returnFee: v.optional(v.number()),
187
+ accountId: v.string(),
188
+ ownerKey: v.string(),
189
+ outcomes: v.array(outcomeArgs),
195
190
  },
196
- returns: claimDoc,
191
+ returns: v.array(claimDoc),
197
192
  handler: async (ctx, args) => {
198
- const claim = await claimByKey(ctx, args);
199
- if (
200
- !claim ||
201
- claim.attemptedAt === undefined ||
202
- claim.status === "canceled" ||
203
- claim.status === "rejected"
204
- )
205
- throw new Error("Payout receipt has no attempted claim.");
206
193
  if (
207
- !/^po_\w+$/.test(args.stripePayoutId) ||
208
- args.stripePayoutId.trim() !== args.stripePayoutId ||
209
- args.currency !== claim.currency ||
210
- args.amount !== claim.amount ||
211
- (claim.stripePayoutId !== undefined &&
212
- claim.stripePayoutId !== args.stripePayoutId)
194
+ !args.outcomes.length ||
195
+ args.outcomes.length > 25 ||
196
+ new Set(args.outcomes.map((o) => o.operationKey)).size !==
197
+ args.outcomes.length
213
198
  )
214
- throw new Error("Payout receipt identity or amount does not match.");
215
- const adopted = await ctx.db
216
- .query("payoutReleaseClaims")
217
- .withIndex("by_provider_payout", (q) =>
218
- q.eq("stripePayoutId", args.stripePayoutId),
199
+ throw new Error("Invalid payout outcome batch.");
200
+ const results = [];
201
+ for (const outcome of args.outcomes) {
202
+ if (
203
+ outcome.accountId !== args.accountId ||
204
+ outcome.ownerKey !== args.ownerKey
219
205
  )
220
- .unique();
221
- if (adopted && adopted._id !== claim._id)
222
- throw new Error("Payout receipt identity is already allocated.");
223
- if (
224
- args.returnTransactionId !== undefined &&
225
- (!/^txn_\w+$/.test(args.returnTransactionId) ||
226
- args.returnTransactionId.trim() !== args.returnTransactionId)
227
- )
228
- throw new Error("Invalid payout return receipt identity.");
229
- const returned =
230
- (args.providerStatus === "failed" ||
231
- args.providerStatus === "canceled") &&
232
- args.returnTransactionId !== undefined;
233
- if (returned) {
234
- const adoptedReturn = await ctx.db
235
- .query("payoutReleaseClaims")
236
- .withIndex("by_return_receipt", (q) =>
237
- q.eq("returnTransactionId", args.returnTransactionId),
238
- )
239
- .unique();
240
- if (adoptedReturn && adoptedReturn._id !== claim._id)
241
- throw new Error("Payout return receipt is already allocated.");
242
- }
243
- if (claim.status === "returned") {
244
- if (returned && args.returnTransactionId !== claim.returnTransactionId)
245
- throw new Error("Payout return receipt identity changed.");
246
- if (returned) {
247
- await recordFees(ctx, claim, args, true);
248
- return (await ctx.db.get("payoutReleaseClaims", claim._id))!;
249
- }
250
- return claim;
206
+ throw new Error("Payout outcome batch ownership changed.");
207
+ results.push(await recordPayoutOutcome(ctx, outcome));
251
208
  }
252
- if (claim.status === "paid" && args.providerStatus !== "paid" && !returned)
253
- return claim;
254
- await recordFees(ctx, claim, args, returned);
255
- await releaseRecoveryGuard(ctx, claim);
256
- if (returned) {
257
- await moveAllocations(
258
- ctx,
259
- claim,
260
- claim.status === "paid" ? "return" : "release",
261
- );
262
- await ctx.db.patch("payoutReleaseClaims", claim._id, {
263
- status: "returned",
264
- stripePayoutId: args.stripePayoutId,
265
- returnTransactionId: args.returnTransactionId,
266
- });
267
- } else if (args.providerStatus === "paid" && claim.status !== "paid") {
268
- await moveAllocations(ctx, claim, "pay");
269
- await ctx.db.patch("payoutReleaseClaims", claim._id, {
270
- status: "paid",
271
- stripePayoutId: args.stripePayoutId,
272
- });
273
- } else if (claim.status !== "paid") {
274
- await ctx.db.patch("payoutReleaseClaims", claim._id, {
275
- status: "submitted",
276
- stripePayoutId: args.stripePayoutId,
277
- });
278
- }
279
- return (await ctx.db.get("payoutReleaseClaims", claim._id))!;
209
+ return results;
280
210
  },
281
211
  });
282
212
 
@@ -0,0 +1,119 @@
1
+ import { v, type Infer } from "convex/values";
2
+ import type { MutationCtx } from "../_generated/server.js";
3
+ import { identity } from "./schema.js";
4
+ import { claimByKey, moveAllocations } from "./helpers.js";
5
+ import { recordFees } from "./fees.js";
6
+ import { releaseRecoveryGuard } from "../affiliatePayouts/recipientGuard.js";
7
+
8
+ export const outcomeArgs = v.object({
9
+ ...identity,
10
+ stripePayoutId: v.string(),
11
+ amount: v.number(),
12
+ currency: v.string(),
13
+ providerStatus: v.union(
14
+ v.literal("pending"),
15
+ v.literal("in_transit"),
16
+ v.literal("paid"),
17
+ v.literal("failed"),
18
+ v.literal("canceled"),
19
+ ),
20
+ returnTransactionId: v.optional(v.string()),
21
+ debitTransactionId: v.optional(v.string()),
22
+ debitFee: v.optional(v.number()),
23
+ returnFee: v.optional(v.number()),
24
+ });
25
+ export async function recordPayoutOutcome(
26
+ ctx: MutationCtx,
27
+ args: Infer<typeof outcomeArgs>,
28
+ ) {
29
+ const claim = await claimByKey(ctx, args);
30
+ if (
31
+ !claim ||
32
+ claim.attemptedAt === undefined ||
33
+ claim.status === "canceled" ||
34
+ claim.status === "rejected"
35
+ )
36
+ throw new Error("Payout receipt has no attempted claim.");
37
+ if (
38
+ !/^po_\w+$/.test(args.stripePayoutId) ||
39
+ args.stripePayoutId.trim() !== args.stripePayoutId ||
40
+ args.currency !== claim.currency ||
41
+ args.amount !== claim.amount ||
42
+ (claim.stripePayoutId !== undefined &&
43
+ claim.stripePayoutId !== args.stripePayoutId)
44
+ )
45
+ throw new Error("Payout receipt identity or amount does not match.");
46
+ const adopted = await ctx.db
47
+ .query("payoutReleaseClaims")
48
+ .withIndex("by_provider_payout", (q) =>
49
+ q.eq("stripePayoutId", args.stripePayoutId),
50
+ )
51
+ .unique();
52
+ if (adopted && adopted._id !== claim._id)
53
+ throw new Error("Payout receipt identity is already allocated.");
54
+ if (
55
+ args.returnTransactionId !== undefined &&
56
+ (!/^txn_\w+$/.test(args.returnTransactionId) ||
57
+ args.returnTransactionId.trim() !== args.returnTransactionId)
58
+ )
59
+ throw new Error("Invalid payout return receipt identity.");
60
+ const returned =
61
+ (args.providerStatus === "failed" || args.providerStatus === "canceled") &&
62
+ args.returnTransactionId !== undefined;
63
+ if (returned) {
64
+ const adoptedReturn = await ctx.db
65
+ .query("payoutReleaseClaims")
66
+ .withIndex("by_return_receipt", (q) =>
67
+ q.eq("returnTransactionId", args.returnTransactionId),
68
+ )
69
+ .unique();
70
+ if (adoptedReturn && adoptedReturn._id !== claim._id)
71
+ throw new Error("Payout return receipt is already allocated.");
72
+ }
73
+ if (claim.status === "returned") {
74
+ if (returned && args.returnTransactionId !== claim.returnTransactionId)
75
+ throw new Error("Payout return receipt identity changed.");
76
+ if (returned) {
77
+ await recordFees(ctx, claim, args, true);
78
+ return (await ctx.db.get("payoutReleaseClaims", claim._id))!;
79
+ }
80
+ return claim;
81
+ }
82
+ if (claim.status === "paid" && args.providerStatus !== "paid" && !returned)
83
+ return claim;
84
+ await recordFees(ctx, claim, args, returned);
85
+ await releaseRecoveryGuard(ctx, claim);
86
+ if (
87
+ claim.status === "paid" &&
88
+ args.providerStatus === "paid" &&
89
+ args.debitTransactionId !== undefined &&
90
+ claim.debitTransactionId === args.debitTransactionId &&
91
+ claim.debitFee === args.debitFee &&
92
+ claim.providerFee === args.debitFee
93
+ )
94
+ return claim;
95
+ if (returned) {
96
+ await moveAllocations(
97
+ ctx,
98
+ claim,
99
+ claim.status === "paid" ? "return" : "release",
100
+ );
101
+ await ctx.db.patch("payoutReleaseClaims", claim._id, {
102
+ status: "returned",
103
+ stripePayoutId: args.stripePayoutId,
104
+ returnTransactionId: args.returnTransactionId,
105
+ });
106
+ } else if (args.providerStatus === "paid" && claim.status !== "paid") {
107
+ await moveAllocations(ctx, claim, "pay");
108
+ await ctx.db.patch("payoutReleaseClaims", claim._id, {
109
+ status: "paid",
110
+ stripePayoutId: args.stripePayoutId,
111
+ });
112
+ } else if (claim.status !== "paid") {
113
+ await ctx.db.patch("payoutReleaseClaims", claim._id, {
114
+ status: "submitted",
115
+ stripePayoutId: args.stripePayoutId,
116
+ });
117
+ }
118
+ return (await ctx.db.get("payoutReleaseClaims", claim._id))!;
119
+ }
@@ -26,17 +26,20 @@ export async function readPayoutPlan(
26
26
  ) {
27
27
  const minimum = policy.thresholds.find((t) => t.currency === args.currency);
28
28
  if (!minimum) throw new Error("Payout policy currency is not configured.");
29
+ const collection = await collectedSources(ctx, args, args.observations);
29
30
  const rows = await checkSnapshot(
30
31
  ctx,
31
32
  args.accountId,
32
33
  args.observations,
33
34
  true,
34
35
  args.currency,
35
- await collectedSources(ctx, args, args.observations),
36
+ collection?.transfers,
36
37
  );
37
38
  const sources: PayoutFundingSource[] = [];
38
39
  for (const observation of args.observations) {
39
- const prior = await sourceById(ctx, observation.stripeTransferId);
40
+ const prior = collection?.allocations.has(observation.stripeTransferId)
41
+ ? collection.allocations.get(observation.stripeTransferId)
42
+ : await sourceById(ctx, observation.stripeTransferId);
40
43
  if (
41
44
  prior &&
42
45
  (prior.accountId !== args.accountId ||
@@ -97,6 +97,8 @@ export const snapshot = query({
97
97
  q.eq("destinationAccountId", args.accountId),
98
98
  )
99
99
  .take(101);
100
+ if (transfers.length > 100)
101
+ return { status: "held" as const, reason: "snapshot_limit" as const };
100
102
  const claims = await ctx.db
101
103
  .query("payoutReleaseClaims")
102
104
  .withIndex("by_account_status", (q) => q.eq("accountId", args.accountId))
@@ -0,0 +1,73 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { MutationCtx } from "../_generated/server.js";
3
+ import type { Id } from "../_generated/dataModel.js";
4
+ import type { observation } from "../payoutRelease/schema.js";
5
+ import { payoutClaimFingerprint } from "../payoutRelease/helpers.js";
6
+ import { collectedSources } from "./financial.js";
7
+ import { financialRevision } from "./revisions.js";
8
+ /** Import/control validation only. This never authorizes a bank payout or supplies a liability amount. */
9
+ export async function adoptionCollection(
10
+ ctx: MutationCtx,
11
+ scope: { accountId: string; ownerKey: string },
12
+ proof: {
13
+ snapshotId?: Id<"payoutSnapshots">;
14
+ observations: Infer<typeof observation>[];
15
+ claims: { operationKey: string; fingerprint: string }[];
16
+ },
17
+ ) {
18
+ if (!proof.snapshotId) return undefined;
19
+ const h = await ctx.db.get("payoutSnapshots", proof.snapshotId);
20
+ const revision = await financialRevision(ctx, scope.accountId);
21
+ if (
22
+ !h?.readOnly ||
23
+ h.observedRevision !== revision.revision ||
24
+ h.deferredPositiveChanges
25
+ )
26
+ throw new Error(
27
+ "Adoption collection changed; collect complete current funding again.",
28
+ );
29
+ // No money is released here. Capture the current revision under this same
30
+ // transaction; collectedSources also requires the cached risk fence to match.
31
+ const financial = await collectedSources(
32
+ ctx,
33
+ {
34
+ ...scope,
35
+ snapshotId: proof.snapshotId,
36
+ liabilityRevision: revision.riskRevision,
37
+ },
38
+ proof.observations,
39
+ );
40
+ const keys = new Set(proof.claims.map((c) => c.operationKey));
41
+ if (keys.size !== proof.claims.length || keys.size !== h.claimCount)
42
+ throw new Error("Adoption claim membership is incomplete.");
43
+ const claims = [];
44
+ for (const expected of proof.claims) {
45
+ const cached = await ctx.db
46
+ .query("payoutSnapshotClaims")
47
+ .withIndex("by_snapshot_operation", (q) =>
48
+ q.eq("snapshotId", h._id).eq("operationKey", expected.operationKey),
49
+ )
50
+ .unique();
51
+ const row = await ctx.db
52
+ .query("payoutReleaseClaims")
53
+ .withIndex("by_operation", (q) =>
54
+ q.eq("operationKey", expected.operationKey),
55
+ )
56
+ .unique();
57
+ if (
58
+ !cached ||
59
+ !row ||
60
+ row.accountId !== scope.accountId ||
61
+ row.ownerKey !== scope.ownerKey ||
62
+ expected.fingerprint !== cached.fingerprint ||
63
+ expected.fingerprint !== payoutClaimFingerprint(row)
64
+ )
65
+ throw new Error("Adoption payout history changed.");
66
+ claims.push(row);
67
+ }
68
+ return {
69
+ sources: financial?.transfers,
70
+ allocations: financial?.allocations,
71
+ claims,
72
+ };
73
+ }