@fantastic.dev/better-stripe 0.32.0 → 0.34.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 (129) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/README.md +36 -1
  3. package/dist/client/billing/checkoutPages.d.ts +26 -0
  4. package/dist/client/billing/checkoutPages.d.ts.map +1 -0
  5. package/dist/client/billing/checkoutPages.js +111 -0
  6. package/dist/client/billing/checkoutPages.js.map +1 -0
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +36 -0
  8. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +18 -0
  10. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  11. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +36 -0
  12. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  13. package/dist/client/connect/payoutSyncTestHelpers.d.ts +18 -0
  14. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  15. package/dist/client/connect/refundContext.d.ts +6 -0
  16. package/dist/client/connect/refundContext.d.ts.map +1 -0
  17. package/dist/client/connect/refundContext.js +109 -0
  18. package/dist/client/connect/refundContext.js.map +1 -0
  19. package/dist/client/connect/refundContextHistory.d.ts +20 -0
  20. package/dist/client/connect/refundContextHistory.d.ts.map +1 -0
  21. package/dist/client/connect/refundContextHistory.js +55 -0
  22. package/dist/client/connect/refundContextHistory.js.map +1 -0
  23. package/dist/client/connect/refundContextTypes.d.ts +39 -0
  24. package/dist/client/connect/refundContextTypes.d.ts.map +1 -0
  25. package/dist/client/connect/refundContextTypes.js +15 -0
  26. package/dist/client/connect/refundContextTypes.js.map +1 -0
  27. package/dist/client/connect/refundTarget.d.ts +14 -0
  28. package/dist/client/connect/refundTarget.d.ts.map +1 -0
  29. package/dist/client/connect/refundTarget.js +17 -0
  30. package/dist/client/connect/refundTarget.js.map +1 -0
  31. package/dist/client/connect/refunds.d.ts +17 -1
  32. package/dist/client/connect/refunds.d.ts.map +1 -1
  33. package/dist/client/connect/refunds.js +7 -17
  34. package/dist/client/connect/refunds.js.map +1 -1
  35. package/dist/client/core/accountClosures.d.ts +15 -0
  36. package/dist/client/core/accountClosures.d.ts.map +1 -0
  37. package/dist/client/core/accountClosures.js +10 -0
  38. package/dist/client/core/accountClosures.js.map +1 -0
  39. package/dist/client/core/accounts.d.ts.map +1 -1
  40. package/dist/client/core/accounts.js +15 -23
  41. package/dist/client/core/accounts.js.map +1 -1
  42. package/dist/client/core/personalAccountMapping.d.ts +8 -0
  43. package/dist/client/core/personalAccountMapping.d.ts.map +1 -0
  44. package/dist/client/core/personalAccountMapping.js +11 -0
  45. package/dist/client/core/personalAccountMapping.js.map +1 -0
  46. package/dist/client/index.d.ts +57 -2
  47. package/dist/client/index.d.ts.map +1 -1
  48. package/dist/client/index.js +13 -0
  49. package/dist/client/index.js.map +1 -1
  50. package/dist/client/invoiceReads.d.ts +7 -1
  51. package/dist/client/invoiceReads.d.ts.map +1 -1
  52. package/dist/client/invoiceReads.js +11 -1
  53. package/dist/client/invoiceReads.js.map +1 -1
  54. package/dist/client/publicTypes.d.ts +5 -0
  55. package/dist/client/publicTypes.d.ts.map +1 -0
  56. package/dist/client/publicTypes.js +2 -0
  57. package/dist/client/publicTypes.js.map +1 -0
  58. package/dist/component/_generated/component.d.ts +88 -0
  59. package/dist/component/_generated/component.d.ts.map +1 -1
  60. package/dist/component/accountClosure/helpers.d.ts +18 -0
  61. package/dist/component/accountClosure/helpers.d.ts.map +1 -0
  62. package/dist/component/accountClosure/helpers.js +18 -0
  63. package/dist/component/accountClosure/helpers.js.map +1 -0
  64. package/dist/component/accountClosure/mutations.d.ts +20 -0
  65. package/dist/component/accountClosure/mutations.d.ts.map +1 -0
  66. package/dist/component/accountClosure/mutations.js +55 -0
  67. package/dist/component/accountClosure/mutations.js.map +1 -0
  68. package/dist/component/accountClosure/queries.d.ts +34 -0
  69. package/dist/component/accountClosure/queries.d.ts.map +1 -0
  70. package/dist/component/accountClosure/queries.js +36 -0
  71. package/dist/component/accountClosure/queries.js.map +1 -0
  72. package/dist/component/accountClosure/schema.d.ts +46 -0
  73. package/dist/component/accountClosure/schema.d.ts.map +1 -0
  74. package/dist/component/accountClosure/schema.js +20 -0
  75. package/dist/component/accountClosure/schema.js.map +1 -0
  76. package/dist/component/core/mutations.d.ts.map +1 -1
  77. package/dist/component/core/mutations.js +5 -0
  78. package/dist/component/core/mutations.js.map +1 -1
  79. package/dist/component/core/personalAccountMapping.d.ts +95 -0
  80. package/dist/component/core/personalAccountMapping.d.ts.map +1 -0
  81. package/dist/component/core/personalAccountMapping.js +54 -0
  82. package/dist/component/core/personalAccountMapping.js.map +1 -0
  83. package/dist/component/core/queries.d.ts +27 -0
  84. package/dist/component/core/queries.d.ts.map +1 -1
  85. package/dist/component/core/queries.js +7 -0
  86. package/dist/component/core/queries.js.map +1 -1
  87. package/dist/component/earnings/triggers.d.ts +42 -0
  88. package/dist/component/earnings/triggers.d.ts.map +1 -1
  89. package/dist/component/payoutRelease/queries.d.ts +2 -2
  90. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  91. package/dist/component/schema.d.ts +18 -0
  92. package/dist/component/schema.js +2 -0
  93. package/dist/component/schema.js.map +1 -1
  94. package/docs/checkout-session-pages.md +71 -0
  95. package/docs/personal-account-mapping.md +54 -0
  96. package/docs/read-contracts.md +28 -0
  97. package/docs/refund-context.md +84 -0
  98. package/package.json +5 -2
  99. package/src/client/billing/checkoutPages.test.ts +251 -0
  100. package/src/client/billing/checkoutPages.ts +135 -0
  101. package/src/client/connect/refundContext.ts +140 -0
  102. package/src/client/connect/refundContextHistory.ts +84 -0
  103. package/src/client/connect/refundContextTypes.ts +56 -0
  104. package/src/client/connect/refundTarget.ts +39 -0
  105. package/src/client/connect/refunds.test.ts +72 -0
  106. package/src/client/connect/refunds.ts +8 -22
  107. package/src/client/core/account-close-orchestration.test.ts +131 -0
  108. package/src/client/core/account-closure.test.ts +317 -0
  109. package/src/client/core/accountClosures.ts +37 -0
  110. package/src/client/core/accounts.test.ts +0 -111
  111. package/src/client/core/accounts.ts +24 -29
  112. package/src/client/core/personal-account-mapping.test.ts +71 -0
  113. package/src/client/core/personalAccountMapping.ts +23 -0
  114. package/src/client/index.ts +45 -33
  115. package/src/client/invoiceReads.ts +17 -1
  116. package/src/client/publicTypes.ts +35 -0
  117. package/src/client/refund-context-shapes.test.ts +127 -0
  118. package/src/client/refund-context.test.ts +404 -0
  119. package/src/component/_generated/api.ts +8 -0
  120. package/src/component/_generated/component.ts +126 -0
  121. package/src/component/accountClosure/helpers.ts +21 -0
  122. package/src/component/accountClosure/mutations.ts +56 -0
  123. package/src/component/accountClosure/queries.ts +43 -0
  124. package/src/component/accountClosure/schema.ts +20 -0
  125. package/src/component/core/mutations.ts +3 -0
  126. package/src/component/core/personal-account-mapping.test.ts +173 -0
  127. package/src/component/core/personalAccountMapping.ts +81 -0
  128. package/src/component/core/queries.ts +11 -0
  129. package/src/component/schema.ts +2 -0
@@ -0,0 +1,131 @@
1
+ // @vitest-environment edge-runtime
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import type Stripe from "stripe";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { closeAccount, restartAccountOnboarding } from "./accounts.js";
6
+
7
+ function makeStripe() {
8
+ return { v2: { core: { accounts: { close: vi.fn(), retrieve: vi.fn() } } } };
9
+ }
10
+ function asStripe(stripe: ReturnType<typeof makeStripe>) {
11
+ return stripe as unknown as Stripe;
12
+ }
13
+ function makeComponent() {
14
+ return {
15
+ accountClosure: {
16
+ mutations: {
17
+ prepare: refFor("accountClosure/mutations/prepare"),
18
+ complete: refFor("accountClosure/mutations/complete"),
19
+ },
20
+ },
21
+ } as unknown as Component;
22
+ }
23
+ function refFor(path: string) {
24
+ return { [Symbol.for("toReferencePath")]: `betterStripe/${path}` };
25
+ }
26
+
27
+ describe("closeAccount / restartAccountOnboarding", () => {
28
+ function context(appliedConfigurations?: string[], state = "pending") {
29
+ const runMutation = vi
30
+ .fn()
31
+ .mockResolvedValueOnce({
32
+ closure: { appliedConfigurations, state },
33
+ isRetry: false,
34
+ })
35
+ .mockResolvedValue(null);
36
+ return { ctx: { runMutation } as unknown as RunCtx, runMutation };
37
+ }
38
+
39
+ it("pins stored configurations before close and completes without deleting provenance", async () => {
40
+ const stripe = makeStripe();
41
+ const { ctx, runMutation } = context(["merchant", "recipient"]);
42
+ expect(
43
+ await closeAccount(asStripe(stripe), makeComponent(), ctx, {
44
+ stripeAccountId: "acct_close",
45
+ }),
46
+ ).toEqual({ closed: true });
47
+ expect(stripe.v2.core.accounts.retrieve).not.toHaveBeenCalled();
48
+ expect(stripe.v2.core.accounts.close).toHaveBeenCalledWith(
49
+ "acct_close",
50
+ { applied_configurations: ["merchant", "recipient"] },
51
+ { idempotencyKey: "betterstripe-close:acct_close" },
52
+ );
53
+ expect(runMutation.mock.calls.map((call) => call[0])).toEqual([
54
+ refFor("accountClosure/mutations/prepare"),
55
+ refFor("accountClosure/mutations/complete"),
56
+ ]);
57
+ });
58
+
59
+ it("retrieves configurations when none were stored", async () => {
60
+ const stripe = makeStripe();
61
+ stripe.v2.core.accounts.retrieve.mockResolvedValue({
62
+ applied_configurations: ["merchant"],
63
+ });
64
+ const { ctx } = context();
65
+ await closeAccount(asStripe(stripe), makeComponent(), ctx, {
66
+ stripeAccountId: "acct_fallback",
67
+ });
68
+ expect(stripe.v2.core.accounts.close).toHaveBeenCalledWith(
69
+ "acct_fallback",
70
+ { applied_configurations: ["merchant"] },
71
+ { idempotencyKey: "betterstripe-close:acct_fallback" },
72
+ );
73
+ });
74
+
75
+ it("preserves pending provenance and refuses close when required provider lookup fails", async () => {
76
+ const stripe = makeStripe();
77
+ stripe.v2.core.accounts.retrieve.mockRejectedValue(
78
+ new Error("retrieve unavailable"),
79
+ );
80
+ const { ctx, runMutation } = context();
81
+ await expect(
82
+ closeAccount(asStripe(stripe), makeComponent(), ctx, {
83
+ stripeAccountId: "acct_missing",
84
+ }),
85
+ ).rejects.toThrow("retrieve unavailable");
86
+ expect(stripe.v2.core.accounts.close).not.toHaveBeenCalled();
87
+ expect(runMutation).toHaveBeenCalledTimes(1);
88
+ });
89
+
90
+ it("does not complete local closure after provider refusal", async () => {
91
+ const stripe = makeStripe();
92
+ stripe.v2.core.accounts.close.mockRejectedValue(new Error("close boom"));
93
+ const { ctx, runMutation } = context(["merchant"]);
94
+ await expect(
95
+ closeAccount(asStripe(stripe), makeComponent(), ctx, {
96
+ stripeAccountId: "acct_err",
97
+ }),
98
+ ).rejects.toThrow("close boom");
99
+ expect(runMutation).toHaveBeenCalledTimes(1);
100
+ expect(runMutation).toHaveBeenCalledWith(
101
+ refFor("accountClosure/mutations/prepare"),
102
+ { stripeAccountId: "acct_err" },
103
+ );
104
+ });
105
+
106
+ it("returns an already closed account without another provider operation", async () => {
107
+ const stripe = makeStripe();
108
+ const { ctx } = context([], "closed");
109
+ expect(
110
+ await closeAccount(asStripe(stripe), makeComponent(), ctx, {
111
+ stripeAccountId: "acct_done",
112
+ }),
113
+ ).toEqual({ closed: true });
114
+ expect(stripe.v2.core.accounts.close).not.toHaveBeenCalled();
115
+ expect(stripe.v2.core.accounts.retrieve).not.toHaveBeenCalled();
116
+ });
117
+
118
+ it("restartAccountOnboarding retains the same closure provenance contract", async () => {
119
+ const stripe = makeStripe();
120
+ const { ctx, runMutation } = context([]);
121
+ expect(
122
+ await restartAccountOnboarding(asStripe(stripe), makeComponent(), ctx, {
123
+ stripeAccountId: "acct_restart",
124
+ }),
125
+ ).toEqual({ closed: true });
126
+ expect(runMutation.mock.calls.map((call) => call[0])).toEqual([
127
+ refFor("accountClosure/mutations/prepare"),
128
+ refFor("accountClosure/mutations/complete"),
129
+ ]);
130
+ });
131
+ });
@@ -0,0 +1,317 @@
1
+ // @vitest-environment edge-runtime
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import type Stripe from "stripe";
4
+ import type { RunCtx } from "../helpers.js";
5
+ import { components, initConvexTest } from "../setup.test.js";
6
+ import schema from "../../component/schema.js";
7
+ import { closeAccount } from "./accounts.js";
8
+ import { BetterStripe } from "../index.js";
9
+
10
+ const modules = import.meta.glob("../../component/**/*.ts");
11
+ function fixture() {
12
+ const t = initConvexTest();
13
+ t.registerComponent("betterStripe", schema, modules);
14
+ const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
15
+ const close = vi.fn().mockResolvedValue({ closed: true });
16
+ const retrieve = vi.fn().mockResolvedValue({ closed: true });
17
+ const stripe = {
18
+ v2: { core: { accounts: { close, retrieve } } },
19
+ } as unknown as Stripe;
20
+ const client = new BetterStripe(components.betterStripe, {
21
+ STRIPE_SECRET_KEY: "sk_test_bts202_dummy",
22
+ });
23
+ return {
24
+ client,
25
+ t,
26
+ ctx,
27
+ stripe,
28
+ close,
29
+ retrieve,
30
+ component: components.betterStripe,
31
+ };
32
+ }
33
+
34
+ describe("account closure provenance", () => {
35
+ it("does not resurrect a closed recipient on a late account upsert", async () => {
36
+ const f = fixture();
37
+ const account = {
38
+ stripeAccountId: "acct_closed",
39
+ userId: "original",
40
+ appliedConfigurations: ["recipient" as const],
41
+ };
42
+ await f.t.mutation(f.component.core.mutations.upsertAccount, account);
43
+ await closeAccount(f.stripe, f.component, f.ctx, {
44
+ stripeAccountId: account.stripeAccountId,
45
+ });
46
+ await f.t.mutation(f.component.core.mutations.upsertAccountInternal, {
47
+ ...account,
48
+ userId: "replacement",
49
+ onboardingStatus: "complete",
50
+ });
51
+ await f.t.mutation(f.component.core.mutations.upsertAccount, account);
52
+ expect(
53
+ await f.t.query(f.component.core.queries.getAccountByUserId, {
54
+ userId: "original",
55
+ }),
56
+ ).toBeNull();
57
+ expect(
58
+ await f.t.query(f.component.core.queries.getAccountByUserId, {
59
+ userId: "replacement",
60
+ }),
61
+ ).toBeNull();
62
+ expect(
63
+ await f.t.query(f.component.core.queries.getAccountByStripeId, {
64
+ stripeAccountId: account.stripeAccountId,
65
+ }),
66
+ ).toBeNull();
67
+ });
68
+ it("retains original owner history while active lookups move to another account", async () => {
69
+ const f = fixture();
70
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
71
+ stripeAccountId: "acct_old",
72
+ userId: "original",
73
+ appliedConfigurations: ["recipient"],
74
+ });
75
+ await closeAccount(f.stripe, f.component, f.ctx, {
76
+ stripeAccountId: "acct_old",
77
+ });
78
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
79
+ stripeAccountId: "acct_new",
80
+ userId: "original",
81
+ });
82
+ const history = await f.client.listClosedAccountsByUserId(f.ctx, {
83
+ userId: "original",
84
+ paginationOpts: { numItems: 1, cursor: null },
85
+ });
86
+ expect(history.page.map((row) => row.stripeAccountId)).toEqual([
87
+ "acct_old",
88
+ ]);
89
+ expect(history.page[0].userId).toBe("original");
90
+ expect(history.page[0].closedAt).toBeTypeOf("number");
91
+ expect(
92
+ (
93
+ await f.t.query(f.component.core.queries.getAccountByUserId, {
94
+ userId: "original",
95
+ })
96
+ )?.stripeAccountId,
97
+ ).toBe("acct_new");
98
+ expect(
99
+ (
100
+ await f.t.query(
101
+ f.component.accountClosure.queries.listClosedAccountsByUserId,
102
+ {
103
+ userId: "replacement",
104
+ paginationOpts: { numItems: 1, cursor: null },
105
+ },
106
+ )
107
+ ).page,
108
+ ).toEqual([]);
109
+ });
110
+
111
+ it("keeps the live mapping after provider failure and pins its owner during retry", async () => {
112
+ const f = fixture();
113
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
114
+ stripeAccountId: "acct_fail",
115
+ userId: "original",
116
+ appliedConfigurations: [],
117
+ });
118
+ f.close.mockRejectedValueOnce(new Error("provider refused"));
119
+ await expect(
120
+ closeAccount(f.stripe, f.component, f.ctx, {
121
+ stripeAccountId: "acct_fail",
122
+ }),
123
+ ).rejects.toThrow("provider refused");
124
+ expect(
125
+ (
126
+ await f.t.query(f.component.core.queries.getAccountByUserId, {
127
+ userId: "original",
128
+ })
129
+ )?.stripeAccountId,
130
+ ).toBe("acct_fail");
131
+ expect(
132
+ await f.t.query(
133
+ f.component.accountClosure.queries.getClosedAccountByStripeId,
134
+ { stripeAccountId: "acct_fail" },
135
+ ),
136
+ ).toBeNull();
137
+ await expect(
138
+ f.t.mutation(f.component.core.mutations.upsertAccount, {
139
+ stripeAccountId: "acct_fail",
140
+ userId: "replacement",
141
+ }),
142
+ ).rejects.toThrow("ownership is pinned");
143
+ f.retrieve.mockResolvedValueOnce({
144
+ closed: false,
145
+ applied_configurations: [],
146
+ });
147
+ await closeAccount(f.stripe, f.component, f.ctx, {
148
+ stripeAccountId: "acct_fail",
149
+ });
150
+ expect(f.close).toHaveBeenCalledTimes(2);
151
+ expect(f.close.mock.calls[0][2]).toEqual(f.close.mock.calls[1][2]);
152
+ expect(
153
+ (
154
+ await f.t.query(
155
+ f.component.accountClosure.queries.getClosedAccountByStripeId,
156
+ { stripeAccountId: "acct_fail" },
157
+ )
158
+ )?.userId,
159
+ ).toBe("original");
160
+ });
161
+
162
+ it("recovers provider success followed by local completion failure without another close", async () => {
163
+ const f = fixture();
164
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
165
+ stripeAccountId: "acct_retry",
166
+ userId: "original",
167
+ appliedConfigurations: [],
168
+ });
169
+ const runMutation = vi
170
+ .fn(f.t.mutation)
171
+ .mockImplementationOnce(f.t.mutation)
172
+ .mockRejectedValueOnce(new Error("local completion unavailable"));
173
+ const ctx = { ...f.ctx, runMutation } as RunCtx;
174
+ await expect(
175
+ closeAccount(f.stripe, f.component, ctx, {
176
+ stripeAccountId: "acct_retry",
177
+ }),
178
+ ).rejects.toThrow("local completion unavailable");
179
+ await closeAccount(f.stripe, f.component, f.ctx, {
180
+ stripeAccountId: "acct_retry",
181
+ });
182
+ await closeAccount(f.stripe, f.component, f.ctx, {
183
+ stripeAccountId: "acct_retry",
184
+ });
185
+ expect(f.close).toHaveBeenCalledTimes(1);
186
+ expect(f.close.mock.calls[0][2]).toEqual({
187
+ idempotencyKey: "betterstripe-close:acct_retry",
188
+ });
189
+ expect(
190
+ (
191
+ await f.t.query(
192
+ f.component.accountClosure.queries.getClosedAccountByStripeId,
193
+ { stripeAccountId: "acct_retry" },
194
+ )
195
+ )?.userId,
196
+ ).toBe("original");
197
+ });
198
+
199
+ it("does not disclose organization history through personal owner discovery", async () => {
200
+ const f = fixture();
201
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
202
+ stripeAccountId: "acct_org",
203
+ userId: "original",
204
+ orgId: "org_private",
205
+ appliedConfigurations: [],
206
+ });
207
+ await closeAccount(f.stripe, f.component, f.ctx, {
208
+ stripeAccountId: "acct_org",
209
+ });
210
+ expect(
211
+ (
212
+ await f.t.query(
213
+ f.component.accountClosure.queries.listClosedAccountsByUserId,
214
+ {
215
+ userId: "original",
216
+ paginationOpts: { numItems: 10, cursor: null },
217
+ },
218
+ )
219
+ ).page,
220
+ ).toEqual([]);
221
+ expect(
222
+ (
223
+ await f.t.query(
224
+ f.component.accountClosure.queries.getClosedAccountByStripeId,
225
+ { stripeAccountId: "acct_org" },
226
+ )
227
+ )?.orgId,
228
+ ).toBe("org_private");
229
+ });
230
+ it("preserves payout rows and original account references for historical reads", async () => {
231
+ const f = fixture();
232
+ const accountId = "acct_financial_history";
233
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
234
+ stripeAccountId: accountId,
235
+ userId: "original",
236
+ appliedConfigurations: [],
237
+ });
238
+ await f.t.mutation(f.component.connect.mutations.upsertPayout, {
239
+ stripePayoutId: "po_retained",
240
+ accountId,
241
+ amount: 1200,
242
+ currency: "usd",
243
+ status: "paid",
244
+ });
245
+ const original = await f.t.query(
246
+ f.component.connect.queries.getPayoutByStripeId,
247
+ { stripePayoutId: "po_retained" },
248
+ );
249
+ await closeAccount(f.stripe, f.component, f.ctx, {
250
+ stripeAccountId: accountId,
251
+ });
252
+ const owner = await f.client.getClosedAccountByStripeId(f.ctx, {
253
+ stripeAccountId: accountId,
254
+ });
255
+ expect(owner?.userId).toBe("original");
256
+ expect(owner?.orgId).toBeUndefined();
257
+ expect(
258
+ await f.t.query(f.component.connect.queries.listPayouts, {
259
+ accountId: owner!.stripeAccountId,
260
+ }),
261
+ ).toEqual([original]);
262
+ expect(
263
+ await f.t.query(f.component.connect.queries.getPayoutByStripeId, {
264
+ stripePayoutId: "po_retained",
265
+ }),
266
+ ).toEqual(original);
267
+ });
268
+
269
+ it("paginates personal closed history without unrelated users or organization rows", async () => {
270
+ const f = fixture();
271
+ for (const [stripeAccountId, userId, orgId] of [
272
+ ["acct_p1", "original", undefined],
273
+ ["acct_org_private", "original", "org_private"],
274
+ ["acct_p2", "original", undefined],
275
+ ["acct_other", "other", undefined],
276
+ ]) {
277
+ await f.t.mutation(f.component.core.mutations.upsertAccount, {
278
+ stripeAccountId: stripeAccountId!,
279
+ userId: userId!,
280
+ orgId,
281
+ appliedConfigurations: [],
282
+ });
283
+ await closeAccount(f.stripe, f.component, f.ctx, {
284
+ stripeAccountId: stripeAccountId!,
285
+ });
286
+ }
287
+ const first = await f.t.query(
288
+ f.component.accountClosure.queries.listClosedAccountsByUserId,
289
+ { userId: "original", paginationOpts: { numItems: 1, cursor: null } },
290
+ );
291
+ const second = await f.t.query(
292
+ f.component.accountClosure.queries.listClosedAccountsByUserId,
293
+ {
294
+ userId: "original",
295
+ paginationOpts: { numItems: 1, cursor: first.continueCursor },
296
+ },
297
+ );
298
+ expect(
299
+ [...first.page, ...second.page].map((row) => row.stripeAccountId).sort(),
300
+ ).toEqual(["acct_p1", "acct_p2"]);
301
+ expect(first.isDone).toBe(false);
302
+ const end = await f.client.listClosedAccountsByUserId(f.ctx, {
303
+ userId: "original",
304
+ paginationOpts: { numItems: 1, cursor: second.continueCursor },
305
+ });
306
+ expect(end.page).toEqual([]);
307
+ expect(end.isDone).toBe(true);
308
+ for (const numItems of [0, 101, 1.5]) {
309
+ await expect(
310
+ f.client.listClosedAccountsByUserId(f.ctx, {
311
+ userId: "original",
312
+ paginationOpts: { numItems, cursor: null },
313
+ }),
314
+ ).rejects.toThrow("between 1 and 100");
315
+ }
316
+ });
317
+ });
@@ -0,0 +1,37 @@
1
+ import type { Infer } from "convex/values";
2
+ import type { PaginationOptions, PaginationResult } from "convex/server";
3
+ import type { closureDoc } from "../../component/accountClosure/schema.js";
4
+ import type { Component, RunCtx } from "../helpers.js";
5
+ import { componentRef } from "../webhooks/helpers.js";
6
+
7
+ export type StripeAccountClosure = Infer<typeof closureDoc>;
8
+
9
+ /** Host must authenticate the actor and compare both user and organization ownership. */
10
+ export function getClosedAccountByStripeId(
11
+ component: Component,
12
+ ctx: RunCtx,
13
+ opts: { stripeAccountId: string },
14
+ ): Promise<StripeAccountClosure | null> {
15
+ return ctx.runQuery(
16
+ componentRef(
17
+ component,
18
+ "accountClosure/queries/getClosedAccountByStripeId",
19
+ ),
20
+ opts,
21
+ );
22
+ }
23
+
24
+ /** Personal closed accounts only. A caller-supplied userId is not authentication. */
25
+ export function listClosedAccountsByUserId(
26
+ component: Component,
27
+ ctx: RunCtx,
28
+ opts: { userId: string; paginationOpts: PaginationOptions },
29
+ ): Promise<PaginationResult<StripeAccountClosure>> {
30
+ return ctx.runQuery(
31
+ componentRef(
32
+ component,
33
+ "accountClosure/queries/listClosedAccountsByUserId",
34
+ ),
35
+ opts,
36
+ );
37
+ }
@@ -29,7 +29,6 @@ import {
29
29
  addCustomerConfiguration,
30
30
  addRecipientConfiguration,
31
31
  ensureCustomerAccount,
32
- closeAccount,
33
32
  createAccount,
34
33
  createAccountWithOnboarding,
35
34
  getAccount,
@@ -40,7 +39,6 @@ import {
40
39
  getOrCreateAccount,
41
40
  getV2Account,
42
41
  listStripeAccounts,
43
- restartAccountOnboarding,
44
42
  setAccountStatementDescriptor,
45
43
  syncAllAccounts,
46
44
  updateAccount,
@@ -876,115 +874,6 @@ describe("listStripeAccounts", () => {
876
874
  });
877
875
  });
878
876
 
879
- describe("closeAccount / restartAccountOnboarding", () => {
880
- it("uses stored appliedConfigurations from the DB and deletes after Stripe close", async () => {
881
- const stripe = makeStripe();
882
- stripe.v2.core.accounts.close.mockResolvedValue({});
883
- const runQuery = vi.fn().mockResolvedValue({
884
- appliedConfigurations: ["merchant", "recipient"],
885
- });
886
- const runMutation = vi.fn().mockResolvedValue(undefined);
887
- const ctx = { runQuery, runMutation } as unknown as RunCtx;
888
-
889
- const result = await closeAccount(asStripe(stripe), makeComponent(), ctx, {
890
- stripeAccountId: "acct_close",
891
- });
892
-
893
- expect(result).toEqual({ closed: true });
894
- // never falls back to Stripe retrieve when DB has configs
895
- expect(stripe.v2.core.accounts.retrieve).not.toHaveBeenCalled();
896
- expect(stripe.v2.core.accounts.close).toHaveBeenCalledWith("acct_close", {
897
- applied_configurations: ["merchant", "recipient"],
898
- });
899
- expect(runMutation).toHaveBeenCalledWith(
900
- refFor("core/mutations/deleteAccountByStripeId"),
901
- { stripeAccountId: "acct_close" },
902
- );
903
- });
904
-
905
- it("falls back to Stripe retrieve when the DB has no applied configs", async () => {
906
- const stripe = makeStripe();
907
- stripe.v2.core.accounts.retrieve.mockResolvedValue({
908
- applied_configurations: ["merchant"],
909
- });
910
- stripe.v2.core.accounts.close.mockResolvedValue({});
911
- const ctx = {
912
- runQuery: vi.fn().mockResolvedValue(null), // no DB row
913
- runMutation: vi.fn().mockResolvedValue(undefined),
914
- } as unknown as RunCtx;
915
-
916
- await closeAccount(asStripe(stripe), makeComponent(), ctx, {
917
- stripeAccountId: "acct_fb",
918
- });
919
-
920
- expect(stripe.v2.core.accounts.retrieve).toHaveBeenCalledWith("acct_fb");
921
- expect(stripe.v2.core.accounts.close).toHaveBeenCalledWith("acct_fb", {
922
- applied_configurations: ["merchant"],
923
- });
924
- });
925
-
926
- it("closes with an empty config list when the Stripe retrieve fallback throws", async () => {
927
- const stripe = makeStripe();
928
- stripe.v2.core.accounts.retrieve.mockRejectedValue(
929
- new Error("no such account"),
930
- );
931
- stripe.v2.core.accounts.close.mockResolvedValue({});
932
- const ctx = {
933
- runQuery: vi.fn().mockResolvedValue(null),
934
- runMutation: vi.fn().mockResolvedValue(undefined),
935
- } as unknown as RunCtx;
936
-
937
- await closeAccount(asStripe(stripe), makeComponent(), ctx, {
938
- stripeAccountId: "acct_missing",
939
- });
940
-
941
- expect(stripe.v2.core.accounts.close).toHaveBeenCalledWith("acct_missing", {
942
- applied_configurations: [],
943
- });
944
- });
945
-
946
- it("does not delete from the DB if the Stripe close fails", async () => {
947
- const stripe = makeStripe();
948
- stripe.v2.core.accounts.close.mockRejectedValue(new Error("close boom"));
949
- const runMutation = vi.fn().mockResolvedValue(undefined);
950
- const ctx = {
951
- runQuery: vi
952
- .fn()
953
- .mockResolvedValue({ appliedConfigurations: ["merchant"] }),
954
- runMutation,
955
- } as unknown as RunCtx;
956
-
957
- await expect(
958
- closeAccount(asStripe(stripe), makeComponent(), ctx, {
959
- stripeAccountId: "acct_err",
960
- }),
961
- ).rejects.toThrow(/close boom/);
962
-
963
- expect(runMutation).not.toHaveBeenCalled();
964
- });
965
-
966
- it("restartAccountOnboarding delegates to closeAccount", async () => {
967
- const stripe = makeStripe();
968
- stripe.v2.core.accounts.close.mockResolvedValue({});
969
- const ctx = {
970
- runQuery: vi.fn().mockResolvedValue({ appliedConfigurations: [] }),
971
- runMutation: vi.fn().mockResolvedValue(undefined),
972
- } as unknown as RunCtx;
973
-
974
- const result = await restartAccountOnboarding(
975
- asStripe(stripe),
976
- makeComponent(),
977
- ctx,
978
- { stripeAccountId: "acct_restart" },
979
- );
980
-
981
- expect(result).toEqual({ closed: true });
982
- expect(stripe.v2.core.accounts.close).toHaveBeenCalledWith("acct_restart", {
983
- applied_configurations: [],
984
- });
985
- });
986
- });
987
-
988
877
  describe("syncAllAccounts", () => {
989
878
  it("maps a business V2 account into an upsert and counts it synced", async () => {
990
879
  const stripe = makeStripe();
@@ -432,39 +432,34 @@ export async function closeAccount(
432
432
  ctx: RunCtx,
433
433
  opts: { stripeAccountId: string },
434
434
  ): Promise<{ closed: boolean }> {
435
- // First check our DB for stored applied_configurations
436
- let appliedConfigs: string[] = [];
437
-
438
- const dbAccount = await ctx.runQuery(
439
- componentRef(component, "core/queries/getAccountByStripeId"),
440
- { stripeAccountId: opts.stripeAccountId },
435
+ const { closure, isRetry } = await runMutationOrThrow(
436
+ ctx,
437
+ componentRef(component, "accountClosure/mutations/prepare"),
438
+ opts,
441
439
  );
442
- if (dbAccount?.appliedConfigurations) {
443
- appliedConfigs = dbAccount.appliedConfigurations;
444
- } else {
445
- // Fallback: fetch from Stripe
446
- try {
447
- const stripeAccount = await stripe.v2.core.accounts.retrieve(
448
- opts.stripeAccountId,
449
- );
450
- appliedConfigs = stripeAccount.applied_configurations ?? [];
451
- } catch {
452
- // Account may not exist on Stripe
453
- }
440
+ if (closure.state === "closed") return { closed: true };
441
+ let appliedConfigs = closure.appliedConfigurations;
442
+ let isProviderClosed = false;
443
+ if (isRetry || appliedConfigs === undefined) {
444
+ const account = await stripe.v2.core.accounts.retrieve(
445
+ opts.stripeAccountId,
446
+ );
447
+ appliedConfigs ??= account.applied_configurations ?? [];
448
+ isProviderClosed = account.closed === true;
454
449
  }
455
-
456
- // Close the account on Stripe — must pass all applied_configurations
457
- // See: https://docs.stripe.com/api/v2/core/accounts/close
458
- await stripe.v2.core.accounts.close(opts.stripeAccountId, {
459
- applied_configurations: appliedConfigs as V2CloseAppliedConfiguration[],
460
- });
461
-
462
- // Only remove from component DB after Stripe close succeeds
463
- // This prevents Convex/Stripe getting out of sync if close fails
450
+ if (!isProviderClosed)
451
+ await stripe.v2.core.accounts.close(
452
+ opts.stripeAccountId,
453
+ {
454
+ applied_configurations: (appliedConfigs ??
455
+ []) as V2CloseAppliedConfiguration[],
456
+ },
457
+ { idempotencyKey: `betterstripe-close:${opts.stripeAccountId}` },
458
+ );
464
459
  await runMutationOrThrow(
465
460
  ctx,
466
- componentRef(component, "core/mutations/deleteAccountByStripeId"),
467
- { stripeAccountId: opts.stripeAccountId },
461
+ componentRef(component, "accountClosure/mutations/complete"),
462
+ opts,
468
463
  );
469
464
 
470
465
  return { closed: true };