@fantastic.dev/better-stripe 0.47.1 → 0.48.1

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 (110) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/README.md +1 -1
  3. package/dist/client/billing/historyPages.d.ts +22 -0
  4. package/dist/client/billing/historyPages.d.ts.map +1 -0
  5. package/dist/client/billing/historyPages.js +8 -0
  6. package/dist/client/billing/historyPages.js.map +1 -0
  7. package/dist/client/billing/subscriptions.d.ts +2 -3
  8. package/dist/client/billing/subscriptions.d.ts.map +1 -1
  9. package/dist/client/billing/subscriptions.js.map +1 -1
  10. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts +10 -0
  11. package/dist/client/connect/payoutAdoptionTestHelpers.d.ts.map +1 -1
  12. package/dist/client/connect/payoutExecutionTestHelpers.d.ts +5 -0
  13. package/dist/client/connect/payoutExecutionTestHelpers.d.ts.map +1 -1
  14. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts +10 -0
  15. package/dist/client/connect/payoutLargeAdoptionTestHelpers.d.ts.map +1 -1
  16. package/dist/client/connect/payoutSyncTestHelpers.d.ts +5 -0
  17. package/dist/client/connect/payoutSyncTestHelpers.d.ts.map +1 -1
  18. package/dist/client/core/accounts.d.ts +2 -3
  19. package/dist/client/core/accounts.d.ts.map +1 -1
  20. package/dist/client/core/accounts.js.map +1 -1
  21. package/dist/client/index.d.ts +3 -6
  22. package/dist/client/index.d.ts.map +1 -1
  23. package/dist/client/index.js.map +1 -1
  24. package/dist/client/originalIdReadOptions.d.ts +10 -0
  25. package/dist/client/originalIdReadOptions.d.ts.map +1 -0
  26. package/dist/client/originalIdReadOptions.js +2 -0
  27. package/dist/client/originalIdReadOptions.js.map +1 -0
  28. package/dist/client/publicTypes.d.ts +2 -0
  29. package/dist/client/publicTypes.d.ts.map +1 -1
  30. package/dist/client/readContracts.d.ts +4 -0
  31. package/dist/client/readContracts.d.ts.map +1 -1
  32. package/dist/client/readContracts.js +8 -0
  33. package/dist/client/readContracts.js.map +1 -1
  34. package/dist/client/webhooks/handler.d.ts.map +1 -1
  35. package/dist/client/webhooks/handler.js +6 -3
  36. package/dist/client/webhooks/handler.js.map +1 -1
  37. package/dist/client/webhooks/processors.d.ts.map +1 -1
  38. package/dist/client/webhooks/processors.js +3 -65
  39. package/dist/client/webhooks/processors.js.map +1 -1
  40. package/dist/client/webhooks/refundDelivery.d.ts +5 -0
  41. package/dist/client/webhooks/refundDelivery.d.ts.map +1 -0
  42. package/dist/client/webhooks/refundDelivery.js +28 -0
  43. package/dist/client/webhooks/refundDelivery.js.map +1 -0
  44. package/dist/client/webhooks/refundRecovery.d.ts +5 -0
  45. package/dist/client/webhooks/refundRecovery.d.ts.map +1 -0
  46. package/dist/client/webhooks/refundRecovery.js +36 -0
  47. package/dist/client/webhooks/refundRecovery.js.map +1 -0
  48. package/dist/component/_generated/api.d.ts +4 -0
  49. package/dist/component/_generated/api.d.ts.map +1 -1
  50. package/dist/component/_generated/api.js.map +1 -1
  51. package/dist/component/_generated/component.d.ts +102 -0
  52. package/dist/component/_generated/component.d.ts.map +1 -1
  53. package/dist/component/billing/queries.d.ts +1 -0
  54. package/dist/component/billing/queries.d.ts.map +1 -1
  55. package/dist/component/billing/queries.js +10 -4
  56. package/dist/component/billing/queries.js.map +1 -1
  57. package/dist/component/billing/schema.d.ts +5 -0
  58. package/dist/component/billing/schema.d.ts.map +1 -1
  59. package/dist/component/billing/schema.js +13 -0
  60. package/dist/component/billing/schema.js.map +1 -1
  61. package/dist/component/billingHistory/queries.d.ts +97 -0
  62. package/dist/component/billingHistory/queries.d.ts.map +1 -0
  63. package/dist/component/billingHistory/queries.js +65 -0
  64. package/dist/component/billingHistory/queries.js.map +1 -0
  65. package/dist/component/billingHistory/scope.d.ts +23 -0
  66. package/dist/component/billingHistory/scope.d.ts.map +1 -0
  67. package/dist/component/billingHistory/scope.js +54 -0
  68. package/dist/component/billingHistory/scope.js.map +1 -0
  69. package/dist/component/core/queries.d.ts +1 -0
  70. package/dist/component/core/queries.d.ts.map +1 -1
  71. package/dist/component/core/queries.js +7 -4
  72. package/dist/component/core/queries.js.map +1 -1
  73. package/dist/component/earnings/triggers.d.ts +10 -0
  74. package/dist/component/earnings/triggers.d.ts.map +1 -1
  75. package/dist/component/processingCostReconciliation/rollback.d.ts +1 -1
  76. package/dist/component/refundHistory/queries.d.ts +1 -1
  77. package/dist/component/refundSync/mutations.d.ts +1 -1
  78. package/dist/component/refundSync/mutations.d.ts.map +1 -1
  79. package/dist/component/schema.d.ts +5 -0
  80. package/docs/billing-history.md +13 -0
  81. package/docs/personal-account-mapping.md +30 -0
  82. package/docs/refund-context.md +42 -9
  83. package/package.json +2 -1
  84. package/src/client/billing/historyPages.test.ts +58 -0
  85. package/src/client/billing/historyPages.ts +48 -0
  86. package/src/client/billing/subscriptions.ts +2 -1
  87. package/src/client/core/accounts.ts +2 -1
  88. package/src/client/index.ts +6 -2
  89. package/src/client/originalIdReadOptions.test.ts +63 -0
  90. package/src/client/originalIdReadOptions.ts +10 -0
  91. package/src/client/publicTypes.ts +12 -0
  92. package/src/client/readContracts.ts +16 -0
  93. package/src/client/webhooks/handler.ts +7 -3
  94. package/src/client/webhooks/processors.test.ts +9 -7
  95. package/src/client/webhooks/processors.ts +3 -88
  96. package/src/client/webhooks/refund-delivery.test.ts +512 -0
  97. package/src/client/webhooks/refundDelivery.ts +42 -0
  98. package/src/client/webhooks/refundRecovery.ts +52 -0
  99. package/src/client/webhooks.test.ts +35 -42
  100. package/src/component/_generated/api.ts +4 -0
  101. package/src/component/_generated/component.ts +130 -2
  102. package/src/component/billing/queries.ts +9 -4
  103. package/src/component/billing/schema.ts +13 -0
  104. package/src/component/billingHistory/guards.test.ts +235 -0
  105. package/src/component/billingHistory/options.test.ts +35 -0
  106. package/src/component/billingHistory/pages.test.ts +74 -0
  107. package/src/component/billingHistory/queries.ts +88 -0
  108. package/src/component/billingHistory/scope.ts +77 -0
  109. package/src/component/core/original-id-unique.test.ts +209 -0
  110. package/src/component/core/queries.ts +6 -4
@@ -0,0 +1,74 @@
1
+ import type { PaginationResult } from "convex/server";
2
+ import type { Doc } from "../_generated/dataModel.js";
3
+ // @vitest-environment edge-runtime
4
+ import { convexTest } from "convex-test";
5
+ import { expect, it } from "vitest";
6
+ import { api } from "../_generated/api.js";
7
+ import { schema, modules } from "../../test.js";
8
+
9
+ it("pages all 67 original buyer Checkout rows instead of the legacy first50", async () => {
10
+ const t = convexTest(schema, modules);
11
+ for (let i = 0; i < 67; i++)
12
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
13
+ stripeSessionId: `cs_history_${i}`,
14
+ userId: "buyer_original",
15
+ ...(i % 2 ? { accountId: "acct_original" } : {}),
16
+ mode: i % 2 ? "subscription" : "payment",
17
+ status: "complete",
18
+ });
19
+ expect(
20
+ await t.query(api.billing.queries.listCheckoutSessionsByUser, {
21
+ userId: "buyer_original",
22
+ }),
23
+ ).toHaveLength(50);
24
+ const ids: string[] = [];
25
+ let cursor: string | null = null;
26
+ for (let i = 0; i < 8; i++) {
27
+ const result: PaginationResult<Doc<"checkoutSessions">> = await t.query(
28
+ api.billingHistory.queries.paginateCheckoutSessions,
29
+ {
30
+ userId: "buyer_original",
31
+ paginationOpts: { numItems: 17, cursor },
32
+ },
33
+ );
34
+ ids.push(...result.page.map((row) => row.stripeSessionId));
35
+ if (result.isDone) break;
36
+ cursor = result.continueCursor;
37
+ }
38
+ expect(new Set(ids).size).toBe(67);
39
+ expect(ids).toHaveLength(67);
40
+ });
41
+
42
+ it("pages 67 recurring and trial rows including accountless legacy subscriptions", async () => {
43
+ const t = convexTest(schema, modules);
44
+ for (let i = 0; i < 67; i++)
45
+ await t.mutation(api.billing.mutations.upsertSubscription, {
46
+ stripeSubscriptionId: `sub_history_${i}`,
47
+ userId: "buyer_original",
48
+ ...(i % 2 ? { accountId: "acct_original" } : {}),
49
+ status: i % 2 ? "active" : "trialing",
50
+ isTrialing: i % 2 === 0,
51
+ cancelAtPeriodEnd: false,
52
+ });
53
+ expect(
54
+ await t.query(api.billing.queries.listSubscriptionsByUser, {
55
+ userId: "buyer_original",
56
+ }),
57
+ ).toHaveLength(67);
58
+ const ids: string[] = [];
59
+ let cursor: string | null = null;
60
+ for (let i = 0; i < 8; i++) {
61
+ const result: PaginationResult<Doc<"subscriptions">> = await t.query(
62
+ api.billingHistory.queries.paginateSubscriptions,
63
+ {
64
+ userId: "buyer_original",
65
+ paginationOpts: { numItems: 17, cursor },
66
+ },
67
+ );
68
+ ids.push(...result.page.map((row) => row.stripeSubscriptionId));
69
+ if (result.isDone) break;
70
+ cursor = result.continueCursor;
71
+ }
72
+ expect(new Set(ids).size).toBe(67);
73
+ expect(ids).toHaveLength(67);
74
+ });
@@ -0,0 +1,88 @@
1
+ import { paginator } from "convex-helpers/server/pagination";
2
+ import {
3
+ paginationOptsValidator,
4
+ paginationResultValidator,
5
+ } from "convex/server";
6
+ import { v } from "convex/values";
7
+ import { query } from "../_generated/server.js";
8
+ import schema from "../schema.js";
9
+ import {
10
+ checkoutSessionDocValidator,
11
+ checkoutSessionStatusValidator,
12
+ subscriptionDocValidator,
13
+ subscriptionStatusValidator,
14
+ } from "../billing/validators.js";
15
+ import { historyOptions, historyResult } from "./scope.js";
16
+
17
+ export const paginateSubscriptions = query({
18
+ args: {
19
+ userId: v.string(),
20
+ accountId: v.optional(v.string()),
21
+ status: v.optional(subscriptionStatusValidator),
22
+ paginationOpts: paginationOptsValidator,
23
+ },
24
+ returns: paginationResultValidator(subscriptionDocValidator),
25
+ handler: async (ctx, args) => {
26
+ const { userId, accountId, status } = args;
27
+ const scope = { kind: "subscriptions" as const, userId, accountId, status };
28
+ const options = historyOptions(scope, args.paginationOpts);
29
+ const rows = paginator(ctx.db, schema).query("subscriptions");
30
+ const scoped =
31
+ accountId !== undefined
32
+ ? status !== undefined
33
+ ? rows.withIndex("by_userId_and_accountId_and_status", (q) =>
34
+ q
35
+ .eq("userId", userId)
36
+ .eq("accountId", accountId)
37
+ .eq("status", status),
38
+ )
39
+ : rows.withIndex("by_userId_and_accountId", (q) =>
40
+ q.eq("userId", userId).eq("accountId", accountId),
41
+ )
42
+ : status !== undefined
43
+ ? rows.withIndex("by_userId_and_status", (q) =>
44
+ q.eq("userId", userId).eq("status", status),
45
+ )
46
+ : rows.withIndex("by_user_id", (q) => q.eq("userId", userId));
47
+ return historyResult(scope, await scoped.order("desc").paginate(options));
48
+ },
49
+ });
50
+
51
+ export const paginateCheckoutSessions = query({
52
+ args: {
53
+ userId: v.string(),
54
+ accountId: v.optional(v.string()),
55
+ status: v.optional(checkoutSessionStatusValidator),
56
+ paginationOpts: paginationOptsValidator,
57
+ },
58
+ returns: paginationResultValidator(checkoutSessionDocValidator),
59
+ handler: async (ctx, args) => {
60
+ const { userId, accountId, status } = args;
61
+ const scope = {
62
+ kind: "checkoutSessions" as const,
63
+ userId,
64
+ accountId,
65
+ status,
66
+ };
67
+ const options = historyOptions(scope, args.paginationOpts);
68
+ const rows = paginator(ctx.db, schema).query("checkoutSessions");
69
+ const scoped =
70
+ accountId !== undefined
71
+ ? status !== undefined
72
+ ? rows.withIndex("by_userId_and_accountId_and_status", (q) =>
73
+ q
74
+ .eq("userId", userId)
75
+ .eq("accountId", accountId)
76
+ .eq("status", status),
77
+ )
78
+ : rows.withIndex("by_userId_and_accountId", (q) =>
79
+ q.eq("userId", userId).eq("accountId", accountId),
80
+ )
81
+ : status !== undefined
82
+ ? rows.withIndex("by_user_status", (q) =>
83
+ q.eq("userId", userId).eq("status", status),
84
+ )
85
+ : rows.withIndex("by_user_id", (q) => q.eq("userId", userId));
86
+ return historyResult(scope, await scoped.order("desc").paginate(options));
87
+ },
88
+ });
@@ -0,0 +1,77 @@
1
+ import type { PaginationOptions, PaginationResult } from "convex/server";
2
+
3
+ export type HistoryScope = {
4
+ kind: "subscriptions" | "checkoutSessions";
5
+ userId: string;
6
+ accountId?: string;
7
+ status?: string;
8
+ };
9
+
10
+ function encoded(scope: HistoryScope, cursor: string) {
11
+ return btoa(
12
+ encodeURIComponent(JSON.stringify({ version: 1, scope, cursor })),
13
+ );
14
+ }
15
+
16
+ function decoded(scope: HistoryScope, cursor: string) {
17
+ try {
18
+ const value = JSON.parse(decodeURIComponent(atob(cursor)));
19
+ if (
20
+ value.version !== 1 ||
21
+ typeof value.cursor !== "string" ||
22
+ encoded(scope, value.cursor) !== cursor
23
+ )
24
+ throw new Error();
25
+ return value.cursor as string;
26
+ } catch {
27
+ throw new Error("Invalid billing history cursor or scope");
28
+ }
29
+ }
30
+
31
+ /** Context binding only; the trusted host must authorize every call. */
32
+ export function historyOptions(
33
+ scope: HistoryScope,
34
+ options: PaginationOptions,
35
+ ) {
36
+ if (
37
+ !isCanonical(scope.userId) ||
38
+ (scope.accountId !== undefined && !isCanonical(scope.accountId)) ||
39
+ !Number.isSafeInteger(options.numItems) ||
40
+ options.numItems < 1 ||
41
+ options.numItems > 100
42
+ )
43
+ throw new Error("Invalid billing history selector or page size");
44
+ return {
45
+ ...options,
46
+ cursor: options.cursor === null ? null : decoded(scope, options.cursor),
47
+ ...(options.endCursor !== undefined && options.endCursor !== null
48
+ ? { endCursor: decoded(scope, options.endCursor) }
49
+ : {}),
50
+ maximumRowsRead: ceiling(options.maximumRowsRead, 200),
51
+ maximumBytesRead: ceiling(options.maximumBytesRead, 1_000_000),
52
+ };
53
+ }
54
+
55
+ export function historyResult<T>(
56
+ scope: HistoryScope,
57
+ result: PaginationResult<T>,
58
+ ) {
59
+ return {
60
+ ...result,
61
+ continueCursor: encoded(scope, result.continueCursor),
62
+ ...(result.splitCursor
63
+ ? { splitCursor: encoded(scope, result.splitCursor) }
64
+ : {}),
65
+ };
66
+ }
67
+
68
+ function ceiling(requested: number | undefined, policy: number) {
69
+ if (requested === undefined) return policy;
70
+ if (!Number.isSafeInteger(requested) || requested < 1)
71
+ throw new Error("Invalid billing history read ceiling");
72
+ return Math.min(requested, policy);
73
+ }
74
+
75
+ function isCanonical(value: string) {
76
+ return value.length > 0 && value === value.trim() && !/\p{Cc}/u.test(value);
77
+ }
@@ -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