@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.
Files changed (90) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/historyPages.d.ts +22 -0
  4. package/dist/client/billing/historyPages.d.ts.map +1 -0
  5. package/dist/client/billing/historyPages.js +8 -0
  6. package/dist/client/billing/historyPages.js.map +1 -0
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +21 -16
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +42 -32
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/publicTypes.d.ts +1 -0
  16. package/dist/client/publicTypes.d.ts.map +1 -1
  17. package/dist/client/readContracts.d.ts +4 -0
  18. package/dist/client/readContracts.d.ts.map +1 -1
  19. package/dist/client/readContracts.js +8 -0
  20. package/dist/client/readContracts.js.map +1 -1
  21. package/dist/client/webhooks/handler.d.ts.map +1 -1
  22. package/dist/client/webhooks/handler.js +6 -3
  23. package/dist/client/webhooks/handler.js.map +1 -1
  24. package/dist/client/webhooks/processors.d.ts.map +1 -1
  25. package/dist/client/webhooks/processors.js +3 -65
  26. package/dist/client/webhooks/processors.js.map +1 -1
  27. package/dist/client/webhooks/refundDelivery.d.ts +5 -0
  28. package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
  29. package/dist/client/webhooks/refundDelivery.js +28 -0
  30. package/dist/client/webhooks/refundDelivery.js.map +1 -0
  31. package/dist/client/webhooks/refundRecovery.d.ts +5 -0
  32. package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
  33. package/dist/client/webhooks/refundRecovery.js +36 -0
  34. package/dist/client/webhooks/refundRecovery.js.map +1 -0
  35. package/dist/component/_generated/api.d.ts +4 -0
  36. package/dist/component/_generated/api.d.ts.map +1 -1
  37. package/dist/component/_generated/api.js.map +1 -1
  38. package/dist/component/_generated/component.d.ts +100 -0
  39. package/dist/component/_generated/component.d.ts.map +1 -1
  40. package/dist/component/balanceFunding/mutations.d.ts +16 -16
  41. package/dist/component/billing/schema.d.ts +5 -0
  42. package/dist/component/billing/schema.d.ts.map +1 -1
  43. package/dist/component/billing/schema.js +13 -0
  44. package/dist/component/billing/schema.js.map +1 -1
  45. package/dist/component/billingHistory/queries.d.ts +97 -0
  46. package/dist/component/billingHistory/queries.d.ts.map +1 -0
  47. package/dist/component/billingHistory/queries.js +65 -0
  48. package/dist/component/billingHistory/queries.js.map +1 -0
  49. package/dist/component/billingHistory/scope.d.ts +23 -0
  50. package/dist/component/billingHistory/scope.d.ts.map +1 -0
  51. package/dist/component/billingHistory/scope.js +54 -0
  52. package/dist/component/billingHistory/scope.js.map +1 -0
  53. package/dist/component/connect/validators.js +1 -1
  54. package/dist/component/connect/validators.js.map +1 -1
  55. package/dist/component/earnings/triggers.d.ts +10 -0
  56. package/dist/component/earnings/triggers.d.ts.map +1 -1
  57. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  58. package/dist/component/refundSync/mutations.d.ts +1 -1
  59. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  60. package/dist/component/schema.d.ts +5 -0
  61. package/dist/react/workflows/PlanPricingEditor.js +2 -2
  62. package/dist/react/workflows/PlanPricingEditor.js.map +1 -1
  63. package/docs/billing-history.md +13 -0
  64. package/docs/react-workflows.md +6 -2
  65. package/docs/refund-context.md +42 -9
  66. package/docs/releasing.md +11 -0
  67. package/package.json +3 -2
  68. package/src/client/billing/historyPages.test.ts +58 -0
  69. package/src/client/billing/historyPages.ts +48 -0
  70. package/src/client/publicTypes.ts +7 -0
  71. package/src/client/readContracts.ts +16 -0
  72. package/src/client/webhooks/handler.ts +7 -3
  73. package/src/client/webhooks/processors.test.ts +9 -7
  74. package/src/client/webhooks/processors.ts +3 -88
  75. package/src/client/webhooks/refund-delivery.test.ts +512 -0
  76. package/src/client/webhooks/refundDelivery.ts +42 -0
  77. package/src/client/webhooks/refundRecovery.ts +52 -0
  78. package/src/client/webhooks.test.ts +35 -42
  79. package/src/component/_generated/api.ts +4 -0
  80. package/src/component/_generated/component.ts +128 -0
  81. package/src/component/billing/schema.ts +13 -0
  82. package/src/component/billingHistory/guards.test.ts +235 -0
  83. package/src/component/billingHistory/options.test.ts +35 -0
  84. package/src/component/billingHistory/pages.test.ts +74 -0
  85. package/src/component/billingHistory/queries.ts +88 -0
  86. package/src/component/billingHistory/scope.ts +77 -0
  87. package/src/component/connect/validators.ts +1 -1
  88. package/src/react/workflows/PlanPricingEditor.currency.test.tsx +1 -1
  89. package/src/react/workflows/PlanPricingEditor.tsx +2 -2
  90. package/src/react/workflows/PlanPricingEditor.zero.test.tsx +100 -0
@@ -129,11 +129,11 @@ history is not cardinality bounded: native resource limits can abort the whole
129
129
  accepting transaction, preserving the last committed projection. There is no
130
130
  partial sum, silent truncation or all-backlog-capacity guarantee.
131
131
 
132
- This primitive does **not** yet route the legacy signed refund webhook pipeline
133
- through generation qualification. Legacy `upsertRefund` and raw callbacks remain
134
- unfenced; they can still overwrite observations outside this operation. The
135
- separate shared-pipeline integration must preserve generation qualification
136
- through its callback transaction before hosts claim webhook-wide convergence.
132
+ This standalone primitive does not run application callbacks or transfer recovery.
133
+ The maintained signed route uses the qualified callback seam below. Direct legacy
134
+ `upsertRefund`/raw-dispatcher calls remain outside generation fencing; hosts must
135
+ not reapply notification snapshots after qualified acceptance. No convergence
136
+ claim covers independent legacy writers.
137
137
  The server-only Vite reference is
138
138
  [`example/convex/connect/refundSync.ts`](../example/convex/connect/refundSync.ts).
139
139
 
@@ -160,7 +160,40 @@ reconciliation; the package does not silently retry a raw upsert as fallback.
160
160
 
161
161
  The direct-component path returns the same accepted observation and rejects
162
162
  superseded results. It has no application callback because no host handler was
163
- registered. This seam does not activate signed notification reconciliation or
164
- change existing reversal recovery. Legacy raw refund delivery remains unfenced
165
- until that separate consumer is adopted. A successful or unchanged mirror is not
166
- proof that a prior provider reversal or financial recovery completed.
163
+ registered. A successful or unchanged mirror is not proof that a prior provider
164
+ reversal or financial recovery completed.
165
+
166
+ ### Signed refund delivery and recovery
167
+
168
+ The existing single `registerRoutes` endpoint verifies the signature before any
169
+ provider access. For `refund.created`, `refund.updated` and `refund.failed`, only
170
+ the signed refund ID and `event.account` select the original refund/API realm.
171
+ The package retrieves current provider state, qualifies it and accepts its durable
172
+ generation through the transaction above. It never substitutes notification
173
+ status, metadata or `event.created` for current state. A legitimate current
174
+ bank-return transition remains valid after a previous succeeded observation.
175
+
176
+ Required synchronization failures return non-2xx and retain failed/retryable event
177
+ ledger state. This applies independently of optional application-hook retry policy.
178
+ An in-flight duplicate returns retryable failure; a processed duplicate does not
179
+ read or notify again. Existing stale-processing recovery reopens an abandoned
180
+ attempt. Superseded observations cannot invoke changed callbacks or be acknowledged
181
+ as reconciled merely because a later generation started. Retry does not prove that
182
+ a later provider observation or economic operation succeeded.
183
+
184
+ After acceptance, current succeeded state can select the existing platform split
185
+ recovery operation. An unchanged mirror still checks that operation: an earlier
186
+ reversal failure or lost response is handled by its existing claim, original
187
+ idempotency key and transfer-receipt reconciliation. The synchronization layer
188
+ adds no reversal calculation or new financial retry permission. A connected refund
189
+ with no platform split obligation can synchronize; a connected refund associated
190
+ with platform recovery legs is held before any unscoped platform provider operation.
191
+ Its qualified mirror may already be committed, but the delivery remains retryable
192
+ and must not advertise complete economic recovery.
193
+
194
+ Refund `onCreate`/`onUpdate` callbacks receive qualified current stored rows and run
195
+ only for changed acceptance. Generic `onEvent`/`events` hooks keep their existing
196
+ verified `Stripe.Event` notification payload; that payload is not authoritative
197
+ current refund state or financial-completion evidence. Async hooks keep their
198
+ existing committed-document/scheduling contract. No live-provider atomicity or
199
+ all-history/native-capacity guarantee is introduced.
package/docs/releasing.md CHANGED
@@ -39,3 +39,14 @@ notes through an ordinary reviewed PR and complete the normal reviewed release a
39
39
  public-artifact verification before application adoption. Never substitute a local
40
40
  tarball, a workflow conclusion or a later audit for the required public artifact or
41
41
  premerge acceptance.
42
+
43
+ ## Compiled public exports
44
+
45
+ `pnpm build` compiles the package and runs `scripts/check-public-exports.mjs`
46
+ against the emitted public SDK, React and testing exports using Node's standard
47
+ ESM resolver. It performs no provider calls. Keep this check in the existing
48
+ build path: bundled source tests and successful Convex registration did not catch
49
+ the extensionless import exposed by the public SDK in 0.47.0. Use explicit `.js`
50
+ extensions for reachable relative imports; do not hide failures behind a custom
51
+ resolver. A corrected local build is candidate evidence; verify the normal
52
+ published artifact before application adoption.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fantastic.dev/better-stripe",
3
- "version": "0.47.0",
3
+ "version": "0.48.0",
4
4
  "description": "A Convex component for Stripe V2 Accounts API integration.",
5
5
  "keywords": [
6
6
  "stripe",
@@ -65,6 +65,7 @@
65
65
  "CHANGELOG.md",
66
66
  "MIGRATION.md",
67
67
  "docs/read-contracts.md",
68
+ "docs/billing-history.md",
68
69
  "docs/invoice-payment-pages.md",
69
70
  "docs/checkout-session-pages.md",
70
71
  "docs/refund-context.md",
@@ -84,7 +85,7 @@
84
85
  "docs/release-handoff.md"
85
86
  ],
86
87
  "scripts": {
87
- "build": "tsc --project ./tsconfig.build.json",
88
+ "build": "tsc --project ./tsconfig.build.json && node scripts/check-public-exports.mjs",
88
89
  "dev": "cd example && pnpm run dev",
89
90
  "clean": "rm -rf dist",
90
91
  "codegen": "pnpm run codegen:lib && pnpm run codegen:example",
@@ -0,0 +1,58 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import { components } from "../setup.test.js";
3
+ import { ReadContractClient } from "../readContracts.js";
4
+
5
+ it("exposes both independent bounded billing history readers on the public client", () => {
6
+ expect(ReadContractClient.prototype).toHaveProperty(
7
+ "paginateSubscriptions",
8
+ expect.any(Function),
9
+ );
10
+ expect(ReadContractClient.prototype).toHaveProperty(
11
+ "paginateCheckoutSessions",
12
+ expect.any(Function),
13
+ );
14
+ });
15
+
16
+ it("forwards the original buyer/account and independent cursors without provider operations", async () => {
17
+ const client = new ReadContractClient(components.betterStripe);
18
+ const result = { page: [], isDone: true, continueCursor: "original_cursor" };
19
+ const runQuery = vi.fn().mockResolvedValue(result);
20
+ const ctx = { runQuery };
21
+ const subscriptions = {
22
+ userId: "original_buyer",
23
+ accountId: "acct_original",
24
+ status: "trialing" as const,
25
+ paginationOpts: { cursor: "subscription_cursor", numItems: 17 },
26
+ };
27
+ const sessions = {
28
+ userId: "original_buyer",
29
+ status: "complete" as const,
30
+ paginationOpts: { cursor: "checkout_cursor", numItems: 19 },
31
+ };
32
+ expect(await client.paginateSubscriptions(ctx, subscriptions)).toBe(result);
33
+ expect(await client.paginateCheckoutSessions(ctx, sessions)).toBe(result);
34
+ expect(runQuery).toHaveBeenNthCalledWith(
35
+ 1,
36
+ components.betterStripe.billingHistory.queries.paginateSubscriptions,
37
+ subscriptions,
38
+ );
39
+ expect(runQuery).toHaveBeenNthCalledWith(
40
+ 2,
41
+ components.betterStripe.billingHistory.queries.paginateCheckoutSessions,
42
+ sessions,
43
+ );
44
+ });
45
+
46
+ it("propagates component read errors without returning an empty success page", async () => {
47
+ const client = new ReadContractClient(components.betterStripe);
48
+ const runQuery = vi.fn().mockRejectedValue(new Error("read failed"));
49
+ await expect(
50
+ client.paginateSubscriptions(
51
+ { runQuery },
52
+ {
53
+ userId: "original",
54
+ paginationOpts: { cursor: null, numItems: 10 },
55
+ },
56
+ ),
57
+ ).rejects.toThrow("read failed");
58
+ });
@@ -0,0 +1,48 @@
1
+ import type { PaginationOptions, PaginationResult } from "convex/server";
2
+ import type {
3
+ CheckoutSessionStatus,
4
+ SubscriptionStatus,
5
+ } from "../../component/billing/validators.js";
6
+ import type { Component, RunCtx } from "../helpers.js";
7
+ import type { Doc } from "../../component/_generated/dataModel.js";
8
+ import { componentRef } from "../webhooks/helpers.js";
9
+
10
+ /** A trusted host supplies the authorized original buyer; the cursor is not authorization. */
11
+ export type SubscriptionHistoryPageOptions = {
12
+ userId: string;
13
+ accountId?: string;
14
+ status?: SubscriptionStatus;
15
+ paginationOpts: PaginationOptions;
16
+ };
17
+ export type CheckoutSessionHistoryPageOptions = {
18
+ userId: string;
19
+ accountId?: string;
20
+ status?: CheckoutSessionStatus;
21
+ paginationOpts: PaginationOptions;
22
+ };
23
+ export type SubscriptionHistoryPage = PaginationResult<Doc<"subscriptions">>;
24
+ export type CheckoutSessionHistoryPage = PaginationResult<
25
+ Doc<"checkoutSessions">
26
+ >;
27
+
28
+ export function paginateSubscriptions(
29
+ component: Component,
30
+ ctx: RunCtx,
31
+ opts: SubscriptionHistoryPageOptions,
32
+ ): Promise<SubscriptionHistoryPage> {
33
+ return ctx.runQuery(
34
+ componentRef(component, "billingHistory/queries/paginateSubscriptions"),
35
+ opts,
36
+ );
37
+ }
38
+
39
+ export function paginateCheckoutSessions(
40
+ component: Component,
41
+ ctx: RunCtx,
42
+ opts: CheckoutSessionHistoryPageOptions,
43
+ ): Promise<CheckoutSessionHistoryPage> {
44
+ return ctx.runQuery(
45
+ componentRef(component, "billingHistory/queries/paginateCheckoutSessions"),
46
+ opts,
47
+ );
48
+ }
@@ -91,3 +91,10 @@ export type {
91
91
  PrepareBalanceFundingOptions,
92
92
  SetBalanceFundingOptions,
93
93
  } from "./billing/balanceFunding.js";
94
+
95
+ export type {
96
+ SubscriptionHistoryPageOptions,
97
+ CheckoutSessionHistoryPageOptions,
98
+ SubscriptionHistoryPage,
99
+ CheckoutSessionHistoryPage,
100
+ } from "./billing/historyPages.js";
@@ -1,3 +1,4 @@
1
+ import * as historyPages from "./billing/historyPages.js";
1
2
  import { OperationEvidenceClient } from "./operationEvidence.js";
2
3
  import {
3
4
  normalizeRefundCommandBindings,
@@ -24,6 +25,21 @@ import { componentRef } from "./webhooks/helpers.js";
24
25
  /** Shared component readers inherited by BetterStripe. */
25
26
  export class ReadContractClient {
26
27
  constructor(public component: Component) {}
28
+ /** Cached buyer observations only; the host authorizes exact selectors on every page. */
29
+ paginateSubscriptions(
30
+ ctx: RunCtx,
31
+ opts: historyPages.SubscriptionHistoryPageOptions,
32
+ ) {
33
+ return historyPages.paginateSubscriptions(this.component, ctx, opts);
34
+ }
35
+
36
+ paginateCheckoutSessions(
37
+ ctx: RunCtx,
38
+ opts: historyPages.CheckoutSessionHistoryPageOptions,
39
+ ) {
40
+ return historyPages.paginateCheckoutSessions(this.component, ctx, opts);
41
+ }
42
+
27
43
  get operationEvidence() {
28
44
  return new OperationEvidenceClient(this.component);
29
45
  }
@@ -186,6 +186,10 @@ export async function handleWebhookRequest(
186
186
  console.error("[better-stripe] retryOnHookError selector failed:", error);
187
187
  return jsonResponse({ error: "Webhook retry policy failed" }, 500);
188
188
  }
189
+ // Refund synchronization is required independently of optional app hook policy.
190
+ const requiresLedgerSuccess =
191
+ requiresHookSuccess ||
192
+ ["refund.created", "refund.updated", "refund.failed"].includes(event.type);
189
193
  // --- Atomic webhook dedup via event ledger ---
190
194
  const eventId = event.id;
191
195
  console.info(
@@ -202,7 +206,7 @@ export async function handleWebhookRequest(
202
206
  },
203
207
  );
204
208
  if (dedupStatus !== "inserted") {
205
- if (requiresHookSuccess && dedupStatus === "processing") {
209
+ if (requiresLedgerSuccess && dedupStatus === "processing") {
206
210
  return jsonResponse({ error: "Event processing in progress" }, 503);
207
211
  }
208
212
  console.info(`[better-stripe] ↳ deduplicated (already processed)`);
@@ -214,7 +218,7 @@ export async function handleWebhookRequest(
214
218
  `[better-stripe] Webhook ledger insert failed for ${eventId}:`,
215
219
  error,
216
220
  );
217
- if (requiresHookSuccess)
221
+ if (requiresLedgerSuccess)
218
222
  return jsonResponse({ error: "Webhook ledger unavailable" }, 500);
219
223
  }
220
224
 
@@ -270,7 +274,7 @@ export async function handleWebhookRequest(
270
274
  },
271
275
  );
272
276
  } catch {
273
- if (requiresHookSuccess)
277
+ if (requiresLedgerSuccess)
274
278
  return jsonResponse({ error: "Webhook completion unavailable" }, 500);
275
279
  /* ledger update best-effort */
276
280
  }
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
5
5
  import { computeReversalSlices } from "../../component/lib/reversals.js";
6
6
  import type { WebhookContext } from "./helpers.js";
7
7
  import { processEvent } from "./processors.js";
8
+ import { processRefund } from "../../../tests/fixtures/refund-recovery.js";
8
9
 
9
10
  const TO_REF = Symbol.for("toReferencePath");
10
11
 
@@ -98,6 +99,7 @@ function makeStripe() {
98
99
  return {
99
100
  payouts: { retrieve: vi.fn() },
100
101
  refunds: {
102
+ retrieve: vi.fn(),
101
103
  list: vi.fn(() =>
102
104
  (async function* () {
103
105
  yield { amount: 5000, status: "succeeded" };
@@ -2382,7 +2384,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2382
2384
  amount_refunded: 5000,
2383
2385
  });
2384
2386
  const whCtx = makeWhCtx({ ctx, stripe });
2385
- await processEvent(whCtx, refundEvent());
2387
+ await processRefund(whCtx, refundEvent());
2386
2388
  expect(stripe.transfers.createReversal).toHaveBeenCalledTimes(2);
2387
2389
  expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
2388
2390
  "tr_s",
@@ -2409,7 +2411,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2409
2411
  amount_refunded: 10000,
2410
2412
  });
2411
2413
  const whCtx = makeWhCtx({ ctx, stripe });
2412
- await processEvent(whCtx, refundEvent({ amount: 10000 }));
2414
+ await processRefund(whCtx, refundEvent({ amount: 10000 }));
2413
2415
  expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
2414
2416
  "tr_s",
2415
2417
  { amount: 7000 },
@@ -2437,7 +2439,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2437
2439
  amount_refunded: 7000, // cumulative: 5000 + this refund's 2000
2438
2440
  });
2439
2441
  const whCtx = makeWhCtx({ ctx, stripe });
2440
- await processEvent(whCtx, refundEvent({ id: "re_2", amount: 2000 }));
2442
+ await processRefund(whCtx, refundEvent({ id: "re_2", amount: 2000 }));
2441
2443
  expect(stripe.transfers.createReversal).toHaveBeenCalledWith(
2442
2444
  "tr_s",
2443
2445
  { amount: 1400 },
@@ -2460,14 +2462,14 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2460
2462
  amount_refunded: 5000,
2461
2463
  });
2462
2464
  const whCtx = makeWhCtx({ ctx, stripe });
2463
- await processEvent(whCtx, refundEvent());
2465
+ await processRefund(whCtx, refundEvent());
2464
2466
  expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
2465
2467
  });
2466
2468
  it("skips clawback quietly for a refund on a non-split sale", async () => {
2467
2469
  const ctx = makeCtx({ query: [] });
2468
2470
  const stripe = makeStripe();
2469
2471
  const whCtx = makeWhCtx({ ctx, stripe });
2470
- await processEvent(whCtx, refundEvent());
2472
+ await processRefund(whCtx, refundEvent());
2471
2473
  expect(stripe.charges.retrieve).not.toHaveBeenCalled();
2472
2474
  expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
2473
2475
  });
@@ -2475,7 +2477,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2475
2477
  const ctx = makeCtx({ query: ledgerLegs() });
2476
2478
  const stripe = makeStripe();
2477
2479
  const whCtx = makeWhCtx({ ctx, stripe });
2478
- await processEvent(whCtx, refundEvent({ status: "pending" }));
2480
+ await processRefund(whCtx, refundEvent({ status: "pending" }));
2479
2481
  expect(stripe.transfers.createReversal).not.toHaveBeenCalled();
2480
2482
  });
2481
2483
  it("propagates a reversal failure so the event is marked failed and Stripe retries", async () => {
@@ -2488,7 +2490,7 @@ describe("processEvent — refunds: split clawback + fee-refund denormalization
2488
2490
  });
2489
2491
  stripe.transfers.createReversal.mockRejectedValue(new Error("stripe down"));
2490
2492
  const whCtx = makeWhCtx({ ctx, stripe });
2491
- await expect(processEvent(whCtx, refundEvent())).rejects.toThrow(
2493
+ await expect(processRefund(whCtx, refundEvent())).rejects.toThrow(
2492
2494
  "stripe down",
2493
2495
  );
2494
2496
  });
@@ -1,15 +1,12 @@
1
+ import { handleRefundEvent } from "./refundDelivery.js";
1
2
  import { handlePayoutEvent } from "./payoutReconciliation.js";
2
3
  import { reconcileDisputeMoney } from "./disputeRecovery.js";
3
- import { successfulRefundPrincipal } from "../connect/refundPrincipal.js";
4
4
  import { subscriptionRouting } from "../billing/subscriptionRouting.js";
5
5
  import { cancelsAtPeriodEnd } from "../billing/subscriptionCancellation.js";
6
6
  import type Stripe from "stripe";
7
7
 
8
8
  import type { SplitRecipient } from "../../component/lib/fees.js";
9
- import {
10
- createSplitTransfers,
11
- reverseTransfersForRefund,
12
- } from "../connect/transfers.js";
9
+ import { createSplitTransfers } from "../connect/transfers.js";
13
10
  import { validateStatementDescriptorSuffix } from "../core/descriptors.js";
14
11
  import { computeFee } from "../core/fees.js";
15
12
  import type { PlatformFeeConfig } from "../types.js";
@@ -110,7 +107,7 @@ export async function processEvent(
110
107
  case "refund.created":
111
108
  case "refund.updated":
112
109
  case "refund.failed":
113
- await handleRefundEvent(whCtx, obj as Stripe.Refund);
110
+ await handleRefundEvent(whCtx, obj as Stripe.Refund, event.account);
114
111
  break;
115
112
  case "application_fee.refunded":
116
113
  // Keep feeCollectedAmount/feeRefundedAmount accurate on the linked
@@ -902,88 +899,6 @@ async function upsertPaymentFromStripe(
902
899
  }
903
900
 
904
901
  // Stripe types Refund.status as `string | null`; clamp to the documented union.
905
- const REFUND_STATUSES = new Set([
906
- "pending",
907
- "requires_action",
908
- "succeeded",
909
- "failed",
910
- "canceled",
911
- ]);
912
- const REFUND_REASONS = new Set([
913
- "duplicate",
914
- "fraudulent",
915
- "requested_by_customer",
916
- "expired_uncaptured_charge",
917
- ]);
918
-
919
- async function handleRefundEvent(
920
- whCtx: WebhookContext,
921
- refund: Stripe.Refund,
922
- ): Promise<void> {
923
- const paymentIntentId =
924
- typeof refund.payment_intent === "string"
925
- ? refund.payment_intent
926
- : (refund.payment_intent?.id ?? undefined);
927
- const chargeId =
928
- typeof refund.charge === "string"
929
- ? refund.charge
930
- : (refund.charge?.id ?? undefined);
931
-
932
- const status =
933
- refund.status && REFUND_STATUSES.has(refund.status)
934
- ? refund.status
935
- : "pending";
936
- const reason =
937
- refund.reason && REFUND_REASONS.has(refund.reason)
938
- ? refund.reason
939
- : undefined;
940
-
941
- await dispatchUpsert(whCtx, "refundUpserted", {
942
- stripeRefundId: refund.id,
943
- stripePaymentIntentId: paymentIntentId,
944
- stripeChargeId: chargeId,
945
- amount: refund.amount,
946
- currency: refund.currency,
947
- status,
948
- reason,
949
- failureReason: refund.failure_reason ?? undefined,
950
- metadata: refund.metadata ?? undefined,
951
- });
952
-
953
- // Split-sale clawback (BTS-34): when a separate-charges sale is refunded,
954
- // pull the refunded share back from each recipient pro-rata. Only ledger
955
- // legs identify a split sale — destination-charge auto-transfers are not in
956
- // the ledger and are handled by Stripe-native `reverse_transfer` at refund
957
- // creation. Runs on `refund.updated` too so a pending→succeeded refund
958
- // (e.g. ACH) still claws back. Errors propagate → event `failed` → Stripe
959
- // retries; `reverseTransfersForRefund`'s delta-to-target math makes the
960
- // re-run converge without double-reversing.
961
- if (status !== "succeeded" || !chargeId) return;
962
- const legs = ((await whCtx.ctx.runQuery(
963
- componentRef(whCtx.component, "connect/queries/listTransfersByCharge"),
964
- { sourceChargeId: chargeId },
965
- )) ?? []) as unknown[];
966
- if (legs.length === 0) {
967
- const obligations = (await whCtx.ctx.runQuery(
968
- componentRef(
969
- whCtx.component,
970
- "affiliateRecovery/queries/chargeObligations",
971
- ),
972
- { sourceChargeId: chargeId },
973
- )) as unknown[] | null;
974
- if (!obligations?.length) return;
975
- }
976
-
977
- // Fetch succeeded refunds: charge.amount_refunded can include pending funds.
978
- const charge = await whCtx.stripe.charges.retrieve(chargeId);
979
- await reverseTransfersForRefund(whCtx.stripe, whCtx.component, whCtx.ctx, {
980
- sourceChargeId: chargeId,
981
- refundId: refund.id,
982
- chargeAmount: charge.amount,
983
- amountRefunded: await successfulRefundPrincipal(whCtx.stripe, chargeId),
984
- });
985
- }
986
-
987
902
  /**
988
903
  * Denormalize fee-refund state from `application_fee.refunded` (BTS-34, folded
989
904
  * in from BTS-51): set the linked payment's `feeRefundedAmount` and correct