@fantastic.dev/better-stripe 0.34.0 → 0.35.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 (258) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +486 -2
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +243 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +486 -2
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +243 -1
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/refundCommandEvidence.d.ts +14 -0
  12. package/dist/client/connect/refundCommandEvidence.d.ts.map +1 -0
  13. package/dist/client/connect/refundCommandEvidence.js +20 -0
  14. package/dist/client/connect/refundCommandEvidence.js.map +1 -0
  15. package/dist/client/connect/refundCommandNormalization.d.ts +11 -0
  16. package/dist/client/connect/refundCommandNormalization.d.ts.map +1 -0
  17. package/dist/client/connect/refundCommandNormalization.js +12 -0
  18. package/dist/client/connect/refundCommandNormalization.js.map +1 -0
  19. package/dist/client/financialObservations.d.ts +42 -0
  20. package/dist/client/financialObservations.d.ts.map +1 -0
  21. package/dist/client/financialObservations.js +58 -0
  22. package/dist/client/financialObservations.js.map +1 -0
  23. package/dist/client/financialOwnership.d.ts +52 -0
  24. package/dist/client/financialOwnership.d.ts.map +1 -0
  25. package/dist/client/financialOwnership.js +72 -0
  26. package/dist/client/financialOwnership.js.map +1 -0
  27. package/dist/client/index.d.ts +2 -2
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js +2 -2
  30. package/dist/client/index.js.map +1 -1
  31. package/dist/client/observationPagination.d.ts +10 -0
  32. package/dist/client/observationPagination.d.ts.map +1 -0
  33. package/dist/client/observationPagination.js +12 -0
  34. package/dist/client/observationPagination.js.map +1 -0
  35. package/dist/client/publicTypes.d.ts +5 -0
  36. package/dist/client/publicTypes.d.ts.map +1 -1
  37. package/dist/client/readContracts.d.ts +29 -0
  38. package/dist/client/readContracts.d.ts.map +1 -1
  39. package/dist/client/readContracts.js +10 -0
  40. package/dist/client/readContracts.js.map +1 -1
  41. package/dist/client/transferObservations.d.ts +59 -0
  42. package/dist/client/transferObservations.d.ts.map +1 -0
  43. package/dist/client/transferObservations.js +82 -0
  44. package/dist/client/transferObservations.js.map +1 -0
  45. package/dist/component/_generated/component.d.ts +506 -0
  46. package/dist/component/_generated/component.d.ts.map +1 -1
  47. package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -1
  48. package/dist/component/affiliateRecovery/mutations.js +4 -1
  49. package/dist/component/affiliateRecovery/mutations.js.map +1 -1
  50. package/dist/component/connect/mutations.d.ts.map +1 -1
  51. package/dist/component/connect/mutations.js +18 -2
  52. package/dist/component/connect/mutations.js.map +1 -1
  53. package/dist/component/connect/queries.d.ts +8 -0
  54. package/dist/component/connect/queries.d.ts.map +1 -1
  55. package/dist/component/connect/reversalClaims.d.ts.map +1 -1
  56. package/dist/component/connect/reversalClaims.js +7 -1
  57. package/dist/component/connect/reversalClaims.js.map +1 -1
  58. package/dist/component/connect/reversalReceipts.d.ts.map +1 -1
  59. package/dist/component/connect/reversalReceipts.js +2 -0
  60. package/dist/component/connect/reversalReceipts.js.map +1 -1
  61. package/dist/component/connect/schema.d.ts +11 -1
  62. package/dist/component/connect/schema.d.ts.map +1 -1
  63. package/dist/component/connect/schema.js +9 -1
  64. package/dist/component/connect/schema.js.map +1 -1
  65. package/dist/component/connect/validators.d.ts +9 -1
  66. package/dist/component/connect/validators.d.ts.map +1 -1
  67. package/dist/component/connect/validators.js +2 -0
  68. package/dist/component/connect/validators.js.map +1 -1
  69. package/dist/component/earnings/triggers.d.ts +426 -2
  70. package/dist/component/earnings/triggers.d.ts.map +1 -1
  71. package/dist/component/earnings/triggers.js +7 -1
  72. package/dist/component/earnings/triggers.js.map +1 -1
  73. package/dist/component/financialObservations/continuation.d.ts +7 -0
  74. package/dist/component/financialObservations/continuation.d.ts.map +1 -0
  75. package/dist/component/financialObservations/continuation.js +131 -0
  76. package/dist/component/financialObservations/continuation.js.map +1 -0
  77. package/dist/component/financialObservations/generations.d.ts +6 -0
  78. package/dist/component/financialObservations/generations.d.ts.map +1 -0
  79. package/dist/component/financialObservations/generations.js +46 -0
  80. package/dist/component/financialObservations/generations.js.map +1 -0
  81. package/dist/component/financialObservations/mutations.d.ts +62 -0
  82. package/dist/component/financialObservations/mutations.d.ts.map +1 -0
  83. package/dist/component/financialObservations/mutations.js +69 -0
  84. package/dist/component/financialObservations/mutations.js.map +1 -0
  85. package/dist/component/financialObservations/queries.d.ts +307 -0
  86. package/dist/component/financialObservations/queries.d.ts.map +1 -0
  87. package/dist/component/financialObservations/queries.js +219 -0
  88. package/dist/component/financialObservations/queries.js.map +1 -0
  89. package/dist/component/financialObservations/schema.d.ts +182 -0
  90. package/dist/component/financialObservations/schema.d.ts.map +1 -0
  91. package/dist/component/financialObservations/schema.js +53 -0
  92. package/dist/component/financialObservations/schema.js.map +1 -0
  93. package/dist/component/financialObservations/settlement.d.ts +7 -0
  94. package/dist/component/financialObservations/settlement.d.ts.map +1 -0
  95. package/dist/component/financialObservations/settlement.js +118 -0
  96. package/dist/component/financialObservations/settlement.js.map +1 -0
  97. package/dist/component/financialObservations/settlementHelpers.d.ts +46 -0
  98. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -0
  99. package/dist/component/financialObservations/settlementHelpers.js +70 -0
  100. package/dist/component/financialObservations/settlementHelpers.js.map +1 -0
  101. package/dist/component/financialObservations/transferBatches.d.ts +12 -0
  102. package/dist/component/financialObservations/transferBatches.d.ts.map +1 -0
  103. package/dist/component/financialObservations/transferBatches.js +76 -0
  104. package/dist/component/financialObservations/transferBatches.js.map +1 -0
  105. package/dist/component/financialObservations/transferContinuation.d.ts +5 -0
  106. package/dist/component/financialObservations/transferContinuation.d.ts.map +1 -0
  107. package/dist/component/financialObservations/transferContinuation.js +35 -0
  108. package/dist/component/financialObservations/transferContinuation.js.map +1 -0
  109. package/dist/component/financialObservations/transferContinuationState.d.ts +8 -0
  110. package/dist/component/financialObservations/transferContinuationState.d.ts.map +1 -0
  111. package/dist/component/financialObservations/transferContinuationState.js +69 -0
  112. package/dist/component/financialObservations/transferContinuationState.js.map +1 -0
  113. package/dist/component/financialObservations/transferContinuationSteps.d.ts +5 -0
  114. package/dist/component/financialObservations/transferContinuationSteps.d.ts.map +1 -0
  115. package/dist/component/financialObservations/transferContinuationSteps.js +174 -0
  116. package/dist/component/financialObservations/transferContinuationSteps.js.map +1 -0
  117. package/dist/component/financialObservations/transferHelpers.d.ts +18 -0
  118. package/dist/component/financialObservations/transferHelpers.d.ts.map +1 -0
  119. package/dist/component/financialObservations/transferHelpers.js +37 -0
  120. package/dist/component/financialObservations/transferHelpers.js.map +1 -0
  121. package/dist/component/financialObservations/transferReferenceSchema.d.ts +56 -0
  122. package/dist/component/financialObservations/transferReferenceSchema.d.ts.map +1 -0
  123. package/dist/component/financialObservations/transferReferenceSchema.js +21 -0
  124. package/dist/component/financialObservations/transferReferenceSchema.js.map +1 -0
  125. package/dist/component/financialObservations/transferSchema.d.ts +237 -0
  126. package/dist/component/financialObservations/transferSchema.d.ts.map +1 -0
  127. package/dist/component/financialObservations/transferSchema.js +65 -0
  128. package/dist/component/financialObservations/transferSchema.js.map +1 -0
  129. package/dist/component/financialObservations/transfers.d.ts +7 -0
  130. package/dist/component/financialObservations/transfers.d.ts.map +1 -0
  131. package/dist/component/financialObservations/transfers.js +79 -0
  132. package/dist/component/financialObservations/transfers.js.map +1 -0
  133. package/dist/component/financialOwnership/helpers.d.ts +37 -0
  134. package/dist/component/financialOwnership/helpers.d.ts.map +1 -0
  135. package/dist/component/financialOwnership/helpers.js +76 -0
  136. package/dist/component/financialOwnership/helpers.js.map +1 -0
  137. package/dist/component/financialOwnership/mutations.d.ts +28 -0
  138. package/dist/component/financialOwnership/mutations.d.ts.map +1 -0
  139. package/dist/component/financialOwnership/mutations.js +74 -0
  140. package/dist/component/financialOwnership/mutations.js.map +1 -0
  141. package/dist/component/financialOwnership/queries.d.ts +57 -0
  142. package/dist/component/financialOwnership/queries.d.ts.map +1 -0
  143. package/dist/component/financialOwnership/queries.js +50 -0
  144. package/dist/component/financialOwnership/queries.js.map +1 -0
  145. package/dist/component/financialOwnership/schema.d.ts +140 -0
  146. package/dist/component/financialOwnership/schema.d.ts.map +1 -0
  147. package/dist/component/financialOwnership/schema.js +35 -0
  148. package/dist/component/financialOwnership/schema.js.map +1 -0
  149. package/dist/component/payoutRelease/queries.d.ts +2 -2
  150. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  151. package/dist/component/refundHistory/commandBinding.d.ts +17 -0
  152. package/dist/component/refundHistory/commandBinding.d.ts.map +1 -0
  153. package/dist/component/refundHistory/commandBinding.js +41 -0
  154. package/dist/component/refundHistory/commandBinding.js.map +1 -0
  155. package/dist/component/refundHistory/commandEvidence.d.ts +50 -0
  156. package/dist/component/refundHistory/commandEvidence.d.ts.map +1 -0
  157. package/dist/component/refundHistory/commandEvidence.js +54 -0
  158. package/dist/component/refundHistory/commandEvidence.js.map +1 -0
  159. package/dist/component/refundHistory/commandEvidenceValidator.d.ts +89 -0
  160. package/dist/component/refundHistory/commandEvidenceValidator.d.ts.map +1 -0
  161. package/dist/component/refundHistory/commandEvidenceValidator.js +8 -0
  162. package/dist/component/refundHistory/commandEvidenceValidator.js.map +1 -0
  163. package/dist/component/refundHistory/commandFields.d.ts +8 -0
  164. package/dist/component/refundHistory/commandFields.d.ts.map +1 -0
  165. package/dist/component/refundHistory/commandFields.js +9 -0
  166. package/dist/component/refundHistory/commandFields.js.map +1 -0
  167. package/dist/component/refundHistory/mutations.d.ts +8 -0
  168. package/dist/component/refundHistory/mutations.d.ts.map +1 -0
  169. package/dist/component/refundHistory/mutations.js +25 -0
  170. package/dist/component/refundHistory/mutations.js.map +1 -0
  171. package/dist/component/refundHistory/queries.d.ts +51 -0
  172. package/dist/component/refundHistory/queries.d.ts.map +1 -1
  173. package/dist/component/refundHistory/queries.js +14 -0
  174. package/dist/component/refundHistory/queries.js.map +1 -1
  175. package/dist/component/schema.d.ts +243 -1
  176. package/dist/component/schema.js +12 -0
  177. package/dist/component/schema.js.map +1 -1
  178. package/dist/component/settlement/mutations.d.ts.map +1 -1
  179. package/dist/component/settlement/mutations.js +5 -1
  180. package/dist/component/settlement/mutations.js.map +1 -1
  181. package/dist/shared/refundCommandScope.d.ts +10 -0
  182. package/dist/shared/refundCommandScope.d.ts.map +1 -0
  183. package/dist/shared/refundCommandScope.js +9 -0
  184. package/dist/shared/refundCommandScope.js.map +1 -0
  185. package/docs/financial-observations.md +159 -0
  186. package/docs/financial-ownership.md +54 -0
  187. package/docs/refund-command-evidence.md +49 -0
  188. package/package.json +5 -2
  189. package/src/client/connect/refundCommandEvidence.ts +41 -0
  190. package/src/client/connect/refundCommandNormalization.ts +28 -0
  191. package/src/client/financialObservations.test.ts +109 -0
  192. package/src/client/financialObservations.ts +106 -0
  193. package/src/client/financialOwnership.test.ts +80 -0
  194. package/src/client/financialOwnership.ts +116 -0
  195. package/src/client/index.ts +2 -2
  196. package/src/client/observationPagination.ts +11 -0
  197. package/src/client/publicTypes.ts +37 -0
  198. package/src/client/readContracts.ts +21 -0
  199. package/src/client/refund-command-evidence.test.ts +68 -0
  200. package/src/client/refund-command-normalization.test.ts +61 -0
  201. package/src/client/transferContinuation.test.ts +94 -0
  202. package/src/client/transferObservations.test.ts +98 -0
  203. package/src/client/transferObservations.ts +180 -0
  204. package/src/component/_generated/api.ts +44 -0
  205. package/src/component/_generated/component.ts +590 -0
  206. package/src/component/affiliateRecovery/mutations.ts +10 -1
  207. package/src/component/connect/mutations.ts +29 -2
  208. package/src/component/connect/reversalClaims.ts +19 -1
  209. package/src/component/connect/reversalReceipts.ts +2 -0
  210. package/src/component/connect/schema.ts +9 -1
  211. package/src/component/connect/validators.ts +2 -0
  212. package/src/component/core/reset.test.ts +8 -1
  213. package/src/component/earnings/earnings-totals.test.ts +14 -10
  214. package/src/component/earnings/triggers.ts +9 -1
  215. package/src/component/financialObservations/continuation.test.ts +445 -0
  216. package/src/component/financialObservations/continuation.ts +159 -0
  217. package/src/component/financialObservations/generations.ts +53 -0
  218. package/src/component/financialObservations/mutations.ts +75 -0
  219. package/src/component/financialObservations/observation-boundaries.test.ts +466 -0
  220. package/src/component/financialObservations/queries.ts +246 -0
  221. package/src/component/financialObservations/schema.ts +68 -0
  222. package/src/component/financialObservations/settlement-observations.test.ts +86 -0
  223. package/src/component/financialObservations/settlement.ts +142 -0
  224. package/src/component/financialObservations/settlementHelpers.ts +92 -0
  225. package/src/component/financialObservations/transfer-batches.test.ts +61 -0
  226. package/src/component/financialObservations/transfer-boundaries.test.ts +116 -0
  227. package/src/component/financialObservations/transfer-continuation-guards.test.ts +428 -0
  228. package/src/component/financialObservations/transfer-continuation.test.ts +154 -0
  229. package/src/component/financialObservations/transfer-observations.test.ts +212 -0
  230. package/src/component/financialObservations/transfer-overflow.test.ts +181 -0
  231. package/src/component/financialObservations/transfer-writers.test.ts +162 -0
  232. package/src/component/financialObservations/transferBatches.ts +96 -0
  233. package/src/component/financialObservations/transferContinuation.ts +53 -0
  234. package/src/component/financialObservations/transferContinuationState.ts +85 -0
  235. package/src/component/financialObservations/transferContinuationSteps.ts +232 -0
  236. package/src/component/financialObservations/transferHelpers.ts +38 -0
  237. package/src/component/financialObservations/transferReferenceSchema.ts +20 -0
  238. package/src/component/financialObservations/transferSchema.ts +74 -0
  239. package/src/component/financialObservations/transfers.ts +99 -0
  240. package/src/component/financialOwnership/financial-ownership.test.ts +102 -0
  241. package/src/component/financialOwnership/helpers.ts +98 -0
  242. package/src/component/financialOwnership/mutations.ts +83 -0
  243. package/src/component/financialOwnership/ownership-boundaries.test.ts +308 -0
  244. package/src/component/financialOwnership/queries.ts +65 -0
  245. package/src/component/financialOwnership/schema.ts +35 -0
  246. package/src/component/refundHistory/command-evidence.test.ts +288 -0
  247. package/src/component/refundHistory/command-normalization-resource.test.ts +77 -0
  248. package/src/component/refundHistory/command-normalization.test.ts +229 -0
  249. package/src/component/refundHistory/command-provenance.test.ts +59 -0
  250. package/src/component/refundHistory/commandBinding.ts +54 -0
  251. package/src/component/refundHistory/commandEvidence.ts +71 -0
  252. package/src/component/refundHistory/commandEvidenceValidator.ts +18 -0
  253. package/src/component/refundHistory/commandFields.ts +9 -0
  254. package/src/component/refundHistory/mutations.ts +33 -0
  255. package/src/component/refundHistory/queries.ts +15 -0
  256. package/src/component/schema.ts +22 -0
  257. package/src/component/settlement/mutations.ts +5 -1
  258. package/src/shared/refundCommandScope.ts +19 -0
@@ -1,3 +1,10 @@
1
+ import { refundCommandBinding } from "../refundHistory/commandBinding.js";
2
+ import {
3
+ deferTransferFacts,
4
+ synchronousTransferFactLimit,
5
+ } from "../financialObservations/transferBatches.js";
6
+ import { observeTransfer } from "../financialObservations/transfers.js";
7
+
1
8
  import { syncCommissionTransfer } from "../settlement/clawbacks.js";
2
9
  import { recordTransferReversalDefinition } from "./reversalReceipts.js";
3
10
  import { claimReversalSlicesDefinition } from "./reversalClaims.js";
@@ -140,7 +147,11 @@ export const upsertRefund = mutation({
140
147
 
141
148
  const accountId =
142
149
  args.accountId ?? (await paymentSeller(ctx, args.stripePaymentIntentId));
143
- const record = { ...args, ...(accountId ? { accountId } : {}) };
150
+ const record = {
151
+ ...args,
152
+ ...(accountId ? { accountId } : {}),
153
+ ...refundCommandBinding(existing, args, Date.now()),
154
+ };
144
155
  if (existing) {
145
156
  await ctx.db.patch("refunds", existing._id, record);
146
157
  } else {
@@ -317,13 +328,21 @@ export const upsertTransfer = mutation({
317
328
  );
318
329
  await syncCommissionTransfer(ctx, { ...existing, ...args, ...derived });
319
330
  await ctx.db.patch("transfers", existing._id, { ...args, ...derived });
331
+ await observeTransfer(
332
+ ctx,
333
+ (await ctx.db.get("transfers", existing._id))!,
334
+ );
320
335
  } else {
321
336
  const derived = deriveReversalState(
322
337
  args.amount,
323
338
  args.reversedAmount ?? 0,
324
339
  args.status,
325
340
  );
326
- await ctx.db.insert("transfers", { ...args, ...derived });
341
+ const transferId = await ctx.db.insert("transfers", {
342
+ ...args,
343
+ ...derived,
344
+ });
345
+ await observeTransfer(ctx, (await ctx.db.get("transfers", transferId))!);
327
346
  }
328
347
 
329
348
  return null;
@@ -448,8 +467,16 @@ export const releaseReversalClaim = mutation({
448
467
  await ctx.db.patch("transfers", p.legId, {
449
468
  reversalClaimedAmount: p.from,
450
469
  });
470
+ if (plan.length <= synchronousTransferFactLimit)
471
+ await observeTransfer(ctx, (await ctx.db.get("transfers", p.legId))!);
451
472
  rewound.push({ stripeTransferId: p.stripeTransferId, to: p.from });
452
473
  }
474
+ if (plan.length > synchronousTransferFactLimit)
475
+ await deferTransferFacts(
476
+ ctx,
477
+ op,
478
+ plan.map((p) => p.legId),
479
+ );
453
480
  await ctx.db.delete("transferReversalOps", op._id);
454
481
 
455
482
  return { released: true, rewound };
@@ -1,3 +1,8 @@
1
+ import {
2
+ deferTransferFacts,
3
+ synchronousTransferFactLimit,
4
+ } from "../financialObservations/transferBatches.js";
5
+ import { observeTransfer } from "../financialObservations/transfers.js";
1
6
  import { v } from "convex/values";
2
7
  import type { MutationCtx } from "../_generated/server.js";
3
8
  import { computeReversalSlices } from "../lib/reversals.js";
@@ -203,10 +208,15 @@ export const claimReversalSlicesDefinition = {
203
208
  await ctx.db.patch("transfers", byId.get(s.stripeTransferId)!._id, {
204
209
  reversalClaimedAmount: s.to,
205
210
  });
211
+ if (slices.length <= synchronousTransferFactLimit)
212
+ await observeTransfer(
213
+ ctx,
214
+ (await ctx.db.get("transfers", byId.get(s.stripeTransferId)!._id))!,
215
+ );
206
216
  }
207
217
  // Record the operation even when it claims nothing, so a redelivery is a
208
218
  // deterministic no-op instead of a recomputation against newer state.
209
- await ctx.db.insert("transferReversalOps", {
219
+ const operationId = await ctx.db.insert("transferReversalOps", {
210
220
  operationId: args.operationId,
211
221
  sourceChargeId: args.sourceChargeId,
212
222
  slices,
@@ -215,6 +225,14 @@ export const claimReversalSlicesDefinition = {
215
225
  : {}),
216
226
  });
217
227
 
228
+ if (slices.length > synchronousTransferFactLimit)
229
+ await deferTransferFacts(
230
+ ctx,
231
+ (await ctx.db.get("transferReversalOps", operationId))!,
232
+ slices.map((s) => byId.get(s.stripeTransferId)!._id),
233
+ "transfer_frontier_claim",
234
+ );
235
+
218
236
  return {
219
237
  replay: false,
220
238
  slices: slices.map((s) => ({
@@ -1,3 +1,4 @@
1
+ import { observeTransfer } from "../financialObservations/transfers.js";
1
2
  import { updateObligation } from "../affiliateRecovery/accounting.js";
2
3
  import { v } from "convex/values";
3
4
  import type { Doc } from "../_generated/dataModel.js";
@@ -131,6 +132,7 @@ export const recordTransferReversalDefinition = {
131
132
  args.receipt,
132
133
  );
133
134
  await ctx.db.patch("transfers", transfer._id, derived);
135
+ await observeTransfer(ctx, (await ctx.db.get("transfers", transfer._id))!);
134
136
  const obligation = await ctx.db
135
137
  .query("affiliateObligations")
136
138
  .withIndex("by_transfer", (q) =>
@@ -1,3 +1,4 @@
1
+ import { refundCommandFields } from "../refundHistory/commandFields.js";
1
2
  import { v } from "convex/values";
2
3
  import { defineTable } from "convex/server";
3
4
 
@@ -48,7 +49,14 @@ export const pendingFeeRefundsTable = defineTable(pendingFeeRefundFields).index(
48
49
  * Refunds. Compound status indexes follow Plan 002: filtered list queries
49
50
  * use a compound index, never filter-after-take.
50
51
  */
51
- export const refundsTable = defineTable(refundFields)
52
+ export const refundsTable = defineTable({
53
+ ...refundFields,
54
+ ...refundCommandFields,
55
+ })
56
+ .index("by_refund_command_key", ["refundCommandKey"])
57
+ .index("by_refund_command_normalization_version", [
58
+ "refundCommandNormalizationVersion",
59
+ ])
52
60
  .index("by_stripe_refund_id", ["stripeRefundId"])
53
61
  .index("by_stripe_payment_intent_id", ["stripePaymentIntentId"])
54
62
  .index("by_account_id", ["accountId"])
@@ -1,3 +1,4 @@
1
+ import { refundCommandFields } from "../refundHistory/commandFields.js";
1
2
  import { commissionExposureValidator } from "../settlement/clawbackSchema.js";
2
3
  import { type Infer, v } from "convex/values";
3
4
 
@@ -154,6 +155,7 @@ export const refundDocValidator = v.object({
154
155
  _id: v.id("refunds"),
155
156
  _creationTime: v.number(),
156
157
  ...refundFields,
158
+ ...refundCommandFields,
157
159
  });
158
160
 
159
161
  // =============================================================================
@@ -108,10 +108,17 @@ describe("core — clearAllTables", () => {
108
108
  eventType: "invoice.paid",
109
109
  });
110
110
 
111
+ const seededCount = await t.run(async (ctx) => {
112
+ let count = 0;
113
+ for (const tableName of Object.keys(schema.tables) as TableNames[])
114
+ count += (await ctx.db.query(tableName).collect()).length;
115
+ return count;
116
+ });
117
+ expect(seededCount).toBeGreaterThan(0);
111
118
  const result = await t.mutation(api.core.mutations.clearAllTables, {});
112
119
  const tableCount = Object.keys(schema.tables).length;
113
120
 
114
- expect(result.cleared).toBe(20);
121
+ expect(result.cleared).toBe(seededCount);
115
122
  expect(result.tables).toHaveLength(tableCount);
116
123
 
117
124
  for (const tableName of Object.keys(schema.tables) as TableNames[]) {
@@ -116,16 +116,20 @@ describe("getAccountEarnings — exact totals past the 50-row cap (BTS-64)", ()
116
116
 
117
117
  // 450 transfers, each 100 gross / 10 reversed → exact 45000 / 4500 only if
118
118
  // every page is summed (a single 200-row page would give 20000 / 2000).
119
- for (let i = 0; i < 450; i++) {
120
- await t.mutation(api.connect.mutations.upsertTransfer, {
121
- stripeTransferId: `tr_mp_${i}`,
122
- destinationAccountId: "acct_mp",
123
- amount: 100,
124
- reversedAmount: 10,
125
- currency: "usd",
126
- status: "paid",
127
- });
128
- }
119
+ // Persisted-history fixture isolates the pagination reader from unrelated
120
+ // upsert diagnostics. The 120-row and small-account cases cover actual upserts.
121
+ await t.run(async (ctx) => {
122
+ for (let i = 0; i < 450; i++) {
123
+ await ctx.db.insert("transfers", {
124
+ stripeTransferId: `tr_mp_${i}`,
125
+ destinationAccountId: "acct_mp",
126
+ amount: 100,
127
+ reversedAmount: 10,
128
+ currency: "usd",
129
+ status: "paid",
130
+ });
131
+ }
132
+ });
129
133
  // A second account's rows must not leak in across pages either.
130
134
  await t.mutation(api.connect.mutations.upsertTransfer, {
131
135
  stripeTransferId: "tr_mp_other",
@@ -1,3 +1,4 @@
1
+ import { observeTransfer } from "../financialObservations/transfers.js";
1
2
  import { registerPayoutRevisions } from "../payoutSnapshots/revisions.js";
2
3
  import { Triggers } from "convex-helpers/server/triggers";
3
4
  import {
@@ -68,8 +69,15 @@ triggers.register("transfers", async (ctx, change) => {
68
69
  await adjust(ctx, "earnings", contribution(change.oldDoc), -1);
69
70
  if (change.newDoc) {
70
71
  await adjust(ctx, "earnings", contribution(change.newDoc), 1);
71
- if (!change.newDoc.totalsRecorded)
72
+ if (!change.newDoc.totalsRecorded) {
72
73
  await ctx.innerDb.patch("transfers", change.id, { totalsRecorded: true });
74
+ // Frontier producers own bounded batch observation, including oversized release deferral.
75
+ if (
76
+ change.oldDoc?.reversalClaimedAmount ===
77
+ change.newDoc.reversalClaimedAmount
78
+ )
79
+ await observeTransfer(ctx, { ...change.newDoc, totalsRecorded: true });
80
+ }
73
81
  }
74
82
  });
75
83
  triggers.register("payouts", async (ctx, change) => {
@@ -0,0 +1,445 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { modules, schema } from "../../test.js";
5
+
6
+ const reserve = makeFunctionReference<"mutation">(
7
+ "settlement/mutations:reserveSettlementAllocation",
8
+ );
9
+ const resume = makeFunctionReference<"mutation">(
10
+ "financialObservations/mutations:resume",
11
+ );
12
+ const source = makeFunctionReference<"query">(
13
+ "financialObservations/queries:source",
14
+ );
15
+ function allocation(count = 251) {
16
+ return {
17
+ sourceChargeId: "ch_continuation",
18
+ gross: count + 2,
19
+ currency: "usd",
20
+ processingFee: 1,
21
+ platformNet: 1,
22
+ transfers: Array.from({ length: count }, (_, i) => ({
23
+ destinationAccountId: `bucket_${i}`,
24
+ role: "store" as const,
25
+ amount: 1,
26
+ })),
27
+ };
28
+ }
29
+ it("resumes beyond both bounds and validates the actual end without changing financial rows", async () => {
30
+ const t = convexTest(schema, modules);
31
+ const row = await t.mutation(reserve, allocation());
32
+ let result = await t.query(source, { allocationId: row._id });
33
+ for (let i = 0; i < 6; i++) {
34
+ result = await t.mutation(resume, {
35
+ allocationId: row._id,
36
+ expectedGeneration: result.observation.generation,
37
+ });
38
+ expect(result.coverage).toBe("unknown");
39
+ expect(result.observation.indexedLegCount).toBe(
40
+ Math.min((i + 1) * 100, 251),
41
+ );
42
+ expect(
43
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
44
+ ).toEqual(row);
45
+ }
46
+ expect(result.observation).toMatchObject({
47
+ continuation: { state: "complete", nextLeg: 251, validatedLegs: 251 },
48
+ isOverflow: true,
49
+ isContradictory: false,
50
+ });
51
+ expect(await t.mutation(reserve, allocation())).toEqual(row);
52
+ expect(await t.query(source, { allocationId: row._id })).toEqual(result);
53
+ });
54
+ it("an acknowledged batch replay cannot advance the durable cursor twice", async () => {
55
+ const t = convexTest(schema, modules);
56
+ const row = await t.mutation(reserve, allocation());
57
+ const args = { allocationId: row._id, expectedGeneration: 1 };
58
+ const first = await t.mutation(resume, args);
59
+ expect(first.observation).toMatchObject({
60
+ indexedLegCount: 100,
61
+ continuation: { nextLeg: 100 },
62
+ });
63
+ expect(await t.mutation(resume, args)).toEqual(first);
64
+ expect(
65
+ await t.run((ctx) => ctx.db.query("financialSourceLegs").take(101)),
66
+ ).toHaveLength(100);
67
+ });
68
+ it("holds missing already committed slots without recreating them during validation", async () => {
69
+ const t = convexTest(schema, modules);
70
+ const row = await t.mutation(reserve, allocation(101));
71
+ let result = await t.mutation(resume, {
72
+ allocationId: row._id,
73
+ expectedGeneration: 1,
74
+ });
75
+ result = await t.mutation(resume, {
76
+ allocationId: row._id,
77
+ expectedGeneration: result.observation.generation,
78
+ });
79
+ await t.run(async (ctx) => {
80
+ const leg = await ctx.db
81
+ .query("financialSourceLegs")
82
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
83
+ q.eq("allocationId", row._id).eq("legIndex", 50),
84
+ )
85
+ .unique();
86
+ await ctx.db.delete("financialSourceLegs", leg!._id);
87
+ });
88
+ result = await t.mutation(resume, {
89
+ allocationId: row._id,
90
+ expectedGeneration: result.observation.generation,
91
+ });
92
+ expect(result.observation).toMatchObject({
93
+ isContradictory: true,
94
+ continuation: { state: "held" },
95
+ });
96
+ expect(
97
+ await t.run((ctx) => ctx.db.query("financialSourceLegs").take(102)),
98
+ ).toHaveLength(100);
99
+ });
100
+ it.each([
101
+ "duplicate",
102
+ "destination",
103
+ "fractional",
104
+ "extra",
105
+ "negative",
106
+ ] as const)(
107
+ "holds %s indexed corruption with every existing observation retained",
108
+ async (kind) => {
109
+ const t = convexTest(schema, modules);
110
+ const row = await t.mutation(reserve, allocation(101));
111
+ let result = await t.mutation(resume, {
112
+ allocationId: row._id,
113
+ expectedGeneration: 1,
114
+ });
115
+ result = await t.mutation(resume, {
116
+ allocationId: row._id,
117
+ expectedGeneration: result.observation.generation,
118
+ });
119
+ await t.run(async (ctx) => {
120
+ const leg = await ctx.db
121
+ .query("financialSourceLegs")
122
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
123
+ q.eq("allocationId", row._id).eq("legIndex", 50),
124
+ )
125
+ .unique();
126
+ const { _id, _creationTime, ...fields } = leg!;
127
+ void _creationTime;
128
+ if (kind === "duplicate")
129
+ await ctx.db.insert("financialSourceLegs", fields);
130
+ if (kind === "extra")
131
+ await ctx.db.insert("financialSourceLegs", {
132
+ ...fields,
133
+ legIndex: 101,
134
+ });
135
+ if (kind === "negative")
136
+ await ctx.db.insert("financialSourceLegs", { ...fields, legIndex: -1 });
137
+ if (kind === "destination")
138
+ await ctx.db.patch("financialSourceLegs", _id, {
139
+ bucketKey: "changed",
140
+ });
141
+ if (kind === "fractional")
142
+ await ctx.db.patch("financialSourceLegs", _id, { legIndex: 50.5 });
143
+ });
144
+ const original = await t.run((ctx) =>
145
+ ctx.db.query("financialSourceLegs").take(103),
146
+ );
147
+ for (let i = 0; i < 2 && !result.observation.isContradictory; i++)
148
+ result = await t.mutation(resume, {
149
+ allocationId: row._id,
150
+ expectedGeneration: result.observation.generation,
151
+ });
152
+ expect(result.observation).toMatchObject({
153
+ isContradictory: true,
154
+ continuation: { state: "held" },
155
+ });
156
+ expect(
157
+ await t.run((ctx) => ctx.db.query("financialSourceLegs").take(103)),
158
+ ).toEqual(original);
159
+ expect(
160
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
161
+ ).toEqual(row);
162
+ },
163
+ );
164
+ it.each(["source", "duplicate source", "cursor"] as const)(
165
+ "holds late %s changes before indexing another batch",
166
+ async (kind) => {
167
+ const t = convexTest(schema, modules);
168
+ const row = await t.mutation(reserve, allocation());
169
+ const first = await t.mutation(resume, {
170
+ allocationId: row._id,
171
+ expectedGeneration: 1,
172
+ });
173
+ await t.run(async (ctx) => {
174
+ if (kind === "source")
175
+ await ctx.db.patch("settlementAllocations", row._id, {
176
+ currency: "eur",
177
+ });
178
+ if (kind === "duplicate source")
179
+ await ctx.db.insert("settlementAllocations", allocation());
180
+ if (kind === "cursor")
181
+ await ctx.db.patch(
182
+ "financialSourceObservations",
183
+ first.observation._id,
184
+ {
185
+ continuation: {
186
+ state: "validating",
187
+ nextLeg: 100,
188
+ validatedLegs: 0,
189
+ },
190
+ },
191
+ );
192
+ });
193
+ const result = await t.mutation(resume, {
194
+ allocationId: row._id,
195
+ expectedGeneration: first.observation.generation,
196
+ });
197
+ expect(result.observation).toMatchObject({
198
+ indexedLegCount: 100,
199
+ isContradictory: true,
200
+ continuation: { state: "held" },
201
+ });
202
+ },
203
+ );
204
+ it("a rollback between indexing and cursor persistence leaves no partial batch", async () => {
205
+ const t = convexTest(schema, modules);
206
+ const row = await t.mutation(reserve, allocation());
207
+ const { continueSettlementObservation } = await import("./continuation.js");
208
+ await expect(
209
+ t.run(async (ctx) => {
210
+ const marker = await ctx.db
211
+ .query("financialSourceObservations")
212
+ .withIndex("by_allocation_id", (q) => q.eq("allocationId", row._id))
213
+ .unique();
214
+ await continueSettlementObservation(ctx, marker!, 1);
215
+ throw new Error("interrupted before commit");
216
+ }),
217
+ ).rejects.toThrow("interrupted before commit");
218
+ expect(
219
+ await t.run((ctx) => ctx.db.query("financialSourceLegs").take(1)),
220
+ ).toEqual([]);
221
+ expect(
222
+ (await t.query(source, { allocationId: row._id })).observation
223
+ .indexedLegCount,
224
+ ).toBe(0);
225
+ expect(
226
+ (await t.mutation(resume, { allocationId: row._id, expectedGeneration: 1 }))
227
+ .observation.indexedLegCount,
228
+ ).toBe(100);
229
+ });
230
+ it("preserves previously pinned original ownership across interrupted batches and owner replacement", async () => {
231
+ const t = convexTest(schema, modules);
232
+ const register = makeFunctionReference<"mutation">(
233
+ "financialOwnership/mutations:register",
234
+ );
235
+ await t.mutation(register, {
236
+ bucketKey: "bucket_0",
237
+ kind: "logical",
238
+ userId: "original",
239
+ orgId: "org",
240
+ source: { integration: "host", recordId: "member" },
241
+ });
242
+ const row = await t.mutation(reserve, allocation(101));
243
+ let result = await t.mutation(resume, {
244
+ allocationId: row._id,
245
+ expectedGeneration: 1,
246
+ });
247
+ await t.run(async (ctx) => {
248
+ const registration = await ctx.db
249
+ .query("financialOwnership")
250
+ .withIndex("by_bucket_key", (q) => q.eq("bucketKey", "bucket_0"))
251
+ .unique();
252
+ await ctx.db.delete("financialOwnership", registration!._id);
253
+ });
254
+ await t.mutation(register, {
255
+ bucketKey: "bucket_0",
256
+ kind: "logical",
257
+ userId: "replacement",
258
+ orgId: "org",
259
+ source: { integration: "host", recordId: "newmember" },
260
+ });
261
+ for (let i = 0; i < 3; i++)
262
+ result = await t.mutation(resume, {
263
+ allocationId: row._id,
264
+ expectedGeneration: result.observation.generation,
265
+ });
266
+ const owner = makeFunctionReference<"query">(
267
+ "financialObservations/queries:owner",
268
+ );
269
+ const paginationOpts = { numItems: 100, cursor: null };
270
+ expect(
271
+ await t.query(owner, { userId: "original", orgId: "org", paginationOpts }),
272
+ ).toMatchObject({
273
+ coverage: "unknown",
274
+ page: [
275
+ expect.objectContaining({
276
+ userId: "original",
277
+ ownershipStatus: "contradictory",
278
+ }),
279
+ ],
280
+ });
281
+ expect(
282
+ await t.query(owner, {
283
+ userId: "replacement",
284
+ orgId: "org",
285
+ paginationOpts,
286
+ }),
287
+ ).toMatchObject({ page: [] });
288
+ expect(
289
+ await t.query(owner, { userId: "original", paginationOpts }),
290
+ ).toMatchObject({ page: [] });
291
+ expect(result.observation.continuation.state).toBe("complete");
292
+ expect(
293
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
294
+ ).toEqual(row);
295
+ });
296
+ it("validates all roles and exposes every unknown-owned leg through bounded exact bucket pages", async () => {
297
+ const t = convexTest(schema, modules);
298
+ const original = allocation(301);
299
+ const args = {
300
+ ...original,
301
+ transfers: original.transfers.map((leg, i) => ({
302
+ ...leg,
303
+ role: (["store", "affiliate", "other"] as const)[i % 3]!,
304
+ })),
305
+ };
306
+ const row = await t.mutation(reserve, args);
307
+ let result = await t.query(source, { allocationId: row._id });
308
+ for (let i = 0; i < 8; i++)
309
+ result = await t.mutation(resume, {
310
+ allocationId: row._id,
311
+ expectedGeneration: result.observation.generation,
312
+ });
313
+ expect(result.observation).toMatchObject({
314
+ indexedLegCount: 301,
315
+ continuation: { state: "complete", validatedLegs: 301 },
316
+ });
317
+ const rows = await t.run((ctx) =>
318
+ ctx.db
319
+ .query("financialSourceLegs")
320
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
321
+ q.eq("allocationId", row._id),
322
+ )
323
+ .take(302),
324
+ );
325
+ expect(rows).toHaveLength(301);
326
+ expect(
327
+ rows.map((r) => [r.legIndex, r.bucketKey, r.role, r.ownershipStatus]),
328
+ ).toEqual(
329
+ args.transfers.map((leg, i) => [
330
+ i,
331
+ leg.destinationAccountId,
332
+ leg.role,
333
+ "unknown",
334
+ ]),
335
+ );
336
+ });
337
+ it("refuses invalid generation selectors, missing markers and ambiguous marker identity without writes", async () => {
338
+ const t = convexTest(schema, modules);
339
+ const row = await t.mutation(reserve, allocation());
340
+ await expect(
341
+ t.mutation(resume, { allocationId: row._id, expectedGeneration: 0.5 }),
342
+ ).rejects.toThrow("generation");
343
+ expect(
344
+ (await t.mutation(resume, { allocationId: row._id, expectedGeneration: 2 }))
345
+ .observation.indexedLegCount,
346
+ ).toBe(0);
347
+ await t.run(async (ctx) => {
348
+ const marker = await ctx.db.query("financialSourceObservations").unique();
349
+ const { _id, _creationTime, ...fields } = marker!;
350
+ void _id;
351
+ void _creationTime;
352
+ await ctx.db.insert("financialSourceObservations", fields);
353
+ });
354
+ expect(
355
+ await t.mutation(resume, { allocationId: row._id, expectedGeneration: 1 }),
356
+ ).toEqual({ coverage: "unknown", observation: null });
357
+ expect(
358
+ await t.run((ctx) => ctx.db.query("financialSourceLegs").take(1)),
359
+ ).toEqual([]);
360
+ });
361
+ it("does not retain a completed traversal after contradictory original source content changes", async () => {
362
+ const t = convexTest(schema, modules);
363
+ const row = await t.mutation(reserve, allocation(101));
364
+ let result = await t.query(source, { allocationId: row._id });
365
+ for (let i = 0; i < 4; i++)
366
+ result = await t.mutation(resume, {
367
+ allocationId: row._id,
368
+ expectedGeneration: result.observation.generation,
369
+ });
370
+ expect(result.observation.continuation.state).toBe("complete");
371
+ await t.run((ctx) =>
372
+ ctx.db.patch("settlementAllocations", row._id, { currency: "eur" }),
373
+ );
374
+ result = await t.mutation(resume, {
375
+ allocationId: row._id,
376
+ expectedGeneration: result.observation.generation,
377
+ });
378
+ expect(result.observation).toMatchObject({
379
+ isContradictory: true,
380
+ continuation: { state: "held" },
381
+ });
382
+ });
383
+ it("reservation replay holds completed contradictory traversal without truncating indexed progress", async () => {
384
+ const t = convexTest(schema, modules);
385
+ const row = await t.mutation(reserve, allocation(251));
386
+ let result = await t.query(source, { allocationId: row._id });
387
+ for (let i = 0; i < 6; i++)
388
+ result = await t.mutation(resume, {
389
+ allocationId: row._id,
390
+ expectedGeneration: result.observation.generation,
391
+ });
392
+ await t.run((ctx) =>
393
+ ctx.db.patch("settlementAllocations", row._id, { gross: 999 }),
394
+ );
395
+ await t.mutation(reserve, allocation(251));
396
+ result = await t.query(source, { allocationId: row._id });
397
+ expect(result.observation).toMatchObject({
398
+ indexedLegCount: 251,
399
+ isContradictory: true,
400
+ continuation: { state: "held", nextLeg: 251 },
401
+ });
402
+ });
403
+ it.each([
404
+ { state: "complete" as const, nextLeg: 100, validatedLegs: 0 },
405
+ { state: "complete" as const, nextLeg: 100, validatedLegs: 100 },
406
+ { state: "indexing" as const, nextLeg: 100, validatedLegs: 1 },
407
+ { state: "validating" as const, nextLeg: 100, validatedLegs: 0 },
408
+ ])(
409
+ "holds impossible $state cursor/count combinations",
410
+ async (continuation) => {
411
+ const t = convexTest(schema, modules);
412
+ const row = await t.mutation(reserve, allocation());
413
+ const first = await t.mutation(resume, {
414
+ allocationId: row._id,
415
+ expectedGeneration: 1,
416
+ });
417
+ await t.run((ctx) =>
418
+ ctx.db.patch("financialSourceObservations", first.observation._id, {
419
+ continuation,
420
+ }),
421
+ );
422
+ const result = await t.mutation(resume, {
423
+ allocationId: row._id,
424
+ expectedGeneration: first.observation.generation,
425
+ });
426
+ expect(result.observation).toMatchObject({
427
+ isContradictory: true,
428
+ continuation: { state: "held" },
429
+ });
430
+ },
431
+ );
432
+ it("does not expose caller-controlled cursor or completion state through the public resume validator", async () => {
433
+ const t = convexTest(schema, modules);
434
+ const row = await t.mutation(reserve, allocation());
435
+ await expect(
436
+ t.mutation(resume, {
437
+ allocationId: row._id,
438
+ expectedGeneration: 1,
439
+ continuation: { state: "complete", nextLeg: 251, validatedLegs: 251 },
440
+ }),
441
+ ).rejects.toThrow();
442
+ expect(
443
+ (await t.query(source, { allocationId: row._id })).observation,
444
+ ).toMatchObject({ generation: 1, indexedLegCount: 0 });
445
+ });