@fantastic.dev/better-stripe 0.28.5 → 0.29.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 (137) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/MIGRATION.md +6 -0
  3. package/README.md +7 -1
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +28 -8
  5. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  6. package/dist/client/connect/payoutCollectedInput.d.ts +110 -0
  7. package/dist/client/connect/payoutCollectedInput.d.ts.map +1 -0
  8. package/dist/client/connect/payoutCollectedInput.js +70 -0
  9. package/dist/client/connect/payoutCollectedInput.js.map +1 -0
  10. package/dist/client/connect/payoutExecution.d.ts +1 -0
  11. package/dist/client/connect/payoutExecution.d.ts.map +1 -1
  12. package/dist/client/connect/payoutExecution.js +94 -67
  13. package/dist/client/connect/payoutExecution.js.map +1 -1
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +16 -4
  15. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  16. package/dist/client/connect/payoutExecutionTestHelpers.js +9 -6
  17. package/dist/client/connect/payoutExecutionTestHelpers.js.map +1 -1
  18. package/dist/client/connect/payoutPreview.d.ts +1 -0
  19. package/dist/client/connect/payoutPreview.d.ts.map +1 -1
  20. package/dist/client/connect/payoutPreview.js +31 -19
  21. package/dist/client/connect/payoutPreview.js.map +1 -1
  22. package/dist/client/connect/payoutQualification.d.ts +7 -1
  23. package/dist/client/connect/payoutQualification.d.ts.map +1 -1
  24. package/dist/client/connect/payoutQualification.js +39 -20
  25. package/dist/client/connect/payoutQualification.js.map +1 -1
  26. package/dist/client/connect/payoutSyncTestHelpers.d.ts +14 -4
  27. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  28. package/dist/client/connect/payoutWorker.d.ts.map +1 -1
  29. package/dist/client/connect/payoutWorker.js +4 -1
  30. package/dist/client/connect/payoutWorker.js.map +1 -1
  31. package/dist/client/costRecovery.d.ts +5 -0
  32. package/dist/client/costRecovery.d.ts.map +1 -1
  33. package/dist/client/costRecovery.js +5 -0
  34. package/dist/client/costRecovery.js.map +1 -1
  35. package/dist/client/payoutPolicy.d.ts +4 -0
  36. package/dist/client/payoutPolicy.d.ts.map +1 -1
  37. package/dist/component/_generated/component.d.ts +175 -0
  38. package/dist/component/_generated/component.d.ts.map +1 -1
  39. package/dist/component/costRecovery/mutations.js +1 -1
  40. package/dist/component/costRecovery/queries.d.ts +9 -0
  41. package/dist/component/costRecovery/queries.d.ts.map +1 -1
  42. package/dist/component/costRecovery/queries.js +20 -0
  43. package/dist/component/costRecovery/queries.js.map +1 -1
  44. package/dist/component/earnings/triggers.d.ts +16 -6
  45. package/dist/component/earnings/triggers.d.ts.map +1 -1
  46. package/dist/component/payoutRelease/adoption.d.ts +6 -0
  47. package/dist/component/payoutRelease/adoption.d.ts.map +1 -1
  48. package/dist/component/payoutRelease/helpers.d.ts +4 -1
  49. package/dist/component/payoutRelease/helpers.d.ts.map +1 -1
  50. package/dist/component/payoutRelease/helpers.js +18 -10
  51. package/dist/component/payoutRelease/helpers.js.map +1 -1
  52. package/dist/component/payoutRelease/mutations.d.ts +20 -0
  53. package/dist/component/payoutRelease/mutations.d.ts.map +1 -1
  54. package/dist/component/payoutRelease/mutations.js +14 -2
  55. package/dist/component/payoutRelease/mutations.js.map +1 -1
  56. package/dist/component/payoutRelease/planning.d.ts +4 -0
  57. package/dist/component/payoutRelease/planning.d.ts.map +1 -1
  58. package/dist/component/payoutRelease/planning.js +4 -2
  59. package/dist/component/payoutRelease/planning.js.map +1 -1
  60. package/dist/component/payoutRelease/preview.d.ts +2 -0
  61. package/dist/component/payoutRelease/preview.d.ts.map +1 -1
  62. package/dist/component/payoutRelease/preview.js +5 -1
  63. package/dist/component/payoutRelease/preview.js.map +1 -1
  64. package/dist/component/payoutRelease/queries.d.ts +11 -0
  65. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  66. package/dist/component/payoutRelease/schema.d.ts +17 -2
  67. package/dist/component/payoutRelease/schema.d.ts.map +1 -1
  68. package/dist/component/payoutRelease/schema.js +3 -0
  69. package/dist/component/payoutRelease/schema.js.map +1 -1
  70. package/dist/component/payoutSnapshots/financial.d.ts +35 -0
  71. package/dist/component/payoutSnapshots/financial.d.ts.map +1 -0
  72. package/dist/component/payoutSnapshots/financial.js +89 -0
  73. package/dist/component/payoutSnapshots/financial.js.map +1 -0
  74. package/dist/component/payoutSnapshots/liabilities.d.ts +7 -0
  75. package/dist/component/payoutSnapshots/liabilities.d.ts.map +1 -0
  76. package/dist/component/payoutSnapshots/liabilities.js +18 -0
  77. package/dist/component/payoutSnapshots/liabilities.js.map +1 -0
  78. package/dist/component/payoutSnapshots/localState.d.ts +2 -0
  79. package/dist/component/payoutSnapshots/localState.d.ts.map +1 -1
  80. package/dist/component/payoutSnapshots/localState.js +6 -3
  81. package/dist/component/payoutSnapshots/localState.js.map +1 -1
  82. package/dist/component/payoutSnapshots/mutations.d.ts +6 -0
  83. package/dist/component/payoutSnapshots/mutations.d.ts.map +1 -1
  84. package/dist/component/payoutSnapshots/mutations.js +2 -0
  85. package/dist/component/payoutSnapshots/mutations.js.map +1 -1
  86. package/dist/component/payoutSnapshots/queries.d.ts +133 -0
  87. package/dist/component/payoutSnapshots/queries.d.ts.map +1 -0
  88. package/dist/component/payoutSnapshots/queries.js +84 -0
  89. package/dist/component/payoutSnapshots/queries.js.map +1 -0
  90. package/dist/component/payoutSnapshots/revisions.d.ts.map +1 -1
  91. package/dist/component/payoutSnapshots/revisions.js +19 -0
  92. package/dist/component/payoutSnapshots/revisions.js.map +1 -1
  93. package/dist/component/payoutSnapshots/schema.d.ts +15 -5
  94. package/dist/component/payoutSnapshots/schema.d.ts.map +1 -1
  95. package/dist/component/payoutSnapshots/schema.js +3 -1
  96. package/dist/component/payoutSnapshots/schema.js.map +1 -1
  97. package/dist/component/payoutWorker/mutations.d.ts.map +1 -1
  98. package/dist/component/payoutWorker/mutations.js +3 -1
  99. package/dist/component/payoutWorker/mutations.js.map +1 -1
  100. package/dist/component/schema.d.ts +14 -4
  101. package/dist/react/workflows/payout-attempt-state.d.ts.map +1 -1
  102. package/dist/react/workflows/payout-attempt-state.js +3 -0
  103. package/dist/react/workflows/payout-attempt-state.js.map +1 -1
  104. package/dist/react/workflows/payout-progress-state.d.ts.map +1 -1
  105. package/dist/react/workflows/payout-progress-state.js +3 -0
  106. package/dist/react/workflows/payout-progress-state.js.map +1 -1
  107. package/docs/settlement.md +84 -17
  108. package/package.json +1 -1
  109. package/src/client/connect/payoutCollectedInput.ts +120 -0
  110. package/src/client/connect/payoutExecution.ts +116 -84
  111. package/src/client/connect/payoutExecutionTestHelpers.ts +19 -6
  112. package/src/client/connect/payoutLargeHistory.test.ts +222 -0
  113. package/src/client/connect/payoutLiabilityVersion.test.ts +221 -0
  114. package/src/client/connect/payoutPreview.ts +43 -23
  115. package/src/client/connect/payoutQualification.ts +69 -22
  116. package/src/client/connect/payoutQualificationFreshness.test.ts +192 -0
  117. package/src/client/connect/payoutWorker.ts +4 -1
  118. package/src/client/costRecovery.ts +8 -0
  119. package/src/component/_generated/api.ts +6 -0
  120. package/src/component/_generated/component.ts +203 -0
  121. package/src/component/costRecovery/mutations.ts +1 -1
  122. package/src/component/costRecovery/queries.ts +21 -0
  123. package/src/component/payoutRelease/helpers.ts +21 -11
  124. package/src/component/payoutRelease/mutations.ts +25 -2
  125. package/src/component/payoutRelease/planning.ts +8 -1
  126. package/src/component/payoutRelease/preview.ts +5 -1
  127. package/src/component/payoutRelease/schema.ts +3 -0
  128. package/src/component/payoutSnapshots/financial.ts +121 -0
  129. package/src/component/payoutSnapshots/liabilities.ts +25 -0
  130. package/src/component/payoutSnapshots/localState.ts +7 -3
  131. package/src/component/payoutSnapshots/mutations.ts +2 -0
  132. package/src/component/payoutSnapshots/queries.ts +102 -0
  133. package/src/component/payoutSnapshots/revisions.ts +26 -0
  134. package/src/component/payoutSnapshots/schema.ts +3 -0
  135. package/src/component/payoutWorker/mutations.ts +3 -1
  136. package/src/react/workflows/payout-attempt-state.ts +6 -0
  137. package/src/react/workflows/payout-progress-state.ts +6 -0
@@ -71,24 +71,30 @@ export async function checkSnapshot(
71
71
  accountId: string,
72
72
  observations: Infer<typeof observation>[],
73
73
  fresh: boolean,
74
+ freshCurrency?: string,
75
+ membership?: Map<string, Doc<"transfers">>,
74
76
  ) {
75
- const rows = await ctx.db
76
- .query("transfers")
77
- .withIndex("by_destination_account_id", (q) =>
78
- q.eq("destinationAccountId", accountId),
79
- )
80
- .take(101);
77
+ const rows = membership
78
+ ? [...membership.values()]
79
+ : await ctx.db
80
+ .query("transfers")
81
+ .withIndex("by_destination_account_id", (q) =>
82
+ q.eq("destinationAccountId", accountId),
83
+ )
84
+ .take(101);
81
85
  if (
82
- rows.length > 100 ||
86
+ (!membership && rows.length > 100) ||
83
87
  observations.length !== rows.length ||
84
88
  new Set(observations.map((o) => o.stripeTransferId)).size !== rows.length
85
89
  )
86
90
  throw new Error("Payout source snapshot is incomplete or duplicated.");
87
91
  const byId = new Map(rows.map((row) => [row.stripeTransferId, row]));
88
- const allocated = await ctx.db
89
- .query("payoutSourceAllocations")
90
- .withIndex("by_account", (q) => q.eq("accountId", accountId))
91
- .take(101);
92
+ const allocated = membership
93
+ ? []
94
+ : await ctx.db
95
+ .query("payoutSourceAllocations")
96
+ .withIndex("by_account", (q) => q.eq("accountId", accountId))
97
+ .take(101);
92
98
  if (
93
99
  allocated.length > 100 ||
94
100
  allocated.some((source) => !byId.has(source.stripeTransferId))
@@ -106,6 +112,7 @@ export async function checkSnapshot(
106
112
  throw new Error("Payout source snapshot changed or is not ready.");
107
113
  if (
108
114
  fresh &&
115
+ (freshCurrency === undefined || o.currency === freshCurrency) &&
109
116
  (!Number.isSafeInteger(o.observedAt) ||
110
117
  o.observedAt > Date.now() ||
111
118
  o.observedAt < Date.now() - 30000)
@@ -177,6 +184,9 @@ export function payoutClaimFingerprint(c: Doc<"payoutReleaseClaims">) {
177
184
  c.ownerKey,
178
185
  c.operationKey,
179
186
  c.historical ?? false,
187
+ c.snapshotId,
188
+ c.liabilityRevision,
189
+ c.independentLiabilities,
180
190
  c.currency,
181
191
  c.amount,
182
192
  c.status,
@@ -1,3 +1,8 @@
1
+ import {
2
+ collectedSources,
3
+ bindCollection,
4
+ retireCollection,
5
+ } from "../payoutSnapshots/financial.js";
1
6
  import {
2
7
  reserveRecoveryGuard,
3
8
  releaseRecoveryGuard,
@@ -43,6 +48,8 @@ export const claim = mutation({
43
48
  providerAvailable: v.number(),
44
49
  independentLiabilities: v.number(),
45
50
  observations: v.array(observation),
51
+ snapshotId: v.optional(v.id("payoutSnapshots")),
52
+ liabilityRevision: v.optional(v.number()),
46
53
  },
47
54
  returns: v.union(claimDoc, held),
48
55
  handler: async (ctx, args) => {
@@ -106,10 +113,17 @@ export const claim = mutation({
106
113
  ...(args.destinationId ? { destinationId: args.destinationId } : {}),
107
114
  allocations: plan.allocations,
108
115
  observations: args.observations,
116
+ independentLiabilities: args.independentLiabilities,
117
+ ...(args.snapshotId ? { snapshotId: args.snapshotId } : {}),
118
+ ...(args.liabilityRevision === undefined
119
+ ? {}
120
+ : { liabilityRevision: args.liabilityRevision }),
109
121
  feeRevision: fees?.revision ?? 0,
110
122
  status: "reserved",
111
123
  });
112
- return (await ctx.db.get("payoutReleaseClaims", id))!;
124
+ const claim = (await ctx.db.get("payoutReleaseClaims", id))!;
125
+ await bindCollection(ctx, claim);
126
+ return claim;
113
127
  },
114
128
  });
115
129
  export const beginAttempt = mutation({
@@ -124,11 +138,19 @@ export const beginAttempt = mutation({
124
138
  const feeRevision = (await readFees(ctx, claim))?.revision ?? 0;
125
139
  if (feeRevision !== (claim.feeRevision ?? 0))
126
140
  throw new Error("Payout fee revision changed after reservation.");
127
- await checkSnapshot(ctx, claim.accountId, claim.observations, true);
141
+ await checkSnapshot(
142
+ ctx,
143
+ claim.accountId,
144
+ claim.observations,
145
+ true,
146
+ claim.currency,
147
+ await collectedSources(ctx, claim, claim.observations),
148
+ );
128
149
  await reserveRecoveryGuard(ctx, claim, claim.amount);
129
150
  await ctx.db.patch("payoutReleaseClaims", claim._id, {
130
151
  attemptedAt: Date.now(),
131
152
  });
153
+ await retireCollection(ctx, claim);
132
154
  return (await ctx.db.get("payoutReleaseClaims", claim._id))!;
133
155
  },
134
156
  });
@@ -145,6 +167,7 @@ export const cancelUnattempted = mutation({
145
167
  throw new Error("An attempted payout claim cannot be canceled.");
146
168
  if (claim.status === "canceled") return claim;
147
169
  await moveAllocations(ctx, claim, "release");
170
+ await retireCollection(ctx, claim);
148
171
  await releaseRecoveryGuard(ctx, claim);
149
172
  await ctx.db.patch("payoutReleaseClaims", claim._id, {
150
173
  status: "canceled",
@@ -1,3 +1,5 @@
1
+ import { collectedSources } from "../payoutSnapshots/financial.js";
2
+ import type { Id } from "../_generated/dataModel.js";
1
3
  import type { Infer } from "convex/values";
2
4
  import type { MutationCtx, QueryCtx } from "../_generated/server.js";
3
5
  import type { policyDoc } from "../payoutPolicy/schema.js";
@@ -14,6 +16,9 @@ export async function readPayoutPlan(
14
16
  ownerKey: string;
15
17
  currency: string;
16
18
  observations: Infer<typeof observation>[];
19
+ snapshotId?: Id<"payoutSnapshots">;
20
+ operationKey?: string;
21
+ liabilityRevision?: number;
17
22
  providerAvailable: number;
18
23
  independentLiabilities: number;
19
24
  },
@@ -26,6 +31,8 @@ export async function readPayoutPlan(
26
31
  args.accountId,
27
32
  args.observations,
28
33
  true,
34
+ args.currency,
35
+ await collectedSources(ctx, args, args.observations),
29
36
  );
30
37
  const sources: PayoutFundingSource[] = [];
31
38
  for (const observation of args.observations) {
@@ -45,7 +52,7 @@ export async function readPayoutPlan(
45
52
  });
46
53
  }
47
54
  const fees = await readFees(ctx, args);
48
- await assertAllocationTotals(ctx, args, sources);
55
+ if (!args.snapshotId) await assertAllocationTotals(ctx, args, sources);
49
56
  const minimumWaived = waiveApplicationMinimum(policy, Date.now());
50
57
  const plan = planRecipientPayout({
51
58
  currency: args.currency,
@@ -14,6 +14,8 @@ export const previewFields = {
14
14
  providerAvailable: v.number(),
15
15
  independentLiabilities: v.number(),
16
16
  observations: v.array(observation),
17
+ snapshotId: v.optional(v.id("payoutSnapshots")),
18
+ liabilityRevision: v.optional(v.number()),
17
19
  };
18
20
  const held = v.object({
19
21
  status: v.literal("held"),
@@ -106,7 +108,9 @@ export async function previewPlan(
106
108
  providerAvailable: args.providerAvailable,
107
109
  observedAt: Math.min(
108
110
  Date.now(),
109
- ...args.observations.map((o) => o.observedAt),
111
+ ...args.observations
112
+ .filter((o) => o.currency === args.currency)
113
+ .map((o) => o.observedAt),
110
114
  ),
111
115
  ...progress,
112
116
  };
@@ -13,6 +13,9 @@ export const allocation = v.object({
13
13
  export const claimFields = {
14
14
  ...scopeFields,
15
15
  historical: v.optional(v.boolean()),
16
+ snapshotId: v.optional(v.id("payoutSnapshots")),
17
+ liabilityRevision: v.optional(v.number()),
18
+ independentLiabilities: v.optional(v.number()),
16
19
  operationKey: v.string(),
17
20
  expectedRevision: v.number(),
18
21
  currency: v.string(),
@@ -0,0 +1,121 @@
1
+ import { assertLiabilityVersion } from "./liabilities.js";
2
+ import type { Infer } from "convex/values";
3
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
4
+ import type { Id, Doc } from "../_generated/dataModel.js";
5
+ import type { observation } from "../payoutRelease/schema.js";
6
+ import { readPolicy } from "../payoutPolicy/helpers.js";
7
+ import { riskRevision } from "./revisions.js";
8
+ export type CollectionScope = {
9
+ accountId: string;
10
+ ownerKey: string;
11
+ snapshotId?: Id<"payoutSnapshots">;
12
+ operationKey?: string;
13
+ liabilityRevision?: number;
14
+ };
15
+ /** The complete collector baseline is checked again under the claim's OCC transaction. */
16
+ export async function collectedSources(
17
+ ctx: QueryCtx | MutationCtx,
18
+ scope: CollectionScope,
19
+ observations: Infer<typeof observation>[],
20
+ ) {
21
+ if (!scope.snapshotId) {
22
+ await assertLiabilityVersion(ctx, scope);
23
+ return undefined;
24
+ }
25
+ const h = await ctx.db.get("payoutSnapshots", scope.snapshotId);
26
+ const policy = await readPolicy(ctx, scope);
27
+ if (
28
+ !h ||
29
+ h.accountId !== scope.accountId ||
30
+ h.ownerKey !== scope.ownerKey ||
31
+ h.phase !== "local_ready" ||
32
+ h.expiresAt <= Date.now() ||
33
+ h.expectedRevision !== policy?.revision ||
34
+ h.policyMode !== policy?.mode ||
35
+ h.policyOperationKey !== policy?.operationKey ||
36
+ (!h.readOnly && h.boundOperationKey !== scope.operationKey) ||
37
+ (await riskRevision(ctx, scope.accountId)) !==
38
+ (h.readOnly ? h.riskRevision : h.boundRiskRevision)
39
+ )
40
+ throw new Error("Financial payout collection changed or is unavailable.");
41
+ if (h.readOnly) await assertLiabilityVersion(ctx, scope);
42
+ if (
43
+ observations.length !== h.sourceCount ||
44
+ new Set(observations.map((o) => o.stripeTransferId)).size !== h.sourceCount
45
+ )
46
+ throw new Error("Financial payout collection membership is incomplete.");
47
+ const rows = new Map<string, Doc<"transfers">>();
48
+ for (const o of observations) {
49
+ const cached = await ctx.db
50
+ .query("payoutSnapshotSources")
51
+ .withIndex("by_snapshot_transfer", (q) =>
52
+ q.eq("snapshotId", h._id).eq("stripeTransferId", o.stripeTransferId),
53
+ )
54
+ .unique();
55
+ const row = await ctx.db
56
+ .query("transfers")
57
+ .withIndex("by_stripe_transfer_id", (q) =>
58
+ q.eq("stripeTransferId", o.stripeTransferId),
59
+ )
60
+ .unique();
61
+ if (
62
+ !cached ||
63
+ !row ||
64
+ cached.needsCheck ||
65
+ cached.ledgerFingerprint !== o.ledgerFingerprint ||
66
+ cached.expectedPaid !== cached.paidAmount ||
67
+ cached.expectedReserved !== cached.reservedAmount
68
+ )
69
+ throw new Error("Financial payout collection source changed.");
70
+ if (h.readOnly) {
71
+ const allocation = await ctx.db
72
+ .query("payoutSourceAllocations")
73
+ .withIndex("by_transfer", (q) =>
74
+ q.eq("stripeTransferId", o.stripeTransferId),
75
+ )
76
+ .unique();
77
+ if (
78
+ (allocation?.paidAmount ?? 0) !== cached.paidAmount ||
79
+ (allocation?.reservedAmount ?? 0) !== cached.reservedAmount ||
80
+ (allocation &&
81
+ (allocation.accountId !== scope.accountId ||
82
+ allocation.ownerKey !== scope.ownerKey ||
83
+ allocation.currency !== o.currency))
84
+ )
85
+ throw new Error("Financial payout collection allocation changed.");
86
+ }
87
+ rows.set(o.stripeTransferId, row);
88
+ }
89
+ return rows;
90
+ }
91
+ export async function bindCollection(
92
+ ctx: MutationCtx,
93
+ claim: Doc<"payoutReleaseClaims">,
94
+ ) {
95
+ if (!claim.snapshotId) return;
96
+ await ctx.db.patch("payoutSnapshots", claim.snapshotId, {
97
+ readOnly: false,
98
+ boundOperationKey: claim.operationKey,
99
+ boundRiskRevision: await riskRevision(ctx, claim.accountId),
100
+ });
101
+ }
102
+ /** The immutable claim retains all financial proof; only its disposable cache becomes discardable. */
103
+ export async function retireCollection(
104
+ ctx: MutationCtx,
105
+ claim: Doc<"payoutReleaseClaims">,
106
+ ) {
107
+ if (!claim.snapshotId) return;
108
+ const h = await ctx.db.get("payoutSnapshots", claim.snapshotId);
109
+ if (!h || h.readOnly) return;
110
+ if (
111
+ h.accountId !== claim.accountId ||
112
+ h.ownerKey !== claim.ownerKey ||
113
+ h.boundOperationKey !== claim.operationKey
114
+ )
115
+ throw new Error("Financial payout collection binding changed.");
116
+ await ctx.db.patch("payoutSnapshots", h._id, {
117
+ readOnly: true,
118
+ phase: "invalidated",
119
+ reason: "financial_consumed",
120
+ });
121
+ }
@@ -0,0 +1,25 @@
1
+ import type { QueryCtx, MutationCtx } from "../_generated/server.js";
2
+ import { riskRevision } from "./revisions.js";
3
+ /** Recovery-backed recipients must carry the version captured with their authorized amount. */
4
+ export async function assertLiabilityVersion(
5
+ ctx: QueryCtx | MutationCtx,
6
+ scope: { accountId: string; liabilityRevision?: number },
7
+ ) {
8
+ if (scope.liabilityRevision === undefined) {
9
+ const recovery = await ctx.db
10
+ .query("recoveryBalances")
11
+ .withIndex("by_scope", (q) => q.eq("accountId", scope.accountId))
12
+ .first();
13
+ if (recovery)
14
+ throw new Error(
15
+ "A versioned recovery liability quote is required before payout qualification.",
16
+ );
17
+ return;
18
+ }
19
+ if (
20
+ !Number.isSafeInteger(scope.liabilityRevision) ||
21
+ scope.liabilityRevision < 0 ||
22
+ scope.liabilityRevision !== (await riskRevision(ctx, scope.accountId))
23
+ )
24
+ throw new Error("Payout liability version changed; resolve a fresh quote.");
25
+ }
@@ -171,9 +171,13 @@ export async function cacheClaim(
171
171
  }
172
172
  if (total !== row.amount || total <= 0)
173
173
  throw new CollectionError("allocation_amount_mismatch");
174
- for (const a of row.allocations)
175
- if (!(await sourceCache(ctx, h, a.stripeTransferId)))
176
- await cacheSource(ctx, h, a.stripeTransferId, counts);
174
+ for (const a of row.allocations) {
175
+ const source =
176
+ (await sourceCache(ctx, h, a.stripeTransferId)) ??
177
+ (await cacheSource(ctx, h, a.stripeTransferId, counts));
178
+ if ((source.allocationCurrency ?? source.currency) !== row.currency)
179
+ throw new CollectionError("allocation_currency_changed");
180
+ }
177
181
  const old = await ctx.db
178
182
  .query("payoutSnapshotClaims")
179
183
  .withIndex("by_snapshot_operation", (q) =>
@@ -183,6 +183,8 @@ export const advance = mutation({
183
183
  await cacheSource(ctx, h, event.key, counts);
184
184
  else if (event.kind === "claim")
185
185
  await cacheClaim(ctx, h, event.key, counts);
186
+ else if (event.kind === "liability")
187
+ throw new CollectionError("liability_changed");
186
188
  else if (event.kind === "fee")
187
189
  await cacheFee(ctx, h, event.key, counts);
188
190
  else patch.providerChanged = true;
@@ -0,0 +1,102 @@
1
+ import { v } from "convex/values";
2
+ import { paginationOptsValidator } from "convex/server";
3
+ import { paginator } from "convex-helpers/server/pagination";
4
+ import { query } from "../_generated/server.js";
5
+ import schema from "../schema.js";
6
+ import { identity } from "./scope.js";
7
+ import { snapshotDoc } from "./schema.js";
8
+ import { ownedSnapshot } from "./localState.js";
9
+ import { riskRevision } from "./revisions.js";
10
+ import { transferDocValidator } from "../connect/validators.js";
11
+ import { claimDoc } from "../payoutRelease/schema.js";
12
+ import {
13
+ transferFingerprint,
14
+ payoutClaimFingerprint,
15
+ } from "../payoutRelease/helpers.js";
16
+ export const get = query({
17
+ args: identity,
18
+ returns: v.union(snapshotDoc, v.null()),
19
+ handler: ownedSnapshot,
20
+ });
21
+ const args = { ...identity, paginationOpts: paginationOptsValidator };
22
+ const pageFields = { continueCursor: v.string(), isDone: v.boolean() };
23
+ export const sources = query({
24
+ args,
25
+ returns: v.object({ ...pageFields, page: v.array(transferDocValidator) }),
26
+ handler: async (ctx, args) => {
27
+ const h = await ownedSnapshot(ctx, args);
28
+ if (
29
+ !h ||
30
+ !h.readOnly ||
31
+ h.phase !== "local_ready" ||
32
+ h.expiresAt <= Date.now() ||
33
+ (await riskRevision(ctx, h.accountId)) !== h.riskRevision
34
+ )
35
+ throw new Error(
36
+ "Payout collection is not ready for provider verification.",
37
+ );
38
+ if (
39
+ !Number.isInteger(args.paginationOpts.numItems) ||
40
+ args.paginationOpts.numItems < 1 ||
41
+ args.paginationOpts.numItems > 25
42
+ )
43
+ throw new Error("Invalid collection page.");
44
+ const page = await paginator(ctx.db, schema)
45
+ .query("payoutSnapshotSources")
46
+ .withIndex("by_snapshot", (q) => q.eq("snapshotId", h._id))
47
+ .paginate(args.paginationOpts);
48
+ const rows = [];
49
+ for (const cached of page.page) {
50
+ const row = await ctx.db
51
+ .query("transfers")
52
+ .withIndex("by_stripe_transfer_id", (q) =>
53
+ q.eq("stripeTransferId", cached.stripeTransferId),
54
+ )
55
+ .unique();
56
+ if (!row || transferFingerprint(row) !== cached.ledgerFingerprint)
57
+ throw new Error("Payout collection source changed.");
58
+ rows.push(row);
59
+ }
60
+ return { ...page, page: rows };
61
+ },
62
+ });
63
+ export const claims = query({
64
+ args,
65
+ returns: v.object({ ...pageFields, page: v.array(claimDoc) }),
66
+ handler: async (ctx, args) => {
67
+ const h = await ownedSnapshot(ctx, args);
68
+ if (
69
+ !h ||
70
+ !h.readOnly ||
71
+ h.phase !== "local_ready" ||
72
+ h.expiresAt <= Date.now() ||
73
+ (await riskRevision(ctx, h.accountId)) !== h.riskRevision
74
+ )
75
+ throw new Error(
76
+ "Payout collection is not ready for provider verification.",
77
+ );
78
+ if (
79
+ !Number.isInteger(args.paginationOpts.numItems) ||
80
+ args.paginationOpts.numItems < 1 ||
81
+ args.paginationOpts.numItems > 25
82
+ )
83
+ throw new Error("Invalid collection page.");
84
+ const page = await paginator(ctx.db, schema)
85
+ .query("payoutSnapshotClaims")
86
+ .withIndex("by_snapshot", (q) => q.eq("snapshotId", h._id))
87
+ .paginate(args.paginationOpts);
88
+ const rows = [];
89
+ for (const cached of page.page) {
90
+ const row = await ctx.db
91
+ .query("payoutReleaseClaims")
92
+ .withIndex("by_operation", (q) =>
93
+ q.eq("operationKey", cached.operationKey),
94
+ )
95
+ .unique();
96
+ if (!row || payoutClaimFingerprint(row) !== cached.fingerprint)
97
+ throw new Error("Payout collection claim changed.");
98
+ rows.push(row);
99
+ }
100
+ return { ...page, page: rows };
101
+ },
102
+ });
@@ -120,6 +120,32 @@ function payoutFingerprint(p: Doc<"payouts">) {
120
120
  }
121
121
  /** Funding, payout claims and allocations commit with their revision counters. */
122
122
  export function registerPayoutRevisions(triggers: Triggers<DataModel>) {
123
+ triggers.register("recoveryBalances", async (ctx, change) => {
124
+ const fingerprint = (row: Doc<"recoveryBalances"> | null) =>
125
+ row
126
+ ? JSON.stringify([
127
+ row.accountId,
128
+ row.scopeKey,
129
+ row.currency,
130
+ row.amountDue,
131
+ row.collectedAmount,
132
+ ])
133
+ : null;
134
+ if (fingerprint(change.oldDoc) === fingerprint(change.newDoc)) return;
135
+ for (const account of new Set([
136
+ change.oldDoc?.accountId,
137
+ change.newDoc?.accountId,
138
+ ]))
139
+ if (account)
140
+ await bump(
141
+ ctx,
142
+ account,
143
+ true,
144
+ "liability",
145
+ (change.newDoc ?? change.oldDoc)!.scopeKey,
146
+ change.newDoc === null,
147
+ );
148
+ });
123
149
  triggers.register("transfers", async (ctx, change) => {
124
150
  if (
125
151
  change.oldDoc &&
@@ -11,6 +11,7 @@ export const riskKind = v.union(
11
11
  v.literal("allocation"),
12
12
  v.literal("claim"),
13
13
  v.literal("fee"),
14
+ v.literal("liability"),
14
15
  );
15
16
  export const riskEventsTable = defineTable({
16
17
  accountId: v.string(),
@@ -32,6 +33,8 @@ export const collectionPhase = v.union(
32
33
  );
33
34
  export const snapshotFields = {
34
35
  readOnly: v.boolean(),
36
+ boundOperationKey: v.optional(v.string()),
37
+ boundRiskRevision: v.optional(v.number()),
35
38
  accountId: v.string(),
36
39
  ownerKey: v.string(),
37
40
  operationKey: v.string(),
@@ -180,7 +180,9 @@ export const finish = mutation({
180
180
  if (claim && claim.currency !== job.currency)
181
181
  throw new Error("Worker payout currency changed.");
182
182
  const retain =
183
- claim?.status === "reserved" || claim?.status === "submitted";
183
+ args.reason === "collection_pending" ||
184
+ claim?.status === "reserved" ||
185
+ claim?.status === "submitted";
184
186
  await ctx.db.patch("payoutWorkerJobs", job._id, {
185
187
  operationKey: retain ? job.operationKey : undefined,
186
188
  hasOperation: retain,
@@ -18,6 +18,12 @@ const messages: Record<string, string> = {
18
18
  "No payout was requested because the supported available Stripe balance is insufficient.",
19
19
  schedule_drift:
20
20
  "Payout scheduling changed outside the application. Contact platform support to verify controls.",
21
+ collection_pending:
22
+ "Complete payout history is still being collected. This collection has not requested a new bank payout; the automatic worker will resume the same collection.",
23
+ collection_invalidated:
24
+ "Payout history changed during collection. A fresh assessment is required before funds can qualify.",
25
+ collection_requires_action:
26
+ "This account requires a server action to collect its complete payout history.",
21
27
  snapshot_limit:
22
28
  "History reconciliation is incomplete. No payout was requested from a partial balance.",
23
29
  policy_inactive:
@@ -94,6 +94,12 @@ const reasons: Record<string, string> = {
94
94
  observations_stale: "Provider observations expired. Refresh the assessment.",
95
95
  expired:
96
96
  "The custom holding deadline has passed. Eligibility is unavailable until the payout schedule is restored and verified.",
97
+ collection_pending:
98
+ "Complete payout history is still being collected. This collection has not requested a new bank payout; the automatic worker will resume the same collection.",
99
+ collection_invalidated:
100
+ "Payout history changed during collection. A fresh assessment is required before funds can qualify.",
101
+ collection_requires_action:
102
+ "This account requires a server action to collect its complete payout history.",
97
103
  snapshot_limit:
98
104
  "This account needs continued history reconciliation before eligibility can be assessed.",
99
105
  policy_changed: "Payout settings changed. Refresh the assessment.",