@fantastic.dev/better-stripe 0.40.0 → 0.42.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 (183) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +1 -1
  3. package/dist/client/balanceFundingWorkflow/client.d.ts +172 -0
  4. package/dist/client/balanceFundingWorkflow/client.d.ts.map +1 -0
  5. package/dist/client/balanceFundingWorkflow/client.js +289 -0
  6. package/dist/client/balanceFundingWorkflow/client.js.map +1 -0
  7. package/dist/client/billing/balanceFunding.d.ts +5 -0
  8. package/dist/client/billing/balanceFunding.d.ts.map +1 -1
  9. package/dist/client/billing/balanceFunding.js +30 -0
  10. package/dist/client/billing/balanceFunding.js.map +1 -1
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +808 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +404 -1
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +808 -2
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +404 -1
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/costRecovery-invoices.d.ts +2 -2
  20. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  21. package/dist/client/costRecovery-invoices.js +4 -1
  22. package/dist/client/costRecovery-invoices.js.map +1 -1
  23. package/dist/client/costRecovery.d.ts +5 -2
  24. package/dist/client/costRecovery.d.ts.map +1 -1
  25. package/dist/client/costRecovery.js +3 -1
  26. package/dist/client/costRecovery.js.map +1 -1
  27. package/dist/client/index.d.ts +3 -0
  28. package/dist/client/index.d.ts.map +1 -1
  29. package/dist/client/index.js +4 -0
  30. package/dist/client/index.js.map +1 -1
  31. package/dist/client/recoveryWorkflow/client.d.ts +14 -0
  32. package/dist/client/recoveryWorkflow/client.d.ts.map +1 -0
  33. package/dist/client/recoveryWorkflow/client.js +34 -0
  34. package/dist/client/recoveryWorkflow/client.js.map +1 -0
  35. package/dist/client/recoveryWorkflow/contracts.d.ts +63 -0
  36. package/dist/client/recoveryWorkflow/contracts.d.ts.map +1 -0
  37. package/dist/client/recoveryWorkflow/contracts.js +11 -0
  38. package/dist/client/recoveryWorkflow/contracts.js.map +1 -0
  39. package/dist/client/recoveryWorkflow/provider.d.ts +10 -0
  40. package/dist/client/recoveryWorkflow/provider.d.ts.map +1 -0
  41. package/dist/client/recoveryWorkflow/provider.js +80 -0
  42. package/dist/client/recoveryWorkflow/provider.js.map +1 -0
  43. package/dist/client/recoveryWorkflow/settlement.d.ts +6 -0
  44. package/dist/client/recoveryWorkflow/settlement.d.ts.map +1 -0
  45. package/dist/client/recoveryWorkflow/settlement.js +43 -0
  46. package/dist/client/recoveryWorkflow/settlement.js.map +1 -0
  47. package/dist/component/_generated/api.d.ts +30 -0
  48. package/dist/component/_generated/api.d.ts.map +1 -1
  49. package/dist/component/_generated/api.js.map +1 -1
  50. package/dist/component/_generated/component.d.ts +637 -0
  51. package/dist/component/_generated/component.d.ts.map +1 -1
  52. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  53. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  54. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  55. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  56. package/dist/component/balanceFunding/internal/actions.js +80 -0
  57. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  58. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  59. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  60. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  61. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  62. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  63. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/internal/queries.js +35 -0
  65. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  66. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  67. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  68. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  69. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  70. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  71. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  72. package/dist/component/balanceFunding/mutations.d.ts +419 -16
  73. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  74. package/dist/component/balanceFunding/mutations.js +24 -0
  75. package/dist/component/balanceFunding/mutations.js.map +1 -1
  76. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  77. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  78. package/dist/component/balanceFunding/queries.d.ts +78 -0
  79. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  80. package/dist/component/balanceFunding/queries.js +35 -0
  81. package/dist/component/balanceFunding/queries.js.map +1 -1
  82. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  83. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  84. package/dist/component/balanceFunding/receipt.js +37 -0
  85. package/dist/component/balanceFunding/receipt.js.map +1 -0
  86. package/dist/component/balanceFunding/schema.d.ts +506 -2
  87. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  88. package/dist/component/balanceFunding/schema.js +2 -0
  89. package/dist/component/balanceFunding/schema.js.map +1 -1
  90. package/dist/component/balanceFunding/stateHandlers.d.ts +42 -0
  91. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  92. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  93. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  94. package/dist/component/balanceFunding/workflowControl.js +149 -0
  95. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  96. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  97. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  98. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  99. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  100. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  101. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  102. package/dist/component/balanceFunding/workflowState.js +194 -0
  103. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  104. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  105. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  106. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  107. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  108. package/dist/component/earnings/triggers.d.ts +280 -2
  109. package/dist/component/earnings/triggers.d.ts.map +1 -1
  110. package/dist/component/payoutRelease/queries.d.ts +2 -2
  111. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  112. package/dist/component/recoveryWorkflow/bridge.d.ts +21 -0
  113. package/dist/component/recoveryWorkflow/bridge.d.ts.map +1 -0
  114. package/dist/component/recoveryWorkflow/bridge.js +52 -0
  115. package/dist/component/recoveryWorkflow/bridge.js.map +1 -0
  116. package/dist/component/recoveryWorkflow/helpers.d.ts +83 -0
  117. package/dist/component/recoveryWorkflow/helpers.d.ts.map +1 -0
  118. package/dist/component/recoveryWorkflow/helpers.js +48 -0
  119. package/dist/component/recoveryWorkflow/helpers.js.map +1 -0
  120. package/dist/component/recoveryWorkflow/mutations.d.ts +91 -0
  121. package/dist/component/recoveryWorkflow/mutations.d.ts.map +1 -0
  122. package/dist/component/recoveryWorkflow/mutations.js +177 -0
  123. package/dist/component/recoveryWorkflow/mutations.js.map +1 -0
  124. package/dist/component/recoveryWorkflow/queries.d.ts +118 -0
  125. package/dist/component/recoveryWorkflow/queries.d.ts.map +1 -0
  126. package/dist/component/recoveryWorkflow/queries.js +20 -0
  127. package/dist/component/recoveryWorkflow/queries.js.map +1 -0
  128. package/dist/component/recoveryWorkflow/schema.d.ts +653 -0
  129. package/dist/component/recoveryWorkflow/schema.d.ts.map +1 -0
  130. package/dist/component/recoveryWorkflow/schema.js +81 -0
  131. package/dist/component/recoveryWorkflow/schema.js.map +1 -0
  132. package/dist/component/recoveryWorkflow/steps.d.ts +70 -0
  133. package/dist/component/recoveryWorkflow/steps.d.ts.map +1 -0
  134. package/dist/component/recoveryWorkflow/steps.js +94 -0
  135. package/dist/component/recoveryWorkflow/steps.js.map +1 -0
  136. package/dist/component/recoveryWorkflow/workflow.d.ts +22 -0
  137. package/dist/component/recoveryWorkflow/workflow.d.ts.map +1 -0
  138. package/dist/component/recoveryWorkflow/workflow.js +56 -0
  139. package/dist/component/recoveryWorkflow/workflow.js.map +1 -0
  140. package/dist/component/schema.d.ts +404 -1
  141. package/dist/component/schema.js +3 -0
  142. package/dist/component/schema.js.map +1 -1
  143. package/package.json +1 -1
  144. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  145. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  146. package/src/client/billing/balanceFunding.ts +50 -0
  147. package/src/client/costRecovery-invoices.ts +6 -0
  148. package/src/client/costRecovery.ts +8 -3
  149. package/src/client/index.ts +15 -0
  150. package/src/client/recoveryWorkflow/client.test.ts +37 -0
  151. package/src/client/recoveryWorkflow/client.ts +76 -0
  152. package/src/client/recoveryWorkflow/contracts.ts +72 -0
  153. package/src/client/recoveryWorkflow/provider.test.ts +424 -0
  154. package/src/client/recoveryWorkflow/provider.ts +119 -0
  155. package/src/client/recoveryWorkflow/settlement.ts +67 -0
  156. package/src/component/_generated/api.ts +30 -0
  157. package/src/component/_generated/component.ts +746 -0
  158. package/src/component/balanceFunding/internal/actions.ts +107 -0
  159. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  160. package/src/component/balanceFunding/internal/queries.ts +34 -0
  161. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  162. package/src/component/balanceFunding/mutations.ts +34 -0
  163. package/src/component/balanceFunding/queries.ts +38 -0
  164. package/src/component/balanceFunding/receipt.ts +48 -0
  165. package/src/component/balanceFunding/schema.ts +2 -0
  166. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  167. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  168. package/src/component/balanceFunding/workflow.test.ts +552 -0
  169. package/src/component/balanceFunding/workflowControl.ts +198 -0
  170. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  171. package/src/component/balanceFunding/workflowState.ts +285 -0
  172. package/src/component/balanceFunding/workflowValidators.ts +40 -0
  173. package/src/component/recoveryWorkflow/bridge.test.ts +481 -0
  174. package/src/component/recoveryWorkflow/bridge.ts +66 -0
  175. package/src/component/recoveryWorkflow/helpers.ts +58 -0
  176. package/src/component/recoveryWorkflow/journal.test.ts +104 -0
  177. package/src/component/recoveryWorkflow/mutations.ts +224 -0
  178. package/src/component/recoveryWorkflow/queries.ts +19 -0
  179. package/src/component/recoveryWorkflow/schema.ts +92 -0
  180. package/src/component/recoveryWorkflow/state.test.ts +191 -0
  181. package/src/component/recoveryWorkflow/steps.ts +97 -0
  182. package/src/component/recoveryWorkflow/workflow.ts +73 -0
  183. package/src/component/schema.ts +6 -0
@@ -0,0 +1,224 @@
1
+ import { allocationFields } from "../settlement/schema.js";
2
+ import { anyApi, type FunctionReference } from "convex/server";
3
+ import type { WorkflowId } from "@convex-dev/workflow";
4
+ import { mutation } from "../_generated/server.js";
5
+ import { executionWorkflow } from "../durableExecution/runtime.js";
6
+ import { validateScope } from "../costRecovery/helpers.js";
7
+ import {
8
+ bindingFields,
9
+ startFields,
10
+ startResult,
11
+ refFields,
12
+ safeStatus,
13
+ } from "./schema.js";
14
+ import { identityConflict, read, reference, same, status } from "./helpers.js";
15
+ const workflow = anyApi.recoveryWorkflow.workflow.run as FunctionReference<
16
+ "mutation",
17
+ "internal"
18
+ >;
19
+ export const start = mutation({
20
+ args: startFields,
21
+ returns: startResult,
22
+ handler: async (ctx, args) => {
23
+ validateScope(args);
24
+ if (
25
+ !args.requestKey ||
26
+ !args.provider ||
27
+ !/^\d{4}-\d{2}-\d{2}\.[a-z][a-z0-9_.-]*$/.test(args.providerApiVersion) ||
28
+ args.definitionVersion !== 1 ||
29
+ !Number.isSafeInteger(args.maxAttempts) ||
30
+ args.maxAttempts < 1 ||
31
+ args.maxAttempts > 20 ||
32
+ !Number.isSafeInteger(args.retryDelayMs) ||
33
+ args.retryDelayMs < 1 ||
34
+ args.retryDelayMs > 86400000
35
+ )
36
+ throw new Error("Invalid recovery workflow policy.");
37
+ const { requestKey, ...binding } = args;
38
+ const request = await ctx.db
39
+ .query("recoveryWorkflowRequests")
40
+ .withIndex("by_key", (q) => q.eq("requestKey", requestKey))
41
+ .unique();
42
+ if (request) {
43
+ if (!same(request.binding, binding)) return identityConflict;
44
+ return status(
45
+ (await ctx.db.get("recoveryWorkflowOperations", request.operationId))!,
46
+ );
47
+ }
48
+ const group = await ctx.db
49
+ .query("recoveryGroups")
50
+ .withIndex("by_key", (q) => q.eq("groupKey", args.groupKey))
51
+ .unique();
52
+ if (
53
+ !group ||
54
+ group.accountId !== args.accountId ||
55
+ group.scopeKey !== args.scopeKey ||
56
+ group.currency !== args.currency
57
+ )
58
+ return identityConflict;
59
+ const existing = await ctx.db
60
+ .query("recoveryWorkflowOperations")
61
+ .withIndex("by_group", (q) => q.eq("groupKey", args.groupKey))
62
+ .unique();
63
+ if (existing) {
64
+ const saved = Object.fromEntries(
65
+ Object.keys(bindingFields).map((k) => [
66
+ k,
67
+ existing[k as keyof typeof existing],
68
+ ]),
69
+ );
70
+ if (!same(saved, binding)) return identityConflict;
71
+ await ctx.db.insert("recoveryWorkflowRequests", {
72
+ requestKey,
73
+ binding,
74
+ operationId: existing._id,
75
+ });
76
+ return status(existing);
77
+ }
78
+ if (group.status !== "sealed")
79
+ return {
80
+ status: "not_ready",
81
+ reason: "history_incomplete",
82
+ retryable: true,
83
+ } as const;
84
+ if (group.sourceKind === "settlement") {
85
+ const a = args.allocation;
86
+ if (
87
+ !a ||
88
+ a.sourceChargeId !== group.sourceId ||
89
+ a.currency !== group.currency ||
90
+ a.gross !== group.sourceGross ||
91
+ a.processingFee !== group.sourceProcessingFee ||
92
+ (a.adjustmentAmount ?? 0) !== group.amount
93
+ )
94
+ return identityConflict;
95
+ const priorOperation = await ctx.db
96
+ .query("recoveryWorkflowOperations")
97
+ .withIndex("by_source", (q) =>
98
+ q.eq("sourceKind", "settlement").eq("sourceId", group.sourceId),
99
+ )
100
+ .first();
101
+ if (priorOperation) return identityConflict;
102
+ const prior = await ctx.db
103
+ .query("settlementAllocations")
104
+ .withIndex("by_source_charge", (q) =>
105
+ q.eq("sourceChargeId", a.sourceChargeId),
106
+ )
107
+ .first();
108
+ if (
109
+ prior &&
110
+ !same(
111
+ Object.fromEntries(
112
+ Object.keys(allocationFields).map((k) => [
113
+ k,
114
+ prior[k as keyof typeof prior],
115
+ ]),
116
+ ),
117
+ a,
118
+ )
119
+ )
120
+ return identityConflict;
121
+ await ctx.runMutation(
122
+ anyApi.settlement.mutations.reserveSettlementAllocation,
123
+ a,
124
+ );
125
+ } else if (args.allocation) return identityConflict;
126
+ const operationId = await ctx.db.insert("recoveryWorkflowOperations", {
127
+ ...binding,
128
+ sourceKind: group.sourceKind,
129
+ sourceId: group.sourceId,
130
+ version: 1,
131
+ status: "queued",
132
+ cancelRequested: false,
133
+ providerStarted: false,
134
+ resumeQueued: false,
135
+ });
136
+ const op = (await ctx.db.get("recoveryWorkflowOperations", operationId))!;
137
+ await ctx.db.insert("recoveryWorkflowRequests", {
138
+ requestKey,
139
+ binding,
140
+ operationId,
141
+ });
142
+ const workflowId = await executionWorkflow.start(
143
+ ctx,
144
+ workflow,
145
+ { ...reference(op), initialPhase: "execute" },
146
+ { startAsync: true },
147
+ );
148
+ await ctx.db.patch("recoveryWorkflowOperations", operationId, {
149
+ workflowId,
150
+ });
151
+ return status(op);
152
+ },
153
+ });
154
+ export const requestCancel = mutation({
155
+ args: refFields,
156
+ returns: safeStatus,
157
+ handler: async (ctx, args) => {
158
+ const op = await read(ctx, args);
159
+ if (op.status === "completed" || op.status === "canceled")
160
+ return status(op);
161
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
162
+ cancelRequested: true,
163
+ });
164
+ return status((await ctx.db.get("recoveryWorkflowOperations", op._id))!);
165
+ },
166
+ });
167
+ export const resume = mutation({
168
+ args: refFields,
169
+ returns: safeStatus,
170
+ handler: async (ctx, args) => {
171
+ const op = await read(ctx, args);
172
+ const workflowStatus = await executionWorkflow.status(
173
+ ctx,
174
+ op.workflowId as WorkflowId,
175
+ );
176
+ if (workflowStatus.type === "failed") {
177
+ const last = (
178
+ await executionWorkflow.listSteps(ctx, op.workflowId as WorkflowId, {
179
+ order: "desc",
180
+ paginationOpts: { cursor: null, numItems: 1 },
181
+ })
182
+ ).page[0];
183
+ if (
184
+ last &&
185
+ ["receipt", "finish", "completion"].includes(last.name) &&
186
+ last.runResult?.kind === "failed"
187
+ )
188
+ await executionWorkflow.restart(ctx, op.workflowId as WorkflowId, {
189
+ from: last.stepNumber,
190
+ startAsync: true,
191
+ });
192
+ else {
193
+ // A bounded/exhausted or unjournaled provider segment must never
194
+ // replay an execute phase. Keep the same operation and money keys.
195
+ const workflowId = await executionWorkflow.start(
196
+ ctx,
197
+ workflow,
198
+ { ...reference(op), initialPhase: "reconcile" },
199
+ { startAsync: true },
200
+ );
201
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
202
+ workflowId,
203
+ resumeQueued: false,
204
+ status: op.outcome ? "running" : "queued",
205
+ });
206
+ }
207
+ return status((await ctx.db.get("recoveryWorkflowOperations", op._id))!);
208
+ }
209
+ if (
210
+ (op.status === "unknown" || op.status === "waiting") &&
211
+ !op.resumeQueued
212
+ ) {
213
+ await executionWorkflow.sendEvent(ctx, {
214
+ workflowId: op.workflowId as WorkflowId,
215
+ name: "reconcile",
216
+ value: null,
217
+ });
218
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
219
+ resumeQueued: true,
220
+ });
221
+ }
222
+ return status((await ctx.db.get("recoveryWorkflowOperations", op._id))!);
223
+ },
224
+ });
@@ -0,0 +1,19 @@
1
+ import { query, internalQuery } from "../_generated/server.js";
2
+ import { refFields, safeStatus, operationDoc } from "./schema.js";
3
+ import { read, status } from "./helpers.js";
4
+ export const get = query({
5
+ args: refFields,
6
+ returns: safeStatus,
7
+ handler: async (ctx, args) => status(await read(ctx, args)),
8
+ });
9
+ /** Authorized host action reads the pinned public inputs; credentials are never stored here. */
10
+ export const snapshot = query({
11
+ args: refFields,
12
+ returns: operationDoc,
13
+ handler: read,
14
+ });
15
+ export const saved = internalQuery({
16
+ args: refFields,
17
+ returns: operationDoc,
18
+ handler: read,
19
+ });
@@ -0,0 +1,92 @@
1
+ import { defineTable } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { scopeFields } from "../costRecovery/schema.js";
4
+ import { allocationFields } from "../settlement/schema.js";
5
+ export const bindingFields = {
6
+ ...scopeFields,
7
+ groupKey: v.string(),
8
+ provider: v.string(),
9
+ completion: v.optional(v.string()),
10
+ providerApiVersion: v.string(),
11
+ definitionVersion: v.number(),
12
+ releaseUncollectible: v.boolean(),
13
+ maxAttempts: v.number(),
14
+ retryDelayMs: v.number(),
15
+ allocation: v.optional(v.object(allocationFields)),
16
+ };
17
+ export const startFields = { ...bindingFields, requestKey: v.string() };
18
+ export const refFields = {
19
+ ...scopeFields,
20
+ groupKey: v.string(),
21
+ operationId: v.id("recoveryWorkflowOperations"),
22
+ version: v.number(),
23
+ };
24
+ export const phase = v.union(v.literal("execute"), v.literal("reconcile"));
25
+ export const operationFields = {
26
+ ...bindingFields,
27
+ version: v.number(),
28
+ sourceKind: v.union(v.literal("settlement"), v.literal("invoice")),
29
+ sourceId: v.string(),
30
+ workflowId: v.optional(v.string()),
31
+ status: v.union(
32
+ v.literal("queued"),
33
+ v.literal("running"),
34
+ v.literal("waiting"),
35
+ v.literal("unknown"),
36
+ v.literal("completed"),
37
+ v.literal("canceled"),
38
+ ),
39
+ cancelRequested: v.boolean(),
40
+ providerStarted: v.boolean(),
41
+ activePhase: v.optional(phase),
42
+ resumeQueued: v.boolean(),
43
+ outcome: v.optional(v.union(v.literal("collect"), v.literal("release"))),
44
+ };
45
+ export const operationsTable = defineTable(operationFields)
46
+ .index("by_group", ["groupKey"])
47
+ .index("by_source", ["sourceKind", "sourceId"]);
48
+ export const requestsTable = defineTable({
49
+ requestKey: v.string(),
50
+ binding: v.object(bindingFields),
51
+ operationId: v.id("recoveryWorkflowOperations"),
52
+ }).index("by_key", ["requestKey"]);
53
+ export const operationDoc = v.object({
54
+ ...operationFields,
55
+ _id: v.id("recoveryWorkflowOperations"),
56
+ _creationTime: v.number(),
57
+ });
58
+ export const statusFields = {
59
+ ...refFields,
60
+ sourceKind: v.union(v.literal("settlement"), v.literal("invoice")),
61
+ sourceId: v.string(),
62
+ status: operationFields.status,
63
+ cancelRequested: v.boolean(),
64
+ outcome: operationFields.outcome,
65
+ };
66
+ export const safeStatus = v.object(statusFields);
67
+ export const conflict = v.object({
68
+ status: v.literal("conflict"),
69
+ reason: v.literal("identity_changed"),
70
+ retryable: v.literal(false),
71
+ });
72
+ export const unavailable = v.object({
73
+ status: v.literal("not_ready"),
74
+ reason: v.literal("history_incomplete"),
75
+ retryable: v.literal(true),
76
+ });
77
+ export const startResult = v.union(safeStatus, conflict, unavailable);
78
+ export const receipt = v.union(
79
+ v.object({
80
+ status: v.literal("ready"),
81
+ outcome: v.union(v.literal("collect"), v.literal("release")),
82
+ }),
83
+ v.object({
84
+ status: v.literal("not_ready"),
85
+ reason: v.literal("provider_pending"),
86
+ }),
87
+ v.object({
88
+ status: v.literal("unknown"),
89
+ reason: v.literal("provider_outcome_unknown"),
90
+ }),
91
+ v.object({ status: v.literal("canceled") }),
92
+ );
@@ -0,0 +1,191 @@
1
+ import { convexTest } from "convex-test";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import { makeFunctionReference } from "convex/server";
4
+ import { expect, it } from "vitest";
5
+ import { modules, schema } from "../../test.js";
6
+ const start = makeFunctionReference<"mutation">(
7
+ "recoveryWorkflow/mutations:start",
8
+ );
9
+ const scope = {
10
+ accountId: "acct_a",
11
+ scopeKey: "seller",
12
+ currency: "usd",
13
+ groupKey: "group",
14
+ };
15
+ async function fixture() {
16
+ const t = convexTest(schema, modules);
17
+ workflowTest.register(t, "workflow");
18
+ await t.run(async (ctx) => {
19
+ await ctx.db.insert("recoveryGroups", {
20
+ ...scope,
21
+ sourceKind: "invoice",
22
+ sourceId: "in_a",
23
+ maxDebit: 100,
24
+ maxCredit: 0,
25
+ amount: 0,
26
+ pendingOperations: 0,
27
+ status: "sealed",
28
+ });
29
+ });
30
+ return t;
31
+ }
32
+ const args = {
33
+ ...scope,
34
+ requestKey: "request",
35
+ provider: "function://host/provider",
36
+ providerApiVersion: "2026-09-30.endive",
37
+ definitionVersion: 1,
38
+ releaseUncollectible: false,
39
+ maxAttempts: 3,
40
+ retryDelayMs: 1000,
41
+ };
42
+ it("binds duplicate requests to one operation and rejects changed policy", async () => {
43
+ const t = await fixture();
44
+ const first = await t.mutation(start, args);
45
+ expect(await t.mutation(start, args)).toEqual(first);
46
+ expect(
47
+ await t.mutation(start, { ...args, releaseUncollectible: true }),
48
+ ).toEqual({
49
+ status: "conflict",
50
+ reason: "identity_changed",
51
+ retryable: false,
52
+ });
53
+ expect(
54
+ await t.run((ctx) => ctx.db.query("recoveryWorkflowOperations").collect()),
55
+ ).toHaveLength(1);
56
+ });
57
+ it("does not expose operations through another authorized scope", async () => {
58
+ const t = await fixture();
59
+ await t.mutation(start, args);
60
+ expect(
61
+ await t.mutation(start, {
62
+ ...args,
63
+ requestKey: "other",
64
+ accountId: "acct_b",
65
+ }),
66
+ ).toEqual({
67
+ status: "conflict",
68
+ reason: "identity_changed",
69
+ retryable: false,
70
+ });
71
+ });
72
+ it("rejects a second group that would reuse the same settlement adjustment", async () => {
73
+ const t = await fixture();
74
+ const allocation = {
75
+ sourceChargeId: "ch_a",
76
+ currency: "usd",
77
+ gross: 100,
78
+ processingFee: 10,
79
+ platformNet: 90,
80
+ adjustmentAmount: 0,
81
+ transfers: [],
82
+ };
83
+ await t.run(async (ctx) => {
84
+ for (const groupKey of ["settle_a", "settle_b"])
85
+ await ctx.db.insert("recoveryGroups", {
86
+ ...scope,
87
+ groupKey,
88
+ sourceKind: "settlement",
89
+ sourceId: "ch_a",
90
+ sourceGross: 100,
91
+ sourceProcessingFee: 10,
92
+ maxDebit: 100,
93
+ maxCredit: 0,
94
+ amount: 0,
95
+ pendingOperations: 0,
96
+ status: "sealed",
97
+ });
98
+ });
99
+ await t.mutation(start, { ...args, groupKey: "settle_a", allocation });
100
+ expect(
101
+ await t.mutation(start, {
102
+ ...args,
103
+ groupKey: "settle_b",
104
+ requestKey: "second",
105
+ allocation,
106
+ }),
107
+ ).toEqual({
108
+ status: "conflict",
109
+ reason: "identity_changed",
110
+ retryable: false,
111
+ });
112
+ });
113
+ it("compares every existing allocation field even when optional requested fields are absent", async () => {
114
+ const t = await fixture();
115
+ const allocation = {
116
+ sourceChargeId: "ch_a",
117
+ currency: "usd",
118
+ gross: 100,
119
+ processingFee: 10,
120
+ platformNet: 90,
121
+ transfers: [],
122
+ };
123
+ await t.run(async (ctx) => {
124
+ await ctx.db.insert("recoveryGroups", {
125
+ ...scope,
126
+ groupKey: "settle",
127
+ sourceKind: "settlement",
128
+ sourceId: "ch_a",
129
+ sourceGross: 100,
130
+ sourceProcessingFee: 10,
131
+ maxDebit: 100,
132
+ maxCredit: 0,
133
+ amount: 0,
134
+ pendingOperations: 0,
135
+ status: "sealed",
136
+ });
137
+ await ctx.db.insert("settlementAllocations", {
138
+ ...allocation,
139
+ paymentId: "original_payment",
140
+ });
141
+ });
142
+ expect(
143
+ await t.mutation(start, { ...args, groupKey: "settle", allocation }),
144
+ ).toEqual({
145
+ status: "conflict",
146
+ reason: "identity_changed",
147
+ retryable: false,
148
+ });
149
+ });
150
+ it("concurrent aliases join one immutable group operation", async () => {
151
+ const t = await fixture();
152
+ const outcomes = await Promise.all([
153
+ t.mutation(start, args),
154
+ t.mutation(start, { ...args, requestKey: "alias" }),
155
+ ]);
156
+ expect(outcomes[0].operationId).toBe(outcomes[1].operationId);
157
+ expect(
158
+ await t.run((ctx) => ctx.db.query("recoveryWorkflowOperations").collect()),
159
+ ).toHaveLength(1);
160
+ expect(
161
+ await t.run((ctx) => ctx.db.query("recoveryWorkflowRequests").collect()),
162
+ ).toHaveLength(2);
163
+ });
164
+ it("admits execution only after preparation has sealed the group", async () => {
165
+ const t = await fixture();
166
+ await t.run(async (ctx) => {
167
+ const group = (await ctx.db.query("recoveryGroups").first())!;
168
+ await ctx.db.patch(group._id, { status: "open" });
169
+ });
170
+ expect(await t.mutation(start, args)).toEqual({
171
+ status: "not_ready",
172
+ reason: "history_incomplete",
173
+ retryable: true,
174
+ });
175
+ expect(
176
+ await t.run((ctx) => ctx.db.query("recoveryWorkflowRequests").collect()),
177
+ ).toHaveLength(0);
178
+ });
179
+ it.each([
180
+ { maxAttempts: 0 },
181
+ { maxAttempts: 21 },
182
+ { retryDelayMs: 0 },
183
+ { retryDelayMs: 86400001 },
184
+ { providerApiVersion: "sk_test_not_a_version" },
185
+ { definitionVersion: 2 },
186
+ ])("rejects invalid durable execution policy %j", async (patch) => {
187
+ const t = await fixture();
188
+ await expect(t.mutation(start, { ...args, ...patch })).rejects.toThrow(
189
+ "Invalid recovery workflow policy",
190
+ );
191
+ });
@@ -0,0 +1,97 @@
1
+ import { type FunctionHandle } from "convex/server";
2
+ import { v } from "convex/values";
3
+ import { internalMutation } from "../_generated/server.js";
4
+ import { finishGroup } from "../costRecovery/completion.js";
5
+ import { refFields, phase, receipt, safeStatus } from "./schema.js";
6
+ import { read, status } from "./helpers.js";
7
+ export const beginProvider = internalMutation({
8
+ args: { ...refFields, phase },
9
+ returns: v.boolean(),
10
+ handler: async (ctx, args) => {
11
+ const op = await read(ctx, args);
12
+ if (op.status === "completed" || op.status === "canceled") return false;
13
+ if (op.cancelRequested && !op.providerStarted) {
14
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
15
+ status: "canceled",
16
+ });
17
+ return false;
18
+ }
19
+ if (args.phase === "execute" && op.providerStarted)
20
+ throw new Error("Recovery provider execution has already started.");
21
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
22
+ status: "running",
23
+ providerStarted: true,
24
+ activePhase: args.phase,
25
+ resumeQueued: false,
26
+ });
27
+ return true;
28
+ },
29
+ });
30
+ export const saveReceipt = internalMutation({
31
+ args: { ...refFields, result: receipt },
32
+ returns: safeStatus,
33
+ handler: async (ctx, args) => {
34
+ const op = await read(ctx, args);
35
+ if (args.result.status === "ready") {
36
+ if (op.sourceKind === "settlement" && args.result.outcome !== "collect")
37
+ throw new Error("Settlement recovery cannot release after execution.");
38
+ if (op.outcome && op.outcome !== args.result.outcome)
39
+ throw new Error("Recovery receipt outcome cannot change.");
40
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
41
+ outcome: args.result.outcome,
42
+ status: "running",
43
+ });
44
+ } else if (args.result.status !== "canceled")
45
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
46
+ status:
47
+ args.result.status === "unknown" || op.cancelRequested
48
+ ? "unknown"
49
+ : "waiting",
50
+ });
51
+ return status((await ctx.db.get("recoveryWorkflowOperations", op._id))!);
52
+ },
53
+ });
54
+ export const finish = internalMutation({
55
+ args: refFields,
56
+ returns: v.boolean(),
57
+ handler: async (ctx, args) => {
58
+ const op = await read(ctx, args);
59
+ if (!op.outcome) throw new Error("Verified recovery receipt is required.");
60
+ return (
61
+ await finishGroup(ctx, { groupKey: op.groupKey, outcome: op.outcome })
62
+ ).isDone;
63
+ },
64
+ });
65
+ export const complete = internalMutation({
66
+ args: refFields,
67
+ returns: safeStatus,
68
+ handler: async (ctx, args) => {
69
+ const op = await read(ctx, args);
70
+ if (op.status === "completed") return status(op);
71
+ const group = await ctx.db
72
+ .query("recoveryGroups")
73
+ .withIndex("by_key", (q) => q.eq("groupKey", op.groupKey))
74
+ .unique();
75
+ if (
76
+ !op.outcome ||
77
+ group?.status !== (op.outcome === "collect" ? "collected" : "released")
78
+ )
79
+ throw new Error("Recovery collection is incomplete.");
80
+ const completed = { ...status(op), status: "completed" as const };
81
+ // This callback and terminal status commit atomically; callback must be DB-only.
82
+ if (op.completion) {
83
+ try {
84
+ await ctx.runMutation(
85
+ op.completion as FunctionHandle<"mutation">,
86
+ completed,
87
+ );
88
+ } catch {
89
+ throw new Error("Recovery completion callback failed.");
90
+ }
91
+ }
92
+ await ctx.db.patch("recoveryWorkflowOperations", op._id, {
93
+ status: "completed",
94
+ });
95
+ return completed;
96
+ },
97
+ });
@@ -0,0 +1,73 @@
1
+ import { financialRetryDecision } from "../../client/financialOutcomes/retry.js";
2
+ import { anyApi } from "convex/server";
3
+ import { executionWorkflow } from "../durableExecution/runtime.js";
4
+ import { refFields, safeStatus, phase as phaseValidator } from "./schema.js";
5
+ import type { Infer } from "convex/values";
6
+ export const run = executionWorkflow
7
+ .define({
8
+ args: { ...refFields, initialPhase: phaseValidator },
9
+ returns: safeStatus,
10
+ })
11
+ .handler(async (step, input): Promise<Infer<typeof safeStatus>> => {
12
+ const { initialPhase, ...args } = input;
13
+ const saved = await step.runQuery(
14
+ anyApi.recoveryWorkflow.queries.saved,
15
+ args,
16
+ );
17
+ const finish = async (): Promise<Infer<typeof safeStatus>> => {
18
+ for (let batch = 0; batch < 20; batch++) {
19
+ if (
20
+ await step.runMutation(anyApi.recoveryWorkflow.steps.finish, args, {
21
+ name: "finish",
22
+ })
23
+ )
24
+ return step.runMutation(
25
+ anyApi.recoveryWorkflow.steps.complete,
26
+ args,
27
+ { name: "completion" },
28
+ );
29
+ }
30
+ throw new Error("Recovery finish batch budget exhausted.");
31
+ };
32
+ if (saved.outcome) return finish();
33
+ let phase: "execute" | "reconcile" = initialPhase;
34
+ let attempts = 0;
35
+ for (let turn = 0; turn < 20; turn++) {
36
+ const result = await step.runAction(
37
+ anyApi.recoveryWorkflow.bridge.invoke,
38
+ { ...args, phase },
39
+ { name: `provider-${phase}-${turn}`, retry: false },
40
+ );
41
+ const status = await step.runMutation(
42
+ anyApi.recoveryWorkflow.steps.saveReceipt,
43
+ { ...args, result },
44
+ { name: "receipt" },
45
+ );
46
+ if (result.status === "canceled") return status;
47
+ if (result.status === "ready") return finish();
48
+ phase = "reconcile";
49
+ const retry = financialRetryDecision(
50
+ result.status === "not_ready"
51
+ ? { status: "not_ready", reason: "provider_pending", retryable: true }
52
+ : {
53
+ status: "unknown",
54
+ reason: "provider_outcome_unknown",
55
+ retryable: false,
56
+ },
57
+ attempts,
58
+ {
59
+ maxRetries: saved.maxAttempts - 1,
60
+ initialDelayMs: saved.retryDelayMs,
61
+ maxDelayMs: saved.retryDelayMs,
62
+ },
63
+ );
64
+ if (!status.cancelRequested && retry.status === "retry") {
65
+ attempts = retry.nextAttempt;
66
+ await step.sleep(retry.delayMs);
67
+ } else {
68
+ await step.awaitEvent({ name: "reconcile" });
69
+ attempts = 0;
70
+ }
71
+ }
72
+ throw new Error("Recovery reconciliation budget exhausted.");
73
+ });