@fantastic.dev/better-stripe 0.47.0 → 0.48.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 +30 -0
- package/README.md +1 -1
- package/dist/client/billing/historyPages.d.ts +22 -0
- package/dist/client/billing/historyPages.d.ts.map +1 -0
- package/dist/client/billing/historyPages.js +8 -0
- package/dist/client/billing/historyPages.js.map +1 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
- package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts +21 -16
- package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +42 -32
- package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
- package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
- package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
- package/dist/client/publicTypes.d.ts +1 -0
- package/dist/client/publicTypes.d.ts.map +1 -1
- package/dist/client/readContracts.d.ts +4 -0
- package/dist/client/readContracts.d.ts.map +1 -1
- package/dist/client/readContracts.js +8 -0
- package/dist/client/readContracts.js.map +1 -1
- package/dist/client/webhooks/handler.d.ts.map +1 -1
- package/dist/client/webhooks/handler.js +6 -3
- package/dist/client/webhooks/handler.js.map +1 -1
- package/dist/client/webhooks/processors.d.ts.map +1 -1
- package/dist/client/webhooks/processors.js +3 -65
- package/dist/client/webhooks/processors.js.map +1 -1
- package/dist/client/webhooks/refundDelivery.d.ts +5 -0
- package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
- package/dist/client/webhooks/refundDelivery.js +28 -0
- package/dist/client/webhooks/refundDelivery.js.map +1 -0
- package/dist/client/webhooks/refundRecovery.d.ts +5 -0
- package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
- package/dist/client/webhooks/refundRecovery.js +36 -0
- package/dist/client/webhooks/refundRecovery.js.map +1 -0
- package/dist/component/_generated/api.d.ts +4 -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 +100 -0
- package/dist/component/_generated/component.d.ts.map +1 -1
- package/dist/component/balanceFunding/mutations.d.ts +16 -16
- package/dist/component/billing/schema.d.ts +5 -0
- package/dist/component/billing/schema.d.ts.map +1 -1
- package/dist/component/billing/schema.js +13 -0
- package/dist/component/billing/schema.js.map +1 -1
- package/dist/component/billingHistory/queries.d.ts +97 -0
- package/dist/component/billingHistory/queries.d.ts.map +1 -0
- package/dist/component/billingHistory/queries.js +65 -0
- package/dist/component/billingHistory/queries.js.map +1 -0
- package/dist/component/billingHistory/scope.d.ts +23 -0
- package/dist/component/billingHistory/scope.d.ts.map +1 -0
- package/dist/component/billingHistory/scope.js +54 -0
- package/dist/component/billingHistory/scope.js.map +1 -0
- package/dist/component/connect/validators.js +1 -1
- package/dist/component/connect/validators.js.map +1 -1
- package/dist/component/earnings/triggers.d.ts +10 -0
- package/dist/component/earnings/triggers.d.ts.map +1 -1
- package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
- package/dist/component/refundSync/mutations.d.ts +1 -1
- package/dist/component/refundSync/mutations.d.ts.map +1 -1
- package/dist/component/schema.d.ts +5 -0
- package/dist/react/workflows/PlanPricingEditor.js +2 -2
- package/dist/react/workflows/PlanPricingEditor.js.map +1 -1
- package/docs/billing-history.md +13 -0
- package/docs/react-workflows.md +6 -2
- package/docs/refund-context.md +42 -9
- package/docs/releasing.md +11 -0
- package/package.json +3 -2
- package/src/client/billing/historyPages.test.ts +58 -0
- package/src/client/billing/historyPages.ts +48 -0
- package/src/client/publicTypes.ts +7 -0
- package/src/client/readContracts.ts +16 -0
- package/src/client/webhooks/handler.ts +7 -3
- package/src/client/webhooks/processors.test.ts +9 -7
- package/src/client/webhooks/processors.ts +3 -88
- package/src/client/webhooks/refund-delivery.test.ts +512 -0
- package/src/client/webhooks/refundDelivery.ts +42 -0
- package/src/client/webhooks/refundRecovery.ts +52 -0
- package/src/client/webhooks.test.ts +35 -42
- package/src/component/_generated/api.ts +4 -0
- package/src/component/_generated/component.ts +128 -0
- package/src/component/billing/schema.ts +13 -0
- package/src/component/billingHistory/guards.test.ts +235 -0
- package/src/component/billingHistory/options.test.ts +35 -0
- package/src/component/billingHistory/pages.test.ts +74 -0
- package/src/component/billingHistory/queries.ts +88 -0
- package/src/component/billingHistory/scope.ts +77 -0
- package/src/component/connect/validators.ts +1 -1
- package/src/react/workflows/PlanPricingEditor.currency.test.tsx +1 -1
- package/src/react/workflows/PlanPricingEditor.tsx +2 -2
- package/src/react/workflows/PlanPricingEditor.zero.test.tsx +100 -0
|
@@ -0,0 +1,512 @@
|
|
|
1
|
+
// @vitest-environment edge-runtime
|
|
2
|
+
import Stripe from "stripe";
|
|
3
|
+
import { convexTest } from "convex-test";
|
|
4
|
+
import {
|
|
5
|
+
componentsGeneric,
|
|
6
|
+
defineSchema,
|
|
7
|
+
httpRouter,
|
|
8
|
+
makeFunctionReference,
|
|
9
|
+
} from "convex/server";
|
|
10
|
+
import { expect, it, vi } from "vitest";
|
|
11
|
+
import schema from "../../component/schema.js";
|
|
12
|
+
import { BetterStripe, registerRoutes } from "../index.js";
|
|
13
|
+
import { getStripeClient, type Component, type RunCtx } from "../helpers.js";
|
|
14
|
+
import type { WebhookHandlerRefs } from "../types.js";
|
|
15
|
+
|
|
16
|
+
const component = componentsGeneric().betterStripe as unknown as Component;
|
|
17
|
+
const modules = import.meta.glob("../../component/**/*.*s");
|
|
18
|
+
const secret = "whsec_synthetic_refund_delivery";
|
|
19
|
+
const original = {
|
|
20
|
+
id: "re_delivery",
|
|
21
|
+
object: "refund",
|
|
22
|
+
amount: 250,
|
|
23
|
+
currency: "usd",
|
|
24
|
+
payment_intent: "pi_delivery",
|
|
25
|
+
charge: "ch_delivery",
|
|
26
|
+
status: "pending",
|
|
27
|
+
reason: "requested_by_customer",
|
|
28
|
+
metadata: {},
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
async function signature(body: string) {
|
|
32
|
+
const timestamp = Math.floor(Date.now() / 1000);
|
|
33
|
+
const encoder = new TextEncoder();
|
|
34
|
+
const key = await crypto.subtle.importKey(
|
|
35
|
+
"raw",
|
|
36
|
+
encoder.encode(secret),
|
|
37
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
38
|
+
false,
|
|
39
|
+
["sign"],
|
|
40
|
+
);
|
|
41
|
+
const bytes = await crypto.subtle.sign(
|
|
42
|
+
"HMAC",
|
|
43
|
+
key,
|
|
44
|
+
encoder.encode(`${timestamp}.${body}`),
|
|
45
|
+
);
|
|
46
|
+
const hash = [...new Uint8Array(bytes)]
|
|
47
|
+
.map((byte) => byte.toString(16).padStart(2, "0"))
|
|
48
|
+
.join("");
|
|
49
|
+
return `t=${timestamp},v1=${hash}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function fixture(isRegistered = true) {
|
|
53
|
+
const key = `sk_test_delivery_${crypto.randomUUID()}`;
|
|
54
|
+
let isCallbackFailing = false;
|
|
55
|
+
const callbackStatuses: string[] = [];
|
|
56
|
+
const observe = async (_ctx: object, doc: { status: string }) => {
|
|
57
|
+
if (isCallbackFailing)
|
|
58
|
+
throw new Error("Synthetic application callback failure");
|
|
59
|
+
callbackStatuses.push(doc.status);
|
|
60
|
+
};
|
|
61
|
+
const sdk = new BetterStripe(component, {
|
|
62
|
+
STRIPE_SECRET_KEY: key,
|
|
63
|
+
triggers: { refund: { onCreate: observe, onUpdate: observe } },
|
|
64
|
+
});
|
|
65
|
+
const http = httpRouter();
|
|
66
|
+
registerRoutes(http, component, {
|
|
67
|
+
stripeSecretKey: key,
|
|
68
|
+
webhookSecret: secret,
|
|
69
|
+
...(isRegistered
|
|
70
|
+
? {
|
|
71
|
+
webhooks: {
|
|
72
|
+
syncWebhook: makeFunctionReference("refundHost:syncWebhook"),
|
|
73
|
+
asyncWebhook: makeFunctionReference("refundHost:asyncWebhook"),
|
|
74
|
+
} as unknown as WebhookHandlerRefs,
|
|
75
|
+
}
|
|
76
|
+
: {}),
|
|
77
|
+
});
|
|
78
|
+
const t = convexTest(defineSchema({}), {
|
|
79
|
+
"./_generated/server.ts": () =>
|
|
80
|
+
import("../../component/_generated/server.js"),
|
|
81
|
+
"./http.ts": async () => ({ default: http }),
|
|
82
|
+
"./refundHost.ts": async () => sdk.webhookHandlers(),
|
|
83
|
+
});
|
|
84
|
+
t.registerComponent("betterStripe", schema, modules);
|
|
85
|
+
const stripe = getStripeClient(key, sdk.stripeApiVersion);
|
|
86
|
+
const calls: { path: string; method: string; account?: string }[] = [];
|
|
87
|
+
let current = { ...original };
|
|
88
|
+
let statusCode = 200;
|
|
89
|
+
let isRecoveryEnabled = false;
|
|
90
|
+
let isReversalFailing = false;
|
|
91
|
+
let isResponseLost = false;
|
|
92
|
+
let providerReversed = 0;
|
|
93
|
+
let pausedRead: { started: () => void; resume: Promise<void> } | undefined;
|
|
94
|
+
const reversalRequests: {
|
|
95
|
+
body: string;
|
|
96
|
+
key: string | undefined;
|
|
97
|
+
account: string | undefined;
|
|
98
|
+
}[] = [];
|
|
99
|
+
const slot = stripe as unknown as {
|
|
100
|
+
_setApiField: (key: string, value: unknown) => void;
|
|
101
|
+
};
|
|
102
|
+
slot._setApiField("maxNetworkRetries", 0);
|
|
103
|
+
slot._setApiField("httpClient", {
|
|
104
|
+
getClientName: () => "synthetic-refund-delivery",
|
|
105
|
+
makeRequest: async (
|
|
106
|
+
...[, , path, method, headers, body]: Parameters<
|
|
107
|
+
ReturnType<typeof Stripe.createNodeHttpClient>["makeRequest"]
|
|
108
|
+
>
|
|
109
|
+
) => {
|
|
110
|
+
calls.push({
|
|
111
|
+
path,
|
|
112
|
+
method,
|
|
113
|
+
account: headers["Stripe-Account"] as string | undefined,
|
|
114
|
+
});
|
|
115
|
+
let response: object = current;
|
|
116
|
+
let responseCode = statusCode;
|
|
117
|
+
if (method === "GET" && path.startsWith("/v1/refunds/re_delivery")) {
|
|
118
|
+
response = current;
|
|
119
|
+
if (pausedRead) {
|
|
120
|
+
const pending = pausedRead;
|
|
121
|
+
pausedRead = undefined;
|
|
122
|
+
pending.started();
|
|
123
|
+
await pending.resume;
|
|
124
|
+
}
|
|
125
|
+
} else if (
|
|
126
|
+
isRecoveryEnabled &&
|
|
127
|
+
method === "GET" &&
|
|
128
|
+
path === "/v1/charges/ch_delivery"
|
|
129
|
+
) {
|
|
130
|
+
response = {
|
|
131
|
+
id: "ch_delivery",
|
|
132
|
+
object: "charge",
|
|
133
|
+
amount: 1000,
|
|
134
|
+
currency: "usd",
|
|
135
|
+
payment_intent: "pi_delivery",
|
|
136
|
+
};
|
|
137
|
+
responseCode = 200;
|
|
138
|
+
} else if (
|
|
139
|
+
isRecoveryEnabled &&
|
|
140
|
+
method === "GET" &&
|
|
141
|
+
path.startsWith("/v1/refunds?")
|
|
142
|
+
) {
|
|
143
|
+
response = { object: "list", data: [current], has_more: false };
|
|
144
|
+
responseCode = 200;
|
|
145
|
+
} else if (
|
|
146
|
+
isRecoveryEnabled &&
|
|
147
|
+
method === "GET" &&
|
|
148
|
+
path === "/v1/transfers/tr_delivery"
|
|
149
|
+
) {
|
|
150
|
+
response = {
|
|
151
|
+
id: "tr_delivery",
|
|
152
|
+
object: "transfer",
|
|
153
|
+
amount: 1000,
|
|
154
|
+
amount_reversed: providerReversed,
|
|
155
|
+
};
|
|
156
|
+
responseCode = 200;
|
|
157
|
+
} else if (
|
|
158
|
+
isRecoveryEnabled &&
|
|
159
|
+
method === "POST" &&
|
|
160
|
+
path === "/v1/transfers/tr_delivery/reversals"
|
|
161
|
+
) {
|
|
162
|
+
reversalRequests.push({
|
|
163
|
+
body: String(body),
|
|
164
|
+
key: headers["Idempotency-Key"] as string | undefined,
|
|
165
|
+
account: headers["Stripe-Account"] as string | undefined,
|
|
166
|
+
});
|
|
167
|
+
responseCode = isReversalFailing ? 503 : 200;
|
|
168
|
+
if (!isReversalFailing)
|
|
169
|
+
providerReversed = Number(
|
|
170
|
+
new URLSearchParams(String(body)).get("amount"),
|
|
171
|
+
);
|
|
172
|
+
response = {
|
|
173
|
+
id: "trr_delivery",
|
|
174
|
+
object: "transfer_reversal",
|
|
175
|
+
amount: providerReversed,
|
|
176
|
+
};
|
|
177
|
+
if (isResponseLost) {
|
|
178
|
+
isResponseLost = false;
|
|
179
|
+
throw new Error("Synthetic lost committed reversal response");
|
|
180
|
+
}
|
|
181
|
+
} else throw new Error("Unexpected provider operation");
|
|
182
|
+
return {
|
|
183
|
+
getStatusCode: () => responseCode,
|
|
184
|
+
getHeaders: () => ({}),
|
|
185
|
+
getRawResponse: () => ({}),
|
|
186
|
+
toJSON: async () =>
|
|
187
|
+
responseCode >= 400
|
|
188
|
+
? {
|
|
189
|
+
error: {
|
|
190
|
+
type: "api_error",
|
|
191
|
+
message: "Synthetic current refund unavailable",
|
|
192
|
+
},
|
|
193
|
+
}
|
|
194
|
+
: structuredClone(response),
|
|
195
|
+
toStream: () => {
|
|
196
|
+
throw new Error("Unexpected stream");
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
},
|
|
200
|
+
});
|
|
201
|
+
const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
|
|
202
|
+
return {
|
|
203
|
+
t,
|
|
204
|
+
sdk,
|
|
205
|
+
ctx,
|
|
206
|
+
calls,
|
|
207
|
+
callbackStatuses,
|
|
208
|
+
reversalRequests,
|
|
209
|
+
providerReversed: () => providerReversed,
|
|
210
|
+
pauseNextRead: () => {
|
|
211
|
+
let start!: () => void;
|
|
212
|
+
let release!: () => void;
|
|
213
|
+
const started = new Promise<void>((resolve) => {
|
|
214
|
+
start = resolve;
|
|
215
|
+
});
|
|
216
|
+
const resume = new Promise<void>((resolve) => {
|
|
217
|
+
release = resolve;
|
|
218
|
+
});
|
|
219
|
+
pausedRead = { started: start, resume };
|
|
220
|
+
return { started, release };
|
|
221
|
+
},
|
|
222
|
+
enableRecovery: () => {
|
|
223
|
+
isRecoveryEnabled = true;
|
|
224
|
+
},
|
|
225
|
+
failReversal: (value: boolean) => {
|
|
226
|
+
isReversalFailing = value;
|
|
227
|
+
},
|
|
228
|
+
loseReversalResponse: () => {
|
|
229
|
+
isResponseLost = true;
|
|
230
|
+
},
|
|
231
|
+
seedLeg: () =>
|
|
232
|
+
t.mutation(component.connect.mutations.upsertTransfer, {
|
|
233
|
+
stripeTransferId: "tr_delivery",
|
|
234
|
+
sourceChargeId: "ch_delivery",
|
|
235
|
+
destinationAccountId: "acct_recipient",
|
|
236
|
+
amount: 1000,
|
|
237
|
+
currency: "usd",
|
|
238
|
+
status: "paid",
|
|
239
|
+
role: "store",
|
|
240
|
+
}),
|
|
241
|
+
failCallback: (value: boolean) => {
|
|
242
|
+
isCallbackFailing = value;
|
|
243
|
+
},
|
|
244
|
+
setRefund: (patch: Partial<typeof original>) => {
|
|
245
|
+
current = { ...original, ...patch };
|
|
246
|
+
},
|
|
247
|
+
set: (status: string, code = 200) => {
|
|
248
|
+
current = { ...original, status };
|
|
249
|
+
statusCode = code;
|
|
250
|
+
},
|
|
251
|
+
row: () => sdk.getRefundByStripeId(ctx, { stripeRefundId: original.id }),
|
|
252
|
+
send: async (
|
|
253
|
+
id: string,
|
|
254
|
+
snapshotStatus = "pending",
|
|
255
|
+
account?: string,
|
|
256
|
+
isValid = true,
|
|
257
|
+
type = "refund.updated",
|
|
258
|
+
) => {
|
|
259
|
+
const body = JSON.stringify({
|
|
260
|
+
id,
|
|
261
|
+
object: "event",
|
|
262
|
+
type,
|
|
263
|
+
livemode: false,
|
|
264
|
+
created: Math.floor(Date.now() / 1000),
|
|
265
|
+
...(account ? { account } : {}),
|
|
266
|
+
data: { object: { ...original, status: snapshotStatus } },
|
|
267
|
+
});
|
|
268
|
+
return t.fetch("/stripe/webhook", {
|
|
269
|
+
method: "POST",
|
|
270
|
+
body,
|
|
271
|
+
headers: {
|
|
272
|
+
"stripe-signature": isValid
|
|
273
|
+
? await signature(body)
|
|
274
|
+
: "t=0,v1=invalid",
|
|
275
|
+
},
|
|
276
|
+
});
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
it("control: rejects an invalid signature before provider/component writes", async () => {
|
|
282
|
+
const f = fixture();
|
|
283
|
+
expect(
|
|
284
|
+
(await f.send("evt_invalid", "pending", undefined, false)).status,
|
|
285
|
+
).toBe(400);
|
|
286
|
+
expect(f.calls).toEqual([]);
|
|
287
|
+
expect(await f.row()).toBeNull();
|
|
288
|
+
});
|
|
289
|
+
|
|
290
|
+
it.each([true, false])(
|
|
291
|
+
"reconciles current provider state through registered=%s delivery",
|
|
292
|
+
async (registered) => {
|
|
293
|
+
const f = fixture(registered);
|
|
294
|
+
f.set("requires_action");
|
|
295
|
+
expect((await f.send("evt_old_pending")).status).toBe(200);
|
|
296
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
297
|
+
expect(f.calls).toEqual([
|
|
298
|
+
{ path: "/v1/refunds/re_delivery", method: "GET", account: undefined },
|
|
299
|
+
]);
|
|
300
|
+
},
|
|
301
|
+
);
|
|
302
|
+
|
|
303
|
+
it("does not ACK a current-provider outage or apply the snapshot", async () => {
|
|
304
|
+
const f = fixture();
|
|
305
|
+
f.set("pending", 503);
|
|
306
|
+
expect((await f.send("evt_outage")).status).toBe(500);
|
|
307
|
+
expect(await f.row()).toBeNull();
|
|
308
|
+
expect(
|
|
309
|
+
await f.t.query(component.webhooks.queries.getWebhookEvent, {
|
|
310
|
+
stripeEventId: "evt_outage",
|
|
311
|
+
}),
|
|
312
|
+
).toMatchObject({ status: "failed" });
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
it("reopens the same failed event against current provider state", async () => {
|
|
316
|
+
const f = fixture();
|
|
317
|
+
f.set("pending", 503);
|
|
318
|
+
expect((await f.send("evt_retry")).status).toBe(500);
|
|
319
|
+
f.set("requires_action");
|
|
320
|
+
expect((await f.send("evt_retry")).status).toBe(200);
|
|
321
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
322
|
+
expect(f.callbackStatuses).toEqual(["requires_action"]);
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
it("deduplicates a processed event without another GET or changed callback", async () => {
|
|
326
|
+
const f = fixture();
|
|
327
|
+
f.set("requires_action");
|
|
328
|
+
expect((await f.send("evt_duplicate")).status).toBe(200);
|
|
329
|
+
expect((await f.send("evt_duplicate")).status).toBe(200);
|
|
330
|
+
expect(f.calls).toHaveLength(1);
|
|
331
|
+
expect(f.callbackStatuses).toEqual(["requires_action"]);
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
it("does not ACK a fresh processing refund when optional hook retry is disabled", async () => {
|
|
335
|
+
const f = fixture();
|
|
336
|
+
await f.t.mutation(component.webhooks.mutations.insertWebhookEvent, {
|
|
337
|
+
stripeEventId: "evt_processing",
|
|
338
|
+
eventType: "refund.updated",
|
|
339
|
+
});
|
|
340
|
+
expect((await f.send("evt_processing")).status).toBe(503);
|
|
341
|
+
expect(f.calls).toEqual([]);
|
|
342
|
+
});
|
|
343
|
+
|
|
344
|
+
it("reopens stale processing through current provider reconciliation", async () => {
|
|
345
|
+
const f = fixture();
|
|
346
|
+
await f.t.mutation(component.webhooks.mutations.insertWebhookEvent, {
|
|
347
|
+
stripeEventId: "evt_stale",
|
|
348
|
+
eventType: "refund.updated",
|
|
349
|
+
});
|
|
350
|
+
vi.useFakeTimers({ toFake: ["Date"] });
|
|
351
|
+
try {
|
|
352
|
+
vi.setSystemTime(Date.now() + 11 * 60 * 1000);
|
|
353
|
+
f.set("requires_action");
|
|
354
|
+
expect((await f.send("evt_stale")).status).toBe(200);
|
|
355
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
356
|
+
} finally {
|
|
357
|
+
vi.useRealTimers();
|
|
358
|
+
}
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
it("rolls back acceptance when a registered changed callback fails, then retries", async () => {
|
|
362
|
+
const f = fixture();
|
|
363
|
+
f.set("requires_action");
|
|
364
|
+
f.failCallback(true);
|
|
365
|
+
expect((await f.send("evt_callback")).status).toBe(500);
|
|
366
|
+
expect(await f.row()).toBeNull();
|
|
367
|
+
f.failCallback(false);
|
|
368
|
+
expect((await f.send("evt_callback")).status).toBe(200);
|
|
369
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
it("uses signed connected account only as the HTTP API realm", async () => {
|
|
373
|
+
const f = fixture();
|
|
374
|
+
f.set("requires_action");
|
|
375
|
+
expect(
|
|
376
|
+
(await f.send("evt_connected", "pending", "acct_signed_realm")).status,
|
|
377
|
+
).toBe(200);
|
|
378
|
+
expect(f.calls).toEqual([
|
|
379
|
+
{
|
|
380
|
+
path: "/v1/refunds/re_delivery",
|
|
381
|
+
method: "GET",
|
|
382
|
+
account: "acct_signed_realm",
|
|
383
|
+
},
|
|
384
|
+
]);
|
|
385
|
+
expect((await f.row())?.accountId).toBeUndefined();
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
it("allows a legitimate current bank-return transition after succeeded", async () => {
|
|
389
|
+
const f = fixture();
|
|
390
|
+
f.set("succeeded");
|
|
391
|
+
expect((await f.send("evt_success", "pending")).status).toBe(200);
|
|
392
|
+
f.set("requires_action");
|
|
393
|
+
expect((await f.send("evt_return", "succeeded")).status).toBe(200);
|
|
394
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
395
|
+
expect(f.callbackStatuses).toEqual(["succeeded", "requires_action"]);
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
it("does not substitute notification fields for malformed current identity", async () => {
|
|
399
|
+
const f = fixture();
|
|
400
|
+
f.setRefund({ id: "re_foreign", status: "requires_action" });
|
|
401
|
+
expect((await f.send("evt_foreign")).status).toBe(500);
|
|
402
|
+
expect(await f.row()).toBeNull();
|
|
403
|
+
expect(f.callbackStatuses).toEqual([]);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
it.each(["refund.created", "refund.updated", "refund.failed"])(
|
|
407
|
+
"reconciles %s from the current source",
|
|
408
|
+
async (type) => {
|
|
409
|
+
const f = fixture();
|
|
410
|
+
f.set("requires_action");
|
|
411
|
+
expect(
|
|
412
|
+
(await f.send(`evt_${type}`, "pending", undefined, true, type)).status,
|
|
413
|
+
).toBe(200);
|
|
414
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
415
|
+
},
|
|
416
|
+
);
|
|
417
|
+
|
|
418
|
+
it("holds connected refund recovery before any unscoped platform transfer operation", async () => {
|
|
419
|
+
const f = fixture();
|
|
420
|
+
await f.seedLeg();
|
|
421
|
+
f.enableRecovery();
|
|
422
|
+
f.set("succeeded");
|
|
423
|
+
expect(
|
|
424
|
+
(await f.send("evt_connected_leg", "pending", "acct_signed_realm")).status,
|
|
425
|
+
).toBe(500);
|
|
426
|
+
expect(f.calls).toEqual([
|
|
427
|
+
{
|
|
428
|
+
path: "/v1/refunds/re_delivery",
|
|
429
|
+
method: "GET",
|
|
430
|
+
account: "acct_signed_realm",
|
|
431
|
+
},
|
|
432
|
+
]);
|
|
433
|
+
expect(f.reversalRequests).toEqual([]);
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
it("runs existing platform split recovery from current success despite pending snapshot", async () => {
|
|
437
|
+
const f = fixture();
|
|
438
|
+
await f.seedLeg();
|
|
439
|
+
f.enableRecovery();
|
|
440
|
+
f.set("succeeded");
|
|
441
|
+
expect((await f.send("evt_split", "pending")).status).toBe(200);
|
|
442
|
+
expect(f.reversalRequests).toEqual([
|
|
443
|
+
{
|
|
444
|
+
body: "amount=250",
|
|
445
|
+
key: "bs_rev_re_delivery_tr_delivery",
|
|
446
|
+
account: undefined,
|
|
447
|
+
},
|
|
448
|
+
]);
|
|
449
|
+
expect(f.providerReversed()).toBe(250);
|
|
450
|
+
expect((await f.send("evt_split", "pending")).status).toBe(200);
|
|
451
|
+
expect(f.reversalRequests).toHaveLength(1);
|
|
452
|
+
// A distinct ledger event must still reuse the existing refund operation.
|
|
453
|
+
expect((await f.send("evt_split_distinct", "pending")).status).toBe(200);
|
|
454
|
+
expect(f.reversalRequests).toHaveLength(1);
|
|
455
|
+
expect(f.providerReversed()).toBe(250);
|
|
456
|
+
expect(f.callbackStatuses).toEqual(["succeeded"]);
|
|
457
|
+
});
|
|
458
|
+
|
|
459
|
+
it("retries an existing failed reversal after unchanged mirror without repeating changed callback", async () => {
|
|
460
|
+
const f = fixture();
|
|
461
|
+
await f.seedLeg();
|
|
462
|
+
f.enableRecovery();
|
|
463
|
+
f.set("succeeded");
|
|
464
|
+
f.failReversal(true);
|
|
465
|
+
expect((await f.send("evt_split_retry", "pending")).status).toBe(500);
|
|
466
|
+
expect(await f.row()).toMatchObject({ status: "succeeded" });
|
|
467
|
+
expect(f.callbackStatuses).toEqual(["succeeded"]);
|
|
468
|
+
f.failReversal(false);
|
|
469
|
+
expect((await f.send("evt_split_retry", "pending")).status).toBe(200);
|
|
470
|
+
expect(f.reversalRequests).toHaveLength(2);
|
|
471
|
+
expect(f.reversalRequests[0]).toEqual(f.reversalRequests[1]);
|
|
472
|
+
expect(f.providerReversed()).toBe(250);
|
|
473
|
+
expect(f.callbackStatuses).toEqual(["succeeded"]);
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
it("recovers a lost committed reversal response from existing transfer receipt without another POST", async () => {
|
|
477
|
+
const f = fixture();
|
|
478
|
+
await f.seedLeg();
|
|
479
|
+
f.enableRecovery();
|
|
480
|
+
f.set("succeeded");
|
|
481
|
+
f.loseReversalResponse();
|
|
482
|
+
expect((await f.send("evt_split_lost", "pending")).status).toBe(500);
|
|
483
|
+
expect(f.providerReversed()).toBe(250);
|
|
484
|
+
expect((await f.send("evt_split_lost", "pending")).status).toBe(200);
|
|
485
|
+
expect(f.reversalRequests).toHaveLength(1);
|
|
486
|
+
const legs = await f.t.query(
|
|
487
|
+
component.connect.queries.listTransfersByCharge,
|
|
488
|
+
{ sourceChargeId: "ch_delivery" },
|
|
489
|
+
);
|
|
490
|
+
expect(legs[0]).toMatchObject({ reversedAmount: 250 });
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
it("fails a delayed older observation after a newer delivery accepts without stale callback", async () => {
|
|
494
|
+
const f = fixture();
|
|
495
|
+
const pause = f.pauseNextRead();
|
|
496
|
+
const old = f.send("evt_old_racing");
|
|
497
|
+
await pause.started;
|
|
498
|
+
try {
|
|
499
|
+
f.set("requires_action");
|
|
500
|
+
expect((await f.send("evt_new_racing")).status).toBe(200);
|
|
501
|
+
} finally {
|
|
502
|
+
pause.release();
|
|
503
|
+
}
|
|
504
|
+
expect((await old).status).toBe(500);
|
|
505
|
+
expect(await f.row()).toMatchObject({ status: "requires_action" });
|
|
506
|
+
expect(f.callbackStatuses).toEqual(["requires_action"]);
|
|
507
|
+
expect(
|
|
508
|
+
await f.t.query(component.webhooks.queries.getWebhookEvent, {
|
|
509
|
+
stripeEventId: "evt_old_racing",
|
|
510
|
+
}),
|
|
511
|
+
).toMatchObject({ status: "failed" });
|
|
512
|
+
});
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type Stripe from "stripe";
|
|
2
|
+
import { prepareRefundSync } from "../connect/refundSync.js";
|
|
3
|
+
import { componentRef, type WebhookContext } from "./helpers.js";
|
|
4
|
+
import { dispatchRefundReconciliation } from "./refundReconciliation.js";
|
|
5
|
+
import type { RefundReconciliationResult } from "./refundReconciliationValidators.js";
|
|
6
|
+
import { recoverRefundTransfers } from "./refundRecovery.js";
|
|
7
|
+
|
|
8
|
+
/** A signed notification selects the refund ID/API realm, never its current state. */
|
|
9
|
+
export async function handleRefundEvent(
|
|
10
|
+
whCtx: WebhookContext,
|
|
11
|
+
notification: Stripe.Refund,
|
|
12
|
+
accountId?: string,
|
|
13
|
+
) {
|
|
14
|
+
const prepared = await prepareRefundSync(
|
|
15
|
+
whCtx.stripe,
|
|
16
|
+
whCtx.component,
|
|
17
|
+
whCtx.ctx,
|
|
18
|
+
{
|
|
19
|
+
stripeRefundId: notification.id,
|
|
20
|
+
scope:
|
|
21
|
+
accountId === undefined
|
|
22
|
+
? { type: "platform" }
|
|
23
|
+
: { type: "connected", accountId },
|
|
24
|
+
},
|
|
25
|
+
);
|
|
26
|
+
let accepted: RefundReconciliationResult;
|
|
27
|
+
try {
|
|
28
|
+
accepted = await dispatchRefundReconciliation(whCtx, prepared);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
await whCtx.ctx.runMutation(
|
|
31
|
+
componentRef(whCtx.component, "refundSync/mutations/markUnknown"),
|
|
32
|
+
{
|
|
33
|
+
stripeRefundId: prepared.stripeRefundId,
|
|
34
|
+
apiContext: prepared.apiContext,
|
|
35
|
+
generation: prepared.generation,
|
|
36
|
+
},
|
|
37
|
+
);
|
|
38
|
+
throw error;
|
|
39
|
+
}
|
|
40
|
+
// Mirror replay does not prove a previously interrupted recovery completed.
|
|
41
|
+
await recoverRefundTransfers(whCtx, accepted.refund, accepted.apiContext);
|
|
42
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { successfulRefundPrincipal } from "../connect/refundPrincipal.js";
|
|
2
|
+
import { reverseTransfersForRefund } from "../connect/transfers.js";
|
|
3
|
+
import type { StripeComponentRefund } from "../types.js";
|
|
4
|
+
import { componentRef, type WebhookContext } from "./helpers.js";
|
|
5
|
+
|
|
6
|
+
/** Existing split recovery, selected only by an accepted current observation. */
|
|
7
|
+
export async function recoverRefundTransfers(
|
|
8
|
+
whCtx: WebhookContext,
|
|
9
|
+
refund: StripeComponentRefund,
|
|
10
|
+
apiContext: string,
|
|
11
|
+
) {
|
|
12
|
+
// Split-sale clawback (BTS-34): when a separate-charges sale is refunded,
|
|
13
|
+
// pull the refunded share back from each recipient pro-rata. Only ledger
|
|
14
|
+
// legs identify a split sale — destination-charge auto-transfers are not in
|
|
15
|
+
// the ledger and are handled by Stripe-native `reverse_transfer` at refund
|
|
16
|
+
// creation. Runs on `refund.updated` too so a pending→succeeded refund
|
|
17
|
+
// (e.g. ACH) still claws back. Errors propagate → event `failed` → Stripe
|
|
18
|
+
// retries; `reverseTransfersForRefund`'s delta-to-target math makes the
|
|
19
|
+
// re-run converge without double-reversing.
|
|
20
|
+
const chargeId = refund.stripeChargeId;
|
|
21
|
+
if (refund.status !== "succeeded" || !chargeId) return;
|
|
22
|
+
const legs = ((await whCtx.ctx.runQuery(
|
|
23
|
+
componentRef(whCtx.component, "connect/queries/listTransfersByCharge"),
|
|
24
|
+
{ sourceChargeId: chargeId },
|
|
25
|
+
)) ?? []) as unknown[];
|
|
26
|
+
if (legs.length === 0) {
|
|
27
|
+
const obligations = (await whCtx.ctx.runQuery(
|
|
28
|
+
componentRef(
|
|
29
|
+
whCtx.component,
|
|
30
|
+
"affiliateRecovery/queries/chargeObligations",
|
|
31
|
+
),
|
|
32
|
+
{ sourceChargeId: chargeId },
|
|
33
|
+
)) as unknown[] | null;
|
|
34
|
+
if (!obligations?.length) return;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// The existing split recovery engine operates in the platform namespace.
|
|
38
|
+
// A signed connected read cannot authorize unscoped platform money operations.
|
|
39
|
+
if (apiContext !== "platform")
|
|
40
|
+
throw new Error(
|
|
41
|
+
"Connected refund split recovery requires qualified platform authority.",
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
// Fetch succeeded refunds: charge.amount_refunded can include pending funds.
|
|
45
|
+
const charge = await whCtx.stripe.charges.retrieve(chargeId);
|
|
46
|
+
await reverseTransfersForRefund(whCtx.stripe, whCtx.component, whCtx.ctx, {
|
|
47
|
+
sourceChargeId: chargeId,
|
|
48
|
+
refundId: refund.stripeRefundId,
|
|
49
|
+
chargeAmount: charge.amount,
|
|
50
|
+
amountRefunded: await successfulRefundPrincipal(whCtx.stripe, chargeId),
|
|
51
|
+
});
|
|
52
|
+
}
|