@fantastic.dev/better-stripe 0.42.0 → 0.44.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.
- package/CHANGELOG.md +31 -0
- package/README.md +11 -4
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +1022 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +511 -0
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +1054 -32
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +527 -16
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/costRecovery-invoices.d.ts +3 -2
- package/dist/client/costRecovery-invoices.d.ts.map +1 -1
- package/dist/client/costRecovery-invoices.js +10 -5
- package/dist/client/costRecovery-invoices.js.map +1 -1
- package/dist/client/costRecovery.d.ts +4 -2
- package/dist/client/costRecovery.d.ts.map +1 -1
- package/dist/client/costRecovery.js +2 -2
- package/dist/client/costRecovery.js.map +1 -1
- package/dist/client/processingCostReconciliation/client.d.ts +14 -0
- package/dist/client/processingCostReconciliation/client.d.ts.map +1 -0
- package/dist/client/processingCostReconciliation/client.js +35 -0
- package/dist/client/processingCostReconciliation/client.js.map +1 -0
- package/dist/client/processingCostReconciliation/contracts.d.ts +172 -0
- package/dist/client/processingCostReconciliation/contracts.d.ts.map +1 -0
- package/dist/client/processingCostReconciliation/contracts.js +55 -0
- package/dist/client/processingCostReconciliation/contracts.js.map +1 -0
- package/dist/client/processingCostReconciliation/invoiceFunding.d.ts +15 -0
- package/dist/client/processingCostReconciliation/invoiceFunding.d.ts.map +1 -0
- package/dist/client/processingCostReconciliation/invoiceFunding.js +195 -0
- package/dist/client/processingCostReconciliation/invoiceFunding.js.map +1 -0
- package/dist/client/processingCostReconciliation/provider.d.ts +9 -0
- package/dist/client/processingCostReconciliation/provider.d.ts.map +1 -0
- package/dist/client/processingCostReconciliation/provider.js +148 -0
- package/dist/client/processingCostReconciliation/provider.js.map +1 -0
- package/dist/client/settlement/processingCostHistory.d.ts +12 -0
- package/dist/client/settlement/processingCostHistory.d.ts.map +1 -0
- package/dist/client/settlement/processingCostHistory.js +20 -0
- package/dist/client/settlement/processingCostHistory.js.map +1 -0
- package/dist/client/settlement/processingCosts.d.ts +3 -0
- package/dist/client/settlement/processingCosts.d.ts.map +1 -1
- package/dist/client/settlement/processingCosts.js +27 -7
- package/dist/client/settlement/processingCosts.js.map +1 -1
- package/dist/component/_generated/api.d.ts +18 -0
- package/dist/component/_generated/api.d.ts.map +1 -1
- package/dist/component/_generated/api.js.map +1 -1
- package/dist/component/_generated/component.d.ts +515 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/internal/actions.d.ts +11 -11
- package/dist/component/balanceFunding/mutations.d.ts +16 -16
- package/dist/component/balanceFunding/stateHandlers.d.ts +8 -8
- package/dist/component/balanceFunding/workflowValidators.d.ts +16 -16
- package/dist/component/earnings/triggers.d.ts +318 -16
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/payoutRelease/queries.d.ts +2 -2
- package/dist/component/payoutRelease/queries.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/adoption.d.ts +29 -0
- package/dist/component/processingCostReconciliation/adoption.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/adoption.js +58 -0
- package/dist/component/processingCostReconciliation/adoption.js.map +1 -0
- package/dist/component/processingCostReconciliation/bridge.d.ts +45 -0
- package/dist/component/processingCostReconciliation/bridge.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/bridge.js +41 -0
- package/dist/component/processingCostReconciliation/bridge.js.map +1 -0
- package/dist/component/processingCostReconciliation/helpers.d.ts +327 -0
- package/dist/component/processingCostReconciliation/helpers.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/helpers.js +39 -0
- package/dist/component/processingCostReconciliation/helpers.js.map +1 -0
- package/dist/component/processingCostReconciliation/mutations.d.ts +303 -0
- package/dist/component/processingCostReconciliation/mutations.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/mutations.js +121 -0
- package/dist/component/processingCostReconciliation/mutations.js.map +1 -0
- package/dist/component/processingCostReconciliation/queries.d.ts +422 -0
- package/dist/component/processingCostReconciliation/queries.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/queries.js +19 -0
- package/dist/component/processingCostReconciliation/queries.js.map +1 -0
- package/dist/component/processingCostReconciliation/rollback.d.ts +21 -0
- package/dist/component/processingCostReconciliation/rollback.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/rollback.js +54 -0
- package/dist/component/processingCostReconciliation/rollback.js.map +1 -0
- package/dist/component/processingCostReconciliation/schema.d.ts +2460 -0
- package/dist/component/processingCostReconciliation/schema.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/schema.js +137 -0
- package/dist/component/processingCostReconciliation/schema.js.map +1 -0
- package/dist/component/processingCostReconciliation/steps.d.ts +306 -0
- package/dist/component/processingCostReconciliation/steps.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/steps.js +149 -0
- package/dist/component/processingCostReconciliation/steps.js.map +1 -0
- package/dist/component/processingCostReconciliation/validation.d.ts +13 -0
- package/dist/component/processingCostReconciliation/validation.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/validation.js +61 -0
- package/dist/component/processingCostReconciliation/validation.js.map +1 -0
- package/dist/component/processingCostReconciliation/workflow.d.ts +105 -0
- package/dist/component/processingCostReconciliation/workflow.d.ts.map +1 -0
- package/dist/component/processingCostReconciliation/workflow.js +33 -0
- package/dist/component/processingCostReconciliation/workflow.js.map +1 -0
- package/dist/component/schema.d.ts +511 -0
- package/dist/component/schema.js +2 -0
- package/dist/component/schema.js.map +1 -1
- package/docs/react-workflows.md +16 -8
- package/package.json +1 -1
- package/src/client/costRecovery-invoices.ts +19 -4
- package/src/client/costRecovery.ts +4 -2
- package/src/client/processingCostReconciliation/client.ts +75 -0
- package/src/client/processingCostReconciliation/contracts.ts +176 -0
- package/src/client/processingCostReconciliation/invoiceFunding.ts +270 -0
- package/src/client/processingCostReconciliation/invoiceProvider.test.ts +353 -0
- package/src/client/processingCostReconciliation/provider.test.ts +324 -0
- package/src/client/processingCostReconciliation/provider.ts +178 -0
- package/src/client/settlement/processingCostHistory.ts +31 -0
- package/src/client/settlement/processingCosts.ts +50 -15
- package/src/component/_generated/api.ts +18 -0
- package/src/component/_generated/component.ts +570 -0
- package/src/component/processingCostReconciliation/adoption.test.ts +206 -0
- package/src/component/processingCostReconciliation/adoption.ts +77 -0
- package/src/component/processingCostReconciliation/bridge.ts +50 -0
- package/src/component/processingCostReconciliation/helpers.ts +55 -0
- package/src/component/processingCostReconciliation/invoice.test.ts +152 -0
- package/src/component/processingCostReconciliation/mutations.ts +148 -0
- package/src/component/processingCostReconciliation/queries.ts +18 -0
- package/src/component/processingCostReconciliation/rollback.ts +72 -0
- package/src/component/processingCostReconciliation/schema.ts +191 -0
- package/src/component/processingCostReconciliation/state.test.ts +407 -0
- package/src/component/processingCostReconciliation/steps.ts +168 -0
- package/src/component/processingCostReconciliation/validation.ts +79 -0
- package/src/component/processingCostReconciliation/workflow.test.ts +329 -0
- package/src/component/processingCostReconciliation/workflow.ts +50 -0
- 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
|
+
});
|