@fantastic.dev/better-stripe 0.41.0 → 0.43.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 (209) hide show
  1. package/CHANGELOG.md +25 -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 +1388 -2
  12. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +710 -17
  14. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +1420 -34
  16. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts +694 -1
  18. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  19. package/dist/client/costRecovery-invoices.d.ts +3 -2
  20. package/dist/client/costRecovery-invoices.d.ts.map +1 -1
  21. package/dist/client/costRecovery-invoices.js +10 -5
  22. package/dist/client/costRecovery-invoices.js.map +1 -1
  23. package/dist/client/costRecovery.d.ts +4 -2
  24. package/dist/client/costRecovery.d.ts.map +1 -1
  25. package/dist/client/costRecovery.js +2 -2
  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/processingCostReconciliation/client.d.ts +14 -0
  32. package/dist/client/processingCostReconciliation/client.d.ts.map +1 -0
  33. package/dist/client/processingCostReconciliation/client.js +35 -0
  34. package/dist/client/processingCostReconciliation/client.js.map +1 -0
  35. package/dist/client/processingCostReconciliation/contracts.d.ts +172 -0
  36. package/dist/client/processingCostReconciliation/contracts.d.ts.map +1 -0
  37. package/dist/client/processingCostReconciliation/contracts.js +55 -0
  38. package/dist/client/processingCostReconciliation/contracts.js.map +1 -0
  39. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts +15 -0
  40. package/dist/client/processingCostReconciliation/invoiceFunding.d.ts.map +1 -0
  41. package/dist/client/processingCostReconciliation/invoiceFunding.js +195 -0
  42. package/dist/client/processingCostReconciliation/invoiceFunding.js.map +1 -0
  43. package/dist/client/processingCostReconciliation/provider.d.ts +9 -0
  44. package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -0
  45. package/dist/client/processingCostReconciliation/provider.js +148 -0
  46. package/dist/client/processingCostReconciliation/provider.js.map +1 -0
  47. package/dist/client/settlement/processingCostHistory.d.ts +12 -0
  48. package/dist/client/settlement/processingCostHistory.d.ts.map +1 -0
  49. package/dist/client/settlement/processingCostHistory.js +20 -0
  50. package/dist/client/settlement/processingCostHistory.js.map +1 -0
  51. package/dist/client/settlement/processingCosts.d.ts +3 -0
  52. package/dist/client/settlement/processingCosts.d.ts.map +1 -1
  53. package/dist/client/settlement/processingCosts.js +27 -7
  54. package/dist/client/settlement/processingCosts.js.map +1 -1
  55. package/dist/component/_generated/api.d.ts +36 -0
  56. package/dist/component/_generated/api.d.ts.map +1 -1
  57. package/dist/component/_generated/api.js.map +1 -1
  58. package/dist/component/_generated/component.d.ts +988 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/balanceFunding/helpers.d.ts +42 -0
  61. package/dist/component/balanceFunding/helpers.d.ts.map +1 -1
  62. package/dist/component/balanceFunding/internal/actions.d.ts +39 -0
  63. package/dist/component/balanceFunding/internal/actions.d.ts.map +1 -0
  64. package/dist/component/balanceFunding/internal/actions.js +80 -0
  65. package/dist/component/balanceFunding/internal/actions.js.map +1 -0
  66. package/dist/component/balanceFunding/internal/mutations.d.ts +55 -0
  67. package/dist/component/balanceFunding/internal/mutations.d.ts.map +1 -0
  68. package/dist/component/balanceFunding/internal/mutations.js +54 -0
  69. package/dist/component/balanceFunding/internal/mutations.js.map +1 -0
  70. package/dist/component/balanceFunding/internal/queries.d.ts +116 -0
  71. package/dist/component/balanceFunding/internal/queries.d.ts.map +1 -0
  72. package/dist/component/balanceFunding/internal/queries.js +35 -0
  73. package/dist/component/balanceFunding/internal/queries.js.map +1 -0
  74. package/dist/component/balanceFunding/internal/workflow.d.ts +10 -0
  75. package/dist/component/balanceFunding/internal/workflow.d.ts.map +1 -0
  76. package/dist/component/balanceFunding/internal/workflow.js +31 -0
  77. package/dist/component/balanceFunding/internal/workflow.js.map +1 -0
  78. package/dist/component/balanceFunding/lifecycleHandlers.d.ts +126 -0
  79. package/dist/component/balanceFunding/lifecycleHandlers.d.ts.map +1 -1
  80. package/dist/component/balanceFunding/mutations.d.ts +419 -16
  81. package/dist/component/balanceFunding/mutations.d.ts.map +1 -1
  82. package/dist/component/balanceFunding/mutations.js +24 -0
  83. package/dist/component/balanceFunding/mutations.js.map +1 -1
  84. package/dist/component/balanceFunding/preparationHandlers.d.ts +42 -0
  85. package/dist/component/balanceFunding/preparationHandlers.d.ts.map +1 -1
  86. package/dist/component/balanceFunding/queries.d.ts +78 -0
  87. package/dist/component/balanceFunding/queries.d.ts.map +1 -1
  88. package/dist/component/balanceFunding/queries.js +35 -0
  89. package/dist/component/balanceFunding/queries.js.map +1 -1
  90. package/dist/component/balanceFunding/receipt.d.ts +5 -0
  91. package/dist/component/balanceFunding/receipt.d.ts.map +1 -0
  92. package/dist/component/balanceFunding/receipt.js +37 -0
  93. package/dist/component/balanceFunding/receipt.js.map +1 -0
  94. package/dist/component/balanceFunding/schema.d.ts +506 -2
  95. package/dist/component/balanceFunding/schema.d.ts.map +1 -1
  96. package/dist/component/balanceFunding/schema.js +2 -0
  97. package/dist/component/balanceFunding/schema.js.map +1 -1
  98. package/dist/component/balanceFunding/stateHandlers.d.ts +42 -0
  99. package/dist/component/balanceFunding/stateHandlers.d.ts.map +1 -1
  100. package/dist/component/balanceFunding/workflowControl.d.ts +19 -0
  101. package/dist/component/balanceFunding/workflowControl.d.ts.map +1 -0
  102. package/dist/component/balanceFunding/workflowControl.js +149 -0
  103. package/dist/component/balanceFunding/workflowControl.js.map +1 -0
  104. package/dist/component/balanceFunding/workflowSchema.d.ts +356 -0
  105. package/dist/component/balanceFunding/workflowSchema.d.ts.map +1 -0
  106. package/dist/component/balanceFunding/workflowSchema.js +48 -0
  107. package/dist/component/balanceFunding/workflowSchema.js.map +1 -0
  108. package/dist/component/balanceFunding/workflowState.d.ts +157 -0
  109. package/dist/component/balanceFunding/workflowState.d.ts.map +1 -0
  110. package/dist/component/balanceFunding/workflowState.js +194 -0
  111. package/dist/component/balanceFunding/workflowState.js.map +1 -0
  112. package/dist/component/balanceFunding/workflowValidators.d.ts +306 -0
  113. package/dist/component/balanceFunding/workflowValidators.d.ts.map +1 -0
  114. package/dist/component/balanceFunding/workflowValidators.js +27 -0
  115. package/dist/component/balanceFunding/workflowValidators.js.map +1 -0
  116. package/dist/component/earnings/triggers.d.ts +388 -2
  117. package/dist/component/earnings/triggers.d.ts.map +1 -1
  118. package/dist/component/payoutRelease/queries.d.ts +2 -2
  119. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  120. package/dist/component/processingCostReconciliation/adoption.d.ts +29 -0
  121. package/dist/component/processingCostReconciliation/adoption.d.ts.map +1 -0
  122. package/dist/component/processingCostReconciliation/adoption.js +58 -0
  123. package/dist/component/processingCostReconciliation/adoption.js.map +1 -0
  124. package/dist/component/processingCostReconciliation/bridge.d.ts +45 -0
  125. package/dist/component/processingCostReconciliation/bridge.d.ts.map +1 -0
  126. package/dist/component/processingCostReconciliation/bridge.js +41 -0
  127. package/dist/component/processingCostReconciliation/bridge.js.map +1 -0
  128. package/dist/component/processingCostReconciliation/helpers.d.ts +327 -0
  129. package/dist/component/processingCostReconciliation/helpers.d.ts.map +1 -0
  130. package/dist/component/processingCostReconciliation/helpers.js +39 -0
  131. package/dist/component/processingCostReconciliation/helpers.js.map +1 -0
  132. package/dist/component/processingCostReconciliation/mutations.d.ts +303 -0
  133. package/dist/component/processingCostReconciliation/mutations.d.ts.map +1 -0
  134. package/dist/component/processingCostReconciliation/mutations.js +121 -0
  135. package/dist/component/processingCostReconciliation/mutations.js.map +1 -0
  136. package/dist/component/processingCostReconciliation/queries.d.ts +422 -0
  137. package/dist/component/processingCostReconciliation/queries.d.ts.map +1 -0
  138. package/dist/component/processingCostReconciliation/queries.js +19 -0
  139. package/dist/component/processingCostReconciliation/queries.js.map +1 -0
  140. package/dist/component/processingCostReconciliation/rollback.d.ts +21 -0
  141. package/dist/component/processingCostReconciliation/rollback.d.ts.map +1 -0
  142. package/dist/component/processingCostReconciliation/rollback.js +54 -0
  143. package/dist/component/processingCostReconciliation/rollback.js.map +1 -0
  144. package/dist/component/processingCostReconciliation/schema.d.ts +2460 -0
  145. package/dist/component/processingCostReconciliation/schema.d.ts.map +1 -0
  146. package/dist/component/processingCostReconciliation/schema.js +137 -0
  147. package/dist/component/processingCostReconciliation/schema.js.map +1 -0
  148. package/dist/component/processingCostReconciliation/steps.d.ts +306 -0
  149. package/dist/component/processingCostReconciliation/steps.d.ts.map +1 -0
  150. package/dist/component/processingCostReconciliation/steps.js +149 -0
  151. package/dist/component/processingCostReconciliation/steps.js.map +1 -0
  152. package/dist/component/processingCostReconciliation/validation.d.ts +13 -0
  153. package/dist/component/processingCostReconciliation/validation.d.ts.map +1 -0
  154. package/dist/component/processingCostReconciliation/validation.js +61 -0
  155. package/dist/component/processingCostReconciliation/validation.js.map +1 -0
  156. package/dist/component/processingCostReconciliation/workflow.d.ts +105 -0
  157. package/dist/component/processingCostReconciliation/workflow.d.ts.map +1 -0
  158. package/dist/component/processingCostReconciliation/workflow.js +33 -0
  159. package/dist/component/processingCostReconciliation/workflow.js.map +1 -0
  160. package/dist/component/schema.d.ts +694 -1
  161. package/dist/component/schema.js +2 -0
  162. package/dist/component/schema.js.map +1 -1
  163. package/package.json +1 -1
  164. package/src/client/balanceFundingWorkflow/capture.test.ts +144 -0
  165. package/src/client/balanceFundingWorkflow/client.ts +419 -0
  166. package/src/client/billing/balanceFunding.ts +50 -0
  167. package/src/client/costRecovery-invoices.ts +19 -4
  168. package/src/client/costRecovery.ts +4 -2
  169. package/src/client/index.ts +15 -0
  170. package/src/client/processingCostReconciliation/client.ts +75 -0
  171. package/src/client/processingCostReconciliation/contracts.ts +176 -0
  172. package/src/client/processingCostReconciliation/invoiceFunding.ts +270 -0
  173. package/src/client/processingCostReconciliation/invoiceProvider.test.ts +353 -0
  174. package/src/client/processingCostReconciliation/provider.test.ts +324 -0
  175. package/src/client/processingCostReconciliation/provider.ts +178 -0
  176. package/src/client/settlement/processingCostHistory.ts +31 -0
  177. package/src/client/settlement/processingCosts.ts +50 -15
  178. package/src/component/_generated/api.ts +36 -0
  179. package/src/component/_generated/component.ts +1094 -0
  180. package/src/component/balanceFunding/internal/actions.ts +107 -0
  181. package/src/component/balanceFunding/internal/mutations.ts +66 -0
  182. package/src/component/balanceFunding/internal/queries.ts +34 -0
  183. package/src/component/balanceFunding/internal/workflow.ts +49 -0
  184. package/src/component/balanceFunding/mutations.ts +34 -0
  185. package/src/component/balanceFunding/queries.ts +38 -0
  186. package/src/component/balanceFunding/receipt.ts +48 -0
  187. package/src/component/balanceFunding/schema.ts +2 -0
  188. package/src/component/balanceFunding/scopeLookup.test.ts +94 -0
  189. package/src/component/balanceFunding/workflow.fixtures.ts +366 -0
  190. package/src/component/balanceFunding/workflow.test.ts +552 -0
  191. package/src/component/balanceFunding/workflowControl.ts +198 -0
  192. package/src/component/balanceFunding/workflowSchema.ts +78 -0
  193. package/src/component/balanceFunding/workflowState.ts +285 -0
  194. package/src/component/balanceFunding/workflowValidators.ts +40 -0
  195. package/src/component/processingCostReconciliation/adoption.test.ts +206 -0
  196. package/src/component/processingCostReconciliation/adoption.ts +77 -0
  197. package/src/component/processingCostReconciliation/bridge.ts +50 -0
  198. package/src/component/processingCostReconciliation/helpers.ts +55 -0
  199. package/src/component/processingCostReconciliation/invoice.test.ts +152 -0
  200. package/src/component/processingCostReconciliation/mutations.ts +148 -0
  201. package/src/component/processingCostReconciliation/queries.ts +18 -0
  202. package/src/component/processingCostReconciliation/rollback.ts +72 -0
  203. package/src/component/processingCostReconciliation/schema.ts +191 -0
  204. package/src/component/processingCostReconciliation/state.test.ts +407 -0
  205. package/src/component/processingCostReconciliation/steps.ts +168 -0
  206. package/src/component/processingCostReconciliation/validation.ts +79 -0
  207. package/src/component/processingCostReconciliation/workflow.test.ts +329 -0
  208. package/src/component/processingCostReconciliation/workflow.ts +50 -0
  209. package/src/component/schema.ts +2 -0
@@ -0,0 +1,206 @@
1
+ import { convexTest } from "convex-test";
2
+ import workflowTest from "@convex-dev/workflow/test";
3
+ import {
4
+ anyApi,
5
+ componentsGeneric,
6
+ createFunctionHandle,
7
+ defineSchema,
8
+ defineTable,
9
+ internalMutationGeneric,
10
+ mutationGeneric,
11
+ } from "convex/server";
12
+ import { v } from "convex/values";
13
+ import { beforeEach, expect, it } from "vitest";
14
+ import { schema, modules } from "../../test.js";
15
+ import { observation as validator, refFields } from "./schema.js";
16
+ const nested = componentsGeneric();
17
+ const scope = { accountId: "acct_owner", scopeKey: "store", currency: "usd" };
18
+ const observation = {
19
+ paymentIntentId: "pi_a",
20
+ sourceChargeId: "ch_a",
21
+ currency: "usd",
22
+ gross: 1000,
23
+ originalProcessingFee: 30,
24
+ processingFee: 30,
25
+ disputeFees: 0,
26
+ principalReturned: 1000,
27
+ provenance: {
28
+ invoiceId: "in_a",
29
+ invoicePaymentId: "inpay_a",
30
+ customerAccountId: "acct_buyer",
31
+ stripePriceId: "price_original",
32
+ stripeProductId: "prod_original",
33
+ },
34
+ };
35
+ let failProjection = false;
36
+ const host = {
37
+ start: internalMutationGeneric({
38
+ args: {},
39
+ returns: v.any(),
40
+ handler: async (ctx) =>
41
+ ctx.runMutation(
42
+ nested.betterStripe.processingCostReconciliation.mutations.start,
43
+ {
44
+ ...scope,
45
+ claimKey: "cost:pi_a",
46
+ requestKey: "legacy-refund",
47
+ expectedRevision: -1,
48
+ source: {
49
+ kind: "sale",
50
+ paymentIntentId: "pi_a",
51
+ gross: 1000,
52
+ customerAccountId: "acct_buyer",
53
+ },
54
+ policy: {
55
+ sellingFee: 100,
56
+ liability: { processingCosts: "uncovered", disputeCosts: "all" },
57
+ rounding: "nearest",
58
+ },
59
+ provider: "function://fixture/provider",
60
+ importHook: await createFunctionHandle(anyApi.host.importHook),
61
+ projection: await createFunctionHandle(anyApi.host.project),
62
+ providerApiVersion: "2026-09-30.endive",
63
+ definitionVersion: 1,
64
+ maxAttempts: 2,
65
+ retryDelayMs: 1,
66
+ },
67
+ ),
68
+ }),
69
+ apply: internalMutationGeneric({
70
+ args: { operationId: v.string(), version: v.number() },
71
+ returns: v.any(),
72
+ handler: (ctx, args) =>
73
+ ctx.runMutation(nested.betterStripe.fixture.apply, {
74
+ ...scope,
75
+ ...args,
76
+ observation,
77
+ }),
78
+ }),
79
+ importHook: internalMutationGeneric({
80
+ args: {
81
+ ...refFields,
82
+ operationId: v.string(),
83
+ claimKey: v.string(),
84
+ expectedRevision: v.number(),
85
+ sourceChargeId: v.string(),
86
+ sourceGross: v.number(),
87
+ sourceProcessingFee: v.number(),
88
+ },
89
+ returns: v.any(),
90
+ handler: async (ctx) => {
91
+ const legacy = (await ctx.db.query("legacy").first())!;
92
+ await ctx.db.patch(legacy._id, { adopted: true });
93
+ return {
94
+ operationKey: "legacy:cost_a",
95
+ amountDue: 50,
96
+ collectedAmount: 20,
97
+ revision: 0,
98
+ };
99
+ },
100
+ }),
101
+ project: internalMutationGeneric({
102
+ args: {
103
+ ...refFields,
104
+ operationId: v.string(),
105
+ status: v.string(),
106
+ result: v.any(),
107
+ },
108
+ returns: v.null(),
109
+ handler: async (ctx, args) => {
110
+ if (failProjection) {
111
+ failProjection = false;
112
+ throw new Error("private projection failure");
113
+ }
114
+ await ctx.db.insert("reports", {
115
+ operationId: args.operationId,
116
+ revision: args.result.claim.revision,
117
+ });
118
+ return null;
119
+ },
120
+ }),
121
+ };
122
+ function fixture() {
123
+ const t = convexTest(
124
+ defineSchema({
125
+ legacy: defineTable({ adopted: v.boolean() }),
126
+ reports: defineTable({ operationId: v.string(), revision: v.number() }),
127
+ }),
128
+ { "./_generated/api.ts": async () => ({}), "./host.ts": async () => host },
129
+ );
130
+ t.registerComponent("betterStripe", schema, {
131
+ ...modules,
132
+ "./component/fixture.ts": async () => ({
133
+ apply: mutationGeneric({
134
+ args: { ...refFields, observation: validator },
135
+ returns: v.any(),
136
+ handler: (ctx, args) =>
137
+ ctx.runMutation(
138
+ anyApi.processingCostReconciliation.steps.apply,
139
+ args,
140
+ ),
141
+ }),
142
+ }),
143
+ });
144
+ workflowTest.register(t, "betterStripe/workflow");
145
+ return t;
146
+ }
147
+ beforeEach(() => {
148
+ failProjection = false;
149
+ });
150
+ it("imports a verified opening collection and projects the reconciled claim atomically", async () => {
151
+ const t = fixture();
152
+ await t.run((ctx) => ctx.db.insert("legacy", { adopted: false }));
153
+ const op = await t.mutation(anyApi.host.start, {});
154
+ const ref = { operationId: op.operationId, version: op.version };
155
+ const result = await t.mutation(anyApi.host.apply, ref);
156
+ expect(result).toMatchObject({
157
+ status: "completed",
158
+ result: {
159
+ claim: {
160
+ revision: 1,
161
+ amountDue: 30,
162
+ collectedAmount: 20,
163
+ outstanding: 10,
164
+ openingCollection: {
165
+ operationKey: "legacy:cost_a",
166
+ amountDue: 50,
167
+ collectedAmount: 20,
168
+ revision: 0,
169
+ },
170
+ },
171
+ },
172
+ });
173
+ expect(await t.run((ctx) => ctx.db.query("legacy").first())).toMatchObject({
174
+ adopted: true,
175
+ });
176
+ expect(await t.run((ctx) => ctx.db.query("reports").collect())).toMatchObject(
177
+ [{ operationId: op.operationId, revision: 1 }],
178
+ );
179
+ expect(await t.mutation(anyApi.host.apply, ref)).toEqual(result);
180
+ expect(await t.run((ctx) => ctx.db.query("reports").collect())).toHaveLength(
181
+ 1,
182
+ );
183
+ });
184
+ it("rolls back adoption, financial writes and host projection on callback failure", async () => {
185
+ const t = fixture();
186
+ await t.run((ctx) => ctx.db.insert("legacy", { adopted: false }));
187
+ const op = await t.mutation(anyApi.host.start, {});
188
+ const ref = { operationId: op.operationId, version: op.version };
189
+ failProjection = true;
190
+ await expect(t.mutation(anyApi.host.apply, ref)).rejects.toThrow(
191
+ "Processing-cost projection failed",
192
+ );
193
+ expect(await t.run((ctx) => ctx.db.query("legacy").first())).toMatchObject({
194
+ adopted: false,
195
+ });
196
+ expect(await t.run((ctx) => ctx.db.query("reports").collect())).toEqual([]);
197
+ expect(
198
+ await t.query(nested.betterStripe.costRecovery.queries.claim, {
199
+ claimKey: "cost:pi_a",
200
+ }),
201
+ ).toBeNull();
202
+ expect(await t.mutation(anyApi.host.apply, ref)).toMatchObject({
203
+ status: "completed",
204
+ result: { claim: { revision: 1, collectedAmount: 20, outstanding: 10 } },
205
+ });
206
+ });
@@ -0,0 +1,77 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { FunctionHandle } from "convex/server";
3
+ import type { MutationCtx } from "../_generated/server.js";
4
+ import type { Doc } from "../_generated/dataModel.js";
5
+ import { importOpeningClaim } from "../costRecovery/imports.js";
6
+ import { importSnapshot, observation } from "./schema.js";
7
+ import { reference } from "./helpers.js";
8
+ type Opening = Exclude<Infer<typeof importSnapshot>, null>;
9
+ function opening(value: unknown): Opening | null {
10
+ if (value === null) return null;
11
+ if (!value || typeof value !== "object" || Array.isArray(value))
12
+ throw new Error("Invalid opening snapshot.");
13
+ const r = value as Record<string, unknown>;
14
+ if (
15
+ Object.keys(r).some(
16
+ (k) =>
17
+ !["operationKey", "amountDue", "collectedAmount", "revision"].includes(
18
+ k,
19
+ ),
20
+ ) ||
21
+ typeof r.operationKey !== "string" ||
22
+ !r.operationKey.trim() ||
23
+ ![r.amountDue, r.collectedAmount, r.revision].every(
24
+ (n) => typeof n === "number" && Number.isSafeInteger(n),
25
+ ) ||
26
+ (r.revision as number) < 0
27
+ )
28
+ throw new Error("Invalid opening snapshot.");
29
+ return r as Opening;
30
+ }
31
+ /** Host verifies its historical record. Adoption and host marker share this transaction. */
32
+ export async function adopt(
33
+ ctx: MutationCtx,
34
+ op: Doc<"processingCostReconciliationOperations">,
35
+ o: Infer<typeof observation>,
36
+ ) {
37
+ try {
38
+ const snapshot = opening(
39
+ await ctx.runMutation(op.importHook as FunctionHandle<"mutation">, {
40
+ ...reference(op),
41
+ claimKey: op.claimKey,
42
+ expectedRevision: op.expectedRevision,
43
+ sourceChargeId: o.sourceChargeId,
44
+ sourceGross: o.gross,
45
+ sourceProcessingFee: o.originalProcessingFee,
46
+ }),
47
+ );
48
+ if (!snapshot) {
49
+ const current = await ctx.db
50
+ .query("recoveryClaims")
51
+ .withIndex("by_key", (q) => q.eq("claimKey", op.claimKey))
52
+ .unique();
53
+ if (current) throw new Error("Opening hook changed the live claim.");
54
+ return null;
55
+ }
56
+ const imported = await importOpeningClaim(ctx, {
57
+ accountId: op.accountId,
58
+ scopeKey: op.scopeKey,
59
+ currency: op.currency,
60
+ claimKey: op.claimKey,
61
+ sourceChargeId: o.sourceChargeId,
62
+ sourceGross: o.gross,
63
+ sourceProcessingFee: o.originalProcessingFee,
64
+ ...snapshot,
65
+ });
66
+ if (
67
+ imported.revision !== snapshot.revision ||
68
+ imported.amountDue !== snapshot.amountDue ||
69
+ imported.collectedAmount !== snapshot.collectedAmount ||
70
+ imported.reservedAmount !== 0
71
+ )
72
+ throw new Error("Opening claim changed during adoption.");
73
+ return imported;
74
+ } catch {
75
+ throw new Error("Processing-cost import failed.");
76
+ }
77
+ }
@@ -0,0 +1,50 @@
1
+ import { anyApi, type FunctionHandle } from "convex/server";
2
+ import type { Infer } from "convex/values";
3
+ import { v } from "convex/values";
4
+ import { internalAction } from "../_generated/server.js";
5
+ import { refFields, observation, failure } from "./schema.js";
6
+ import { providerReceiptSchema } from "../../client/processingCostReconciliation/contracts.js";
7
+ import { same } from "../recoveryWorkflow/helpers.js";
8
+ const outcome = v.union(
9
+ v.object({ status: v.literal("ready"), value: observation }),
10
+ failure,
11
+ );
12
+ const unknown = {
13
+ status: "unknown",
14
+ reason: "provider_outcome_unknown",
15
+ retryable: false,
16
+ } as const;
17
+ export const invoke = internalAction({
18
+ args: refFields,
19
+ returns: outcome,
20
+ handler: async (ctx, args): Promise<Infer<typeof outcome>> => {
21
+ try {
22
+ const op = await ctx.runQuery(
23
+ anyApi.processingCostReconciliation.queries.saved,
24
+ args,
25
+ );
26
+ if (op.result) return { status: "ready", value: op.result.observation };
27
+ if (op.failure && ["conflict", "rejected"].includes(op.failure.status))
28
+ return op.failure;
29
+ await ctx.runMutation(
30
+ anyApi.processingCostReconciliation.steps.begin,
31
+ args,
32
+ );
33
+ const request = {
34
+ ...args,
35
+ providerApiVersion: op.providerApiVersion,
36
+ definitionVersion: op.definitionVersion,
37
+ };
38
+ const raw: unknown = await ctx.runAction(
39
+ op.provider as FunctionHandle<"action">,
40
+ request,
41
+ );
42
+ const parsed = providerReceiptSchema.safeParse(raw);
43
+ if (!parsed.success) return unknown;
44
+ const { outcome, ...echo } = parsed.data;
45
+ return same(request, echo) ? outcome : unknown;
46
+ } catch {
47
+ return unknown;
48
+ }
49
+ },
50
+ });
@@ -0,0 +1,55 @@
1
+ import { v, type Infer } from "convex/values";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
4
+ import { refFields, failure } from "./schema.js";
5
+ const _ref = v.object(refFields);
6
+ export type OperationRef = Infer<typeof _ref>;
7
+ export const conflict = (reason: "identity_changed" | "revision_changed") =>
8
+ ({ status: "conflict", reason, retryable: false }) as const;
9
+ export function reference(
10
+ op: Doc<"processingCostReconciliationOperations">,
11
+ ): OperationRef {
12
+ return {
13
+ accountId: op.accountId,
14
+ scopeKey: op.scopeKey,
15
+ currency: op.currency,
16
+ operationId: op._id,
17
+ version: op.version,
18
+ };
19
+ }
20
+ export function status(op: Doc<"processingCostReconciliationOperations">) {
21
+ const ref = reference(op);
22
+ if (op.result)
23
+ return { ...ref, status: "completed" as const, result: op.result };
24
+ if (op.failure) return { ...ref, ...op.failure };
25
+ return {
26
+ ...ref,
27
+ status: op.status === "queued" ? ("queued" as const) : ("running" as const),
28
+ };
29
+ }
30
+ export async function read(ctx: QueryCtx | MutationCtx, args: OperationRef) {
31
+ const op = await ctx.db.get(
32
+ "processingCostReconciliationOperations",
33
+ args.operationId,
34
+ );
35
+ if (
36
+ !op ||
37
+ Object.entries(reference(op)).some(
38
+ ([k, value]) => value !== args[k as keyof OperationRef],
39
+ )
40
+ )
41
+ throw new Error("Processing-cost operation identity does not match.");
42
+ return op;
43
+ }
44
+
45
+ export async function setFailure(
46
+ ctx: MutationCtx,
47
+ op: Doc<"processingCostReconciliationOperations">,
48
+ value: Infer<typeof failure>,
49
+ ) {
50
+ await ctx.db.patch("processingCostReconciliationOperations", op._id, {
51
+ status: value.status === "not_ready" ? "waiting" : value.status,
52
+ failure: value,
53
+ });
54
+ return { ...reference(op), ...value };
55
+ }
@@ -0,0 +1,152 @@
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 { schema, modules } from "../../test.js";
6
+ const start = makeFunctionReference<"mutation">(
7
+ "processingCostReconciliation/mutations:start",
8
+ );
9
+ const apply = makeFunctionReference<"mutation">(
10
+ "processingCostReconciliation/steps:apply",
11
+ );
12
+ const scope = { accountId: "acct_owner", scopeKey: "store", currency: "usd" };
13
+ const args = {
14
+ ...scope,
15
+ claimKey: "cost:pi_a",
16
+ requestKey: "invoice-refund",
17
+ expectedRevision: -1,
18
+ source: {
19
+ kind: "invoice_recovery",
20
+ paymentIntentId: "pi_a",
21
+ gross: 1000,
22
+ groupKey: "old-invoice",
23
+ },
24
+ rollback: { groupKey: "old-invoice", expectedRevision: -1 },
25
+ policy: {
26
+ sellingFee: 100,
27
+ liability: { processingCosts: "uncovered", disputeCosts: "all" },
28
+ rounding: "nearest",
29
+ },
30
+ provider: "function://fixture/provider",
31
+ providerApiVersion: "2026-09-30.endive",
32
+ definitionVersion: 1,
33
+ maxAttempts: 3,
34
+ retryDelayMs: 1,
35
+ };
36
+ const observation = {
37
+ paymentIntentId: "pi_a",
38
+ sourceChargeId: "ch_a",
39
+ currency: "usd",
40
+ gross: 1000,
41
+ originalProcessingFee: 30,
42
+ processingFee: 30,
43
+ disputeFees: 0,
44
+ principalReturned: 500,
45
+ provenance: {
46
+ invoiceId: "in_original",
47
+ invoicePaymentId: "inpay_original",
48
+ customerAccountId: scope.accountId,
49
+ recoveryInvoiceItemId: "ii_original",
50
+ },
51
+ };
52
+ async function fixture(patch: Record<string, unknown> = {}) {
53
+ const t = convexTest(schema, modules);
54
+ workflowTest.register(t, "workflow");
55
+ await t.run((ctx) =>
56
+ ctx.db.insert("recoveryGroups", {
57
+ ...scope,
58
+ groupKey: "old-invoice",
59
+ sourceKind: "invoice",
60
+ sourceId: "in_original",
61
+ invoiceItemId: "ii_original",
62
+ amount: 80,
63
+ maxDebit: 100,
64
+ maxCredit: 0,
65
+ pendingOperations: 0,
66
+ status: "collected",
67
+ ...patch,
68
+ }),
69
+ );
70
+ return t;
71
+ }
72
+ const ref = (op: { operationId: string; version: number }) => ({
73
+ ...scope,
74
+ operationId: op.operationId,
75
+ version: op.version,
76
+ });
77
+ it("binds verified original funding and rolls back a collected invoice without a fictitious price", async () => {
78
+ const t = await fixture();
79
+ const op = await t.mutation(start, args);
80
+ const result = await t.mutation(apply, { ...ref(op), observation });
81
+ expect(result).toMatchObject({
82
+ status: "completed",
83
+ result: {
84
+ rollbackClaim: { amountDue: 40, revision: 0 },
85
+ observation: { provenance: { recoveryInvoiceItemId: "ii_original" } },
86
+ },
87
+ });
88
+ expect(
89
+ await t.run((ctx) => ctx.db.query("recoveryGroups").first()),
90
+ ).toMatchObject({
91
+ invoiceItemId: "ii_original",
92
+ invoiceFunding: {
93
+ sourceChargeId: "ch_a",
94
+ sourceGross: 1000,
95
+ sourceProcessingFee: 30,
96
+ },
97
+ });
98
+ expect(await t.mutation(apply, { ...ref(op), observation })).toEqual(result);
99
+ });
100
+ it.each([
101
+ { invoiceId: "in_foreign" },
102
+ { recoveryInvoiceItemId: "ii_foreign" },
103
+ { customerAccountId: "acct_foreign" },
104
+ ])("rejects a mismatched original invoice receipt %j", async (patch) => {
105
+ const t = await fixture();
106
+ const op = await t.mutation(start, args);
107
+ expect(
108
+ await t.mutation(apply, {
109
+ ...ref(op),
110
+ observation: {
111
+ ...observation,
112
+ provenance: { ...observation.provenance, ...patch },
113
+ },
114
+ }),
115
+ ).toMatchObject({ status: "conflict", reason: "identity_changed" });
116
+ expect(
117
+ await t.run((ctx) => ctx.db.query("recoveryClaims").collect()),
118
+ ).toEqual([]);
119
+ expect(
120
+ (await t.run((ctx) => ctx.db.query("recoveryGroups").first()))
121
+ ?.invoiceFunding,
122
+ ).toBeUndefined();
123
+ });
124
+ it("never rewrites the original invoice funding economics", async () => {
125
+ const t = await fixture({
126
+ invoiceFunding: {
127
+ sourceChargeId: "ch_original",
128
+ sourceGross: 1000,
129
+ sourceProcessingFee: 30,
130
+ },
131
+ });
132
+ const op = await t.mutation(start, args);
133
+ expect(await t.mutation(apply, { ...ref(op), observation })).toMatchObject({
134
+ status: "conflict",
135
+ reason: "identity_changed",
136
+ });
137
+ expect(
138
+ await t.run((ctx) => ctx.db.query("recoveryGroups").first()),
139
+ ).toMatchObject({ invoiceFunding: { sourceChargeId: "ch_original" } });
140
+ });
141
+ it("keeps uncollected recovery invoices pending without creating any claim or funding binding", async () => {
142
+ const t = await fixture({ status: "sealed" });
143
+ const op = await t.mutation(start, args);
144
+ expect(await t.mutation(apply, { ...ref(op), observation })).toMatchObject({
145
+ status: "not_ready",
146
+ reason: "provider_pending",
147
+ retryable: true,
148
+ });
149
+ expect(
150
+ await t.run((ctx) => ctx.db.query("recoveryClaims").collect()),
151
+ ).toEqual([]);
152
+ });
@@ -0,0 +1,148 @@
1
+ import { v } from "convex/values";
2
+ import type { WorkflowId } from "@convex-dev/workflow";
3
+ import { anyApi, type FunctionReference } from "convex/server";
4
+ import { mutation } from "../_generated/server.js";
5
+ import { startFields, safeStatus, failure, refFields } from "./schema.js";
6
+ import { executionWorkflow } from "../durableExecution/runtime.js";
7
+ import { calculateProcessingCostDeficit } from "../../client/processingCostDeficit/index.js";
8
+ import { validateScope } from "../costRecovery/helpers.js";
9
+ import { same } from "../recoveryWorkflow/helpers.js";
10
+ import { conflict, reference, status, read } from "./helpers.js";
11
+ const workflow = anyApi.processingCostReconciliation.workflow
12
+ .run as FunctionReference<"mutation", "internal">;
13
+ export const start = mutation({
14
+ args: startFields,
15
+ returns: v.union(safeStatus, failure),
16
+ handler: async (ctx, args) => {
17
+ validateScope(args);
18
+ if (
19
+ !args.requestKey ||
20
+ !args.claimKey ||
21
+ args.claimKey.startsWith("rollback:") ||
22
+ !args.source.paymentIntentId ||
23
+ !Number.isSafeInteger(args.expectedRevision) ||
24
+ args.expectedRevision < -1 ||
25
+ (args.rollback !== undefined &&
26
+ (!args.rollback.groupKey ||
27
+ !Number.isSafeInteger(args.rollback.expectedRevision) ||
28
+ args.rollback.expectedRevision < -1)) ||
29
+ (args.source.kind === "invoice_recovery" &&
30
+ (!args.rollback || args.rollback.groupKey !== args.source.groupKey)) ||
31
+ args.definitionVersion !== 1 ||
32
+ !/^\d{4}-\d{2}-\d{2}\.[a-z][a-z0-9_.-]*$/.test(args.providerApiVersion) ||
33
+ !Number.isSafeInteger(args.maxAttempts) ||
34
+ args.maxAttempts < 1 ||
35
+ args.maxAttempts > 20 ||
36
+ !Number.isSafeInteger(args.retryDelayMs) ||
37
+ args.retryDelayMs < 1 ||
38
+ args.retryDelayMs > 86400000
39
+ )
40
+ throw new Error("Invalid processing-cost reconciliation policy.");
41
+ calculateProcessingCostDeficit({
42
+ currency: args.currency,
43
+ gross: args.source.gross,
44
+ ...args.policy,
45
+ processingFee: 0,
46
+ principalReturned: 0,
47
+ disputeFees: 0,
48
+ });
49
+ const prior = await ctx.db
50
+ .query("processingCostReconciliationOperations")
51
+ .withIndex("by_request", (q) => q.eq("requestKey", args.requestKey))
52
+ .unique();
53
+ if (prior) {
54
+ const binding = Object.fromEntries(
55
+ Object.keys(startFields).map((k) => [
56
+ k,
57
+ prior[k as keyof typeof prior],
58
+ ]),
59
+ );
60
+ if (!same(binding, args)) return conflict("identity_changed");
61
+ return status(prior);
62
+ }
63
+ const id = await ctx.db.insert("processingCostReconciliationOperations", {
64
+ ...args,
65
+ version: 1,
66
+ status: "queued",
67
+ });
68
+ const op = (await ctx.db.get(
69
+ "processingCostReconciliationOperations",
70
+ id,
71
+ ))!;
72
+ const canonical = await ctx.db
73
+ .query("processingCostReconciliationOperations")
74
+ .withIndex("by_payment_scope", (q) =>
75
+ q
76
+ .eq("accountId", args.accountId)
77
+ .eq("scopeKey", args.scopeKey)
78
+ .eq("currency", args.currency)
79
+ .eq("source.paymentIntentId", args.source.paymentIntentId),
80
+ )
81
+ .first();
82
+ if (canonical && canonical.claimKey !== args.claimKey) {
83
+ const failure = conflict("identity_changed");
84
+ await ctx.db.patch("processingCostReconciliationOperations", id, {
85
+ status: "conflict",
86
+ failure,
87
+ });
88
+ return { ...reference(op), ...failure };
89
+ }
90
+ const workflowId = await executionWorkflow.start(
91
+ ctx,
92
+ workflow,
93
+ reference(op),
94
+ { startAsync: true },
95
+ );
96
+ await ctx.db.patch("processingCostReconciliationOperations", id, {
97
+ workflowId,
98
+ });
99
+ return status(op);
100
+ },
101
+ });
102
+
103
+ export const resume = mutation({
104
+ args: refFields,
105
+ returns: safeStatus,
106
+ handler: async (ctx, args) => {
107
+ const op = await read(ctx, args);
108
+ if (
109
+ op.result ||
110
+ (op.failure && ["conflict", "rejected"].includes(op.failure.status))
111
+ )
112
+ return status(op);
113
+ const state = await executionWorkflow.status(
114
+ ctx,
115
+ op.workflowId as WorkflowId,
116
+ );
117
+ if (state.type === "inProgress") return status(op);
118
+ if (state.type === "failed") {
119
+ const last = (
120
+ await executionWorkflow.listSteps(ctx, op.workflowId as WorkflowId, {
121
+ order: "desc",
122
+ paginationOpts: { cursor: null, numItems: 1 },
123
+ })
124
+ ).page[0];
125
+ if (last?.name === "apply" && last.runResult?.kind === "failed") {
126
+ await executionWorkflow.restart(ctx, op.workflowId as WorkflowId, {
127
+ from: last.stepNumber,
128
+ startAsync: true,
129
+ });
130
+ return status(op);
131
+ }
132
+ }
133
+ const workflowId = await executionWorkflow.start(
134
+ ctx,
135
+ workflow,
136
+ reference(op),
137
+ { startAsync: true },
138
+ );
139
+ await ctx.db.patch("processingCostReconciliationOperations", op._id, {
140
+ workflowId,
141
+ status: "queued",
142
+ failure: undefined,
143
+ });
144
+ return status(
145
+ (await ctx.db.get("processingCostReconciliationOperations", op._id))!,
146
+ );
147
+ },
148
+ });