@fantastic.dev/better-stripe 0.74.0 → 0.76.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 (73) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/capturedCheckoutPayment.d.ts +31 -0
  4. package/dist/client/billing/capturedCheckoutPayment.d.ts.map +1 -0
  5. package/dist/client/billing/capturedCheckoutPayment.js +91 -0
  6. package/dist/client/billing/capturedCheckoutPayment.js.map +1 -0
  7. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +32 -32
  8. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +32 -32
  9. package/dist/client/core/accountCloseOptions.d.ts +21 -0
  10. package/dist/client/core/accountCloseOptions.d.ts.map +1 -0
  11. package/dist/client/core/accountCloseOptions.js +15 -0
  12. package/dist/client/core/accountCloseOptions.js.map +1 -0
  13. package/dist/client/core/accountCloseScope.d.ts +9 -0
  14. package/dist/client/core/accountCloseScope.d.ts.map +1 -0
  15. package/dist/client/core/accountCloseScope.js +49 -0
  16. package/dist/client/core/accountCloseScope.js.map +1 -0
  17. package/dist/client/core/accountClosurePreview.d.ts +40 -0
  18. package/dist/client/core/accountClosurePreview.d.ts.map +1 -0
  19. package/dist/client/core/accountClosurePreview.js +98 -0
  20. package/dist/client/core/accountClosurePreview.js.map +1 -0
  21. package/dist/client/core/accounts.d.ts +3 -6
  22. package/dist/client/core/accounts.d.ts.map +1 -1
  23. package/dist/client/core/accounts.js +21 -5
  24. package/dist/client/core/accounts.js.map +1 -1
  25. package/dist/client/index.d.ts +10 -6
  26. package/dist/client/index.d.ts.map +1 -1
  27. package/dist/client/index.js +8 -0
  28. package/dist/client/index.js.map +1 -1
  29. package/dist/client/publicTypes.d.ts +2 -0
  30. package/dist/client/publicTypes.d.ts.map +1 -1
  31. package/dist/component/_generated/api.d.ts +2 -0
  32. package/dist/component/_generated/api.d.ts.map +1 -1
  33. package/dist/component/_generated/api.js.map +1 -1
  34. package/dist/component/_generated/component.d.ts +14 -0
  35. package/dist/component/_generated/component.d.ts.map +1 -1
  36. package/dist/component/accountClosure/blockers.d.ts +6 -0
  37. package/dist/component/accountClosure/blockers.d.ts.map +1 -0
  38. package/dist/component/accountClosure/blockers.js +43 -0
  39. package/dist/component/accountClosure/blockers.js.map +1 -0
  40. package/dist/component/accountClosure/mutations.d.ts.map +1 -1
  41. package/dist/component/accountClosure/mutations.js +6 -31
  42. package/dist/component/accountClosure/mutations.js.map +1 -1
  43. package/dist/component/accountClosure/queries.d.ts +48 -0
  44. package/dist/component/accountClosure/queries.d.ts.map +1 -1
  45. package/dist/component/accountClosure/queries.js +32 -0
  46. package/dist/component/accountClosure/queries.js.map +1 -1
  47. package/dist/component/balanceFunding/mutations.d.ts +43 -43
  48. package/dist/component/balanceFunding/preparationHandlers.d.ts +8 -8
  49. package/dist/component/payoutRelease/queries.d.ts +2 -2
  50. package/dist/component/payoutRelease/queries.d.ts.map +1 -1
  51. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  52. package/dist/component/usage/allowance.fixtures.d.ts +16 -16
  53. package/docs/README.md +1 -0
  54. package/docs/captured-checkout-payment.md +136 -0
  55. package/docs/client-api.md +41 -0
  56. package/docs/react-workflows.md +37 -3
  57. package/package.json +1 -1
  58. package/src/client/billing/captured-checkout-payment.test.ts +272 -0
  59. package/src/client/billing/capturedCheckoutPayment.ts +120 -0
  60. package/src/client/core/account-close-guard.test.ts +349 -0
  61. package/src/client/core/account-closure-preview.test.ts +219 -0
  62. package/src/client/core/accountCloseOptions.ts +23 -0
  63. package/src/client/core/accountCloseScope.ts +87 -0
  64. package/src/client/core/accountClosurePreview.ts +149 -0
  65. package/src/client/core/accounts.ts +33 -7
  66. package/src/client/index.ts +19 -2
  67. package/src/client/publicTypes.ts +6 -0
  68. package/src/component/_generated/api.ts +2 -0
  69. package/src/component/_generated/component.ts +16 -0
  70. package/src/component/accountClosure/blockers.test.ts +114 -0
  71. package/src/component/accountClosure/blockers.ts +60 -0
  72. package/src/component/accountClosure/mutations.ts +6 -39
  73. package/src/component/accountClosure/queries.ts +41 -1
@@ -0,0 +1,149 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+ import type { Component, RunCtx } from "../helpers.js";
4
+ import type { AccountBalance } from "../connect/payouts.js";
5
+ import { getAccountBalance } from "../connect/payouts.js";
6
+ import { getCheckoutSessionPageFromStripe } from "../billing/checkoutPages.js";
7
+ import { componentRef } from "../webhooks/helpers.js";
8
+ import { closureConfigurations } from "./accountCloseOptions.js";
9
+ import type { ClosureBlocker } from "../../component/accountClosure/blockers.js";
10
+ import type { AppliedConfiguration } from "../../component/core/validators.js";
11
+
12
+ export type ClosureObservation<T> =
13
+ { status: "observed"; value: T } | { status: "unknown" };
14
+ export type AccountClosurePreview = {
15
+ stripeAccountId: string;
16
+ observedAt: number;
17
+ financialCoverage: "unknown";
18
+ account: ClosureObservation<{
19
+ appliedConfigurations: AppliedConfiguration[];
20
+ closed: boolean;
21
+ }>;
22
+ balances: ClosureObservation<AccountBalance[]>;
23
+ openSessions: ClosureObservation<{ sessionIds: string[]; hasMore: boolean }>;
24
+ componentBlockers: ClosureObservation<ClosureBlocker[]>;
25
+ knownBlockers: string[];
26
+ unknownReasons: string[];
27
+ };
28
+ export type AccountClosurePreviewOptions = {
29
+ stripeAccountId: string;
30
+ sessionLimit?: number;
31
+ };
32
+ export const accountClosurePreviewOptionsSchema = z
33
+ .object({
34
+ stripeAccountId: z
35
+ .string()
36
+ .regex(/^acct_[A-Za-z0-9_]+$/)
37
+ .max(128),
38
+ sessionLimit: z.number().int().min(1).max(100).optional(),
39
+ })
40
+ .strict();
41
+
42
+ /** Point-in-time known blockers; never a positive closure authorization. */
43
+ export async function previewAccountClosure(
44
+ stripe: Stripe,
45
+ component: Component,
46
+ ctx: RunCtx,
47
+ input: AccountClosurePreviewOptions,
48
+ ): Promise<AccountClosurePreview> {
49
+ const opts = accountClosurePreviewOptionsSchema.parse(input);
50
+ const [account, balances, openSessions, componentBlockers] =
51
+ await Promise.all([
52
+ observe(async () => {
53
+ const account = z
54
+ .object({
55
+ id: z.literal(opts.stripeAccountId),
56
+ closed: z.boolean(),
57
+ applied_configurations: closureConfigurations,
58
+ })
59
+ .passthrough()
60
+ .parse(await stripe.v2.core.accounts.retrieve(opts.stripeAccountId));
61
+ return {
62
+ appliedConfigurations: account.applied_configurations,
63
+ closed: account.closed,
64
+ };
65
+ }),
66
+ observe(async () =>
67
+ z
68
+ .array(
69
+ z
70
+ .object({
71
+ available: z.number().int().safe(),
72
+ pending: z.number().int().safe(),
73
+ currency: z.string().regex(/^[a-z]{3}$/),
74
+ })
75
+ .strict(),
76
+ )
77
+ .parse(
78
+ await getAccountBalance(stripe, {
79
+ stripeAccountId: opts.stripeAccountId,
80
+ }),
81
+ ),
82
+ ),
83
+ observe(async () => {
84
+ const page = await getCheckoutSessionPageFromStripe(stripe, {
85
+ customerAccount: opts.stripeAccountId,
86
+ status: "open",
87
+ limit: opts.sessionLimit ?? 25,
88
+ });
89
+ return {
90
+ sessionIds: page.page.map((session) => session.id),
91
+ hasMore: page.hasMore,
92
+ };
93
+ }),
94
+ observe(async () =>
95
+ z
96
+ .array(
97
+ z.enum(["usageCorrections", "prepaidCredits", "usageEnrollment"]),
98
+ )
99
+ .max(3)
100
+ .parse(
101
+ await ctx.runQuery(
102
+ componentRef(component, "accountClosure/queries/knownBlockers"),
103
+ { stripeAccountId: opts.stripeAccountId },
104
+ ),
105
+ ),
106
+ ),
107
+ ]);
108
+ const knownBlockers: string[] =
109
+ componentBlockers.status === "observed" ? [...componentBlockers.value] : [];
110
+ const unknownReasons = ["financial_coverage_unknown"];
111
+ if (account.status === "unknown") unknownReasons.push("account_unavailable");
112
+ if (balances.status === "unknown")
113
+ unknownReasons.push("balances_unavailable");
114
+ else if (
115
+ balances.value.some((item) => item.available !== 0 || item.pending !== 0)
116
+ )
117
+ knownBlockers.push("nonzero_balance");
118
+ if (openSessions.status === "unknown")
119
+ unknownReasons.push("open_sessions_unavailable");
120
+ else {
121
+ if (openSessions.value.sessionIds.length)
122
+ knownBlockers.push("open_checkout_sessions");
123
+ if (openSessions.value.hasMore)
124
+ unknownReasons.push("open_sessions_truncated");
125
+ }
126
+ if (componentBlockers.status === "unknown")
127
+ unknownReasons.push("component_blockers_unavailable");
128
+ return {
129
+ stripeAccountId: opts.stripeAccountId,
130
+ observedAt: Date.now(),
131
+ financialCoverage: "unknown",
132
+ account,
133
+ balances,
134
+ openSessions,
135
+ componentBlockers,
136
+ knownBlockers,
137
+ unknownReasons,
138
+ };
139
+ }
140
+
141
+ async function observe<T>(
142
+ read: () => Promise<T>,
143
+ ): Promise<ClosureObservation<T>> {
144
+ try {
145
+ return { status: "observed", value: await read() };
146
+ } catch {
147
+ return { status: "unknown" };
148
+ }
149
+ }
@@ -1,6 +1,15 @@
1
1
  import type { AccountByStripeIdOptions } from "../originalIdReadOptions.js";
2
2
  import { addCustomerConfiguration } from "./accountConfigurations.js";
3
3
  import { idempotencyOptions } from "./idempotency.js";
4
+ import {
5
+ closeAccountOptionsSchema,
6
+ type CloseAccountOptions,
7
+ } from "./accountCloseOptions.js";
8
+ import {
9
+ confirmedClosureScope,
10
+ guardedAccountIsClosed,
11
+ assertGuardedCloseAcknowledgement,
12
+ } from "./accountCloseScope.js";
4
13
  export type CreateAccountOptions = {
5
14
  userId: string;
6
15
  email?: string;
@@ -432,25 +441,39 @@ export async function closeAccount(
432
441
  stripe: Stripe,
433
442
  component: Component,
434
443
  ctx: RunCtx,
435
- opts: { stripeAccountId: string },
444
+ opts: CloseAccountOptions,
436
445
  ): Promise<{ closed: boolean }> {
446
+ const isGuarded = opts.expectedAppliedConfigurations !== undefined;
447
+ if (isGuarded) closeAccountOptionsSchema.parse(opts);
448
+ const originalOptions = isGuarded
449
+ ? { stripeAccountId: opts.stripeAccountId }
450
+ : opts;
437
451
  const { closure, isRetry } = await runMutationOrThrow(
438
452
  ctx,
439
453
  componentRef(component, "accountClosure/mutations/prepare"),
440
- opts,
454
+ originalOptions,
441
455
  );
456
+ if (isGuarded) confirmedClosureScope(opts, closure);
442
457
  if (closure.state === "closed") return { closed: true };
443
458
  let appliedConfigs = closure.appliedConfigurations;
444
459
  let isProviderClosed = false;
445
- if (isRetry || appliedConfigs === undefined) {
460
+ if (isGuarded) {
461
+ isProviderClosed = await guardedAccountIsClosed(
462
+ stripe,
463
+ component,
464
+ ctx,
465
+ opts,
466
+ closure,
467
+ );
468
+ } else if (isRetry || appliedConfigs === undefined) {
446
469
  const account = await stripe.v2.core.accounts.retrieve(
447
470
  opts.stripeAccountId,
448
471
  );
449
472
  appliedConfigs ??= account.applied_configurations ?? [];
450
473
  isProviderClosed = account.closed === true;
451
474
  }
452
- if (!isProviderClosed)
453
- await stripe.v2.core.accounts.close(
475
+ if (!isProviderClosed) {
476
+ const response = await stripe.v2.core.accounts.close(
454
477
  opts.stripeAccountId,
455
478
  {
456
479
  applied_configurations: (appliedConfigs ??
@@ -458,10 +481,13 @@ export async function closeAccount(
458
481
  },
459
482
  { idempotencyKey: `betterstripe-close:${opts.stripeAccountId}` },
460
483
  );
484
+ if (isGuarded)
485
+ assertGuardedCloseAcknowledgement(response, opts.stripeAccountId);
486
+ }
461
487
  await runMutationOrThrow(
462
488
  ctx,
463
489
  componentRef(component, "accountClosure/mutations/complete"),
464
- opts,
490
+ originalOptions,
465
491
  );
466
492
 
467
493
  return { closed: true };
@@ -471,7 +497,7 @@ export async function restartAccountOnboarding(
471
497
  stripe: Stripe,
472
498
  component: Component,
473
499
  ctx: RunCtx,
474
- opts: { stripeAccountId: string },
500
+ opts: CloseAccountOptions,
475
501
  ): Promise<{ closed: boolean }> {
476
502
  return closeAccount(stripe, component, ctx, opts);
477
503
  }
@@ -1,3 +1,8 @@
1
+ export { qualifyCapturedCheckoutPayment } from "./billing/capturedCheckoutPayment.js";
2
+ export type {
3
+ CapturedCheckoutPaymentExpected,
4
+ CapturedCheckoutPaymentObservation,
5
+ } from "./billing/capturedCheckoutPayment.js";
1
6
  export type {
2
7
  ProductIdentityResult,
3
8
  PriceIdentityResult,
@@ -35,6 +40,13 @@ export type {
35
40
  export type { RefundSyncScope } from "./connect/refundSyncValidation.js";
36
41
  import * as personalAccountMappingImpl from "./core/personalAccountMapping.js";
37
42
  export type * from "./publicTypes.js";
43
+ export { closeAccountOptionsSchema } from "./core/accountCloseOptions.js";
44
+ export { accountClosurePreviewOptionsSchema } from "./core/accountClosurePreview.js";
45
+ import type { CloseAccountOptions } from "./core/accountCloseOptions.js";
46
+ import {
47
+ previewAccountClosure,
48
+ type AccountClosurePreviewOptions,
49
+ } from "./core/accountClosurePreview.js";
38
50
  export * from "./financialOutcomes/index.js";
39
51
  export * from "./processingCostDeficit/index.js";
40
52
  import * as accountClosuresImpl from "./core/accountClosures.js";
@@ -506,16 +518,21 @@ export class BetterStripe extends PaymentSourceClient {
506
518
  return accountsImpl.listStripeAccounts(this.stripe(), ctx, opts);
507
519
  }
508
520
 
521
+ /** Known point-in-time blockers only. Host authentication and independent clearance remain required. */
522
+ async previewAccountClosure(ctx: RunCtx, opts: AccountClosurePreviewOptions) {
523
+ return previewAccountClosure(this.stripe(), this.component, ctx, opts);
524
+ }
525
+
509
526
  async closeAccount(
510
527
  ctx: RunCtx,
511
- opts: { stripeAccountId: string },
528
+ opts: CloseAccountOptions,
512
529
  ): Promise<{ closed: boolean }> {
513
530
  return accountsImpl.closeAccount(this.stripe(), this.component, ctx, opts);
514
531
  }
515
532
 
516
533
  async restartAccountOnboarding(
517
534
  ctx: RunCtx,
518
- opts: { stripeAccountId: string },
535
+ opts: CloseAccountOptions,
519
536
  ): Promise<{ closed: boolean }> {
520
537
  return accountsImpl.restartAccountOnboarding(
521
538
  this.stripe(),
@@ -1,4 +1,10 @@
1
1
  export type { StripeAccountClosure } from "./core/accountClosures.js";
2
+ export type { CloseAccountOptions } from "./core/accountCloseOptions.js";
3
+ export type {
4
+ AccountClosurePreview,
5
+ AccountClosurePreviewOptions,
6
+ ClosureObservation,
7
+ } from "./core/accountClosurePreview.js";
2
8
  export type {
3
9
  BetterStripeOptions,
4
10
  FeeOverride,
@@ -8,6 +8,7 @@
8
8
  * @module
9
9
  */
10
10
 
11
+ import type * as accountClosure_blockers from "../accountClosure/blockers.js";
11
12
  import type * as accountClosure_helpers from "../accountClosure/helpers.js";
12
13
  import type * as accountClosure_mutations from "../accountClosure/mutations.js";
13
14
  import type * as accountClosure_queries from "../accountClosure/queries.js";
@@ -226,6 +227,7 @@ import type {
226
227
  import { anyApi, componentsGeneric } from "convex/server";
227
228
 
228
229
  const fullApi: ApiFromModules<{
230
+ "accountClosure/blockers": typeof accountClosure_blockers;
229
231
  "accountClosure/helpers": typeof accountClosure_helpers;
230
232
  "accountClosure/mutations": typeof accountClosure_mutations;
231
233
  "accountClosure/queries": typeof accountClosure_queries;
@@ -55,6 +55,15 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
55
55
  >;
56
56
  };
57
57
  queries: {
58
+ currentOwner: FunctionReference<
59
+ "query",
60
+ "internal",
61
+ { stripeAccountId: string },
62
+ | { status: "missing" }
63
+ | { status: "ambiguous" }
64
+ | { orgId?: string; status: "unique"; userId: string },
65
+ Name
66
+ >;
58
67
  getClosedAccountByStripeId: FunctionReference<
59
68
  "query",
60
69
  "internal",
@@ -73,6 +82,13 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
73
82
  } | null,
74
83
  Name
75
84
  >;
85
+ knownBlockers: FunctionReference<
86
+ "query",
87
+ "internal",
88
+ { stripeAccountId: string },
89
+ Array<"usageCorrections" | "prepaidCredits" | "usageEnrollment">,
90
+ Name
91
+ >;
76
92
  listClosedAccountsByUserId: FunctionReference<
77
93
  "query",
78
94
  "internal",
@@ -0,0 +1,114 @@
1
+ import { convexTest } from "convex-test";
2
+ import { makeFunctionReference } from "convex/server";
3
+ import { expect, it } from "vitest";
4
+ import { schema, modules } from "../../test.js";
5
+
6
+ const read = makeFunctionReference<"query">(
7
+ "accountClosure/queries:knownBlockers",
8
+ );
9
+ const prepare = makeFunctionReference<"mutation">(
10
+ "accountClosure/mutations:prepare",
11
+ );
12
+
13
+ it("distinguishes missing, exact and ambiguous current ownership with bounded registered reads", async () => {
14
+ const t = convexTest(schema, modules);
15
+ const readOwner = makeFunctionReference<"query">(
16
+ "accountClosure/queries:currentOwner",
17
+ );
18
+ expect(await t.query(readOwner, { stripeAccountId: "acct_owner" })).toEqual({
19
+ status: "missing",
20
+ });
21
+ await t.run(async (ctx) => {
22
+ await ctx.db.insert("accounts", {
23
+ stripeAccountId: "acct_owner",
24
+ userId: "original",
25
+ onboardingStatus: "pending",
26
+ });
27
+ });
28
+ expect(await t.query(readOwner, { stripeAccountId: "acct_owner" })).toEqual({
29
+ status: "unique",
30
+ userId: "original",
31
+ });
32
+ await t.run(async (ctx) => {
33
+ await ctx.db.insert("accounts", {
34
+ stripeAccountId: "acct_owner",
35
+ userId: "conflicting",
36
+ onboardingStatus: "pending",
37
+ });
38
+ });
39
+ expect(await t.query(readOwner, { stripeAccountId: "acct_owner" })).toEqual({
40
+ status: "ambiguous",
41
+ });
42
+ });
43
+
44
+ it.each(["usageCorrections", "usageEnrollment", "prepaidCredits"] as const)(
45
+ "shares actual indexed %s blockers between read-only preview and close",
46
+ async (kind) => {
47
+ const t = convexTest(schema, modules);
48
+ await t.run(async (ctx) => {
49
+ if (kind === "usageEnrollment")
50
+ await ctx.db.insert("usageSubscriptionLocks", {
51
+ key: "lock",
52
+ intentKey: "original",
53
+ customerAccount: "acct_target",
54
+ stripeAccountId: "acct_realm",
55
+ });
56
+ if (kind === "prepaidCredits")
57
+ await ctx.db.insert("usageCreditAccounts", {
58
+ key: "credits",
59
+ scopeKey: "original",
60
+ bindingJson: "{}",
61
+ customerAccount: "acct_target",
62
+ stripeAccountId: "acct_realm",
63
+ closed: false,
64
+ purchaseCount: 0,
65
+ historyCount: 0,
66
+ });
67
+ if (kind === "usageCorrections") {
68
+ const eventId = await ctx.db.insert("usageEvents", {
69
+ scopeKey: "original",
70
+ identity: "event",
71
+ recordJson: "{}",
72
+ subscriptionJson: "{}",
73
+ occurredAt: 1,
74
+ acceptedAt: 1,
75
+ });
76
+ await ctx.db.insert("usageCorrections", {
77
+ eventId,
78
+ key: "correction",
79
+ scopeKey: "original",
80
+ customerAccount: "acct_target",
81
+ stripeAccountId: "acct_realm",
82
+ correctionId: "original",
83
+ inputJson: "{}",
84
+ recordJson: "{}",
85
+ subscriptionJson: "{}",
86
+ quantity: "1",
87
+ scaledQuantity: "1",
88
+ state: "held",
89
+ reason: "original",
90
+ firstAttemptAt: 1,
91
+ attempt: 0,
92
+ cashConsequence: "none",
93
+ restoredQuantity: "0",
94
+ historyCount: 0,
95
+ });
96
+ }
97
+ });
98
+ expect(await t.query(read, { stripeAccountId: "acct_target" })).toContain(
99
+ kind,
100
+ );
101
+ expect(await t.query(read, { stripeAccountId: "acct_realm" })).toContain(
102
+ kind,
103
+ );
104
+ expect(await t.query(read, { stripeAccountId: "acct_unrelated" })).toEqual(
105
+ [],
106
+ );
107
+ await expect(
108
+ t.mutation(prepare, { stripeAccountId: "acct_target" }),
109
+ ).rejects.toThrow();
110
+ expect(await t.query(read, { stripeAccountId: "acct_target" })).toContain(
111
+ kind,
112
+ );
113
+ },
114
+ );
@@ -0,0 +1,60 @@
1
+ import { v } from "convex/values";
2
+ import type { MutationCtx, QueryCtx } from "../_generated/server.js";
3
+ import { unresolvedCorrectionStates } from "../usageCorrections/cancellation.js";
4
+
5
+ export const closureBlocker = v.union(
6
+ v.literal("usageCorrections"),
7
+ v.literal("prepaidCredits"),
8
+ v.literal("usageEnrollment"),
9
+ );
10
+ export type ClosureBlocker =
11
+ "usageCorrections" | "prepaidCredits" | "usageEnrollment";
12
+
13
+ /** Known indexed component blockers only; absence is not whole-account clearance. */
14
+ export async function readClosureBlockers(
15
+ ctx: QueryCtx | MutationCtx,
16
+ stripeAccountId: string,
17
+ ): Promise<ClosureBlocker[]> {
18
+ const result: ClosureBlocker[] = [];
19
+ for (const state of unresolvedCorrectionStates) {
20
+ const payer = await ctx.db
21
+ .query("usageCorrections")
22
+ .withIndex("by_payer_state", (q) =>
23
+ q.eq("customerAccount", stripeAccountId).eq("state", state),
24
+ )
25
+ .first();
26
+ const realm = await ctx.db
27
+ .query("usageCorrections")
28
+ .withIndex("by_realm_state", (q) =>
29
+ q.eq("stripeAccountId", stripeAccountId).eq("state", state),
30
+ )
31
+ .first();
32
+ if (payer || realm) {
33
+ result.push("usageCorrections");
34
+ break;
35
+ }
36
+ }
37
+ const payerLock = await ctx.db
38
+ .query("usageSubscriptionLocks")
39
+ .withIndex("by_payer", (q) => q.eq("customerAccount", stripeAccountId))
40
+ .first();
41
+ const realmLock = await ctx.db
42
+ .query("usageSubscriptionLocks")
43
+ .withIndex("by_realm", (q) => q.eq("stripeAccountId", stripeAccountId))
44
+ .first();
45
+ const payerCredits = await ctx.db
46
+ .query("usageCreditAccounts")
47
+ .withIndex("by_payer_closed", (q) =>
48
+ q.eq("customerAccount", stripeAccountId).eq("closed", false),
49
+ )
50
+ .first();
51
+ const realmCredits = await ctx.db
52
+ .query("usageCreditAccounts")
53
+ .withIndex("by_realm_closed", (q) =>
54
+ q.eq("stripeAccountId", stripeAccountId).eq("closed", false),
55
+ )
56
+ .first();
57
+ if (payerCredits || realmCredits) result.push("prepaidCredits");
58
+ if (payerLock || realmLock) result.push("usageEnrollment");
59
+ return result;
60
+ }
@@ -1,4 +1,4 @@
1
- import { unresolvedCorrectionStates } from "../usageCorrections/cancellation.js";
1
+ import { readClosureBlockers } from "./blockers.js";
2
2
  import { v } from "convex/values";
3
3
  import { mutation } from "../_generated/server.js";
4
4
  import { closureByStripeId } from "./helpers.js";
@@ -8,45 +8,12 @@ export const prepare = mutation({
8
8
  args: { stripeAccountId: v.string() },
9
9
  returns: v.object({ closure: closureDoc, isRetry: v.boolean() }),
10
10
  handler: async (ctx, { stripeAccountId }) => {
11
- for (const state of unresolvedCorrectionStates) {
12
- const payerCorrection = await ctx.db
13
- .query("usageCorrections")
14
- .withIndex("by_payer_state", (q) =>
15
- q.eq("customerAccount", stripeAccountId).eq("state", state),
16
- )
17
- .first();
18
- const realmCorrection = await ctx.db
19
- .query("usageCorrections")
20
- .withIndex("by_realm_state", (q) =>
21
- q.eq("stripeAccountId", stripeAccountId).eq("state", state),
22
- )
23
- .first();
24
- if (payerCorrection || realmCorrection)
25
- throw new Error("Resolve usage corrections before account closure");
26
- }
27
- const payerLock = await ctx.db
28
- .query("usageSubscriptionLocks")
29
- .withIndex("by_payer", (q) => q.eq("customerAccount", stripeAccountId))
30
- .first();
31
- const realmLock = await ctx.db
32
- .query("usageSubscriptionLocks")
33
- .withIndex("by_realm", (q) => q.eq("stripeAccountId", stripeAccountId))
34
- .first();
35
- const payerCredits = await ctx.db
36
- .query("usageCreditAccounts")
37
- .withIndex("by_payer_closed", (q) =>
38
- q.eq("customerAccount", stripeAccountId).eq("closed", false),
39
- )
40
- .first();
41
- const realmCredits = await ctx.db
42
- .query("usageCreditAccounts")
43
- .withIndex("by_realm_closed", (q) =>
44
- q.eq("stripeAccountId", stripeAccountId).eq("closed", false),
45
- )
46
- .first();
47
- if (payerCredits || realmCredits)
11
+ const blockers = await readClosureBlockers(ctx, stripeAccountId);
12
+ if (blockers.includes("usageCorrections"))
13
+ throw new Error("Resolve usage corrections before account closure");
14
+ if (blockers.includes("prepaidCredits"))
48
15
  throw new Error("Close out prepaid credits before account closure");
49
- if (payerLock || realmLock)
16
+ if (blockers.includes("usageEnrollment"))
50
17
  throw new Error(
51
18
  "Close out managed usage enrollment before account closure",
52
19
  );
@@ -3,11 +3,51 @@ import {
3
3
  paginationResultValidator,
4
4
  } from "convex/server";
5
5
  import { paginator } from "convex-helpers/server/pagination";
6
- import { v } from "convex/values";
6
+ import { v, type Infer } from "convex/values";
7
7
  import { query } from "../_generated/server.js";
8
8
  import schema from "../schema.js";
9
9
  import { closureByStripeId } from "./helpers.js";
10
10
  import { closureDoc } from "./schema.js";
11
+ import { closureBlocker, readClosureBlockers } from "./blockers.js";
12
+
13
+ const currentOwnerResult = v.union(
14
+ v.object({ status: v.literal("missing") }),
15
+ v.object({ status: v.literal("ambiguous") }),
16
+ v.object({
17
+ status: v.literal("unique"),
18
+ userId: v.string(),
19
+ orgId: v.optional(v.string()),
20
+ }),
21
+ );
22
+ export type CurrentClosureOwner = Infer<typeof currentOwnerResult>;
23
+
24
+ /** Missing live mapping and contradictory/duplicate ownership are distinct observations. */
25
+ export const currentOwner = query({
26
+ args: { stripeAccountId: v.string() },
27
+ returns: currentOwnerResult,
28
+ handler: async (ctx, args) => {
29
+ const rows = await ctx.db
30
+ .query("accounts")
31
+ .withIndex("by_stripe_account_id", (q) =>
32
+ q.eq("stripeAccountId", args.stripeAccountId),
33
+ )
34
+ .take(2);
35
+ if (!rows.length) return { status: "missing" as const };
36
+ if (rows.length !== 1) return { status: "ambiguous" as const };
37
+ return {
38
+ status: "unique" as const,
39
+ userId: rows[0]!.userId,
40
+ orgId: rows[0]!.orgId,
41
+ };
42
+ },
43
+ });
44
+
45
+ /** Trusted host read; no mutation, authorization or positive clearance. */
46
+ export const knownBlockers = query({
47
+ args: { stripeAccountId: v.string() },
48
+ returns: v.array(closureBlocker),
49
+ handler: (ctx, args) => readClosureBlockers(ctx, args.stripeAccountId),
50
+ });
11
51
  /** This is provenance, not end-user authentication; hosts must compare the authenticated owner. */
12
52
  export const getClosedAccountByStripeId = query({
13
53
  args: { stripeAccountId: v.string() },