@fantastic.dev/better-stripe 0.33.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 (85) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/README.md +30 -1
  3. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +36 -0
  4. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  5. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +18 -0
  6. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  7. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +36 -0
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  9. package/dist/client/connect/payoutSyncTestHelpers.d.ts +18 -0
  10. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  11. package/dist/client/core/accountClosures.d.ts +15 -0
  12. package/dist/client/core/accountClosures.d.ts.map +1 -0
  13. package/dist/client/core/accountClosures.js +10 -0
  14. package/dist/client/core/accountClosures.js.map +1 -0
  15. package/dist/client/core/accounts.d.ts.map +1 -1
  16. package/dist/client/core/accounts.js +15 -23
  17. package/dist/client/core/accounts.js.map +1 -1
  18. package/dist/client/core/personalAccountMapping.d.ts +8 -0
  19. package/dist/client/core/personalAccountMapping.d.ts.map +1 -0
  20. package/dist/client/core/personalAccountMapping.js +11 -0
  21. package/dist/client/core/personalAccountMapping.js.map +1 -0
  22. package/dist/client/index.d.ts +55 -2
  23. package/dist/client/index.d.ts.map +1 -1
  24. package/dist/client/index.js +13 -0
  25. package/dist/client/index.js.map +1 -1
  26. package/dist/client/publicTypes.d.ts +5 -0
  27. package/dist/client/publicTypes.d.ts.map +1 -0
  28. package/dist/client/publicTypes.js +2 -0
  29. package/dist/client/publicTypes.js.map +1 -0
  30. package/dist/component/_generated/component.d.ts +88 -0
  31. package/dist/component/_generated/component.d.ts.map +1 -1
  32. package/dist/component/accountClosure/helpers.d.ts +18 -0
  33. package/dist/component/accountClosure/helpers.d.ts.map +1 -0
  34. package/dist/component/accountClosure/helpers.js +18 -0
  35. package/dist/component/accountClosure/helpers.js.map +1 -0
  36. package/dist/component/accountClosure/mutations.d.ts +20 -0
  37. package/dist/component/accountClosure/mutations.d.ts.map +1 -0
  38. package/dist/component/accountClosure/mutations.js +55 -0
  39. package/dist/component/accountClosure/mutations.js.map +1 -0
  40. package/dist/component/accountClosure/queries.d.ts +34 -0
  41. package/dist/component/accountClosure/queries.d.ts.map +1 -0
  42. package/dist/component/accountClosure/queries.js +36 -0
  43. package/dist/component/accountClosure/queries.js.map +1 -0
  44. package/dist/component/accountClosure/schema.d.ts +46 -0
  45. package/dist/component/accountClosure/schema.d.ts.map +1 -0
  46. package/dist/component/accountClosure/schema.js +20 -0
  47. package/dist/component/accountClosure/schema.js.map +1 -0
  48. package/dist/component/core/mutations.d.ts.map +1 -1
  49. package/dist/component/core/mutations.js +5 -0
  50. package/dist/component/core/mutations.js.map +1 -1
  51. package/dist/component/core/personalAccountMapping.d.ts +95 -0
  52. package/dist/component/core/personalAccountMapping.d.ts.map +1 -0
  53. package/dist/component/core/personalAccountMapping.js +54 -0
  54. package/dist/component/core/personalAccountMapping.js.map +1 -0
  55. package/dist/component/core/queries.d.ts +27 -0
  56. package/dist/component/core/queries.d.ts.map +1 -1
  57. package/dist/component/core/queries.js +7 -0
  58. package/dist/component/core/queries.js.map +1 -1
  59. package/dist/component/earnings/triggers.d.ts +42 -0
  60. package/dist/component/earnings/triggers.d.ts.map +1 -1
  61. package/dist/component/schema.d.ts +18 -0
  62. package/dist/component/schema.js +2 -0
  63. package/dist/component/schema.js.map +1 -1
  64. package/docs/personal-account-mapping.md +54 -0
  65. package/package.json +3 -2
  66. package/src/client/core/account-close-orchestration.test.ts +131 -0
  67. package/src/client/core/account-closure.test.ts +317 -0
  68. package/src/client/core/accountClosures.ts +37 -0
  69. package/src/client/core/accounts.test.ts +0 -111
  70. package/src/client/core/accounts.ts +24 -29
  71. package/src/client/core/personal-account-mapping.test.ts +71 -0
  72. package/src/client/core/personalAccountMapping.ts +23 -0
  73. package/src/client/index.ts +36 -33
  74. package/src/client/publicTypes.ts +35 -0
  75. package/src/component/_generated/api.ts +8 -0
  76. package/src/component/_generated/component.ts +126 -0
  77. package/src/component/accountClosure/helpers.ts +21 -0
  78. package/src/component/accountClosure/mutations.ts +56 -0
  79. package/src/component/accountClosure/queries.ts +43 -0
  80. package/src/component/accountClosure/schema.ts +20 -0
  81. package/src/component/core/mutations.ts +3 -0
  82. package/src/component/core/personal-account-mapping.test.ts +173 -0
  83. package/src/component/core/personalAccountMapping.ts +81 -0
  84. package/src/component/core/queries.ts +11 -0
  85. package/src/component/schema.ts +2 -0
@@ -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 };
@@ -0,0 +1,71 @@
1
+ // @vitest-environment edge-runtime
2
+ import { describe, expect, it, vi } from "vitest";
3
+
4
+ import schema from "../../component/schema.js";
5
+ import { BetterStripe } from "../index.js";
6
+ import type { RunCtx } from "../helpers.js";
7
+ import { components, initConvexTest } from "../setup.test.js";
8
+
9
+ const modules = import.meta.glob("../../component/**/*.ts");
10
+ function fixture() {
11
+ const t = initConvexTest();
12
+ t.registerComponent("betterStripe", schema, modules);
13
+ const ctx = { runQuery: t.query, runMutation: t.mutation } as RunCtx;
14
+ const client = new BetterStripe(components.betterStripe, {});
15
+ return { t, ctx, client };
16
+ }
17
+
18
+ describe("public personal account mapping", () => {
19
+ it("returns real component proof without a Stripe secret or provider read", async () => {
20
+ const f = fixture();
21
+ await f.client.upsertAccount(f.ctx, {
22
+ stripeAccountId: "acct_original",
23
+ userId: "user_original",
24
+ });
25
+ expect(
26
+ await f.client.getPersonalAccountMapping(f.ctx, {
27
+ userId: "user_original",
28
+ }),
29
+ ).toMatchObject({
30
+ status: "unique",
31
+ account: { stripeAccountId: "acct_original", userId: "user_original" },
32
+ });
33
+ await f.client.upsertAccount(f.ctx, {
34
+ stripeAccountId: "acct_replacement",
35
+ userId: "user_original",
36
+ });
37
+ expect(
38
+ await f.client.getPersonalAccountMapping(f.ctx, {
39
+ userId: "user_original",
40
+ }),
41
+ ).toEqual({ status: "unavailable", reason: "ambiguous" });
42
+ expect(
43
+ (await f.client.getAccountByUserId(f.ctx, { userId: "user_original" }))
44
+ ?.stripeAccountId,
45
+ ).toBe("acct_original");
46
+ });
47
+
48
+ it.each([
49
+ undefined,
50
+ null,
51
+ {},
52
+ { userId: "" },
53
+ { userId: " a" },
54
+ { userId: 123 },
55
+ { userId: "x".repeat(257) },
56
+ { userId: "user_original", stripeAccountId: "acct_browser" },
57
+ ])(
58
+ "rejects malformed options %j before component lookup",
59
+ async (options) => {
60
+ const f = fixture();
61
+ const runQuery = vi.fn();
62
+ const ctx = { runQuery } as RunCtx;
63
+ const read = f.client.getPersonalAccountMapping.bind(f.client) as (
64
+ ctx: RunCtx,
65
+ opts: unknown,
66
+ ) => Promise<unknown>;
67
+ await expect(read(ctx, options)).rejects.toThrow();
68
+ expect(runQuery).not.toHaveBeenCalled();
69
+ },
70
+ );
71
+ });
@@ -0,0 +1,23 @@
1
+ import { z } from "zod";
2
+
3
+ import { assertPersonalAccountUserId } from "../../component/core/personalAccountMapping.js";
4
+ import type { PersonalAccountMapping } from "../../component/core/personalAccountMapping.js";
5
+ import type { Component, RunCtx } from "../helpers.js";
6
+ import { componentRef } from "../webhooks/helpers.js";
7
+
8
+ export type { PersonalAccountMapping } from "../../component/core/personalAccountMapping.js";
9
+ const optionsSchema = z.object({ userId: z.string() }).strict();
10
+
11
+ /** Mapping evidence only. Authenticate the host actor before passing its server-owned identity. */
12
+ export async function getPersonalAccountMapping(
13
+ component: Component,
14
+ ctx: RunCtx,
15
+ input: { userId: string },
16
+ ): Promise<PersonalAccountMapping> {
17
+ const opts = optionsSchema.parse(input);
18
+ assertPersonalAccountUserId(opts.userId);
19
+ return ctx.runQuery(
20
+ componentRef(component, "core/queries/getPersonalAccountMapping"),
21
+ opts,
22
+ );
23
+ }
@@ -1,3 +1,7 @@
1
+ import * as personalAccountMappingImpl from "./core/personalAccountMapping.js";
2
+ export type * from "./publicTypes.js";
3
+ import * as accountClosuresImpl from "./core/accountClosures.js";
4
+ import type { PaginationOptions } from "convex/server";
1
5
  import { reconcilePayoutAndTrigger } from "./webhooks/payoutReconciliation.js";
2
6
  import { AffiliateRecoveryClient } from "./affiliateRecovery.js";
3
7
  export * from "./affiliateRecovery.js";
@@ -190,43 +194,10 @@ export type {
190
194
  BetterStripeWebhookEvent,
191
195
  } from "./utils/webhookEndpoints.js";
192
196
  // Re-export types for consumers
193
- export type {
194
- BetterStripeOptions,
195
- FeeOverride,
196
- FeeTier,
197
- PlatformFeeConfig,
198
- RegisterRoutesConfig,
199
- } from "./types.js";
200
197
  export type {
201
198
  StripeDashboardResourceType,
202
199
  StripeMode,
203
200
  } from "./utils/stripeDashboardUrl.js";
204
- export type {
205
- AccountLinkWithStatus,
206
- AsyncHookCtx,
207
- AsyncHooks,
208
- PaymentMethodCard,
209
- PaymentMethodLike,
210
- StripeComponentAccount,
211
- StripeComponentCheckoutSession,
212
- StripeComponentDispute,
213
- StripeComponentInvoice,
214
- StripeComponentPayment,
215
- StripeComponentPayout,
216
- StripeComponentPrice,
217
- StripeComponentProduct,
218
- StripeComponentRefund,
219
- StripeComponentSubscription,
220
- StripeCountrySpecs,
221
- StripeEventHandler,
222
- StripeEventHandlers,
223
- StripeV2Account,
224
- StripeWebhookEvent,
225
- SyncTriggerCtx,
226
- SyncTriggers,
227
- V2ThinEvent,
228
- WebhookActionCtx,
229
- } from "./types.js";
230
201
  export type BetterStripeComponent = ComponentApi;
231
202
 
232
203
  // BETTER STRIPE CLIENT
@@ -368,6 +339,38 @@ export class BetterStripe extends InvoiceReadClient {
368
339
  return accountsImpl.getAccountByUserId(this.component, ctx, opts);
369
340
  }
370
341
 
342
+ /** Unambiguous personal mapping only; host authentication and provider usability remain separate. */
343
+ getPersonalAccountMapping(ctx: RunCtx, opts: { userId: string }) {
344
+ return personalAccountMappingImpl.getPersonalAccountMapping(
345
+ this.component,
346
+ ctx,
347
+ opts,
348
+ );
349
+ }
350
+
351
+ /** Authenticate the host actor before consulting closed-account provenance. */
352
+ async getClosedAccountByStripeId(
353
+ ctx: RunCtx,
354
+ opts: { stripeAccountId: string },
355
+ ) {
356
+ return accountClosuresImpl.getClosedAccountByStripeId(
357
+ this.component,
358
+ ctx,
359
+ opts,
360
+ );
361
+ }
362
+
363
+ async listClosedAccountsByUserId(
364
+ ctx: RunCtx,
365
+ opts: { userId: string; paginationOpts: PaginationOptions },
366
+ ) {
367
+ return accountClosuresImpl.listClosedAccountsByUserId(
368
+ this.component,
369
+ ctx,
370
+ opts,
371
+ );
372
+ }
373
+
371
374
  async getAccountByOrgId(
372
375
  ctx: RunCtx,
373
376
  opts: { orgId: string },
@@ -0,0 +1,35 @@
1
+ export type { StripeAccountClosure } from "./core/accountClosures.js";
2
+ export type {
3
+ BetterStripeOptions,
4
+ FeeOverride,
5
+ FeeTier,
6
+ PlatformFeeConfig,
7
+ RegisterRoutesConfig,
8
+ } from "./types.js";
9
+ export type {
10
+ AccountLinkWithStatus,
11
+ AsyncHookCtx,
12
+ AsyncHooks,
13
+ PaymentMethodCard,
14
+ PaymentMethodLike,
15
+ StripeComponentAccount,
16
+ StripeComponentCheckoutSession,
17
+ StripeComponentDispute,
18
+ StripeComponentInvoice,
19
+ StripeComponentPayment,
20
+ StripeComponentPayout,
21
+ StripeComponentPrice,
22
+ StripeComponentProduct,
23
+ StripeComponentRefund,
24
+ StripeComponentSubscription,
25
+ StripeCountrySpecs,
26
+ StripeEventHandler,
27
+ StripeEventHandlers,
28
+ StripeV2Account,
29
+ StripeWebhookEvent,
30
+ SyncTriggerCtx,
31
+ SyncTriggers,
32
+ V2ThinEvent,
33
+ WebhookActionCtx,
34
+ } from "./types.js";
35
+ export type { PersonalAccountMapping } from "./core/personalAccountMapping.js";
@@ -8,6 +8,9 @@
8
8
  * @module
9
9
  */
10
10
 
11
+ import type * as accountClosure_helpers from "../accountClosure/helpers.js";
12
+ import type * as accountClosure_mutations from "../accountClosure/mutations.js";
13
+ import type * as accountClosure_queries from "../accountClosure/queries.js";
11
14
  import type * as affiliateEarnings_mutations from "../affiliateEarnings/mutations.js";
12
15
  import type * as affiliatePayouts_mutations from "../affiliatePayouts/mutations.js";
13
16
  import type * as affiliatePayouts_queries from "../affiliatePayouts/queries.js";
@@ -26,6 +29,7 @@ import type * as connect_reversalDiagnostics from "../connect/reversalDiagnostic
26
29
  import type * as connect_reversalReceipts from "../connect/reversalReceipts.js";
27
30
  import type * as connect_validators from "../connect/validators.js";
28
31
  import type * as core_mutations from "../core/mutations.js";
32
+ import type * as core_personalAccountMapping from "../core/personalAccountMapping.js";
29
33
  import type * as core_queries from "../core/queries.js";
30
34
  import type * as core_resetSafety from "../core/resetSafety.js";
31
35
  import type * as core_validators from "../core/validators.js";
@@ -99,6 +103,9 @@ import type {
99
103
  import { anyApi, componentsGeneric } from "convex/server";
100
104
 
101
105
  const fullApi: ApiFromModules<{
106
+ "accountClosure/helpers": typeof accountClosure_helpers;
107
+ "accountClosure/mutations": typeof accountClosure_mutations;
108
+ "accountClosure/queries": typeof accountClosure_queries;
102
109
  "affiliateEarnings/mutations": typeof affiliateEarnings_mutations;
103
110
  "affiliatePayouts/mutations": typeof affiliatePayouts_mutations;
104
111
  "affiliatePayouts/queries": typeof affiliatePayouts_queries;
@@ -117,6 +124,7 @@ const fullApi: ApiFromModules<{
117
124
  "connect/reversalReceipts": typeof connect_reversalReceipts;
118
125
  "connect/validators": typeof connect_validators;
119
126
  "core/mutations": typeof core_mutations;
127
+ "core/personalAccountMapping": typeof core_personalAccountMapping;
120
128
  "core/queries": typeof core_queries;
121
129
  "core/resetSafety": typeof core_resetSafety;
122
130
  "core/validators": typeof core_validators;
@@ -23,6 +23,92 @@ import type { FunctionReference } from "convex/server";
23
23
  */
24
24
  export type ComponentApi<Name extends string | undefined = string | undefined> =
25
25
  {
26
+ accountClosure: {
27
+ mutations: {
28
+ complete: FunctionReference<
29
+ "mutation",
30
+ "internal",
31
+ { stripeAccountId: string },
32
+ null,
33
+ Name
34
+ >;
35
+ prepare: FunctionReference<
36
+ "mutation",
37
+ "internal",
38
+ { stripeAccountId: string },
39
+ {
40
+ closure: {
41
+ _creationTime: number;
42
+ _id: string;
43
+ appliedConfigurations?: Array<
44
+ "customer" | "merchant" | "recipient"
45
+ >;
46
+ closedAt?: number;
47
+ orgId?: string;
48
+ state: "pending" | "closed";
49
+ stripeAccountId: string;
50
+ userId?: string;
51
+ };
52
+ isRetry: boolean;
53
+ },
54
+ Name
55
+ >;
56
+ };
57
+ queries: {
58
+ getClosedAccountByStripeId: FunctionReference<
59
+ "query",
60
+ "internal",
61
+ { stripeAccountId: string },
62
+ {
63
+ _creationTime: number;
64
+ _id: string;
65
+ appliedConfigurations?: Array<
66
+ "customer" | "merchant" | "recipient"
67
+ >;
68
+ closedAt?: number;
69
+ orgId?: string;
70
+ state: "pending" | "closed";
71
+ stripeAccountId: string;
72
+ userId?: string;
73
+ } | null,
74
+ Name
75
+ >;
76
+ listClosedAccountsByUserId: FunctionReference<
77
+ "query",
78
+ "internal",
79
+ {
80
+ paginationOpts: {
81
+ cursor: string | null;
82
+ endCursor?: string | null;
83
+ id?: number;
84
+ maximumBytesRead?: number;
85
+ maximumRowsRead?: number;
86
+ numItems: number;
87
+ };
88
+ userId: string;
89
+ },
90
+ {
91
+ continueCursor: string;
92
+ isDone: boolean;
93
+ page: Array<{
94
+ _creationTime: number;
95
+ _id: string;
96
+ appliedConfigurations?: Array<
97
+ "customer" | "merchant" | "recipient"
98
+ >;
99
+ closedAt?: number;
100
+ orgId?: string;
101
+ state: "pending" | "closed";
102
+ stripeAccountId: string;
103
+ userId?: string;
104
+ }>;
105
+ pageStatus?: "SplitRecommended" | "SplitRequired" | null;
106
+ splitCursor?: string | null;
107
+ },
108
+ Name
109
+ >;
110
+ };
111
+ };
26
112
  affiliateEarnings: {
27
113
  mutations: {
28
114
  confirmEarning: FunctionReference<
@@ -2223,6 +2309,46 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2223
2309
  } | null,
2224
2310
  Name
2225
2311
  >;
2312
+ getPersonalAccountMapping: FunctionReference<
2313
+ "query",
2314
+ "internal",
2315
+ { userId: string },
2316
+ | {
2317
+ account: {
2318
+ _creationTime: number;
2319
+ _id: string;
2320
+ appliedConfigurations?: Array<
2321
+ "customer" | "merchant" | "recipient"
2322
+ >;
2323
+ capabilities?: any;
2324
+ configuration?: any;
2325
+ country?: string;
2326
+ email?: string;
2327
+ metadata?: any;
2328
+ missingRequirements?: Array<string>;
2329
+ name?: string;
2330
+ onboardingStatus:
2331
+ "pending" | "in_progress" | "complete" | "restricted";
2332
+ orgId?: string;
2333
+ requirements?: any;
2334
+ statementDescriptor?: string;
2335
+ stripeAccountId: string;
2336
+ userId: string;
2337
+ };
2338
+ status: "unique";
2339
+ }
2340
+ | {
2341
+ reason:
2342
+ | "missing"
2343
+ | "ambiguous"
2344
+ | "organization"
2345
+ | "invalid_account"
2346
+ | "closure_unresolved"
2347
+ | "closed";
2348
+ status: "unavailable";
2349
+ },
2350
+ Name
2351
+ >;
2226
2352
  getPublishableKey: FunctionReference<
2227
2353
  "query",
2228
2354
  "internal",
@@ -0,0 +1,21 @@
1
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
2
+ export function closureByStripeId(ctx: QueryCtx, stripeAccountId: string) {
3
+ return ctx.db
4
+ .query("accountClosures")
5
+ .withIndex("by_stripe_account_id", (q) =>
6
+ q.eq("stripeAccountId", stripeAccountId),
7
+ )
8
+ .unique();
9
+ }
10
+ /** A delayed account event cannot revive a closed recipient or change a pinned owner. */
11
+ export async function canUpsertAccount(
12
+ ctx: MutationCtx,
13
+ account: { stripeAccountId: string; userId: string; orgId?: string },
14
+ ) {
15
+ const closure = await closureByStripeId(ctx, account.stripeAccountId);
16
+ if (!closure) return true;
17
+ if (closure.state === "closed") return false;
18
+ if (closure.userId !== account.userId || closure.orgId !== account.orgId)
19
+ throw new Error("Account ownership is pinned while closure is unresolved");
20
+ return true;
21
+ }