@fantastic.dev/better-stripe 0.34.0 → 0.37.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 (308) hide show
  1. package/CHANGELOG.md +260 -0
  2. package/README.md +1 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +664 -2
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +332 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +664 -2
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +332 -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/operationEvidence.d.ts +37 -0
  36. package/dist/client/operationEvidence.d.ts.map +1 -0
  37. package/dist/client/operationEvidence.js +44 -0
  38. package/dist/client/operationEvidence.js.map +1 -0
  39. package/dist/client/publicTypes.d.ts +6 -0
  40. package/dist/client/publicTypes.d.ts.map +1 -1
  41. package/dist/client/readContracts.d.ts +31 -0
  42. package/dist/client/readContracts.d.ts.map +1 -1
  43. package/dist/client/readContracts.js +14 -0
  44. package/dist/client/readContracts.js.map +1 -1
  45. package/dist/client/transferObservations.d.ts +59 -0
  46. package/dist/client/transferObservations.d.ts.map +1 -0
  47. package/dist/client/transferObservations.js +82 -0
  48. package/dist/client/transferObservations.js.map +1 -0
  49. package/dist/component/_generated/component.d.ts +687 -0
  50. package/dist/component/_generated/component.d.ts.map +1 -1
  51. package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -1
  52. package/dist/component/affiliateRecovery/mutations.js +4 -1
  53. package/dist/component/affiliateRecovery/mutations.js.map +1 -1
  54. package/dist/component/connect/mutations.d.ts.map +1 -1
  55. package/dist/component/connect/mutations.js +18 -2
  56. package/dist/component/connect/mutations.js.map +1 -1
  57. package/dist/component/connect/queries.d.ts +8 -0
  58. package/dist/component/connect/queries.d.ts.map +1 -1
  59. package/dist/component/connect/reversalClaims.d.ts.map +1 -1
  60. package/dist/component/connect/reversalClaims.js +7 -1
  61. package/dist/component/connect/reversalClaims.js.map +1 -1
  62. package/dist/component/connect/reversalReceipts.d.ts.map +1 -1
  63. package/dist/component/connect/reversalReceipts.js +2 -0
  64. package/dist/component/connect/reversalReceipts.js.map +1 -1
  65. package/dist/component/connect/schema.d.ts +11 -1
  66. package/dist/component/connect/schema.d.ts.map +1 -1
  67. package/dist/component/connect/schema.js +9 -1
  68. package/dist/component/connect/schema.js.map +1 -1
  69. package/dist/component/connect/validators.d.ts +9 -1
  70. package/dist/component/connect/validators.d.ts.map +1 -1
  71. package/dist/component/connect/validators.js +2 -0
  72. package/dist/component/connect/validators.js.map +1 -1
  73. package/dist/component/earnings/pairedAdjustment.d.ts +12 -0
  74. package/dist/component/earnings/pairedAdjustment.d.ts.map +1 -0
  75. package/dist/component/earnings/pairedAdjustment.js +46 -0
  76. package/dist/component/earnings/pairedAdjustment.js.map +1 -0
  77. package/dist/component/earnings/triggers.d.ts +546 -2
  78. package/dist/component/earnings/triggers.d.ts.map +1 -1
  79. package/dist/component/earnings/triggers.js +17 -3
  80. package/dist/component/earnings/triggers.js.map +1 -1
  81. package/dist/component/financialObservations/continuation.d.ts +7 -0
  82. package/dist/component/financialObservations/continuation.d.ts.map +1 -0
  83. package/dist/component/financialObservations/continuation.js +131 -0
  84. package/dist/component/financialObservations/continuation.js.map +1 -0
  85. package/dist/component/financialObservations/generations.d.ts +6 -0
  86. package/dist/component/financialObservations/generations.d.ts.map +1 -0
  87. package/dist/component/financialObservations/generations.js +46 -0
  88. package/dist/component/financialObservations/generations.js.map +1 -0
  89. package/dist/component/financialObservations/mutations.d.ts +62 -0
  90. package/dist/component/financialObservations/mutations.d.ts.map +1 -0
  91. package/dist/component/financialObservations/mutations.js +69 -0
  92. package/dist/component/financialObservations/mutations.js.map +1 -0
  93. package/dist/component/financialObservations/queries.d.ts +307 -0
  94. package/dist/component/financialObservations/queries.d.ts.map +1 -0
  95. package/dist/component/financialObservations/queries.js +219 -0
  96. package/dist/component/financialObservations/queries.js.map +1 -0
  97. package/dist/component/financialObservations/schema.d.ts +182 -0
  98. package/dist/component/financialObservations/schema.d.ts.map +1 -0
  99. package/dist/component/financialObservations/schema.js +53 -0
  100. package/dist/component/financialObservations/schema.js.map +1 -0
  101. package/dist/component/financialObservations/settlement.d.ts +7 -0
  102. package/dist/component/financialObservations/settlement.d.ts.map +1 -0
  103. package/dist/component/financialObservations/settlement.js +118 -0
  104. package/dist/component/financialObservations/settlement.js.map +1 -0
  105. package/dist/component/financialObservations/settlementHelpers.d.ts +46 -0
  106. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -0
  107. package/dist/component/financialObservations/settlementHelpers.js +70 -0
  108. package/dist/component/financialObservations/settlementHelpers.js.map +1 -0
  109. package/dist/component/financialObservations/transferBatches.d.ts +12 -0
  110. package/dist/component/financialObservations/transferBatches.d.ts.map +1 -0
  111. package/dist/component/financialObservations/transferBatches.js +76 -0
  112. package/dist/component/financialObservations/transferBatches.js.map +1 -0
  113. package/dist/component/financialObservations/transferContinuation.d.ts +5 -0
  114. package/dist/component/financialObservations/transferContinuation.d.ts.map +1 -0
  115. package/dist/component/financialObservations/transferContinuation.js +35 -0
  116. package/dist/component/financialObservations/transferContinuation.js.map +1 -0
  117. package/dist/component/financialObservations/transferContinuationState.d.ts +8 -0
  118. package/dist/component/financialObservations/transferContinuationState.d.ts.map +1 -0
  119. package/dist/component/financialObservations/transferContinuationState.js +69 -0
  120. package/dist/component/financialObservations/transferContinuationState.js.map +1 -0
  121. package/dist/component/financialObservations/transferContinuationSteps.d.ts +5 -0
  122. package/dist/component/financialObservations/transferContinuationSteps.d.ts.map +1 -0
  123. package/dist/component/financialObservations/transferContinuationSteps.js +174 -0
  124. package/dist/component/financialObservations/transferContinuationSteps.js.map +1 -0
  125. package/dist/component/financialObservations/transferHelpers.d.ts +18 -0
  126. package/dist/component/financialObservations/transferHelpers.d.ts.map +1 -0
  127. package/dist/component/financialObservations/transferHelpers.js +37 -0
  128. package/dist/component/financialObservations/transferHelpers.js.map +1 -0
  129. package/dist/component/financialObservations/transferReferenceSchema.d.ts +56 -0
  130. package/dist/component/financialObservations/transferReferenceSchema.d.ts.map +1 -0
  131. package/dist/component/financialObservations/transferReferenceSchema.js +21 -0
  132. package/dist/component/financialObservations/transferReferenceSchema.js.map +1 -0
  133. package/dist/component/financialObservations/transferSchema.d.ts +237 -0
  134. package/dist/component/financialObservations/transferSchema.d.ts.map +1 -0
  135. package/dist/component/financialObservations/transferSchema.js +65 -0
  136. package/dist/component/financialObservations/transferSchema.js.map +1 -0
  137. package/dist/component/financialObservations/transfers.d.ts +7 -0
  138. package/dist/component/financialObservations/transfers.d.ts.map +1 -0
  139. package/dist/component/financialObservations/transfers.js +79 -0
  140. package/dist/component/financialObservations/transfers.js.map +1 -0
  141. package/dist/component/financialOwnership/helpers.d.ts +37 -0
  142. package/dist/component/financialOwnership/helpers.d.ts.map +1 -0
  143. package/dist/component/financialOwnership/helpers.js +76 -0
  144. package/dist/component/financialOwnership/helpers.js.map +1 -0
  145. package/dist/component/financialOwnership/mutations.d.ts +28 -0
  146. package/dist/component/financialOwnership/mutations.d.ts.map +1 -0
  147. package/dist/component/financialOwnership/mutations.js +74 -0
  148. package/dist/component/financialOwnership/mutations.js.map +1 -0
  149. package/dist/component/financialOwnership/queries.d.ts +57 -0
  150. package/dist/component/financialOwnership/queries.d.ts.map +1 -0
  151. package/dist/component/financialOwnership/queries.js +50 -0
  152. package/dist/component/financialOwnership/queries.js.map +1 -0
  153. package/dist/component/financialOwnership/schema.d.ts +140 -0
  154. package/dist/component/financialOwnership/schema.d.ts.map +1 -0
  155. package/dist/component/financialOwnership/schema.js +35 -0
  156. package/dist/component/financialOwnership/schema.js.map +1 -0
  157. package/dist/component/operationEvidence/canonical.d.ts +4 -0
  158. package/dist/component/operationEvidence/canonical.d.ts.map +1 -0
  159. package/dist/component/operationEvidence/canonical.js +8 -0
  160. package/dist/component/operationEvidence/canonical.js.map +1 -0
  161. package/dist/component/operationEvidence/helpers.d.ts +87 -0
  162. package/dist/component/operationEvidence/helpers.d.ts.map +1 -0
  163. package/dist/component/operationEvidence/helpers.js +49 -0
  164. package/dist/component/operationEvidence/helpers.js.map +1 -0
  165. package/dist/component/operationEvidence/maintenance.d.ts +88 -0
  166. package/dist/component/operationEvidence/maintenance.d.ts.map +1 -0
  167. package/dist/component/operationEvidence/maintenance.js +59 -0
  168. package/dist/component/operationEvidence/maintenance.js.map +1 -0
  169. package/dist/component/operationEvidence/mutations.d.ts +97 -0
  170. package/dist/component/operationEvidence/mutations.d.ts.map +1 -0
  171. package/dist/component/operationEvidence/mutations.js +14 -0
  172. package/dist/component/operationEvidence/mutations.js.map +1 -0
  173. package/dist/component/operationEvidence/queries.d.ts +205 -0
  174. package/dist/component/operationEvidence/queries.d.ts.map +1 -0
  175. package/dist/component/operationEvidence/queries.js +75 -0
  176. package/dist/component/operationEvidence/queries.js.map +1 -0
  177. package/dist/component/operationEvidence/schema.d.ts +536 -0
  178. package/dist/component/operationEvidence/schema.d.ts.map +1 -0
  179. package/dist/component/operationEvidence/schema.js +53 -0
  180. package/dist/component/operationEvidence/schema.js.map +1 -0
  181. package/dist/component/refundHistory/commandBinding.d.ts +17 -0
  182. package/dist/component/refundHistory/commandBinding.d.ts.map +1 -0
  183. package/dist/component/refundHistory/commandBinding.js +41 -0
  184. package/dist/component/refundHistory/commandBinding.js.map +1 -0
  185. package/dist/component/refundHistory/commandEvidence.d.ts +50 -0
  186. package/dist/component/refundHistory/commandEvidence.d.ts.map +1 -0
  187. package/dist/component/refundHistory/commandEvidence.js +58 -0
  188. package/dist/component/refundHistory/commandEvidence.js.map +1 -0
  189. package/dist/component/refundHistory/commandEvidenceValidator.d.ts +89 -0
  190. package/dist/component/refundHistory/commandEvidenceValidator.d.ts.map +1 -0
  191. package/dist/component/refundHistory/commandEvidenceValidator.js +8 -0
  192. package/dist/component/refundHistory/commandEvidenceValidator.js.map +1 -0
  193. package/dist/component/refundHistory/commandFields.d.ts +8 -0
  194. package/dist/component/refundHistory/commandFields.d.ts.map +1 -0
  195. package/dist/component/refundHistory/commandFields.js +9 -0
  196. package/dist/component/refundHistory/commandFields.js.map +1 -0
  197. package/dist/component/refundHistory/mutations.d.ts +8 -0
  198. package/dist/component/refundHistory/mutations.d.ts.map +1 -0
  199. package/dist/component/refundHistory/mutations.js +25 -0
  200. package/dist/component/refundHistory/mutations.js.map +1 -0
  201. package/dist/component/refundHistory/originalSeller.d.ts +5 -0
  202. package/dist/component/refundHistory/originalSeller.d.ts.map +1 -0
  203. package/dist/component/refundHistory/originalSeller.js +35 -0
  204. package/dist/component/refundHistory/originalSeller.js.map +1 -0
  205. package/dist/component/refundHistory/queries.d.ts +51 -0
  206. package/dist/component/refundHistory/queries.d.ts.map +1 -1
  207. package/dist/component/refundHistory/queries.js +14 -0
  208. package/dist/component/refundHistory/queries.js.map +1 -1
  209. package/dist/component/schema.d.ts +332 -1
  210. package/dist/component/schema.js +15 -0
  211. package/dist/component/schema.js.map +1 -1
  212. package/dist/component/settlement/mutations.d.ts.map +1 -1
  213. package/dist/component/settlement/mutations.js +5 -1
  214. package/dist/component/settlement/mutations.js.map +1 -1
  215. package/dist/shared/refundCommandScope.d.ts +10 -0
  216. package/dist/shared/refundCommandScope.d.ts.map +1 -0
  217. package/dist/shared/refundCommandScope.js +9 -0
  218. package/dist/shared/refundCommandScope.js.map +1 -0
  219. package/docs/financial-observations.md +244 -0
  220. package/docs/financial-ownership.md +54 -0
  221. package/docs/refund-command-evidence.md +55 -0
  222. package/package.json +5 -2
  223. package/src/client/connect/refundCommandEvidence.ts +41 -0
  224. package/src/client/connect/refundCommandNormalization.ts +28 -0
  225. package/src/client/financialObservations.test.ts +109 -0
  226. package/src/client/financialObservations.ts +106 -0
  227. package/src/client/financialOwnership.test.ts +80 -0
  228. package/src/client/financialOwnership.ts +116 -0
  229. package/src/client/index.ts +2 -2
  230. package/src/client/observationPagination.ts +11 -0
  231. package/src/client/operationEvidence.test.ts +110 -0
  232. package/src/client/operationEvidence.ts +92 -0
  233. package/src/client/publicTypes.ts +45 -0
  234. package/src/client/readContracts.ts +25 -0
  235. package/src/client/refund-command-evidence.test.ts +68 -0
  236. package/src/client/refund-command-normalization.test.ts +61 -0
  237. package/src/client/transferContinuation.test.ts +94 -0
  238. package/src/client/transferObservations.test.ts +98 -0
  239. package/src/client/transferObservations.ts +180 -0
  240. package/src/component/_generated/api.ts +54 -0
  241. package/src/component/_generated/component.ts +797 -0
  242. package/src/component/affiliateRecovery/mutations.ts +10 -1
  243. package/src/component/connect/mutations.ts +29 -2
  244. package/src/component/connect/reversalClaims.ts +19 -1
  245. package/src/component/connect/reversalReceipts.ts +2 -0
  246. package/src/component/connect/schema.ts +9 -1
  247. package/src/component/connect/validators.ts +2 -0
  248. package/src/component/core/reset.test.ts +8 -1
  249. package/src/component/earnings/earnings-totals.test.ts +14 -10
  250. package/src/component/earnings/paired-adjustment.test.ts +258 -0
  251. package/src/component/earnings/pairedAdjustment.ts +77 -0
  252. package/src/component/earnings/triggers.ts +23 -11
  253. package/src/component/financialObservations/continuation.test.ts +445 -0
  254. package/src/component/financialObservations/continuation.ts +159 -0
  255. package/src/component/financialObservations/generations.ts +53 -0
  256. package/src/component/financialObservations/mutations.ts +75 -0
  257. package/src/component/financialObservations/observation-boundaries.test.ts +466 -0
  258. package/src/component/financialObservations/queries.ts +246 -0
  259. package/src/component/financialObservations/schema.ts +68 -0
  260. package/src/component/financialObservations/settlement-observations.test.ts +86 -0
  261. package/src/component/financialObservations/settlement.ts +142 -0
  262. package/src/component/financialObservations/settlementHelpers.ts +92 -0
  263. package/src/component/financialObservations/transfer-batches.test.ts +61 -0
  264. package/src/component/financialObservations/transfer-boundaries.test.ts +116 -0
  265. package/src/component/financialObservations/transfer-continuation-guards.test.ts +428 -0
  266. package/src/component/financialObservations/transfer-continuation.test.ts +154 -0
  267. package/src/component/financialObservations/transfer-observations.test.ts +212 -0
  268. package/src/component/financialObservations/transfer-overflow.test.ts +181 -0
  269. package/src/component/financialObservations/transfer-writers.test.ts +162 -0
  270. package/src/component/financialObservations/transferBatches.ts +96 -0
  271. package/src/component/financialObservations/transferContinuation.ts +53 -0
  272. package/src/component/financialObservations/transferContinuationState.ts +85 -0
  273. package/src/component/financialObservations/transferContinuationSteps.ts +232 -0
  274. package/src/component/financialObservations/transferHelpers.ts +38 -0
  275. package/src/component/financialObservations/transferReferenceSchema.ts +20 -0
  276. package/src/component/financialObservations/transferSchema.ts +74 -0
  277. package/src/component/financialObservations/transfers.ts +99 -0
  278. package/src/component/financialOwnership/financial-ownership.test.ts +102 -0
  279. package/src/component/financialOwnership/helpers.ts +98 -0
  280. package/src/component/financialOwnership/mutations.ts +83 -0
  281. package/src/component/financialOwnership/ownership-boundaries.test.ts +308 -0
  282. package/src/component/financialOwnership/queries.ts +65 -0
  283. package/src/component/financialOwnership/schema.ts +35 -0
  284. package/src/component/operationEvidence/canonical.ts +10 -0
  285. package/src/component/operationEvidence/helpers.ts +65 -0
  286. package/src/component/operationEvidence/integrity.test.ts +257 -0
  287. package/src/component/operationEvidence/maintenance.test.ts +152 -0
  288. package/src/component/operationEvidence/maintenance.ts +89 -0
  289. package/src/component/operationEvidence/mutations.ts +14 -0
  290. package/src/component/operationEvidence/queries.ts +108 -0
  291. package/src/component/operationEvidence/reads.test.ts +140 -0
  292. package/src/component/operationEvidence/schema.ts +62 -0
  293. package/src/component/refundHistory/command-evidence.test.ts +288 -0
  294. package/src/component/refundHistory/command-normalization-resource.test.ts +77 -0
  295. package/src/component/refundHistory/command-normalization.test.ts +229 -0
  296. package/src/component/refundHistory/command-provenance.test.ts +59 -0
  297. package/src/component/refundHistory/commandBinding.ts +54 -0
  298. package/src/component/refundHistory/commandEvidence.ts +76 -0
  299. package/src/component/refundHistory/commandEvidenceValidator.ts +18 -0
  300. package/src/component/refundHistory/commandFields.ts +9 -0
  301. package/src/component/refundHistory/mutations.ts +33 -0
  302. package/src/component/refundHistory/original-seller-boundaries.test.ts +138 -0
  303. package/src/component/refundHistory/original-seller.test.ts +175 -0
  304. package/src/component/refundHistory/originalSeller.ts +48 -0
  305. package/src/component/refundHistory/queries.ts +15 -0
  306. package/src/component/schema.ts +28 -0
  307. package/src/component/settlement/mutations.ts +5 -1
  308. package/src/shared/refundCommandScope.ts +19 -0
@@ -1,3 +1,4 @@
1
+ import { observeTransfer } from "../financialObservations/transfers.js";
1
2
  import { commissionExposureValidator } from "../settlement/clawbackSchema.js";
2
3
  import { applyObligationExposure } from "../settlement/clawbacks.js";
3
4
  import { v } from "convex/values";
@@ -169,6 +170,10 @@ export const completeOperation = mutation({
169
170
  transfer.status,
170
171
  ),
171
172
  );
173
+ await observeTransfer(
174
+ ctx,
175
+ (await ctx.db.get("transfers", transfer._id))!,
176
+ );
172
177
  const duplicate = await ctx.db
173
178
  .query("affiliateReversalReceipts")
174
179
  .withIndex("by_receipt", (q) =>
@@ -187,7 +192,7 @@ export const completeOperation = mutation({
187
192
  });
188
193
  await updateObligation(ctx, row, { ...patch, recoveredAmount: total });
189
194
  } else {
190
- await ctx.db.insert("transfers", {
195
+ const transferId = await ctx.db.insert("transfers", {
191
196
  stripeTransferId: args.receiptId!,
192
197
  sourceChargeId: row.sourceChargeId,
193
198
  sourceInvoiceId: row.sourceInvoiceId,
@@ -199,6 +204,10 @@ export const completeOperation = mutation({
199
204
  reinstatement: true,
200
205
  metadata: { bsRecoveryOperation: op._id },
201
206
  });
207
+ await observeTransfer(
208
+ ctx,
209
+ (await ctx.db.get("transfers", transferId))!,
210
+ );
202
211
  await updateObligation(ctx, row, {
203
212
  ...patch,
204
213
  restoredAmount: (row.restoredAmount ?? 0) + op.amount,
@@ -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",
@@ -0,0 +1,258 @@
1
+ import { convexTest } from "convex-test";
2
+ import { expect, it, vi } from "vitest";
3
+ import { modules, schema } from "../../test.js";
4
+ import { api } from "../_generated/api.js";
5
+ import { replaceContribution } from "./pairedAdjustment.js";
6
+
7
+ const previous = {
8
+ accountId: "acct_pair",
9
+ currency: "usd",
10
+ gross: 5,
11
+ reversed: 1,
12
+ paidOut: 0,
13
+ count: 1,
14
+ };
15
+
16
+ it("validates subtract/reapply using one exact summary lookup", async () => {
17
+ const t = convexTest(schema, modules);
18
+ await t.run(async (ctx) => {
19
+ const id = await ctx.db.insert("currencyTotals", {
20
+ accountId: previous.accountId,
21
+ currency: previous.currency,
22
+ kind: "earnings",
23
+ gross: 12,
24
+ reversed: 2,
25
+ paidOut: 0,
26
+ count: 2,
27
+ });
28
+ const read = vi.spyOn(ctx.db, "query");
29
+ await replaceContribution(ctx, previous, { ...previous, reversed: 3 });
30
+ expect(read).toHaveBeenCalledTimes(1);
31
+ expect(await ctx.db.get("currencyTotals", id)).toMatchObject({
32
+ gross: 12,
33
+ reversed: 4,
34
+ count: 2,
35
+ });
36
+ });
37
+ });
38
+
39
+ it("preserves zero-count discard/reset and missing-summary subtraction semantics", async () => {
40
+ const t = convexTest(schema, modules);
41
+ await t.run(async (ctx) => {
42
+ await ctx.db.insert("currencyTotals", {
43
+ accountId: previous.accountId,
44
+ currency: previous.currency,
45
+ kind: "earnings",
46
+ gross: 10,
47
+ reversed: 1,
48
+ paidOut: 0,
49
+ count: 1,
50
+ });
51
+ await replaceContribution(ctx, previous, previous);
52
+ expect(await ctx.db.query("currencyTotals").unique()).toMatchObject({
53
+ gross: 5,
54
+ reversed: 1,
55
+ count: 1,
56
+ });
57
+ });
58
+ const empty = convexTest(schema, modules);
59
+ await empty.run((ctx) => replaceContribution(ctx, previous, previous));
60
+ expect(
61
+ await empty.run((ctx) => ctx.db.query("currencyTotals").take(1)),
62
+ ).toEqual([]);
63
+ });
64
+
65
+ it.each([
66
+ { gross: Number.MAX_SAFE_INTEGER, reversed: -5, count: 1 },
67
+ { gross: Number.NaN, reversed: 0, count: 1 },
68
+ { gross: 5, reversed: 0, count: Number.POSITIVE_INFINITY },
69
+ ])(
70
+ "does not bypass unsafe stored/intermediate totals on matching replay: %j",
71
+ async (totals) => {
72
+ const t = convexTest(schema, modules);
73
+ await t.run((ctx) =>
74
+ ctx.db.insert("currencyTotals", {
75
+ accountId: previous.accountId,
76
+ currency: previous.currency,
77
+ kind: "earnings",
78
+ paidOut: 0,
79
+ ...totals,
80
+ }),
81
+ );
82
+ const before = await t.run((ctx) =>
83
+ ctx.db.query("currencyTotals").unique(),
84
+ );
85
+ await expect(
86
+ t.run((ctx) => replaceContribution(ctx, previous, previous)),
87
+ ).rejects.toThrow(/safe integer/i);
88
+ expect(
89
+ await t.run((ctx) => ctx.db.query("currencyTotals").unique()),
90
+ ).toEqual(before);
91
+ },
92
+ );
93
+
94
+ it("skips only final unchanged nonzero persistence after validated reset/reapply", async () => {
95
+ const t = convexTest(schema, modules);
96
+ await t.run(async (ctx) => {
97
+ const id = await ctx.db.insert("currencyTotals", {
98
+ accountId: previous.accountId,
99
+ currency: previous.currency,
100
+ kind: "earnings",
101
+ gross: 5,
102
+ reversed: 1,
103
+ paidOut: 0,
104
+ count: 1,
105
+ });
106
+ const write = vi.spyOn(ctx.db, "patch");
107
+ await replaceContribution(ctx, previous, previous);
108
+ expect(write).not.toHaveBeenCalled();
109
+ expect(await ctx.db.get("currencyTotals", id)).not.toBeNull();
110
+ });
111
+ });
112
+
113
+ it("still deletes an unchanged numeric zero-count stored summary", async () => {
114
+ const t = convexTest(schema, modules);
115
+ await t.run(async (ctx) => {
116
+ const id = await ctx.db.insert("currencyTotals", {
117
+ accountId: previous.accountId,
118
+ currency: previous.currency,
119
+ kind: "earnings",
120
+ gross: 5,
121
+ reversed: 1,
122
+ paidOut: 0,
123
+ count: 0,
124
+ });
125
+ await replaceContribution(ctx, previous, previous);
126
+ expect(await ctx.db.get("currencyTotals", id)).toBeNull();
127
+ });
128
+ });
129
+
130
+ it.each(["subtract", "reapply"] as const)(
131
+ "checks unsafe %s arithmetic before unchanged-persistence decisions",
132
+ async (phase) => {
133
+ const t = convexTest(schema, modules);
134
+ await t.run((ctx) =>
135
+ ctx.db.insert("currencyTotals", {
136
+ accountId: previous.accountId,
137
+ currency: previous.currency,
138
+ kind: "earnings",
139
+ gross: Number.MAX_SAFE_INTEGER,
140
+ reversed: 0,
141
+ paidOut: 0,
142
+ count: 2,
143
+ }),
144
+ );
145
+ const old =
146
+ phase === "subtract"
147
+ ? { ...previous, gross: -1, reversed: 0 }
148
+ : { ...previous, reversed: 0 };
149
+ const next = phase === "subtract" ? old : { ...old, gross: 6 };
150
+ const before = await t.run((ctx) =>
151
+ ctx.db.query("currencyTotals").unique(),
152
+ );
153
+ await expect(
154
+ t.run((ctx) => replaceContribution(ctx, old, next)),
155
+ ).rejects.toThrow(/safe integer/i);
156
+ expect(
157
+ await t.run((ctx) => ctx.db.query("currencyTotals").unique()),
158
+ ).toEqual(before);
159
+ },
160
+ );
161
+
162
+ it("rejects duplicate or foreign currency summaries without repinning", async () => {
163
+ const t = convexTest(schema, modules);
164
+ await t.run(async (ctx) => {
165
+ for (let i = 0; i < 2; i++)
166
+ await ctx.db.insert("currencyTotals", {
167
+ accountId: previous.accountId,
168
+ currency: previous.currency,
169
+ kind: "earnings",
170
+ gross: 5,
171
+ reversed: 1,
172
+ paidOut: 0,
173
+ count: 1,
174
+ });
175
+ });
176
+ await expect(
177
+ t.run((ctx) => replaceContribution(ctx, previous, previous)),
178
+ ).rejects.toThrow();
179
+ await expect(
180
+ t.run((ctx) =>
181
+ replaceContribution(ctx, previous, { ...previous, currency: "eur" }),
182
+ ),
183
+ ).rejects.toThrow(/same currency bucket/);
184
+ });
185
+
186
+ it("registered frontier rollback preserves malformed summary, source and both revision fences", async () => {
187
+ const t = convexTest(schema, modules);
188
+ await t.mutation(api.connect.mutations.upsertTransfer, {
189
+ stripeTransferId: "tr_paired_rollback",
190
+ sourceChargeId: "ch_paired_rollback",
191
+ destinationAccountId: "acct_pair",
192
+ amount: 5,
193
+ currency: "usd",
194
+ status: "paid",
195
+ });
196
+ await t.run(async (ctx) => {
197
+ const total = (await ctx.db.query("currencyTotals").unique())!;
198
+ await ctx.db.patch("currencyTotals", total._id, { paidOut: Number.NaN });
199
+ });
200
+ const snapshot = () =>
201
+ t.run(async (ctx) => ({
202
+ source: await ctx.db.query("transfers").take(5),
203
+ totals: await ctx.db.query("currencyTotals").take(5),
204
+ financial: await ctx.db.query("payoutFinancialRevisions").take(5),
205
+ risk: await ctx.db.query("payoutRiskRevisions").take(5),
206
+ events: await ctx.db.query("payoutRiskEvents").take(5),
207
+ operations: await ctx.db.query("transferReversalOps").take(5),
208
+ }));
209
+ const before = await snapshot();
210
+ await expect(
211
+ t.mutation(api.connect.mutations.claimReversalSlices, {
212
+ operationId: "op_paired_rollback",
213
+ sourceChargeId: "ch_paired_rollback",
214
+ mode: { kind: "full" },
215
+ }),
216
+ ).rejects.toThrow(/safe integer/i);
217
+ expect(await snapshot()).toEqual(before);
218
+ });
219
+
220
+ it("retains moved currency buckets and unrecorded legacy contributions", async () => {
221
+ const t = convexTest(schema, modules);
222
+ const value = {
223
+ stripeTransferId: "tr_paired_move",
224
+ destinationAccountId: "acct_pair",
225
+ amount: 5,
226
+ currency: "usd",
227
+ status: "paid" as const,
228
+ };
229
+ await t.mutation(api.connect.mutations.upsertTransfer, value);
230
+ await t.mutation(api.connect.mutations.upsertTransfer, {
231
+ ...value,
232
+ destinationAccountId: "acct_other",
233
+ currency: "eur",
234
+ });
235
+ expect(
236
+ await t.query(api.connect.queries.getAccountEarningsByCurrency, {
237
+ destinationAccountId: "acct_pair",
238
+ previewLimit: 0,
239
+ }),
240
+ ).toMatchObject({ totals: [] });
241
+ expect(
242
+ await t.query(api.connect.queries.getAccountEarningsByCurrency, {
243
+ destinationAccountId: "acct_other",
244
+ previewLimit: 0,
245
+ }),
246
+ ).toMatchObject({
247
+ totals: [{ currency: "eur", gross: 5, transferCount: 1 }],
248
+ });
249
+ const legacy = { ...value, stripeTransferId: "tr_paired_legacy" };
250
+ await t.run((ctx) => ctx.db.insert("transfers", legacy));
251
+ await t.mutation(api.connect.mutations.upsertTransfer, legacy);
252
+ expect(
253
+ await t.query(api.connect.queries.getAccountEarningsByCurrency, {
254
+ destinationAccountId: "acct_pair",
255
+ previewLimit: 0,
256
+ }),
257
+ ).toMatchObject({ totals: [{ gross: 5, transferCount: 1 }] });
258
+ });
@@ -0,0 +1,77 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import { addSummaryAmounts } from "./arithmetic.js";
3
+
4
+ export type Contribution = {
5
+ accountId: string;
6
+ currency: string;
7
+ gross: number;
8
+ reversed: number;
9
+ paidOut: number;
10
+ count: number;
11
+ };
12
+ function apply(
13
+ row: {
14
+ gross: number;
15
+ reversed: number;
16
+ paidOut: number;
17
+ count: number;
18
+ } | null,
19
+ contribution: Contribution,
20
+ sign: 1 | -1,
21
+ ) {
22
+ const totals = {
23
+ gross: addSummaryAmounts(row?.gross ?? 0, sign * contribution.gross),
24
+ reversed: addSummaryAmounts(
25
+ row?.reversed ?? 0,
26
+ sign * contribution.reversed,
27
+ ),
28
+ paidOut: addSummaryAmounts(row?.paidOut ?? 0, sign * contribution.paidOut),
29
+ count: addSummaryAmounts(row?.count ?? 0, sign * contribution.count),
30
+ };
31
+ addSummaryAmounts(totals.gross, -totals.reversed);
32
+ return totals;
33
+ }
34
+ /** Same bucket only: preserve subtract/reset/reapply validation with one read. */
35
+ export async function replaceContribution(
36
+ ctx: MutationCtx,
37
+ previous: Contribution,
38
+ next: Contribution,
39
+ ) {
40
+ if (
41
+ previous.accountId !== next.accountId ||
42
+ previous.currency !== next.currency
43
+ )
44
+ throw new Error("Paired contributions require the same currency bucket");
45
+ const row = await ctx.db
46
+ .query("currencyTotals")
47
+ .withIndex("by_account_kind_currency", (q) =>
48
+ q
49
+ .eq("accountId", previous.accountId)
50
+ .eq("kind", "earnings")
51
+ .eq("currency", previous.currency),
52
+ )
53
+ .unique();
54
+ const removed = apply(row, previous, -1);
55
+ // The existing subtract path deletes a zero-count stored row before reapply.
56
+ const hasIntermediateRow = !row || removed.count !== 0;
57
+ const totals = apply(hasIntermediateRow ? removed : null, next, 1);
58
+ if (hasIntermediateRow && totals.count === 0) {
59
+ if (row) await ctx.db.delete("currencyTotals", row._id);
60
+ return;
61
+ }
62
+ if (
63
+ row &&
64
+ (["gross", "reversed", "paidOut", "count"] as const).every((field) =>
65
+ Object.is(row[field], totals[field]),
66
+ )
67
+ )
68
+ return;
69
+ if (row) await ctx.db.patch("currencyTotals", row._id, totals);
70
+ else
71
+ await ctx.db.insert("currencyTotals", {
72
+ accountId: next.accountId,
73
+ currency: next.currency,
74
+ kind: "earnings",
75
+ ...totals,
76
+ });
77
+ }
@@ -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 {
@@ -6,19 +7,12 @@ import {
6
7
  } from "convex-helpers/server/customFunctions";
7
8
  import type { DataModel } from "../_generated/dataModel.js";
8
9
  import { addSummaryAmounts } from "./arithmetic.js";
10
+ import { replaceContribution, type Contribution } from "./pairedAdjustment.js";
9
11
  import {
10
12
  mutation as rawMutation,
11
13
  type MutationCtx,
12
14
  } from "../_generated/server.js";
13
15
 
14
- type Contribution = {
15
- accountId: string;
16
- currency: string;
17
- gross: number;
18
- reversed: number;
19
- paidOut: number;
20
- count: number;
21
- };
22
16
  async function adjust(
23
17
  ctx: MutationCtx,
24
18
  kind: "earnings" | "payouts",
@@ -64,12 +58,30 @@ triggers.register("transfers", async (ctx, change) => {
64
58
  paidOut: 0,
65
59
  count: 1,
66
60
  });
67
- if (change.oldDoc?.totalsRecorded)
61
+ const canPair =
62
+ change.oldDoc?.totalsRecorded &&
63
+ change.newDoc &&
64
+ change.oldDoc.destinationAccountId === change.newDoc.destinationAccountId &&
65
+ change.oldDoc.currency === change.newDoc.currency;
66
+ if (canPair)
67
+ await replaceContribution(
68
+ ctx,
69
+ contribution(change.oldDoc!),
70
+ contribution(change.newDoc!),
71
+ );
72
+ else if (change.oldDoc?.totalsRecorded)
68
73
  await adjust(ctx, "earnings", contribution(change.oldDoc), -1);
69
74
  if (change.newDoc) {
70
- await adjust(ctx, "earnings", contribution(change.newDoc), 1);
71
- if (!change.newDoc.totalsRecorded)
75
+ if (!canPair) await adjust(ctx, "earnings", contribution(change.newDoc), 1);
76
+ if (!change.newDoc.totalsRecorded) {
72
77
  await ctx.innerDb.patch("transfers", change.id, { totalsRecorded: true });
78
+ // Frontier producers own bounded batch observation, including oversized release deferral.
79
+ if (
80
+ change.oldDoc?.reversalClaimedAmount ===
81
+ change.newDoc.reversalClaimedAmount
82
+ )
83
+ await observeTransfer(ctx, { ...change.newDoc, totalsRecorded: true });
84
+ }
73
85
  }
74
86
  });
75
87
  triggers.register("payouts", async (ctx, change) => {