@fantastic.dev/better-stripe 0.33.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 (314) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +30 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +522 -2
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +261 -1
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +522 -2
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +261 -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/core/accountClosures.d.ts +15 -0
  20. package/dist/client/core/accountClosures.d.ts.map +1 -0
  21. package/dist/client/core/accountClosures.js +10 -0
  22. package/dist/client/core/accountClosures.js.map +1 -0
  23. package/dist/client/core/accounts.d.ts.map +1 -1
  24. package/dist/client/core/accounts.js +15 -23
  25. package/dist/client/core/accounts.js.map +1 -1
  26. package/dist/client/core/personalAccountMapping.d.ts +8 -0
  27. package/dist/client/core/personalAccountMapping.d.ts.map +1 -0
  28. package/dist/client/core/personalAccountMapping.js +11 -0
  29. package/dist/client/core/personalAccountMapping.js.map +1 -0
  30. package/dist/client/financialObservations.d.ts +42 -0
  31. package/dist/client/financialObservations.d.ts.map +1 -0
  32. package/dist/client/financialObservations.js +58 -0
  33. package/dist/client/financialObservations.js.map +1 -0
  34. package/dist/client/financialOwnership.d.ts +52 -0
  35. package/dist/client/financialOwnership.d.ts.map +1 -0
  36. package/dist/client/financialOwnership.js +72 -0
  37. package/dist/client/financialOwnership.js.map +1 -0
  38. package/dist/client/index.d.ts +57 -4
  39. package/dist/client/index.d.ts.map +1 -1
  40. package/dist/client/index.js +15 -2
  41. package/dist/client/index.js.map +1 -1
  42. package/dist/client/observationPagination.d.ts +10 -0
  43. package/dist/client/observationPagination.d.ts.map +1 -0
  44. package/dist/client/observationPagination.js +12 -0
  45. package/dist/client/observationPagination.js.map +1 -0
  46. package/dist/client/publicTypes.d.ts +10 -0
  47. package/dist/client/publicTypes.d.ts.map +1 -0
  48. package/dist/client/publicTypes.js +2 -0
  49. package/dist/client/publicTypes.js.map +1 -0
  50. package/dist/client/readContracts.d.ts +29 -0
  51. package/dist/client/readContracts.d.ts.map +1 -1
  52. package/dist/client/readContracts.js +10 -0
  53. package/dist/client/readContracts.js.map +1 -1
  54. package/dist/client/transferObservations.d.ts +59 -0
  55. package/dist/client/transferObservations.d.ts.map +1 -0
  56. package/dist/client/transferObservations.js +82 -0
  57. package/dist/client/transferObservations.js.map +1 -0
  58. package/dist/component/_generated/component.d.ts +594 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/accountClosure/helpers.d.ts +18 -0
  61. package/dist/component/accountClosure/helpers.d.ts.map +1 -0
  62. package/dist/component/accountClosure/helpers.js +18 -0
  63. package/dist/component/accountClosure/helpers.js.map +1 -0
  64. package/dist/component/accountClosure/mutations.d.ts +20 -0
  65. package/dist/component/accountClosure/mutations.d.ts.map +1 -0
  66. package/dist/component/accountClosure/mutations.js +55 -0
  67. package/dist/component/accountClosure/mutations.js.map +1 -0
  68. package/dist/component/accountClosure/queries.d.ts +34 -0
  69. package/dist/component/accountClosure/queries.d.ts.map +1 -0
  70. package/dist/component/accountClosure/queries.js +36 -0
  71. package/dist/component/accountClosure/queries.js.map +1 -0
  72. package/dist/component/accountClosure/schema.d.ts +46 -0
  73. package/dist/component/accountClosure/schema.d.ts.map +1 -0
  74. package/dist/component/accountClosure/schema.js +20 -0
  75. package/dist/component/accountClosure/schema.js.map +1 -0
  76. package/dist/component/affiliateRecovery/mutations.d.ts.map +1 -1
  77. package/dist/component/affiliateRecovery/mutations.js +4 -1
  78. package/dist/component/affiliateRecovery/mutations.js.map +1 -1
  79. package/dist/component/connect/mutations.d.ts.map +1 -1
  80. package/dist/component/connect/mutations.js +18 -2
  81. package/dist/component/connect/mutations.js.map +1 -1
  82. package/dist/component/connect/queries.d.ts +8 -0
  83. package/dist/component/connect/queries.d.ts.map +1 -1
  84. package/dist/component/connect/reversalClaims.d.ts.map +1 -1
  85. package/dist/component/connect/reversalClaims.js +7 -1
  86. package/dist/component/connect/reversalClaims.js.map +1 -1
  87. package/dist/component/connect/reversalReceipts.d.ts.map +1 -1
  88. package/dist/component/connect/reversalReceipts.js +2 -0
  89. package/dist/component/connect/reversalReceipts.js.map +1 -1
  90. package/dist/component/connect/schema.d.ts +11 -1
  91. package/dist/component/connect/schema.d.ts.map +1 -1
  92. package/dist/component/connect/schema.js +9 -1
  93. package/dist/component/connect/schema.js.map +1 -1
  94. package/dist/component/connect/validators.d.ts +9 -1
  95. package/dist/component/connect/validators.d.ts.map +1 -1
  96. package/dist/component/connect/validators.js +2 -0
  97. package/dist/component/connect/validators.js.map +1 -1
  98. package/dist/component/core/mutations.d.ts.map +1 -1
  99. package/dist/component/core/mutations.js +5 -0
  100. package/dist/component/core/mutations.js.map +1 -1
  101. package/dist/component/core/personalAccountMapping.d.ts +95 -0
  102. package/dist/component/core/personalAccountMapping.d.ts.map +1 -0
  103. package/dist/component/core/personalAccountMapping.js +54 -0
  104. package/dist/component/core/personalAccountMapping.js.map +1 -0
  105. package/dist/component/core/queries.d.ts +27 -0
  106. package/dist/component/core/queries.d.ts.map +1 -1
  107. package/dist/component/core/queries.js +7 -0
  108. package/dist/component/core/queries.js.map +1 -1
  109. package/dist/component/earnings/triggers.d.ts +468 -2
  110. package/dist/component/earnings/triggers.d.ts.map +1 -1
  111. package/dist/component/earnings/triggers.js +7 -1
  112. package/dist/component/earnings/triggers.js.map +1 -1
  113. package/dist/component/financialObservations/continuation.d.ts +7 -0
  114. package/dist/component/financialObservations/continuation.d.ts.map +1 -0
  115. package/dist/component/financialObservations/continuation.js +131 -0
  116. package/dist/component/financialObservations/continuation.js.map +1 -0
  117. package/dist/component/financialObservations/generations.d.ts +6 -0
  118. package/dist/component/financialObservations/generations.d.ts.map +1 -0
  119. package/dist/component/financialObservations/generations.js +46 -0
  120. package/dist/component/financialObservations/generations.js.map +1 -0
  121. package/dist/component/financialObservations/mutations.d.ts +62 -0
  122. package/dist/component/financialObservations/mutations.d.ts.map +1 -0
  123. package/dist/component/financialObservations/mutations.js +69 -0
  124. package/dist/component/financialObservations/mutations.js.map +1 -0
  125. package/dist/component/financialObservations/queries.d.ts +307 -0
  126. package/dist/component/financialObservations/queries.d.ts.map +1 -0
  127. package/dist/component/financialObservations/queries.js +219 -0
  128. package/dist/component/financialObservations/queries.js.map +1 -0
  129. package/dist/component/financialObservations/schema.d.ts +182 -0
  130. package/dist/component/financialObservations/schema.d.ts.map +1 -0
  131. package/dist/component/financialObservations/schema.js +53 -0
  132. package/dist/component/financialObservations/schema.js.map +1 -0
  133. package/dist/component/financialObservations/settlement.d.ts +7 -0
  134. package/dist/component/financialObservations/settlement.d.ts.map +1 -0
  135. package/dist/component/financialObservations/settlement.js +118 -0
  136. package/dist/component/financialObservations/settlement.js.map +1 -0
  137. package/dist/component/financialObservations/settlementHelpers.d.ts +46 -0
  138. package/dist/component/financialObservations/settlementHelpers.d.ts.map +1 -0
  139. package/dist/component/financialObservations/settlementHelpers.js +70 -0
  140. package/dist/component/financialObservations/settlementHelpers.js.map +1 -0
  141. package/dist/component/financialObservations/transferBatches.d.ts +12 -0
  142. package/dist/component/financialObservations/transferBatches.d.ts.map +1 -0
  143. package/dist/component/financialObservations/transferBatches.js +76 -0
  144. package/dist/component/financialObservations/transferBatches.js.map +1 -0
  145. package/dist/component/financialObservations/transferContinuation.d.ts +5 -0
  146. package/dist/component/financialObservations/transferContinuation.d.ts.map +1 -0
  147. package/dist/component/financialObservations/transferContinuation.js +35 -0
  148. package/dist/component/financialObservations/transferContinuation.js.map +1 -0
  149. package/dist/component/financialObservations/transferContinuationState.d.ts +8 -0
  150. package/dist/component/financialObservations/transferContinuationState.d.ts.map +1 -0
  151. package/dist/component/financialObservations/transferContinuationState.js +69 -0
  152. package/dist/component/financialObservations/transferContinuationState.js.map +1 -0
  153. package/dist/component/financialObservations/transferContinuationSteps.d.ts +5 -0
  154. package/dist/component/financialObservations/transferContinuationSteps.d.ts.map +1 -0
  155. package/dist/component/financialObservations/transferContinuationSteps.js +174 -0
  156. package/dist/component/financialObservations/transferContinuationSteps.js.map +1 -0
  157. package/dist/component/financialObservations/transferHelpers.d.ts +18 -0
  158. package/dist/component/financialObservations/transferHelpers.d.ts.map +1 -0
  159. package/dist/component/financialObservations/transferHelpers.js +37 -0
  160. package/dist/component/financialObservations/transferHelpers.js.map +1 -0
  161. package/dist/component/financialObservations/transferReferenceSchema.d.ts +56 -0
  162. package/dist/component/financialObservations/transferReferenceSchema.d.ts.map +1 -0
  163. package/dist/component/financialObservations/transferReferenceSchema.js +21 -0
  164. package/dist/component/financialObservations/transferReferenceSchema.js.map +1 -0
  165. package/dist/component/financialObservations/transferSchema.d.ts +237 -0
  166. package/dist/component/financialObservations/transferSchema.d.ts.map +1 -0
  167. package/dist/component/financialObservations/transferSchema.js +65 -0
  168. package/dist/component/financialObservations/transferSchema.js.map +1 -0
  169. package/dist/component/financialObservations/transfers.d.ts +7 -0
  170. package/dist/component/financialObservations/transfers.d.ts.map +1 -0
  171. package/dist/component/financialObservations/transfers.js +79 -0
  172. package/dist/component/financialObservations/transfers.js.map +1 -0
  173. package/dist/component/financialOwnership/helpers.d.ts +37 -0
  174. package/dist/component/financialOwnership/helpers.d.ts.map +1 -0
  175. package/dist/component/financialOwnership/helpers.js +76 -0
  176. package/dist/component/financialOwnership/helpers.js.map +1 -0
  177. package/dist/component/financialOwnership/mutations.d.ts +28 -0
  178. package/dist/component/financialOwnership/mutations.d.ts.map +1 -0
  179. package/dist/component/financialOwnership/mutations.js +74 -0
  180. package/dist/component/financialOwnership/mutations.js.map +1 -0
  181. package/dist/component/financialOwnership/queries.d.ts +57 -0
  182. package/dist/component/financialOwnership/queries.d.ts.map +1 -0
  183. package/dist/component/financialOwnership/queries.js +50 -0
  184. package/dist/component/financialOwnership/queries.js.map +1 -0
  185. package/dist/component/financialOwnership/schema.d.ts +140 -0
  186. package/dist/component/financialOwnership/schema.d.ts.map +1 -0
  187. package/dist/component/financialOwnership/schema.js +35 -0
  188. package/dist/component/financialOwnership/schema.js.map +1 -0
  189. package/dist/component/payoutRelease/queries.d.ts +2 -2
  190. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  191. package/dist/component/refundHistory/commandBinding.d.ts +17 -0
  192. package/dist/component/refundHistory/commandBinding.d.ts.map +1 -0
  193. package/dist/component/refundHistory/commandBinding.js +41 -0
  194. package/dist/component/refundHistory/commandBinding.js.map +1 -0
  195. package/dist/component/refundHistory/commandEvidence.d.ts +50 -0
  196. package/dist/component/refundHistory/commandEvidence.d.ts.map +1 -0
  197. package/dist/component/refundHistory/commandEvidence.js +54 -0
  198. package/dist/component/refundHistory/commandEvidence.js.map +1 -0
  199. package/dist/component/refundHistory/commandEvidenceValidator.d.ts +89 -0
  200. package/dist/component/refundHistory/commandEvidenceValidator.d.ts.map +1 -0
  201. package/dist/component/refundHistory/commandEvidenceValidator.js +8 -0
  202. package/dist/component/refundHistory/commandEvidenceValidator.js.map +1 -0
  203. package/dist/component/refundHistory/commandFields.d.ts +8 -0
  204. package/dist/component/refundHistory/commandFields.d.ts.map +1 -0
  205. package/dist/component/refundHistory/commandFields.js +9 -0
  206. package/dist/component/refundHistory/commandFields.js.map +1 -0
  207. package/dist/component/refundHistory/mutations.d.ts +8 -0
  208. package/dist/component/refundHistory/mutations.d.ts.map +1 -0
  209. package/dist/component/refundHistory/mutations.js +25 -0
  210. package/dist/component/refundHistory/mutations.js.map +1 -0
  211. package/dist/component/refundHistory/queries.d.ts +51 -0
  212. package/dist/component/refundHistory/queries.d.ts.map +1 -1
  213. package/dist/component/refundHistory/queries.js +14 -0
  214. package/dist/component/refundHistory/queries.js.map +1 -1
  215. package/dist/component/schema.d.ts +261 -1
  216. package/dist/component/schema.js +14 -0
  217. package/dist/component/schema.js.map +1 -1
  218. package/dist/component/settlement/mutations.d.ts.map +1 -1
  219. package/dist/component/settlement/mutations.js +5 -1
  220. package/dist/component/settlement/mutations.js.map +1 -1
  221. package/dist/shared/refundCommandScope.d.ts +10 -0
  222. package/dist/shared/refundCommandScope.d.ts.map +1 -0
  223. package/dist/shared/refundCommandScope.js +9 -0
  224. package/dist/shared/refundCommandScope.js.map +1 -0
  225. package/docs/financial-observations.md +159 -0
  226. package/docs/financial-ownership.md +54 -0
  227. package/docs/personal-account-mapping.md +54 -0
  228. package/docs/refund-command-evidence.md +49 -0
  229. package/package.json +6 -2
  230. package/src/client/connect/refundCommandEvidence.ts +41 -0
  231. package/src/client/connect/refundCommandNormalization.ts +28 -0
  232. package/src/client/core/account-close-orchestration.test.ts +131 -0
  233. package/src/client/core/account-closure.test.ts +317 -0
  234. package/src/client/core/accountClosures.ts +37 -0
  235. package/src/client/core/accounts.test.ts +0 -111
  236. package/src/client/core/accounts.ts +24 -29
  237. package/src/client/core/personal-account-mapping.test.ts +71 -0
  238. package/src/client/core/personalAccountMapping.ts +23 -0
  239. package/src/client/financialObservations.test.ts +109 -0
  240. package/src/client/financialObservations.ts +106 -0
  241. package/src/client/financialOwnership.test.ts +80 -0
  242. package/src/client/financialOwnership.ts +116 -0
  243. package/src/client/index.ts +38 -35
  244. package/src/client/observationPagination.ts +11 -0
  245. package/src/client/publicTypes.ts +72 -0
  246. package/src/client/readContracts.ts +21 -0
  247. package/src/client/refund-command-evidence.test.ts +68 -0
  248. package/src/client/refund-command-normalization.test.ts +61 -0
  249. package/src/client/transferContinuation.test.ts +94 -0
  250. package/src/client/transferObservations.test.ts +98 -0
  251. package/src/client/transferObservations.ts +180 -0
  252. package/src/component/_generated/api.ts +52 -0
  253. package/src/component/_generated/component.ts +716 -0
  254. package/src/component/accountClosure/helpers.ts +21 -0
  255. package/src/component/accountClosure/mutations.ts +56 -0
  256. package/src/component/accountClosure/queries.ts +43 -0
  257. package/src/component/accountClosure/schema.ts +20 -0
  258. package/src/component/affiliateRecovery/mutations.ts +10 -1
  259. package/src/component/connect/mutations.ts +29 -2
  260. package/src/component/connect/reversalClaims.ts +19 -1
  261. package/src/component/connect/reversalReceipts.ts +2 -0
  262. package/src/component/connect/schema.ts +9 -1
  263. package/src/component/connect/validators.ts +2 -0
  264. package/src/component/core/mutations.ts +3 -0
  265. package/src/component/core/personal-account-mapping.test.ts +173 -0
  266. package/src/component/core/personalAccountMapping.ts +81 -0
  267. package/src/component/core/queries.ts +11 -0
  268. package/src/component/core/reset.test.ts +8 -1
  269. package/src/component/earnings/earnings-totals.test.ts +14 -10
  270. package/src/component/earnings/triggers.ts +9 -1
  271. package/src/component/financialObservations/continuation.test.ts +445 -0
  272. package/src/component/financialObservations/continuation.ts +159 -0
  273. package/src/component/financialObservations/generations.ts +53 -0
  274. package/src/component/financialObservations/mutations.ts +75 -0
  275. package/src/component/financialObservations/observation-boundaries.test.ts +466 -0
  276. package/src/component/financialObservations/queries.ts +246 -0
  277. package/src/component/financialObservations/schema.ts +68 -0
  278. package/src/component/financialObservations/settlement-observations.test.ts +86 -0
  279. package/src/component/financialObservations/settlement.ts +142 -0
  280. package/src/component/financialObservations/settlementHelpers.ts +92 -0
  281. package/src/component/financialObservations/transfer-batches.test.ts +61 -0
  282. package/src/component/financialObservations/transfer-boundaries.test.ts +116 -0
  283. package/src/component/financialObservations/transfer-continuation-guards.test.ts +428 -0
  284. package/src/component/financialObservations/transfer-continuation.test.ts +154 -0
  285. package/src/component/financialObservations/transfer-observations.test.ts +212 -0
  286. package/src/component/financialObservations/transfer-overflow.test.ts +181 -0
  287. package/src/component/financialObservations/transfer-writers.test.ts +162 -0
  288. package/src/component/financialObservations/transferBatches.ts +96 -0
  289. package/src/component/financialObservations/transferContinuation.ts +53 -0
  290. package/src/component/financialObservations/transferContinuationState.ts +85 -0
  291. package/src/component/financialObservations/transferContinuationSteps.ts +232 -0
  292. package/src/component/financialObservations/transferHelpers.ts +38 -0
  293. package/src/component/financialObservations/transferReferenceSchema.ts +20 -0
  294. package/src/component/financialObservations/transferSchema.ts +74 -0
  295. package/src/component/financialObservations/transfers.ts +99 -0
  296. package/src/component/financialOwnership/financial-ownership.test.ts +102 -0
  297. package/src/component/financialOwnership/helpers.ts +98 -0
  298. package/src/component/financialOwnership/mutations.ts +83 -0
  299. package/src/component/financialOwnership/ownership-boundaries.test.ts +308 -0
  300. package/src/component/financialOwnership/queries.ts +65 -0
  301. package/src/component/financialOwnership/schema.ts +35 -0
  302. package/src/component/refundHistory/command-evidence.test.ts +288 -0
  303. package/src/component/refundHistory/command-normalization-resource.test.ts +77 -0
  304. package/src/component/refundHistory/command-normalization.test.ts +229 -0
  305. package/src/component/refundHistory/command-provenance.test.ts +59 -0
  306. package/src/component/refundHistory/commandBinding.ts +54 -0
  307. package/src/component/refundHistory/commandEvidence.ts +71 -0
  308. package/src/component/refundHistory/commandEvidenceValidator.ts +18 -0
  309. package/src/component/refundHistory/commandFields.ts +9 -0
  310. package/src/component/refundHistory/mutations.ts +33 -0
  311. package/src/component/refundHistory/queries.ts +15 -0
  312. package/src/component/schema.ts +24 -0
  313. package/src/component/settlement/mutations.ts +5 -1
  314. package/src/shared/refundCommandScope.ts +19 -0
@@ -0,0 +1,53 @@
1
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
2
+
3
+ export function bucketScope(bucketKey: string) {
4
+ return JSON.stringify(["bucket", bucketKey]);
5
+ }
6
+ export function ownerScope(userId: string, orgId?: string) {
7
+ return JSON.stringify(["owner", userId, orgId ?? null]);
8
+ }
9
+ export async function observationGeneration(ctx: QueryCtx, scopeKey: string) {
10
+ const rows = await ctx.db
11
+ .query("financialObservationGenerations")
12
+ .withIndex("by_scope_key", (q) => q.eq("scopeKey", scopeKey))
13
+ .take(2);
14
+ if (
15
+ rows.length > 1 ||
16
+ (rows[0] &&
17
+ (!Number.isSafeInteger(rows[0].generation) || rows[0].generation < 1))
18
+ )
19
+ return null;
20
+ return rows[0]?.generation ?? 0;
21
+ }
22
+ export async function advanceObservationGeneration(
23
+ ctx: MutationCtx,
24
+ scopeKey: string,
25
+ ) {
26
+ const rows = await ctx.db
27
+ .query("financialObservationGenerations")
28
+ .withIndex("by_scope_key", (q) => q.eq("scopeKey", scopeKey))
29
+ .take(2);
30
+ if (rows.length > 1) return;
31
+ if (
32
+ rows[0] &&
33
+ (!Number.isSafeInteger(rows[0].generation) || rows[0].generation < 1)
34
+ )
35
+ return;
36
+ const generation = (rows[0]?.generation ?? 0) + 1;
37
+ if (!Number.isSafeInteger(generation)) {
38
+ if (rows[0])
39
+ await ctx.db.patch("financialObservationGenerations", rows[0]._id, {
40
+ generation: 0,
41
+ });
42
+ return;
43
+ }
44
+ if (rows[0])
45
+ await ctx.db.patch("financialObservationGenerations", rows[0]._id, {
46
+ generation,
47
+ });
48
+ else
49
+ await ctx.db.insert("financialObservationGenerations", {
50
+ scopeKey,
51
+ generation,
52
+ });
53
+ }
@@ -0,0 +1,75 @@
1
+ import { continueTransferBatch } from "./transferContinuation.js";
2
+ import { transferReaderState } from "./transferBatches.js";
3
+ import { transferBatchDoc } from "./transferSchema.js";
4
+ import { v } from "convex/values";
5
+ import { mutation } from "../_generated/server.js";
6
+ import { sourceDoc } from "./schema.js";
7
+ import { continueSettlementObservation } from "./continuation.js";
8
+ /** Trusted host mutation. Host must authorize access and explicitly drain bounded steps. */
9
+ export const resume = mutation({
10
+ args: {
11
+ allocationId: v.id("settlementAllocations"),
12
+ expectedGeneration: v.number(),
13
+ },
14
+ returns: v.object({
15
+ coverage: v.literal("unknown"),
16
+ observation: v.union(sourceDoc, v.null()),
17
+ }),
18
+ handler: async (ctx, args) => {
19
+ if (
20
+ !Number.isSafeInteger(args.expectedGeneration) ||
21
+ args.expectedGeneration < 1
22
+ )
23
+ throw new Error("Invalid observation generation");
24
+ const markers = await ctx.db
25
+ .query("financialSourceObservations")
26
+ .withIndex("by_allocation_id", (q) =>
27
+ q.eq("allocationId", args.allocationId),
28
+ )
29
+ .take(2);
30
+ const marker = markers.length === 1 ? markers[0]! : null;
31
+ if (marker)
32
+ await continueSettlementObservation(ctx, marker, args.expectedGeneration);
33
+ const current = marker
34
+ ? await ctx.db.get("financialSourceObservations", marker._id)
35
+ : null;
36
+ return {
37
+ coverage: "unknown" as const,
38
+ observation:
39
+ current &&
40
+ Number.isSafeInteger(current.generation) &&
41
+ current.generation >= 1
42
+ ? current
43
+ : null,
44
+ };
45
+ },
46
+ });
47
+
48
+ /** Trusted host continuation; caller selects identity and generation, never cursor state. */
49
+ export const resumeTransferBatch = mutation({
50
+ args: {
51
+ batchId: v.id("financialTransferBatches"),
52
+ expectedGeneration: v.number(),
53
+ },
54
+ returns: v.object({
55
+ coverage: v.literal("unknown"),
56
+ producerGeneration: v.union(v.number(), v.null()),
57
+ hasDeferredWork: v.boolean(),
58
+ batch: v.union(transferBatchDoc, v.null()),
59
+ }),
60
+ handler: async (ctx, args) => {
61
+ if (
62
+ !Number.isSafeInteger(args.expectedGeneration) ||
63
+ args.expectedGeneration < 1
64
+ )
65
+ throw new Error("Invalid observation generation");
66
+ const batch = await ctx.db.get("financialTransferBatches", args.batchId);
67
+ if (batch) await continueTransferBatch(ctx, batch, args.expectedGeneration);
68
+ return {
69
+ ...(await transferReaderState(ctx)),
70
+ batch: batch
71
+ ? await ctx.db.get("financialTransferBatches", batch._id)
72
+ : null,
73
+ };
74
+ },
75
+ });
@@ -0,0 +1,466 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference, type PaginationResult } from "convex/server";
3
+ import type { Doc } from "../_generated/dataModel.js";
4
+ import { expect, it } from "vitest";
5
+ import { modules, schema } from "../../test.js";
6
+ import { observeSettlementAllocation } from "./settlement.js";
7
+
8
+ const reserve = makeFunctionReference<"mutation">(
9
+ "settlement/mutations:reserveSettlementAllocation",
10
+ );
11
+ const register = makeFunctionReference<"mutation">(
12
+ "financialOwnership/mutations:register",
13
+ );
14
+ const source = makeFunctionReference<"query">(
15
+ "financialObservations/queries:source",
16
+ );
17
+ const bucket = makeFunctionReference<"query">(
18
+ "financialObservations/queries:bucket",
19
+ );
20
+ const owner = makeFunctionReference<"query">(
21
+ "financialObservations/queries:owner",
22
+ );
23
+ const paginationOpts = { numItems: 25, cursor: null };
24
+ function allocation(charge = "ch_bound", count = 1) {
25
+ return {
26
+ sourceChargeId: charge,
27
+ gross: count + 2,
28
+ currency: "usd",
29
+ processingFee: 1,
30
+ platformNet: 1,
31
+ transfers: Array.from({ length: count }, (_, i) => ({
32
+ destinationAccountId: `opaque_${i}`,
33
+ role: "store" as const,
34
+ amount: 1,
35
+ })),
36
+ };
37
+ }
38
+ function logical(bucketKey = "opaque_0", userId = "owner", orgId?: string) {
39
+ return {
40
+ bucketKey,
41
+ kind: "logical",
42
+ userId,
43
+ ...(orgId ? { orgId } : {}),
44
+ source: { integration: "trusted-host", recordId: bucketKey },
45
+ };
46
+ }
47
+
48
+ it("replays the persisted original allocation and does not advance diagnostics for changed caller amounts", async () => {
49
+ const t = convexTest(schema, modules);
50
+ await t.mutation(register, logical());
51
+ const row = await t.mutation(reserve, allocation());
52
+ const before = await t.query(source, { allocationId: row._id });
53
+ expect(
54
+ await t.mutation(reserve, { ...allocation(), gross: 999, transfers: [] }),
55
+ ).toEqual(row);
56
+ expect(await t.query(source, { allocationId: row._id })).toEqual(before);
57
+ expect(
58
+ await t.query(bucket, { bucketKey: "opaque_0", paginationOpts }),
59
+ ).toMatchObject({ generation: 1 });
60
+ });
61
+ it.each([0, 100, 101, 300])(
62
+ "preserves %i-leg financial writes and honestly marks overflow",
63
+ async (count) => {
64
+ const t = convexTest(schema, modules);
65
+ const row = await t.mutation(reserve, allocation(`ch_${count}`, count));
66
+ expect(await t.query(source, { allocationId: row._id })).toMatchObject({
67
+ coverage: "unknown",
68
+ observation: {
69
+ legCount: count,
70
+ indexedLegCount: count > 100 ? 0 : count,
71
+ isOverflow: count > 100,
72
+ },
73
+ });
74
+ expect(
75
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
76
+ ).toEqual(row);
77
+ expect(await t.mutation(reserve, allocation(`ch_${count}`, count))).toEqual(
78
+ row,
79
+ );
80
+ expect(await t.query(source, { allocationId: row._id })).toMatchObject({
81
+ observation: { generation: 1 },
82
+ });
83
+ },
84
+ );
85
+ it("pins the first registered owner and never redirects historical legs after registry replacement", async () => {
86
+ const t = convexTest(schema, modules);
87
+ await t.mutation(register, logical());
88
+ const row = await t.mutation(reserve, allocation());
89
+ await t.run(async (ctx) => {
90
+ const registration = await ctx.db
91
+ .query("financialOwnership")
92
+ .withIndex("by_bucket_key", (q) => q.eq("bucketKey", "opaque_0"))
93
+ .unique();
94
+ await ctx.db.delete("financialOwnership", registration!._id);
95
+ });
96
+ await t.mutation(register, logical("opaque_0", "replacement"));
97
+ await t.mutation(reserve, allocation());
98
+ expect(
99
+ await t.query(owner, { userId: "owner", paginationOpts }),
100
+ ).toMatchObject({
101
+ coverage: "unknown",
102
+ page: [
103
+ expect.objectContaining({
104
+ userId: "owner",
105
+ ownershipStatus: "contradictory",
106
+ }),
107
+ ],
108
+ });
109
+ expect(
110
+ await t.query(owner, { userId: "replacement", paginationOpts }),
111
+ ).toMatchObject({ page: [] });
112
+ expect(
113
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
114
+ ).toEqual(row);
115
+ });
116
+ it("records late first ownership without guessing it and isolates personal/org scopes", async () => {
117
+ const t = convexTest(schema, modules);
118
+ const row = await t.mutation(reserve, allocation());
119
+ expect(
120
+ await t.query(owner, { userId: "owner", paginationOpts }),
121
+ ).toMatchObject({ page: [] });
122
+ await t.mutation(register, logical("opaque_0", "owner", "org"));
123
+ await t.mutation(reserve, allocation());
124
+ expect(await t.query(source, { allocationId: row._id })).toMatchObject({
125
+ observation: { generation: 2 },
126
+ });
127
+ expect(
128
+ await t.query(owner, { userId: "owner", paginationOpts }),
129
+ ).toMatchObject({ page: [] });
130
+ expect(
131
+ await t.query(owner, { userId: "owner", orgId: "org", paginationOpts }),
132
+ ).toMatchObject({
133
+ generation: 1,
134
+ page: [expect.objectContaining({ userId: "owner", orgId: "org" })],
135
+ });
136
+ });
137
+ it("holds contradictory late source facts and keeps replay generation stable", async () => {
138
+ const t = convexTest(schema, modules);
139
+ await t.mutation(register, logical());
140
+ const row = await t.mutation(reserve, allocation());
141
+ await t.run(async (ctx) => {
142
+ await ctx.db.patch("settlementAllocations", row._id, { currency: "eur" });
143
+ const changed = await ctx.db.get("settlementAllocations", row._id);
144
+ await observeSettlementAllocation(ctx, changed!);
145
+ });
146
+ const after = await t.query(source, { allocationId: row._id });
147
+ expect(after).toMatchObject({
148
+ observation: { generation: 2, isContradictory: true },
149
+ });
150
+ await t.run(async (ctx) =>
151
+ observeSettlementAllocation(
152
+ ctx,
153
+ (await ctx.db.get("settlementAllocations", row._id))!,
154
+ ),
155
+ );
156
+ expect(await t.query(source, { allocationId: row._id })).toEqual(after);
157
+ expect(
158
+ await t.query(bucket, { bucketKey: "opaque_0", paginationOpts }),
159
+ ).toMatchObject({
160
+ generation: 2,
161
+ page: [expect.objectContaining({ ownershipStatus: "contradictory" })],
162
+ });
163
+ });
164
+ it("advances shared bucket/owner generations for new late allocations with bounded native pagination", async () => {
165
+ const t = convexTest(schema, modules);
166
+ await t.mutation(register, logical());
167
+ for (let i = 0; i < 103; i++)
168
+ await t.mutation(reserve, allocation(`ch_page_${i}`));
169
+ let cursor: string | null = null;
170
+ const seen = new Set<string>();
171
+ let done = false;
172
+ while (!done) {
173
+ const result: PaginationResult<Doc<"financialSourceLegs">> & {
174
+ coverage: "unknown";
175
+ generation: number | null;
176
+ } = await t.query(owner, {
177
+ userId: "owner",
178
+ paginationOpts: { numItems: 25, cursor },
179
+ });
180
+ expect(result).toMatchObject({ coverage: "unknown", generation: 103 });
181
+ for (const row of result.page) {
182
+ expect(seen.has(row._id)).toBe(false);
183
+ seen.add(row._id);
184
+ }
185
+ cursor = result.continueCursor;
186
+ done = result.isDone;
187
+ }
188
+ expect(seen.size).toBe(103);
189
+ await expect(
190
+ t.query(bucket, {
191
+ bucketKey: "opaque_0",
192
+ paginationOpts: { numItems: 101, cursor: null },
193
+ }),
194
+ ).rejects.toThrow("page size");
195
+ });
196
+
197
+ it("does not reassign a pinned historical owner when registration is missing or ambiguous", async () => {
198
+ const t = convexTest(schema, modules);
199
+ await t.mutation(register, logical());
200
+ const row = await t.mutation(reserve, allocation());
201
+ const registration = await t.run((ctx) =>
202
+ ctx.db
203
+ .query("financialOwnership")
204
+ .withIndex("by_bucket_key", (q) => q.eq("bucketKey", "opaque_0"))
205
+ .unique(),
206
+ );
207
+ await t.run((ctx) => ctx.db.delete("financialOwnership", registration!._id));
208
+ await t.mutation(reserve, allocation());
209
+ expect(
210
+ await t.query(owner, { userId: "owner", paginationOpts }),
211
+ ).toMatchObject({
212
+ page: [
213
+ expect.objectContaining({ userId: "owner", ownershipStatus: "unknown" }),
214
+ ],
215
+ });
216
+ await t.mutation(register, logical());
217
+ await t.run(async (ctx) => {
218
+ const current = await ctx.db
219
+ .query("financialOwnership")
220
+ .withIndex("by_bucket_key", (q) => q.eq("bucketKey", "opaque_0"))
221
+ .unique();
222
+ const { _id, _creationTime, ...fields } = current!;
223
+ void _id;
224
+ void _creationTime;
225
+ await ctx.db.insert("financialOwnership", {
226
+ ...fields,
227
+ userId: "replacement",
228
+ });
229
+ });
230
+ await t.mutation(reserve, allocation());
231
+ expect(
232
+ await t.query(owner, { userId: "owner", paginationOpts }),
233
+ ).toMatchObject({
234
+ page: [
235
+ expect.objectContaining({
236
+ userId: "owner",
237
+ ownershipStatus: "ambiguous",
238
+ }),
239
+ ],
240
+ });
241
+ expect(
242
+ await t.query(owner, { userId: "replacement", paginationOpts }),
243
+ ).toMatchObject({ page: [] });
244
+ expect(
245
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
246
+ ).toEqual(row);
247
+ });
248
+ it("unknown legacy rows stay unobserved until an actual writer replay and invalid reservations are atomic", async () => {
249
+ const t = convexTest(schema, modules);
250
+ const id = await t.run((ctx) =>
251
+ ctx.db.insert("settlementAllocations", allocation()),
252
+ );
253
+ expect(await t.query(source, { allocationId: id })).toEqual({
254
+ coverage: "unknown",
255
+ observation: null,
256
+ });
257
+ await expect(
258
+ t.mutation(reserve, { ...allocation("ch_invalid"), gross: 999 }),
259
+ ).rejects.toThrow("reconcile");
260
+ expect(
261
+ await t.run((ctx) => ctx.db.query("financialSourceObservations").take(2)),
262
+ ).toEqual([]);
263
+ await t.mutation(reserve, allocation());
264
+ expect(await t.query(source, { allocationId: id })).toMatchObject({
265
+ coverage: "unknown",
266
+ observation: { generation: 1 },
267
+ });
268
+ });
269
+ it("missing buckets and foreign owner scopes expose no rows", async () => {
270
+ const t = convexTest(schema, modules);
271
+ await t.mutation(register, logical());
272
+ await t.mutation(reserve, allocation());
273
+ expect(
274
+ await t.query(bucket, { bucketKey: "unseen", paginationOpts }),
275
+ ).toMatchObject({ coverage: "unknown", generation: 0, page: [] });
276
+ expect(
277
+ await t.query(owner, { userId: "foreign", paginationOpts }),
278
+ ).toMatchObject({ coverage: "unknown", generation: 0, page: [] });
279
+ expect(
280
+ await t.query(owner, { userId: "owner", orgId: "foreign", paginationOpts }),
281
+ ).toMatchObject({ coverage: "unknown", generation: 0, page: [] });
282
+ });
283
+
284
+ it("holds duplicate financial source identity without changing the existing reservation behavior", async () => {
285
+ const t = convexTest(schema, modules);
286
+ const row = await t.mutation(reserve, allocation());
287
+ await t.run((ctx) => ctx.db.insert("settlementAllocations", allocation()));
288
+ expect(await t.mutation(reserve, allocation())).toEqual(row);
289
+ expect(await t.query(source, { allocationId: row._id })).toMatchObject({
290
+ coverage: "unknown",
291
+ observation: { isContradictory: true },
292
+ });
293
+ });
294
+
295
+ it("returns UNKNOWN null diagnostic generation when a scope counter exhausts safe integer identity", async () => {
296
+ const t = convexTest(schema, modules);
297
+ await t.mutation(register, logical());
298
+ await t.mutation(reserve, allocation());
299
+ await t.run(async (ctx) => {
300
+ const counter = await ctx.db
301
+ .query("financialObservationGenerations")
302
+ .withIndex("by_scope_key", (q) =>
303
+ q.eq("scopeKey", JSON.stringify(["bucket", "opaque_0"])),
304
+ )
305
+ .unique();
306
+ await ctx.db.patch("financialObservationGenerations", counter!._id, {
307
+ generation: Number.MAX_SAFE_INTEGER,
308
+ });
309
+ });
310
+ await t.mutation(reserve, allocation("ch_after_exhaustion"));
311
+ expect(
312
+ await t.query(bucket, { bucketKey: "opaque_0", paginationOpts }),
313
+ ).toMatchObject({ coverage: "unknown", generation: null });
314
+ });
315
+
316
+ it("holds exhausted source generations instead of exposing a stale valid observation", async () => {
317
+ const t = convexTest(schema, modules);
318
+ const row = await t.mutation(reserve, allocation());
319
+ await t.run(async (ctx) => {
320
+ const marker = await ctx.db
321
+ .query("financialSourceObservations")
322
+ .withIndex("by_allocation_id", (q) => q.eq("allocationId", row._id))
323
+ .unique();
324
+ await ctx.db.patch("financialSourceObservations", marker!._id, {
325
+ generation: Number.MAX_SAFE_INTEGER,
326
+ });
327
+ });
328
+ await t.mutation(register, logical());
329
+ await t.mutation(reserve, allocation());
330
+ expect(await t.query(source, { allocationId: row._id })).toEqual({
331
+ coverage: "unknown",
332
+ observation: null,
333
+ });
334
+ expect(
335
+ await t.run((ctx) => ctx.db.get("settlementAllocations", row._id)),
336
+ ).toEqual(row);
337
+ });
338
+
339
+ it.each([
340
+ "duplicate",
341
+ "destination",
342
+ "role",
343
+ "source charge",
344
+ "fractional slot",
345
+ ] as const)(
346
+ "holds %s observation identity without rewriting financial facts",
347
+ async (kind) => {
348
+ const t = convexTest(schema, modules);
349
+ const row = await t.mutation(reserve, allocation());
350
+ await t.run(async (ctx) => {
351
+ const leg = await ctx.db
352
+ .query("financialSourceLegs")
353
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
354
+ q.eq("allocationId", row._id),
355
+ )
356
+ .unique();
357
+ if (kind === "duplicate") {
358
+ const { _id, _creationTime, ...fields } = leg!;
359
+ void _id;
360
+ void _creationTime;
361
+ await ctx.db.insert("financialSourceLegs", {
362
+ ...fields,
363
+ bucketKey: "contradictory",
364
+ });
365
+ }
366
+ if (kind === "destination")
367
+ await ctx.db.patch("financialSourceLegs", leg!._id, {
368
+ bucketKey: "contradictory",
369
+ });
370
+ if (kind === "role")
371
+ await ctx.db.patch("financialSourceLegs", leg!._id, {
372
+ role: "affiliate",
373
+ });
374
+ if (kind === "source charge")
375
+ await ctx.db.patch("financialSourceLegs", leg!._id, {
376
+ sourceChargeId: "ch_other",
377
+ });
378
+ if (kind === "fractional slot")
379
+ await ctx.db.patch("financialSourceLegs", leg!._id, { legIndex: 0.5 });
380
+ });
381
+ const originalLegs = await t.run((ctx) =>
382
+ ctx.db
383
+ .query("financialSourceLegs")
384
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
385
+ q.eq("allocationId", row._id),
386
+ )
387
+ .take(101),
388
+ );
389
+ await t.mutation(reserve, allocation());
390
+ const after = await t.query(source, { allocationId: row._id });
391
+ expect(after).toMatchObject({
392
+ coverage: "unknown",
393
+ observation: { isContradictory: true },
394
+ });
395
+ expect(await t.mutation(reserve, allocation())).toEqual(row);
396
+ expect(await t.query(source, { allocationId: row._id })).toEqual(after);
397
+ expect(
398
+ await t.run((ctx) =>
399
+ ctx.db
400
+ .query("financialSourceLegs")
401
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
402
+ q.eq("allocationId", row._id),
403
+ )
404
+ .take(101),
405
+ ),
406
+ ).toEqual(originalLegs);
407
+ },
408
+ );
409
+
410
+ it.each([false, true])(
411
+ "holds missing atomic slots without recreating or repinning history (owner changed: %s)",
412
+ async (hasChangedOwner) => {
413
+ const t = convexTest(schema, modules);
414
+ if (hasChangedOwner)
415
+ await t.mutation(register, logical("opaque_1", "historical-owner"));
416
+ const args = allocation("ch_missing_slot", 2);
417
+ const row = await t.mutation(reserve, args);
418
+ await t.run(async (ctx) => {
419
+ const leg = await ctx.db
420
+ .query("financialSourceLegs")
421
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
422
+ q.eq("allocationId", row._id).eq("legIndex", 1),
423
+ )
424
+ .unique();
425
+ await ctx.db.delete("financialSourceLegs", leg!._id);
426
+ if (hasChangedOwner) {
427
+ const registration = await ctx.db
428
+ .query("financialOwnership")
429
+ .withIndex("by_bucket_key", (q) => q.eq("bucketKey", "opaque_1"))
430
+ .unique();
431
+ await ctx.db.delete("financialOwnership", registration!._id);
432
+ }
433
+ });
434
+ if (hasChangedOwner)
435
+ await t.mutation(register, logical("opaque_1", "replacement-owner"));
436
+ const originalLegs = await t.run((ctx) =>
437
+ ctx.db
438
+ .query("financialSourceLegs")
439
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
440
+ q.eq("allocationId", row._id),
441
+ )
442
+ .take(101),
443
+ );
444
+ expect(await t.mutation(reserve, args)).toEqual(row);
445
+ const after = await t.query(source, { allocationId: row._id });
446
+ expect(after).toMatchObject({
447
+ coverage: "unknown",
448
+ observation: { isContradictory: true },
449
+ });
450
+ expect(
451
+ await t.run((ctx) =>
452
+ ctx.db
453
+ .query("financialSourceLegs")
454
+ .withIndex("by_allocation_id_and_leg_index", (q) =>
455
+ q.eq("allocationId", row._id),
456
+ )
457
+ .take(101),
458
+ ),
459
+ ).toEqual(originalLegs);
460
+ expect(
461
+ await t.query(owner, { userId: "replacement-owner", paginationOpts }),
462
+ ).toMatchObject({ coverage: "unknown", page: [] });
463
+ expect(await t.mutation(reserve, args)).toEqual(row);
464
+ expect(await t.query(source, { allocationId: row._id })).toEqual(after);
465
+ },
466
+ );