@fantastic.dev/better-stripe 0.63.0 → 0.64.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 (174) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +19 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +550 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +275 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +582 -32
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +291 -16
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/financialOwnership.d.ts +2 -2
  12. package/dist/client/financialOwnership.d.ts.map +1 -1
  13. package/dist/client/financialOwnership.js +2 -2
  14. package/dist/client/financialOwnership.js.map +1 -1
  15. package/dist/client/payoutRevisionMigration.d.ts +37 -0
  16. package/dist/client/payoutRevisionMigration.d.ts.map +1 -0
  17. package/dist/client/payoutRevisionMigration.js +49 -0
  18. package/dist/client/payoutRevisionMigration.js.map +1 -0
  19. package/dist/client/publicTypes.d.ts +2 -0
  20. package/dist/client/publicTypes.d.ts.map +1 -1
  21. package/dist/client/reversalObservations.d.ts +62 -0
  22. package/dist/client/reversalObservations.d.ts.map +1 -0
  23. package/dist/client/reversalObservations.js +79 -0
  24. package/dist/client/reversalObservations.js.map +1 -0
  25. package/dist/component/_generated/api.d.ts +28 -0
  26. package/dist/component/_generated/api.d.ts.map +1 -1
  27. package/dist/component/_generated/api.js.map +1 -1
  28. package/dist/component/_generated/component.d.ts +354 -0
  29. package/dist/component/_generated/component.d.ts.map +1 -1
  30. package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
  31. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  32. package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
  33. package/dist/component/connect/mutations.d.ts.map +1 -1
  34. package/dist/component/connect/mutations.js +2 -0
  35. package/dist/component/connect/mutations.js.map +1 -1
  36. package/dist/component/connect/reversalClaims.d.ts.map +1 -1
  37. package/dist/component/connect/reversalClaims.js +10 -1
  38. package/dist/component/connect/reversalClaims.js.map +1 -1
  39. package/dist/component/earnings/triggers.d.ts +408 -16
  40. package/dist/component/earnings/triggers.d.ts.map +1 -1
  41. package/dist/component/financialObservations/transferSchema.d.ts +1 -0
  42. package/dist/component/financialObservations/transferSchema.d.ts.map +1 -1
  43. package/dist/component/financialObservations/transferSchema.js +1 -0
  44. package/dist/component/financialObservations/transferSchema.js.map +1 -1
  45. package/dist/component/payoutRelease/queries.d.ts +2 -2
  46. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  47. package/dist/component/payoutRevisionJournal/mutations.d.ts +15 -0
  48. package/dist/component/payoutRevisionJournal/mutations.d.ts.map +1 -0
  49. package/dist/component/payoutRevisionJournal/mutations.js +11 -0
  50. package/dist/component/payoutRevisionJournal/mutations.js.map +1 -0
  51. package/dist/component/payoutRevisionJournal/schema.d.ts +45 -0
  52. package/dist/component/payoutRevisionJournal/schema.d.ts.map +1 -0
  53. package/dist/component/payoutRevisionJournal/schema.js +22 -0
  54. package/dist/component/payoutRevisionJournal/schema.js.map +1 -0
  55. package/dist/component/payoutRevisionJournal/state.d.ts +36 -0
  56. package/dist/component/payoutRevisionJournal/state.d.ts.map +1 -0
  57. package/dist/component/payoutRevisionJournal/state.js +111 -0
  58. package/dist/component/payoutRevisionJournal/state.js.map +1 -0
  59. package/dist/component/payoutRevisionMigration/mutations.d.ts +36 -0
  60. package/dist/component/payoutRevisionMigration/mutations.d.ts.map +1 -0
  61. package/dist/component/payoutRevisionMigration/mutations.js +126 -0
  62. package/dist/component/payoutRevisionMigration/mutations.js.map +1 -0
  63. package/dist/component/payoutRevisionMigration/queries.d.ts +38 -0
  64. package/dist/component/payoutRevisionMigration/queries.d.ts.map +1 -0
  65. package/dist/component/payoutRevisionMigration/queries.js +39 -0
  66. package/dist/component/payoutRevisionMigration/queries.js.map +1 -0
  67. package/dist/component/payoutRevisionMigration/schema.d.ts +115 -0
  68. package/dist/component/payoutRevisionMigration/schema.d.ts.map +1 -0
  69. package/dist/component/payoutRevisionMigration/schema.js +52 -0
  70. package/dist/component/payoutRevisionMigration/schema.js.map +1 -0
  71. package/dist/component/payoutSnapshots/legacyRevisionWriter.d.ts +4 -0
  72. package/dist/component/payoutSnapshots/legacyRevisionWriter.d.ts.map +1 -0
  73. package/dist/component/payoutSnapshots/legacyRevisionWriter.js +33 -0
  74. package/dist/component/payoutSnapshots/legacyRevisionWriter.js.map +1 -0
  75. package/dist/component/payoutSnapshots/revisions.d.ts.map +1 -1
  76. package/dist/component/payoutSnapshots/revisions.js +23 -29
  77. package/dist/component/payoutSnapshots/revisions.js.map +1 -1
  78. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  79. package/dist/component/refundSync/mutations.d.ts +1 -1
  80. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  81. package/dist/component/reversalObservations/capture.d.ts +6 -0
  82. package/dist/component/reversalObservations/capture.d.ts.map +1 -0
  83. package/dist/component/reversalObservations/capture.js +96 -0
  84. package/dist/component/reversalObservations/capture.js.map +1 -0
  85. package/dist/component/reversalObservations/indexSlice.d.ts +29 -0
  86. package/dist/component/reversalObservations/indexSlice.d.ts.map +1 -0
  87. package/dist/component/reversalObservations/indexSlice.js +101 -0
  88. package/dist/component/reversalObservations/indexSlice.js.map +1 -0
  89. package/dist/component/reversalObservations/integrity.d.ts +25 -0
  90. package/dist/component/reversalObservations/integrity.d.ts.map +1 -0
  91. package/dist/component/reversalObservations/integrity.js +19 -0
  92. package/dist/component/reversalObservations/integrity.js.map +1 -0
  93. package/dist/component/reversalObservations/mutations.d.ts +37 -0
  94. package/dist/component/reversalObservations/mutations.d.ts.map +1 -0
  95. package/dist/component/reversalObservations/mutations.js +181 -0
  96. package/dist/component/reversalObservations/mutations.js.map +1 -0
  97. package/dist/component/reversalObservations/pagination.d.ts +34 -0
  98. package/dist/component/reversalObservations/pagination.d.ts.map +1 -0
  99. package/dist/component/reversalObservations/pagination.js +31 -0
  100. package/dist/component/reversalObservations/pagination.js.map +1 -0
  101. package/dist/component/reversalObservations/queries.d.ts +221 -0
  102. package/dist/component/reversalObservations/queries.d.ts.map +1 -0
  103. package/dist/component/reversalObservations/queries.js +114 -0
  104. package/dist/component/reversalObservations/queries.js.map +1 -0
  105. package/dist/component/reversalObservations/references.d.ts +17 -0
  106. package/dist/component/reversalObservations/references.d.ts.map +1 -0
  107. package/dist/component/reversalObservations/references.js +95 -0
  108. package/dist/component/reversalObservations/references.js.map +1 -0
  109. package/dist/component/reversalObservations/schema.d.ts +525 -0
  110. package/dist/component/reversalObservations/schema.d.ts.map +1 -0
  111. package/dist/component/reversalObservations/schema.js +92 -0
  112. package/dist/component/reversalObservations/schema.js.map +1 -0
  113. package/dist/component/reversalObservations/selectors.d.ts +3 -0
  114. package/dist/component/reversalObservations/selectors.d.ts.map +1 -0
  115. package/dist/component/reversalObservations/selectors.js +8 -0
  116. package/dist/component/reversalObservations/selectors.js.map +1 -0
  117. package/dist/component/reversalObservations/state.d.ts +34 -0
  118. package/dist/component/reversalObservations/state.d.ts.map +1 -0
  119. package/dist/component/reversalObservations/state.js +34 -0
  120. package/dist/component/reversalObservations/state.js.map +1 -0
  121. package/dist/component/schema.d.ts +275 -0
  122. package/dist/component/schema.js +10 -0
  123. package/dist/component/schema.js.map +1 -1
  124. package/dist/component/usage/allowance.fixtures.d.ts +291 -16
  125. package/dist/component/usage/allowance.fixtures.d.ts.map +1 -1
  126. package/dist/component/usageCredits/accounting.fixtures.d.ts +275 -0
  127. package/dist/component/usageCredits/accounting.fixtures.d.ts.map +1 -1
  128. package/docs/README.md +2 -1
  129. package/docs/client-api.md +6 -0
  130. package/docs/financial-observations.md +51 -8
  131. package/docs/payout-revision-migration.md +54 -0
  132. package/docs/react-workflows-audit.md +73 -2
  133. package/docs/usage-example.md +4 -0
  134. package/package.json +3 -2
  135. package/src/client/financialOwnership.ts +2 -2
  136. package/src/client/payoutRevisionMigration.test.ts +40 -0
  137. package/src/client/payoutRevisionMigration.ts +96 -0
  138. package/src/client/publicTypes.ts +15 -0
  139. package/src/client/reversalObservations.test.ts +69 -0
  140. package/src/client/reversalObservations.ts +151 -0
  141. package/src/component/_generated/api.ts +28 -0
  142. package/src/component/_generated/component.ts +423 -0
  143. package/src/component/connect/mutations.ts +2 -0
  144. package/src/component/connect/reversalClaims.ts +13 -1
  145. package/src/component/financialObservations/transferSchema.ts +1 -0
  146. package/src/component/payoutRevisionJournal/mutations.ts +11 -0
  147. package/src/component/payoutRevisionJournal/schema.ts +34 -0
  148. package/src/component/payoutRevisionJournal/state.ts +141 -0
  149. package/src/component/payoutRevisionMigration/mutations.ts +135 -0
  150. package/src/component/payoutRevisionMigration/queries.ts +50 -0
  151. package/src/component/payoutRevisionMigration/schema.ts +51 -0
  152. package/src/component/payoutSnapshots/legacy-revisions.test.ts +246 -0
  153. package/src/component/payoutSnapshots/legacyRevisionWriter.ts +39 -0
  154. package/src/component/payoutSnapshots/revision-journal-callbacks.test.ts +160 -0
  155. package/src/component/payoutSnapshots/revision-journal-held.test.ts +94 -0
  156. package/src/component/payoutSnapshots/revision-journal.test.ts +310 -0
  157. package/src/component/payoutSnapshots/revision-migration.test.ts +128 -0
  158. package/src/component/payoutSnapshots/revisions.ts +22 -30
  159. package/src/component/reversalObservations/boundaries.test.ts +62 -0
  160. package/src/component/reversalObservations/capture-integrity.test.ts +119 -0
  161. package/src/component/reversalObservations/capture.ts +129 -0
  162. package/src/component/reversalObservations/continuation.test.ts +131 -0
  163. package/src/component/reversalObservations/indexSlice.ts +124 -0
  164. package/src/component/reversalObservations/integrity.ts +31 -0
  165. package/src/component/reversalObservations/lifecycle.test.ts +81 -0
  166. package/src/component/reversalObservations/mutations.ts +211 -0
  167. package/src/component/reversalObservations/pagination.ts +40 -0
  168. package/src/component/reversalObservations/provenance.test.ts +167 -0
  169. package/src/component/reversalObservations/queries.ts +121 -0
  170. package/src/component/reversalObservations/references.ts +134 -0
  171. package/src/component/reversalObservations/schema.ts +100 -0
  172. package/src/component/reversalObservations/selectors.ts +9 -0
  173. package/src/component/reversalObservations/state.ts +42 -0
  174. package/src/component/schema.ts +18 -0
@@ -0,0 +1,135 @@
1
+ import { paginator } from "convex-helpers/server/pagination";
2
+ import schema from "../schema.js";
3
+ import { generateIdempotencyKey } from "../lib/idempotency.js";
4
+ import { v } from "convex/values";
5
+ import { mutation } from "../_generated/server.js";
6
+ import { activateRevisionAccount } from "../payoutRevisionJournal/state.js";
7
+ import { inventoryTables, jobDoc } from "./schema.js";
8
+
9
+ /** Trusted-host layout inventory. This grants no financial coverage or eligibility. */
10
+ export const begin = mutation({
11
+ args: { operationKey: v.string() },
12
+ returns: jobDoc,
13
+ handler: async (ctx, { operationKey }) => {
14
+ if (!operationKey || operationKey.length > 256)
15
+ throw new Error("Invalid migration operation key.");
16
+ const prior = await ctx.db
17
+ .query("payoutRevisionMigrations")
18
+ .withIndex("by_operation", (q) => q.eq("operationKey", operationKey))
19
+ .unique();
20
+ if (prior) return prior;
21
+ const id = await ctx.db.insert("payoutRevisionMigrations", {
22
+ operationKey,
23
+ phase: 0,
24
+ cursor: null,
25
+ step: 0,
26
+ status: "running",
27
+ scanned: 0,
28
+ visited: 0,
29
+ activated: 0,
30
+ unchanged: 0,
31
+ held: 0,
32
+ });
33
+ return (await ctx.db.get("payoutRevisionMigrations", id))!;
34
+ },
35
+ });
36
+
37
+ /** One inventory row and at most one account activation per committed step. */
38
+ export const resume = mutation({
39
+ args: { jobId: v.id("payoutRevisionMigrations"), expectedStep: v.number() },
40
+ returns: jobDoc,
41
+ handler: async (ctx, { jobId, expectedStep }) => {
42
+ const job = await ctx.db.get("payoutRevisionMigrations", jobId);
43
+ if (!job) throw new Error("Migration not found.");
44
+ const counters = [
45
+ job.step,
46
+ job.scanned,
47
+ job.visited,
48
+ job.activated,
49
+ job.unchanged,
50
+ job.held,
51
+ ];
52
+ if (
53
+ counters.some(
54
+ (value) =>
55
+ !Number.isSafeInteger(value) ||
56
+ value < 0 ||
57
+ (job.status === "running" && value === Number.MAX_SAFE_INTEGER),
58
+ ) ||
59
+ !Number.isInteger(job.phase) ||
60
+ job.phase < 0 ||
61
+ (job.status === "running"
62
+ ? job.phase >= inventoryTables.length
63
+ : job.phase !== inventoryTables.length || job.cursor !== null) ||
64
+ BigInt(job.activated) + BigInt(job.unchanged) + BigInt(job.held) !==
65
+ BigInt(job.visited) ||
66
+ job.visited > job.scanned
67
+ )
68
+ throw new Error("Invalid migration job state.");
69
+ if (
70
+ !Number.isSafeInteger(expectedStep) ||
71
+ expectedStep < 0 ||
72
+ expectedStep > job.step
73
+ )
74
+ throw new Error("Invalid migration step.");
75
+ if (expectedStep < job.step || job.status === "finished") return job;
76
+ const table = inventoryTables[job.phase];
77
+ if (!table) throw new Error("Invalid migration inventory phase.");
78
+ const page = await paginator(ctx.db, schema).query(table).paginate({
79
+ numItems: 1,
80
+ cursor: job.cursor,
81
+ maximumRowsRead: 1,
82
+ maximumBytesRead: 1100000,
83
+ });
84
+ let activated = job.activated,
85
+ unchanged = job.unchanged,
86
+ held = job.held,
87
+ visited = job.visited;
88
+ for (const row of page.page) {
89
+ const accountId =
90
+ "destinationAccountId" in row
91
+ ? row.destinationAccountId
92
+ : row.accountId;
93
+ const accountDigest = await generateIdempotencyKey(
94
+ "payout-revision-migration-account",
95
+ { accountId },
96
+ );
97
+ const seen = await ctx.db
98
+ .query("payoutRevisionMigrationResults")
99
+ .withIndex("by_job_account", (q) =>
100
+ q.eq("jobId", jobId).eq("accountDigest", accountDigest),
101
+ )
102
+ .unique();
103
+ if (seen) continue;
104
+ const result = await activateRevisionAccount(ctx, accountId);
105
+ await ctx.db.insert("payoutRevisionMigrationResults", {
106
+ jobId,
107
+ status: result.status,
108
+ ...(result.status === "held" ? { reason: result.reason } : {}),
109
+ ...(new TextEncoder().encode(accountId).length <= 256
110
+ ? { accountId }
111
+ : {}),
112
+ accountDigest,
113
+ sourceId: row._id,
114
+ sourceTable: table,
115
+ });
116
+ visited++;
117
+ if (result.status === "activated") activated++;
118
+ else if (result.status === "unchanged") unchanged++;
119
+ else held++;
120
+ }
121
+ const phase = job.phase + (page.isDone ? 1 : 0);
122
+ await ctx.db.patch("payoutRevisionMigrations", jobId, {
123
+ phase,
124
+ cursor: page.isDone ? null : page.continueCursor,
125
+ step: job.step + 1,
126
+ scanned: job.scanned + page.page.length,
127
+ visited,
128
+ activated,
129
+ unchanged,
130
+ held,
131
+ status: phase === inventoryTables.length ? "finished" : "running",
132
+ });
133
+ return (await ctx.db.get("payoutRevisionMigrations", jobId))!;
134
+ },
135
+ });
@@ -0,0 +1,50 @@
1
+ import { paginator } from "convex-helpers/server/pagination";
2
+ import schema from "../schema.js";
3
+ import { paginationOptsValidator } from "convex/server";
4
+ import { v } from "convex/values";
5
+ import { query } from "../_generated/server.js";
6
+ import { jobDoc, resultDoc } from "./schema.js";
7
+ export const get = query({
8
+ args: { jobId: v.id("payoutRevisionMigrations") },
9
+ returns: v.union(jobDoc, v.null()),
10
+ handler: async (ctx, { jobId }) =>
11
+ ctx.db.get("payoutRevisionMigrations", jobId),
12
+ });
13
+ export const results = query({
14
+ args: {
15
+ jobId: v.id("payoutRevisionMigrations"),
16
+ paginationOpts: paginationOptsValidator,
17
+ },
18
+ returns: v.object({
19
+ page: v.array(resultDoc),
20
+ isDone: v.boolean(),
21
+ continueCursor: v.string(),
22
+ splitCursor: v.optional(v.union(v.string(), v.null())),
23
+ pageStatus: v.optional(
24
+ v.union(
25
+ v.literal("SplitRecommended"),
26
+ v.literal("SplitRequired"),
27
+ v.null(),
28
+ ),
29
+ ),
30
+ }),
31
+ handler: async (ctx, { jobId, paginationOpts }) => {
32
+ if (
33
+ !Number.isInteger(paginationOpts.numItems) ||
34
+ paginationOpts.numItems < 1 ||
35
+ paginationOpts.numItems > 100
36
+ )
37
+ throw new Error("Migration result page must contain 1 to 100 items.");
38
+ return paginator(ctx.db, schema)
39
+ .query("payoutRevisionMigrationResults")
40
+ .withIndex("by_job_account", (q) => q.eq("jobId", jobId))
41
+ .paginate({
42
+ ...paginationOpts,
43
+ maximumRowsRead: Math.min(paginationOpts.maximumRowsRead ?? 100, 100),
44
+ maximumBytesRead: Math.min(
45
+ paginationOpts.maximumBytesRead ?? 262144,
46
+ 262144,
47
+ ),
48
+ });
49
+ },
50
+ });
@@ -0,0 +1,51 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { activationResult } from "../payoutRevisionJournal/schema.js";
4
+ export const inventoryTables = [
5
+ "payoutFinancialRevisions",
6
+ "payoutRiskRevisions",
7
+ "transfers",
8
+ "payouts",
9
+ "recoveryBalances",
10
+ "payoutSourceAllocations",
11
+ "payoutReleaseClaims",
12
+ "payoutFeeBalances",
13
+ ] as const;
14
+ export const jobFields = {
15
+ operationKey: v.string(),
16
+ phase: v.number(),
17
+ cursor: v.union(v.string(), v.null()),
18
+ step: v.number(),
19
+ status: v.union(v.literal("running"), v.literal("finished")),
20
+ scanned: v.number(),
21
+ visited: v.number(),
22
+ activated: v.number(),
23
+ unchanged: v.number(),
24
+ held: v.number(),
25
+ };
26
+ export const jobDoc = v.object({
27
+ ...jobFields,
28
+ _id: v.id("payoutRevisionMigrations"),
29
+ _creationTime: v.number(),
30
+ });
31
+ export const jobsTable = defineTable(jobFields).index("by_operation", [
32
+ "operationKey",
33
+ ]);
34
+ const { accountId: _accountId, ...outcome } = activationResult.fields;
35
+ export const resultFields = {
36
+ jobId: v.id("payoutRevisionMigrations"),
37
+ ...outcome,
38
+ accountId: v.optional(v.string()),
39
+ accountDigest: v.string(),
40
+ sourceId: v.string(),
41
+ sourceTable: v.string(),
42
+ };
43
+ export const resultDoc = v.object({
44
+ ...resultFields,
45
+ _id: v.id("payoutRevisionMigrationResults"),
46
+ _creationTime: v.number(),
47
+ });
48
+ export const resultsTable = defineTable(resultFields).index("by_job_account", [
49
+ "jobId",
50
+ "accountDigest",
51
+ ]);
@@ -0,0 +1,246 @@
1
+ // @vitest-environment edge-runtime
2
+ // Preserve the shipped legacy path independently of canonical journal activation.
3
+ import { convexTest } from "convex-test";
4
+ import { makeFunctionReference } from "convex/server";
5
+ import { expect, it } from "vitest";
6
+ import { schema, modules } from "../../test.js";
7
+ const accountId = "acct_revision_compatibility";
8
+ const mutation = (name: string) =>
9
+ makeFunctionReference<"mutation">(`connect/mutations:${name}`);
10
+ const makeTest = () => convexTest(schema, modules);
11
+ type Test = ReturnType<typeof makeTest>;
12
+ async function state(t: Test) {
13
+ return t.run(async (ctx) => ({
14
+ financial: await ctx.db.query("payoutFinancialRevisions").take(10),
15
+ risk: await ctx.db.query("payoutRiskRevisions").take(10),
16
+ events: await ctx.db.query("payoutRiskEvents").take(10),
17
+ transfers: await ctx.db.query("transfers").take(10),
18
+ payouts: await ctx.db.query("payouts").take(10),
19
+ totals: await ctx.db.query("currencyTotals").take(10),
20
+ }));
21
+ }
22
+ async function seed(
23
+ t: Test,
24
+ financial?: { revision: number; riskRevision: number },
25
+ risk?: number,
26
+ duplicate?: "financial" | "risk",
27
+ ) {
28
+ await t.run(async (ctx) => {
29
+ if (financial) {
30
+ await ctx.db.insert("payoutFinancialRevisions", {
31
+ accountId,
32
+ ...financial,
33
+ });
34
+ if (duplicate === "financial")
35
+ await ctx.db.insert("payoutFinancialRevisions", {
36
+ accountId,
37
+ ...financial,
38
+ });
39
+ }
40
+ if (risk !== undefined) {
41
+ await ctx.db.insert("payoutRiskRevisions", {
42
+ accountId,
43
+ riskRevision: risk,
44
+ });
45
+ if (duplicate === "risk")
46
+ await ctx.db.insert("payoutRiskRevisions", {
47
+ accountId,
48
+ riskRevision: risk,
49
+ });
50
+ }
51
+ });
52
+ }
53
+ async function write(t: Test, isRisk = false, id = "one") {
54
+ if (isRisk)
55
+ return t.mutation(mutation("upsertPayout"), {
56
+ stripePayoutId: `po_${id}`,
57
+ accountId,
58
+ amount: 10,
59
+ currency: "usd",
60
+ status: "pending",
61
+ arrivalDate: "2026-10-17T00:00:00Z",
62
+ });
63
+ return t.mutation(mutation("upsertTransfer"), {
64
+ stripeTransferId: `tr_${id}`,
65
+ destinationAccountId: accountId,
66
+ amount: 10,
67
+ currency: "usd",
68
+ status: "paid",
69
+ role: "affiliate",
70
+ sourceChargeId: "ch_compatibility",
71
+ });
72
+ }
73
+ for (const c of [
74
+ {
75
+ name: "both absent",
76
+ financial: undefined,
77
+ risk: undefined,
78
+ isRisk: false,
79
+ expected: { revision: 1, riskRevision: 0 },
80
+ },
81
+ {
82
+ name: "financial only",
83
+ financial: { revision: 4, riskRevision: 3 },
84
+ risk: undefined,
85
+ isRisk: true,
86
+ expected: { revision: 5, riskRevision: 4 },
87
+ },
88
+ {
89
+ name: "risk only",
90
+ financial: undefined,
91
+ risk: 7,
92
+ isRisk: true,
93
+ expected: { revision: 1, riskRevision: 8 },
94
+ },
95
+ {
96
+ name: "equal pair",
97
+ financial: { revision: 4, riskRevision: 3 },
98
+ risk: 3,
99
+ isRisk: true,
100
+ expected: { revision: 5, riskRevision: 4 },
101
+ },
102
+ {
103
+ name: "signed safe legacy counters",
104
+ financial: { revision: -4, riskRevision: -3 },
105
+ risk: -3,
106
+ isRisk: true,
107
+ expected: { revision: -3, riskRevision: -2 },
108
+ },
109
+ {
110
+ name: "risk counter greater than financial",
111
+ financial: { revision: 2, riskRevision: 7 },
112
+ risk: 7,
113
+ isRisk: true,
114
+ expected: { revision: 3, riskRevision: 8 },
115
+ },
116
+ ])
117
+ it(`baseline accepts ${c.name} without invented conversion constraints`, async () => {
118
+ const t = makeTest();
119
+ await seed(t, c.financial, c.risk);
120
+ await write(t, c.isRisk);
121
+ const s = await state(t);
122
+ expect(s.financial).toMatchObject([{ accountId, ...c.expected }]);
123
+ expect(s.risk).toMatchObject([
124
+ { accountId, riskRevision: c.expected.riskRevision },
125
+ ]);
126
+ expect(s.events).toHaveLength(c.isRisk ? 1 : 0);
127
+ });
128
+ for (const c of [
129
+ {
130
+ name: "financial duplicate",
131
+ financial: { revision: 4, riskRevision: 3 },
132
+ risk: 3,
133
+ duplicate: "financial" as const,
134
+ },
135
+ {
136
+ name: "risk duplicate",
137
+ financial: { revision: 4, riskRevision: 3 },
138
+ risk: 3,
139
+ duplicate: "risk" as const,
140
+ },
141
+ {
142
+ name: "disagreement",
143
+ financial: { revision: 4, riskRevision: 3 },
144
+ risk: 2,
145
+ },
146
+ {
147
+ name: "unsafe financial NaN",
148
+ financial: { revision: Number.NaN, riskRevision: 3 },
149
+ risk: 3,
150
+ },
151
+ {
152
+ name: "unsafe financial infinity",
153
+ financial: { revision: Number.POSITIVE_INFINITY, riskRevision: 3 },
154
+ risk: 3,
155
+ },
156
+ {
157
+ name: "fractional financial",
158
+ financial: { revision: 4.5, riskRevision: 3 },
159
+ risk: 3,
160
+ },
161
+ {
162
+ name: "financial overflow",
163
+ financial: { revision: Number.MAX_SAFE_INTEGER, riskRevision: 3 },
164
+ risk: 3,
165
+ },
166
+ {
167
+ name: "risk overflow",
168
+ financial: { revision: 4, riskRevision: Number.MAX_SAFE_INTEGER },
169
+ risk: Number.MAX_SAFE_INTEGER,
170
+ },
171
+ ])
172
+ it(`baseline rejects ${c.name} and rolls back all callbacks`, async () => {
173
+ const t = makeTest();
174
+ await seed(t, c.financial, c.risk, c.duplicate);
175
+ const before = await state(t);
176
+ await expect(write(t, true)).rejects.toThrow();
177
+ expect(await state(t)).toEqual(before);
178
+ });
179
+ it("positive funding physically preserves the risk fence and risk-event journal", async () => {
180
+ const t = makeTest();
181
+ await write(t);
182
+ const before = await state(t);
183
+ await write(t, false, "two");
184
+ const after = await state(t);
185
+ expect(after.risk).toEqual(before.risk);
186
+ expect(after.events).toEqual(before.events);
187
+ expect(after.financial).toMatchObject([
188
+ { accountId, revision: 2, riskRevision: 0 },
189
+ ]);
190
+ });
191
+ import { financialRevision, riskRevision } from "./revisions.js";
192
+ for (const c of [
193
+ {
194
+ name: "both missing readers",
195
+ financial: undefined,
196
+ risk: undefined,
197
+ expectedFinancial: { revision: 0, riskRevision: 0 },
198
+ expectedRisk: 0,
199
+ },
200
+ {
201
+ name: "financial-only readers",
202
+ financial: { revision: 4, riskRevision: 3 },
203
+ risk: undefined,
204
+ expectedFinancial: { revision: 4, riskRevision: 3 },
205
+ expectedRisk: 3,
206
+ },
207
+ {
208
+ name: "risk-only readers",
209
+ financial: undefined,
210
+ risk: 7,
211
+ expectedFinancial: { revision: 0, riskRevision: 0 },
212
+ expectedRisk: 7,
213
+ },
214
+ {
215
+ name: "existing disagreement readers",
216
+ financial: { revision: 4, riskRevision: 3 },
217
+ risk: 2,
218
+ expectedFinancial: { revision: 4, riskRevision: 3 },
219
+ expectedRisk: 2,
220
+ },
221
+ {
222
+ name: "signed legacy readers",
223
+ financial: { revision: -4, riskRevision: -3 },
224
+ risk: -3,
225
+ expectedFinancial: { revision: -4, riskRevision: -3 },
226
+ expectedRisk: -3,
227
+ },
228
+ ])
229
+ it(`baseline preserves ${c.name} rather than unifying contradictory read semantics`, async () => {
230
+ const t = makeTest();
231
+ await seed(t, c.financial, c.risk);
232
+ expect(await t.run((ctx) => financialRevision(ctx, accountId))).toEqual(
233
+ c.expectedFinancial,
234
+ );
235
+ expect(await t.run((ctx) => riskRevision(ctx, accountId))).toBe(
236
+ c.expectedRisk,
237
+ );
238
+ });
239
+ it("risk reader does not inspect duplicate financial rows when an exact risk fence exists", async () => {
240
+ const t = makeTest();
241
+ await seed(t, { revision: 4, riskRevision: 3 }, 3, "financial");
242
+ expect(await t.run((ctx) => riskRevision(ctx, accountId))).toBe(3);
243
+ await expect(
244
+ t.run((ctx) => financialRevision(ctx, accountId)),
245
+ ).rejects.toThrow();
246
+ });
@@ -0,0 +1,39 @@
1
+ import type { MutationCtx } from "../_generated/server.js";
2
+ import { addSummaryAmounts as add } from "../earnings/arithmetic.js";
3
+
4
+ /** Preserve the legacy pair until this account explicitly activates its journal. */
5
+ export async function bumpLegacyRevision(
6
+ ctx: MutationCtx,
7
+ accountId: string,
8
+ risk: boolean,
9
+ ) {
10
+ const row = await ctx.db
11
+ .query("payoutFinancialRevisions")
12
+ .withIndex("by_account", (q) => q.eq("accountId", accountId))
13
+ .unique();
14
+ const fence = await ctx.db
15
+ .query("payoutRiskRevisions")
16
+ .withIndex("by_account", (q) => q.eq("accountId", accountId))
17
+ .unique();
18
+ if (row && fence && row.riskRevision !== fence.riskRevision)
19
+ throw new Error("Financial risk revisions disagree.");
20
+ const next = {
21
+ revision: add(row?.revision ?? 0, 1),
22
+ riskRevision: add(
23
+ fence?.riskRevision ?? row?.riskRevision ?? 0,
24
+ risk ? 1 : 0,
25
+ ),
26
+ };
27
+ if (row) await ctx.db.patch("payoutFinancialRevisions", row._id, next);
28
+ else await ctx.db.insert("payoutFinancialRevisions", { accountId, ...next });
29
+ if (!fence)
30
+ await ctx.db.insert("payoutRiskRevisions", {
31
+ accountId,
32
+ riskRevision: next.riskRevision,
33
+ });
34
+ else if (risk)
35
+ await ctx.db.patch("payoutRiskRevisions", fence._id, {
36
+ riskRevision: next.riskRevision,
37
+ });
38
+ return next.riskRevision;
39
+ }
@@ -0,0 +1,160 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { Triggers } from "convex-helpers/server/triggers";
4
+ import { expect, it } from "vitest";
5
+ import type { DataModel } from "../_generated/dataModel.js";
6
+ import { schema, modules } from "../../test.js";
7
+ import {
8
+ registerPayoutRevisions,
9
+ financialRevision,
10
+ riskRevision,
11
+ } from "./revisions.js";
12
+ import { activateRevisionAccount } from "../payoutRevisionJournal/state.js";
13
+ const makeTest = () => convexTest(schema, modules);
14
+ const triggers = new Triggers<DataModel>();
15
+ registerPayoutRevisions(triggers);
16
+ const scope = { accountId: "acct_canonical", ownerKey: "owner" };
17
+ const writes = [
18
+ {
19
+ table: "transfers" as const,
20
+ value: {
21
+ stripeTransferId: "tr_callback",
22
+ destinationAccountId: scope.accountId,
23
+ amount: 10,
24
+ currency: "usd",
25
+ role: "affiliate" as const,
26
+ status: "paid" as const,
27
+ reversedAmount: 1,
28
+ },
29
+ risk: true,
30
+ },
31
+ {
32
+ table: "payouts" as const,
33
+ value: {
34
+ stripePayoutId: "po_callback",
35
+ accountId: scope.accountId,
36
+ amount: 10,
37
+ currency: "usd",
38
+ status: "pending" as const,
39
+ arrivalDate: "2026-10-18",
40
+ },
41
+ risk: true,
42
+ },
43
+ {
44
+ table: "payoutSourceAllocations" as const,
45
+ value: {
46
+ ...scope,
47
+ stripeTransferId: "tr_callback",
48
+ currency: "usd",
49
+ paidAmount: 0,
50
+ reservedAmount: 10,
51
+ },
52
+ risk: true,
53
+ },
54
+ {
55
+ table: "payoutReleaseClaims" as const,
56
+ value: {
57
+ ...scope,
58
+ operationKey: "callback",
59
+ expectedRevision: 0,
60
+ currency: "usd",
61
+ amount: 10,
62
+ allocations: [],
63
+ observations: [],
64
+ status: "reserved" as const,
65
+ },
66
+ risk: true,
67
+ },
68
+ {
69
+ table: "payoutFeeBalances" as const,
70
+ value: { ...scope, currency: "usd", amount: 10, revision: 0 },
71
+ risk: true,
72
+ },
73
+ {
74
+ table: "recoveryBalances" as const,
75
+ value: {
76
+ accountId: scope.accountId,
77
+ scopeKey: "callback",
78
+ reservedAmount: 0,
79
+ outstanding: 10,
80
+ currency: "usd",
81
+ amountDue: 10,
82
+ collectedAmount: 0,
83
+ },
84
+ risk: true,
85
+ },
86
+ ];
87
+ for (const { table, value } of writes)
88
+ it(`preserves insert, replay, deletion and risk events for activated ${table}`, async () => {
89
+ const t = makeTest();
90
+ await t.run((ctx) => activateRevisionAccount(ctx, scope.accountId));
91
+ const id = await t.run(async (ctx) =>
92
+ triggers.wrapDB(ctx).db.insert(table, value),
93
+ );
94
+ expect(
95
+ await t.run((ctx) => financialRevision(ctx, scope.accountId)),
96
+ ).toEqual({ revision: 1, riskRevision: 1 });
97
+ expect(await t.run((ctx) => riskRevision(ctx, scope.accountId))).toBe(1);
98
+ await t.run(async (ctx) => triggers.wrapDB(ctx).db.patch(table, id, value));
99
+ expect(
100
+ await t.run((ctx) => financialRevision(ctx, scope.accountId)),
101
+ ).toEqual({ revision: 1, riskRevision: 1 });
102
+ await t.run(async (ctx) => triggers.wrapDB(ctx).db.delete(table, id));
103
+ expect(
104
+ await t.run((ctx) => financialRevision(ctx, scope.accountId)),
105
+ ).toEqual({ revision: 2, riskRevision: 2 });
106
+ const events = await t.run((ctx) =>
107
+ ctx.db.query("payoutRiskEvents").take(5),
108
+ );
109
+ expect(events).toHaveLength(2);
110
+ expect(events[1]).toMatchObject({
111
+ accountId: scope.accountId,
112
+ riskRevision: 2,
113
+ removed: true,
114
+ });
115
+ expect(
116
+ await t.run((ctx) => ctx.db.query("payoutFinancialRevisions").take(5)),
117
+ ).toEqual([]);
118
+ expect(
119
+ await t.run((ctx) => ctx.db.query("payoutRiskRevisions").take(5)),
120
+ ).toEqual([]);
121
+ });
122
+ it.each([true, false])(
123
+ "moves transfer accounts with the old account canonical=%s",
124
+ async (oldCanonical) => {
125
+ const t = makeTest();
126
+ const oldId = "acct_old";
127
+ const newId = "acct_new";
128
+ await t.run((ctx) =>
129
+ activateRevisionAccount(ctx, oldCanonical ? oldId : newId),
130
+ );
131
+ const id = await t.run((ctx) =>
132
+ triggers.wrapDB(ctx).db.insert("transfers", {
133
+ stripeTransferId: "tr_move",
134
+ destinationAccountId: oldId,
135
+ amount: 10,
136
+ currency: "usd",
137
+ role: "store",
138
+ status: "paid" as const,
139
+ }),
140
+ );
141
+ await t.run((ctx) =>
142
+ triggers
143
+ .wrapDB(ctx)
144
+ .db.patch("transfers", id, { destinationAccountId: newId }),
145
+ );
146
+ expect(await t.run((ctx) => financialRevision(ctx, oldId))).toEqual({
147
+ revision: 2,
148
+ riskRevision: 1,
149
+ });
150
+ expect(await t.run((ctx) => financialRevision(ctx, newId))).toEqual({
151
+ revision: 1,
152
+ riskRevision: 1,
153
+ });
154
+ const legacy = await t.run((ctx) =>
155
+ ctx.db.query("payoutFinancialRevisions").take(5),
156
+ );
157
+ expect(legacy).toHaveLength(1);
158
+ expect(legacy[0].accountId).toBe(oldCanonical ? newId : oldId);
159
+ },
160
+ );