@fantastic.dev/better-stripe 0.48.0 → 0.49.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 (77) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/invoicePaymentPages.d.ts +2 -5
  4. package/dist/client/billing/invoicePaymentPages.d.ts.map +1 -1
  5. package/dist/client/billing/invoicePaymentPages.js +2 -58
  6. package/dist/client/billing/invoicePaymentPages.js.map +1 -1
  7. package/dist/client/billing/invoicePaymentRead.d.ts +17 -0
  8. package/dist/client/billing/invoicePaymentRead.d.ts.map +1 -0
  9. package/dist/client/billing/invoicePaymentRead.js +25 -0
  10. package/dist/client/billing/invoicePaymentRead.js.map +1 -0
  11. package/dist/client/billing/invoicePaymentShared.d.ts +22 -0
  12. package/dist/client/billing/invoicePaymentShared.d.ts.map +1 -0
  13. package/dist/client/billing/invoicePaymentShared.js +62 -0
  14. package/dist/client/billing/invoicePaymentShared.js.map +1 -0
  15. package/dist/client/billing/subscription-payment-method.d.ts +28 -0
  16. package/dist/client/billing/subscription-payment-method.d.ts.map +1 -0
  17. package/dist/client/billing/subscription-payment-method.js +101 -0
  18. package/dist/client/billing/subscription-payment-method.js.map +1 -0
  19. package/dist/client/billing/subscriptions.d.ts +2 -3
  20. package/dist/client/billing/subscriptions.d.ts.map +1 -1
  21. package/dist/client/billing/subscriptions.js.map +1 -1
  22. package/dist/client/core/accounts.d.ts +2 -3
  23. package/dist/client/core/accounts.d.ts.map +1 -1
  24. package/dist/client/core/accounts.js.map +1 -1
  25. package/dist/client/index.d.ts +8 -6
  26. package/dist/client/index.d.ts.map +1 -1
  27. package/dist/client/index.js +5 -0
  28. package/dist/client/index.js.map +1 -1
  29. package/dist/client/invoiceReads.d.ts +3 -0
  30. package/dist/client/invoiceReads.d.ts.map +1 -1
  31. package/dist/client/invoiceReads.js +5 -0
  32. package/dist/client/invoiceReads.js.map +1 -1
  33. package/dist/client/originalIdReadOptions.d.ts +10 -0
  34. package/dist/client/originalIdReadOptions.d.ts.map +1 -0
  35. package/dist/client/originalIdReadOptions.js +2 -0
  36. package/dist/client/originalIdReadOptions.js.map +1 -0
  37. package/dist/client/publicTypes.d.ts +1 -0
  38. package/dist/client/publicTypes.d.ts.map +1 -1
  39. package/dist/component/_generated/component.d.ts +3 -0
  40. package/dist/component/_generated/component.d.ts.map +1 -1
  41. package/dist/component/billing/queries.d.ts +1 -0
  42. package/dist/component/billing/queries.d.ts.map +1 -1
  43. package/dist/component/billing/queries.js +10 -4
  44. package/dist/component/billing/queries.js.map +1 -1
  45. package/dist/component/connect/queries.d.ts +1 -0
  46. package/dist/component/connect/queries.d.ts.map +1 -1
  47. package/dist/component/connect/queries.js +10 -4
  48. package/dist/component/connect/queries.js.map +1 -1
  49. package/dist/component/core/queries.d.ts +1 -0
  50. package/dist/component/core/queries.d.ts.map +1 -1
  51. package/dist/component/core/queries.js +7 -4
  52. package/dist/component/core/queries.js.map +1 -1
  53. package/docs/invoice-payment-pages.md +62 -0
  54. package/docs/personal-account-mapping.md +30 -0
  55. package/docs/read-contracts.md +45 -0
  56. package/docs/subscription-payment-methods.md +121 -0
  57. package/package.json +2 -1
  58. package/src/client/billing/invoicePaymentPages.ts +9 -74
  59. package/src/client/billing/invoicePaymentRead.test.ts +233 -0
  60. package/src/client/billing/invoicePaymentRead.ts +44 -0
  61. package/src/client/billing/invoicePaymentReadTransport.test.ts +101 -0
  62. package/src/client/billing/invoicePaymentShared.ts +84 -0
  63. package/src/client/billing/subscription-payment-method.test.ts +460 -0
  64. package/src/client/billing/subscription-payment-method.ts +177 -0
  65. package/src/client/billing/subscriptions.ts +2 -1
  66. package/src/client/core/accounts.ts +2 -1
  67. package/src/client/index.ts +27 -2
  68. package/src/client/invoiceReads.ts +9 -0
  69. package/src/client/originalIdReadOptions.test.ts +63 -0
  70. package/src/client/originalIdReadOptions.ts +10 -0
  71. package/src/client/publicTypes.ts +5 -0
  72. package/src/component/_generated/component.ts +3 -3
  73. package/src/component/billing/queries.ts +9 -4
  74. package/src/component/connect/payment-unique.test.ts +195 -0
  75. package/src/component/connect/queries.ts +9 -4
  76. package/src/component/core/original-id-unique.test.ts +209 -0
  77. package/src/component/core/queries.ts +6 -4
@@ -1,3 +1,8 @@
1
+ import * as subscriptionPaymentMethod from "./billing/subscription-payment-method.js";
2
+ import type {
3
+ AccountByStripeIdOptions,
4
+ SubscriptionByStripeIdOptions,
5
+ } from "./originalIdReadOptions.js";
1
6
  import { refundReconciliationResult } from "./webhooks/refundReconciliationValidators.js";
2
7
  import type { RefundReconciliationResult } from "./webhooks/refundReconciliationValidators.js";
3
8
  import { reconcileRefundAndTrigger } from "./webhooks/refundReconciliation.js";
@@ -76,6 +81,10 @@ export type {
76
81
  CouponReadOptions,
77
82
  } from "./billing/providerReads.js";
78
83
  import * as providerReads from "./billing/providerReads.js";
84
+ export type {
85
+ InvoicePaymentReadOptions,
86
+ ProviderInvoicePaymentRead,
87
+ } from "./billing/invoicePaymentRead.js";
79
88
  export type {
80
89
  InvoicePaymentPageOptions,
81
90
  ProviderInvoicePaymentPage,
@@ -403,7 +412,7 @@ export class BetterStripe extends PaymentSourceClient {
403
412
 
404
413
  async getAccountByStripeId(
405
414
  ctx: RunCtx,
406
- opts: { stripeAccountId: string },
415
+ opts: AccountByStripeIdOptions,
407
416
  ): Promise<StripeComponentAccount | null> {
408
417
  return accountsImpl.getAccountByStripeId(this.component, ctx, opts);
409
418
  }
@@ -694,7 +703,7 @@ export class BetterStripe extends PaymentSourceClient {
694
703
 
695
704
  async getSubscriptionByStripeId(
696
705
  ctx: RunCtx,
697
- opts: { stripeSubscriptionId: string },
706
+ opts: SubscriptionByStripeIdOptions,
698
707
  ): Promise<StripeComponentSubscription | null> {
699
708
  return subscriptionsImpl.getSubscriptionByStripeId(
700
709
  this.component,
@@ -1119,6 +1128,17 @@ export class BetterStripe extends PaymentSourceClient {
1119
1128
  ) {
1120
1129
  return providerReads.getCheckoutSessionFromStripe(this.stripe(), opts);
1121
1130
  }
1131
+ /** Host-authorized existing subscription card selection; never an account-wide default. */
1132
+ updateSubscriptionDefaultPaymentMethod(
1133
+ _ctx: RunCtx,
1134
+ opts: subscriptionPaymentMethod.SubscriptionPaymentMethodOptions,
1135
+ ) {
1136
+ return subscriptionPaymentMethod.updateSubscriptionDefaultPaymentMethod(
1137
+ this.stripe(),
1138
+ opts,
1139
+ );
1140
+ }
1141
+
1122
1142
  async getSubscriptionFromStripe(
1123
1143
  _ctx: RunCtx,
1124
1144
  opts: providerReads.SubscriptionReadOptions,
@@ -1772,3 +1792,8 @@ export class BetterStripe extends PaymentSourceClient {
1772
1792
  return { syncWebhook, asyncWebhook };
1773
1793
  }
1774
1794
  }
1795
+
1796
+ export type {
1797
+ SubscriptionPaymentMethodOptions,
1798
+ SubscriptionPaymentMethodResult,
1799
+ } from "./billing/subscription-payment-method.js";
@@ -3,6 +3,7 @@ import { ReadContractClient } from "./readContracts.js";
3
3
  import type { RunCtx } from "./helpers.js";
4
4
  import { getRefundContext } from "./connect/refundContext.js";
5
5
  import type { RefundContextOptions } from "./connect/refundContextTypes.js";
6
+ import * as invoicePaymentRead from "./billing/invoicePaymentRead.js";
6
7
  import * as invoicePages from "./billing/invoicePages.js";
7
8
  import * as invoicePaymentPages from "./billing/invoicePaymentPages.js";
8
9
  import * as checkoutPages from "./billing/checkoutPages.js";
@@ -42,4 +43,12 @@ export abstract class InvoiceReadClient extends ReadContractClient {
42
43
  opts,
43
44
  );
44
45
  }
46
+
47
+ /** Exact original reference read; host authorization and post-read checks remain required. */
48
+ async getInvoicePaymentFromStripe(
49
+ _ctx: RunCtx,
50
+ opts: invoicePaymentRead.InvoicePaymentReadOptions,
51
+ ) {
52
+ return invoicePaymentRead.getInvoicePaymentFromStripe(this.stripe(), opts);
53
+ }
45
54
  }
@@ -0,0 +1,63 @@
1
+ import { expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "./index.js";
3
+ import { components } from "./setup.test.js";
4
+ import type {
5
+ AccountByStripeIdOptions,
6
+ SubscriptionByStripeIdOptions,
7
+ } from "./publicTypes.js";
8
+
9
+ it.each([undefined, false, true])(
10
+ "forwards requireUnique=%s unchanged through both public SDK methods",
11
+ async (requireUnique) => {
12
+ const client = new BetterStripe(components.betterStripe);
13
+ const row = { observed: true };
14
+ const runQuery = vi.fn().mockResolvedValue(row);
15
+ const account: AccountByStripeIdOptions = {
16
+ stripeAccountId: "acct_original",
17
+ ...(requireUnique === undefined ? {} : { requireUnique }),
18
+ };
19
+ const subscription: SubscriptionByStripeIdOptions = {
20
+ stripeSubscriptionId: "sub_original",
21
+ ...(requireUnique === undefined ? {} : { requireUnique }),
22
+ };
23
+ expect(await client.getAccountByStripeId({ runQuery }, account)).toBe(row);
24
+ expect(
25
+ await client.getSubscriptionByStripeId({ runQuery }, subscription),
26
+ ).toBe(row);
27
+ expect(runQuery).toHaveBeenNthCalledWith(
28
+ 1,
29
+ components.betterStripe.core.queries.getAccountByStripeId,
30
+ account,
31
+ );
32
+ expect(runQuery).toHaveBeenNthCalledWith(
33
+ 2,
34
+ components.betterStripe.billing.queries.getSubscriptionByStripeId,
35
+ subscription,
36
+ );
37
+ },
38
+ );
39
+
40
+ it("propagates unique-read failures without inventing missing records", async () => {
41
+ const client = new BetterStripe(components.betterStripe);
42
+ const runQuery = vi
43
+ .fn()
44
+ .mockRejectedValue(new Error("component unavailable"));
45
+ await expect(
46
+ client.getAccountByStripeId(
47
+ { runQuery },
48
+ {
49
+ stripeAccountId: "acct_original",
50
+ requireUnique: true,
51
+ },
52
+ ),
53
+ ).rejects.toThrow("component unavailable");
54
+ await expect(
55
+ client.getSubscriptionByStripeId(
56
+ { runQuery },
57
+ {
58
+ stripeSubscriptionId: "sub_original",
59
+ requireUnique: true,
60
+ },
61
+ ),
62
+ ).rejects.toThrow("component unavailable");
63
+ });
@@ -0,0 +1,10 @@
1
+ /** Trusted-host exact-ID lookup; uniqueness is not ownership or provider usability. */
2
+ export type AccountByStripeIdOptions = {
3
+ stripeAccountId: string;
4
+ requireUnique?: boolean;
5
+ };
6
+
7
+ export type SubscriptionByStripeIdOptions = {
8
+ stripeSubscriptionId: string;
9
+ requireUnique?: boolean;
10
+ };
@@ -98,3 +98,8 @@ export type {
98
98
  SubscriptionHistoryPage,
99
99
  CheckoutSessionHistoryPage,
100
100
  } from "./billing/historyPages.js";
101
+
102
+ export type {
103
+ AccountByStripeIdOptions,
104
+ SubscriptionByStripeIdOptions,
105
+ } from "./originalIdReadOptions.js";
@@ -2072,7 +2072,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2072
2072
  getSubscriptionByStripeId: FunctionReference<
2073
2073
  "query",
2074
2074
  "internal",
2075
- { stripeSubscriptionId: string },
2075
+ { requireUnique?: boolean; stripeSubscriptionId: string },
2076
2076
  {
2077
2077
  _creationTime: number;
2078
2078
  _id: string;
@@ -2974,7 +2974,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
2974
2974
  getPaymentByStripeId: FunctionReference<
2975
2975
  "query",
2976
2976
  "internal",
2977
- { stripePaymentIntentId: string },
2977
+ { requireUnique?: boolean; stripePaymentIntentId: string },
2978
2978
  {
2979
2979
  _creationTime: number;
2980
2980
  _id: string;
@@ -3528,7 +3528,7 @@ export type ComponentApi<Name extends string | undefined = string | undefined> =
3528
3528
  getAccountByStripeId: FunctionReference<
3529
3529
  "query",
3530
3530
  "internal",
3531
- { stripeAccountId: string },
3531
+ { requireUnique?: boolean; stripeAccountId: string },
3532
3532
  {
3533
3533
  _creationTime: number;
3534
3534
  _id: string;
@@ -24,15 +24,20 @@ export const getSubscription = query({
24
24
  });
25
25
 
26
26
  export const getSubscriptionByStripeId = query({
27
- args: { stripeSubscriptionId: v.string() },
27
+ args: {
28
+ stripeSubscriptionId: v.string(),
29
+ requireUnique: v.optional(v.boolean()),
30
+ },
28
31
  returns: v.union(subscriptionDocValidator, v.null()),
29
32
  handler: async (ctx, args) => {
30
- return await ctx.db
33
+ const rows = ctx.db
31
34
  .query("subscriptions")
32
35
  .withIndex("by_stripe_subscription_id", (q) =>
33
36
  q.eq("stripeSubscriptionId", args.stripeSubscriptionId),
34
- )
35
- .first();
37
+ );
38
+ if (!args.requireUnique) return await rows.first();
39
+ const matches = await rows.take(2);
40
+ return matches.length === 1 ? (matches[0] ?? null) : null;
36
41
  },
37
42
  });
38
43
 
@@ -0,0 +1,195 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { expect, it } from "vitest";
4
+ import { api } from "../_generated/api.js";
5
+ import { schema, modules } from "../../test.js";
6
+
7
+ async function fixture() {
8
+ const t = convexTest(schema, modules);
9
+ const paymentId = await t.run((ctx) =>
10
+ ctx.db.insert("payments", {
11
+ stripePaymentIntentId: "pi_original_history",
12
+ userId: "original_buyer",
13
+ accountId: "acct_original_buyer",
14
+ destinationAccountId: "acct_original_merchant",
15
+ chargeType: "destination",
16
+ amount: 123,
17
+ currency: "usd",
18
+ status: "succeeded",
19
+ }),
20
+ );
21
+ return { t, paymentId };
22
+ }
23
+
24
+ it("retains the existing unique-row and legacy duplicate first-row positives", async () => {
25
+ const f = await fixture();
26
+ const args = { stripePaymentIntentId: "pi_original_history" };
27
+ const original = await f.t.query(
28
+ api.connect.queries.getPaymentByStripeId,
29
+ args,
30
+ );
31
+ expect(original).toMatchObject({
32
+ _id: f.paymentId,
33
+ userId: "original_buyer",
34
+ });
35
+ await f.t.run(async (ctx) => {
36
+ if (!original) throw new Error("Missing actual original payment");
37
+ const { _id: _id, _creationTime: _creationTime, ...fields } = original;
38
+ await ctx.db.insert("payments", {
39
+ ...fields,
40
+ userId: "foreign_buyer",
41
+ accountId: "acct_foreign_buyer",
42
+ destinationAccountId: "acct_foreign_merchant",
43
+ currency: "eur",
44
+ status: "failed",
45
+ });
46
+ });
47
+ expect(
48
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
49
+ ).toEqual(original);
50
+ });
51
+
52
+ it("returns null for globally ambiguous exact PI when uniqueness is explicitly required", async () => {
53
+ const f = await fixture();
54
+ await f.t.run((ctx) =>
55
+ ctx.db.insert("payments", {
56
+ stripePaymentIntentId: "pi_original_history",
57
+ userId: "foreign_buyer",
58
+ orgId: "foreign_org",
59
+ accountId: "acct_foreign_buyer",
60
+ destinationAccountId: "acct_foreign_merchant",
61
+ chargeType: "destination",
62
+ amount: 123,
63
+ currency: "eur",
64
+ status: "failed",
65
+ }),
66
+ );
67
+ const args = {
68
+ stripePaymentIntentId: "pi_original_history",
69
+ requireUnique: true,
70
+ };
71
+ await expect(
72
+ f.t.query(api.connect.queries.getPaymentByStripeId, args),
73
+ ).resolves.toBeNull();
74
+ });
75
+
76
+ it("returns null for a missing exact PI when uniqueness is required", async () => {
77
+ const f = await fixture();
78
+ const args = { stripePaymentIntentId: "pi_missing", requireUnique: true };
79
+ expect(
80
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
81
+ ).toBeNull();
82
+ });
83
+
84
+ it("returns the unchanged sole original document without filtering failed state or currency", async () => {
85
+ const f = await fixture();
86
+ await f.t.run((ctx) =>
87
+ ctx.db.patch("payments", f.paymentId, {
88
+ currency: "jpy",
89
+ status: "failed",
90
+ amount: 123,
91
+ }),
92
+ );
93
+ const args = {
94
+ stripePaymentIntentId: "pi_original_history",
95
+ requireUnique: true,
96
+ };
97
+ const stored = await f.t.run((ctx) => ctx.db.get("payments", f.paymentId));
98
+ expect(
99
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
100
+ ).toEqual(stored);
101
+ });
102
+
103
+ it("preserves explicit false first-row behavior on duplicate original PIs", async () => {
104
+ const f = await fixture();
105
+ await f.t.run((ctx) =>
106
+ ctx.db.insert("payments", {
107
+ stripePaymentIntentId: "pi_original_history",
108
+ userId: "foreign_buyer",
109
+ amount: 1,
110
+ currency: "eur",
111
+ status: "failed",
112
+ }),
113
+ );
114
+ const args = {
115
+ stripePaymentIntentId: "pi_original_history",
116
+ requireUnique: false,
117
+ };
118
+ expect(
119
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
120
+ ).toMatchObject({ _id: f.paymentId });
121
+ });
122
+
123
+ it.each([
124
+ { userId: "foreign_buyer" },
125
+ { orgId: "foreign_org" },
126
+ { accountId: "acct_replacement" },
127
+ { destinationAccountId: "acct_foreign_merchant" },
128
+ { currency: "eur" },
129
+ { status: "failed" },
130
+ ] as const)(
131
+ "holds global duplicate PI before qualification of %j",
132
+ async (changed) => {
133
+ const f = await fixture();
134
+ await f.t.run(async (ctx) => {
135
+ const original = await ctx.db.get("payments", f.paymentId);
136
+ if (!original) throw new Error("Missing original");
137
+ const { _id: _id, _creationTime: _creationTime, ...fields } = original;
138
+ await ctx.db.insert("payments", { ...fields, ...changed });
139
+ });
140
+ const args = {
141
+ stripePaymentIntentId: "pi_original_history",
142
+ requireUnique: true,
143
+ };
144
+ expect(
145
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
146
+ ).toBeNull();
147
+ },
148
+ );
149
+
150
+ it("does not depend on whether a matching or foreign duplicate was inserted first", async () => {
151
+ const f = await fixture();
152
+ await f.t.run(async (ctx) => {
153
+ await ctx.db.insert("payments", {
154
+ stripePaymentIntentId: "pi_foreign_first",
155
+ userId: "foreign_buyer",
156
+ amount: 1,
157
+ currency: "eur",
158
+ status: "failed",
159
+ });
160
+ await ctx.db.insert("payments", {
161
+ stripePaymentIntentId: "pi_foreign_first",
162
+ userId: "original_buyer",
163
+ amount: 123,
164
+ currency: "usd",
165
+ status: "succeeded",
166
+ });
167
+ });
168
+ const args = {
169
+ stripePaymentIntentId: "pi_foreign_first",
170
+ requireUnique: true,
171
+ };
172
+ expect(
173
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
174
+ ).toBeNull();
175
+ });
176
+
177
+ it("does not confuse unrelated PIs with ambiguity of the exact requested key", async () => {
178
+ const f = await fixture();
179
+ await f.t.run((ctx) =>
180
+ ctx.db.insert("payments", {
181
+ stripePaymentIntentId: "pi_unrelated_original",
182
+ userId: "original_buyer",
183
+ amount: 123,
184
+ currency: "usd",
185
+ status: "succeeded",
186
+ }),
187
+ );
188
+ const args = {
189
+ stripePaymentIntentId: "pi_original_history",
190
+ requireUnique: true,
191
+ };
192
+ expect(
193
+ await f.t.query(api.connect.queries.getPaymentByStripeId, args),
194
+ ).toMatchObject({ _id: f.paymentId });
195
+ });
@@ -30,15 +30,20 @@ import {
30
30
  // PAYMENT QUERIES
31
31
 
32
32
  export const getPaymentByStripeId = query({
33
- args: { stripePaymentIntentId: v.string() },
33
+ args: {
34
+ stripePaymentIntentId: v.string(),
35
+ requireUnique: v.optional(v.boolean()),
36
+ },
34
37
  returns: v.union(paymentDocValidator, v.null()),
35
38
  handler: async (ctx, args) => {
36
- return await ctx.db
39
+ const rows = ctx.db
37
40
  .query("payments")
38
41
  .withIndex("by_stripe_payment_intent_id", (q) =>
39
42
  q.eq("stripePaymentIntentId", args.stripePaymentIntentId),
40
- )
41
- .first();
43
+ );
44
+ if (!args.requireUnique) return await rows.first();
45
+ const matches = await rows.take(2);
46
+ return matches.length === 1 ? matches[0]! : null;
42
47
  },
43
48
  });
44
49
 
@@ -0,0 +1,209 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { expect, it } from "vitest";
4
+ import { api } from "../_generated/api.js";
5
+ import { schema, modules } from "../../test.js";
6
+
7
+ async function fixture(duplicate = false) {
8
+ const t = convexTest(schema, modules);
9
+ const ids = await t.run(async (ctx) => {
10
+ const account = {
11
+ stripeAccountId: "acct_original_history",
12
+ userId: "original_buyer",
13
+ onboardingStatus: "complete" as const,
14
+ };
15
+ const subscription = {
16
+ stripeSubscriptionId: "sub_original_history",
17
+ userId: "original_buyer",
18
+ accountId: account.stripeAccountId,
19
+ status: "canceled" as const,
20
+ isTrialing: false,
21
+ cancelAtPeriodEnd: false,
22
+ };
23
+ const accountId = await ctx.db.insert("accounts", account);
24
+ const subscriptionId = await ctx.db.insert("subscriptions", subscription);
25
+ if (duplicate) {
26
+ await ctx.db.insert("accounts", {
27
+ ...account,
28
+ userId: "foreign_buyer",
29
+ });
30
+ await ctx.db.insert("subscriptions", {
31
+ ...subscription,
32
+ userId: "foreign_buyer",
33
+ status: "active",
34
+ });
35
+ }
36
+ return { accountId, subscriptionId };
37
+ });
38
+ return { t, ...ids };
39
+ }
40
+
41
+ it("retains existing unique original account and historical subscription reads", async () => {
42
+ const f = await fixture();
43
+ expect(
44
+ await f.t.query(api.core.queries.getAccountByStripeId, {
45
+ stripeAccountId: "acct_original_history",
46
+ }),
47
+ ).toMatchObject({ _id: f.accountId, userId: "original_buyer" });
48
+ expect(
49
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
50
+ stripeSubscriptionId: "sub_original_history",
51
+ }),
52
+ ).toMatchObject({ _id: f.subscriptionId, status: "canceled" });
53
+ });
54
+
55
+ it("preserves legacy first-row defaults when duplicate original provider IDs exist", async () => {
56
+ const f = await fixture(true);
57
+ expect(
58
+ await f.t.query(api.core.queries.getAccountByStripeId, {
59
+ stripeAccountId: "acct_original_history",
60
+ }),
61
+ ).toMatchObject({ _id: f.accountId });
62
+ expect(
63
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
64
+ stripeSubscriptionId: "sub_original_history",
65
+ }),
66
+ ).toMatchObject({ _id: f.subscriptionId });
67
+ });
68
+
69
+ it("returns null instead of selecting the first duplicate original Stripe account ID when uniqueness is required", async () => {
70
+ const f = await fixture(true);
71
+ const args = {
72
+ stripeAccountId: "acct_original_history",
73
+ requireUnique: true,
74
+ };
75
+ await expect(
76
+ f.t.query(api.core.queries.getAccountByStripeId, args),
77
+ ).resolves.toBeNull();
78
+ });
79
+
80
+ it("returns null instead of selecting the first duplicate original Stripe subscription ID when uniqueness is required", async () => {
81
+ const f = await fixture(true);
82
+ const args = {
83
+ stripeSubscriptionId: "sub_original_history",
84
+ requireUnique: true,
85
+ };
86
+ await expect(
87
+ f.t.query(api.billing.queries.getSubscriptionByStripeId, args),
88
+ ).resolves.toBeNull();
89
+ });
90
+
91
+ it("returns null for absent original IDs when uniqueness is required", async () => {
92
+ const f = await fixture();
93
+ expect(
94
+ await f.t.query(api.core.queries.getAccountByStripeId, {
95
+ stripeAccountId: "acct_missing",
96
+ requireUnique: true,
97
+ }),
98
+ ).toBeNull();
99
+ expect(
100
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
101
+ stripeSubscriptionId: "sub_missing",
102
+ requireUnique: true,
103
+ }),
104
+ ).toBeNull();
105
+ });
106
+
107
+ it("returns the unchanged sole original documents when uniqueness is required", async () => {
108
+ const f = await fixture();
109
+ const account = await f.t.query(api.core.queries.getAccount, {
110
+ accountId: f.accountId,
111
+ });
112
+ const subscription = await f.t.query(api.billing.queries.getSubscription, {
113
+ subscriptionId: f.subscriptionId,
114
+ });
115
+ expect(
116
+ await f.t.query(api.core.queries.getAccountByStripeId, {
117
+ stripeAccountId: "acct_original_history",
118
+ requireUnique: true,
119
+ }),
120
+ ).toEqual(account);
121
+ expect(
122
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
123
+ stripeSubscriptionId: "sub_original_history",
124
+ requireUnique: true,
125
+ }),
126
+ ).toEqual(subscription);
127
+ });
128
+
129
+ it("preserves explicit false legacy first-row behavior for duplicate IDs", async () => {
130
+ const f = await fixture(true);
131
+ expect(
132
+ await f.t.query(api.core.queries.getAccountByStripeId, {
133
+ stripeAccountId: "acct_original_history",
134
+ requireUnique: false,
135
+ }),
136
+ ).toMatchObject({ _id: f.accountId });
137
+ expect(
138
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
139
+ stripeSubscriptionId: "sub_original_history",
140
+ requireUnique: false,
141
+ }),
142
+ ).toMatchObject({ _id: f.subscriptionId });
143
+ });
144
+
145
+ it("holds global duplicates even when only one belongs to the original buyer or organization", async () => {
146
+ const f = await fixture();
147
+ await f.t.run(async (ctx) => {
148
+ await ctx.db.insert("accounts", {
149
+ stripeAccountId: "acct_original_history",
150
+ orgId: "foreign_org",
151
+ userId: "foreign_org_buyer",
152
+ onboardingStatus: "pending",
153
+ });
154
+ await ctx.db.insert("subscriptions", {
155
+ stripeSubscriptionId: "sub_original_history",
156
+ orgId: "foreign_org",
157
+ userId: "foreign_org_buyer",
158
+ accountId: "acct_foreign",
159
+ status: "incomplete",
160
+ isTrialing: false,
161
+ cancelAtPeriodEnd: false,
162
+ });
163
+ });
164
+ expect(
165
+ await f.t.query(api.core.queries.getAccountByStripeId, {
166
+ stripeAccountId: "acct_original_history",
167
+ requireUnique: true,
168
+ }),
169
+ ).toBeNull();
170
+ expect(
171
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
172
+ stripeSubscriptionId: "sub_original_history",
173
+ requireUnique: true,
174
+ }),
175
+ ).toBeNull();
176
+ });
177
+
178
+ it("retains a unique closed original account instead of substituting its current replacement", async () => {
179
+ const f = await fixture();
180
+ await f.t.run(async (ctx) => {
181
+ await ctx.db.insert("accountClosures", {
182
+ stripeAccountId: "acct_original_history",
183
+ userId: "original_buyer",
184
+ appliedConfigurations: [],
185
+ state: "closed",
186
+ closedAt: 1,
187
+ });
188
+ await ctx.db.insert("accounts", {
189
+ stripeAccountId: "acct_replacement",
190
+ userId: "original_buyer",
191
+ onboardingStatus: "complete",
192
+ });
193
+ });
194
+ expect(
195
+ await f.t.query(api.core.queries.getAccountByStripeId, {
196
+ stripeAccountId: "acct_original_history",
197
+ requireUnique: true,
198
+ }),
199
+ ).toMatchObject({
200
+ _id: f.accountId,
201
+ stripeAccountId: "acct_original_history",
202
+ });
203
+ expect(
204
+ await f.t.query(api.billing.queries.getSubscriptionByStripeId, {
205
+ stripeSubscriptionId: "sub_original_history",
206
+ requireUnique: true,
207
+ }),
208
+ ).toMatchObject({ _id: f.subscriptionId, status: "canceled" });
209
+ });
@@ -20,15 +20,17 @@ export const getAccount = query({
20
20
  });
21
21
 
22
22
  export const getAccountByStripeId = query({
23
- args: { stripeAccountId: v.string() },
23
+ args: { stripeAccountId: v.string(), requireUnique: v.optional(v.boolean()) },
24
24
  returns: v.union(accountDocValidator, v.null()),
25
25
  handler: async (ctx, args) => {
26
- return await ctx.db
26
+ const rows = ctx.db
27
27
  .query("accounts")
28
28
  .withIndex("by_stripe_account_id", (q) =>
29
29
  q.eq("stripeAccountId", args.stripeAccountId),
30
- )
31
- .first();
30
+ );
31
+ if (!args.requireUnique) return await rows.first();
32
+ const matches = await rows.take(2);
33
+ return matches.length === 1 ? (matches[0] ?? null) : null;
32
34
  },
33
35
  });
34
36