@fantastic.dev/better-stripe 0.30.2 → 0.31.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 (61) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +10 -1
  3. package/dist/client/billing/invoicePages.d.ts +28 -0
  4. package/dist/client/billing/invoicePages.d.ts.map +1 -0
  5. package/dist/client/billing/invoicePages.js +86 -0
  6. package/dist/client/billing/invoicePages.js.map +1 -0
  7. package/dist/client/index.d.ts +4 -0
  8. package/dist/client/index.d.ts.map +1 -1
  9. package/dist/client/index.js +5 -0
  10. package/dist/client/index.js.map +1 -1
  11. package/docs/affiliate-clawbacks.md +5 -5
  12. package/docs/read-contracts.md +32 -0
  13. package/docs/settlement.md +1 -1
  14. package/package.json +4 -3
  15. package/src/client/billing/invoicePages.test.ts +174 -0
  16. package/src/client/billing/invoicePages.ts +110 -0
  17. package/src/client/index.ts +13 -0
  18. package/src/component/{affiliate-direct-payout.test.ts → affiliatePayouts/affiliate-direct-payout.test.ts} +6 -7
  19. package/src/component/{affiliate-component-pagination.test.ts → affiliateRecovery/affiliate-component-pagination.test.ts} +7 -10
  20. package/src/component/{affiliate-recovery-lifecycle.test.ts → affiliateRecovery/affiliate-recovery-lifecycle.test.ts} +6 -7
  21. package/src/component/billing/checkout.test.ts +89 -0
  22. package/src/component/billing/invoices.test.ts +294 -0
  23. package/src/component/{store-subscriptions.test.ts → billing/store-subscriptions.test.ts} +2 -3
  24. package/src/component/{subscription-scoping.test.ts → billing/subscription-scoping.test.ts} +2 -4
  25. package/src/component/billing/subscriptions.test.ts +477 -0
  26. package/src/component/{connect.test.ts → connect/connect.test.ts} +2 -4
  27. package/src/component/{fee-routing.test.ts → connect/fee-routing.test.ts} +2 -4
  28. package/src/component/connect/payments.test.ts +88 -0
  29. package/src/component/connect/payouts.test.ts +173 -0
  30. package/src/component/{reversal-races.test.ts → connect/reversal-races.test.ts} +4 -6
  31. package/src/component/{seller-case-ownership.test.ts → connect/seller-case-ownership.test.ts} +2 -3
  32. package/src/component/{transfers.test.ts → connect/transfers.test.ts} +3 -5
  33. package/src/component/core/accounts.test.ts +266 -0
  34. package/src/component/{config-queries.test.ts → core/config-queries.test.ts} +2 -4
  35. package/src/component/{payout-reset-safety.test.ts → core/payout-reset-safety.test.ts} +1 -2
  36. package/src/component/core/reset.test.ts +124 -0
  37. package/src/component/{cost-recovery.test.ts → costRecovery/cost-recovery.test.ts} +1 -2
  38. package/src/component/{currency-migration.test.ts → earnings/currency-migration.test.ts} +2 -3
  39. package/src/component/{currency-totals.test.ts → earnings/currency-totals.test.ts} +2 -3
  40. package/src/component/{earnings-totals.test.ts → earnings/earnings-totals.test.ts} +3 -5
  41. package/src/component/{summary-arithmetic.test.ts → earnings/summary-arithmetic.test.ts} +2 -3
  42. package/src/component/{payout-policy-adoption.test.ts → payoutPolicy/payout-policy-adoption.test.ts} +2 -3
  43. package/src/component/{payout-policy.test.ts → payoutPolicy/payout-policy.test.ts} +1 -2
  44. package/src/component/{payout-adoption.test.ts → payoutRelease/payout-adoption.test.ts} +2 -6
  45. package/src/component/{payout-fees.test.ts → payoutRelease/payout-fees.test.ts} +2 -3
  46. package/src/component/{payout-recovery-integration.test.ts → payoutRelease/payout-recovery-integration.test.ts} +3 -4
  47. package/src/component/{payout-release-snapshot.test.ts → payoutRelease/payout-release-snapshot.test.ts} +1 -2
  48. package/src/component/{payout-release.test.ts → payoutRelease/payout-release.test.ts} +2 -3
  49. package/src/component/{payout-revisions.test.ts → payoutSnapshots/payout-revisions.test.ts} +1 -2
  50. package/src/component/{payout-snapshots.test.ts → payoutSnapshots/payout-snapshots.test.ts} +4 -5
  51. package/src/component/{payout-sync.test.ts → payoutSync/payout-sync.test.ts} +1 -2
  52. package/src/component/{payout-component-pagination.test.ts → payoutWorker/payout-component-pagination.test.ts} +8 -9
  53. package/src/component/{payout-worker.test.ts → payoutWorker/payout-worker.test.ts} +1 -2
  54. package/src/component/products/products.test.ts +239 -0
  55. package/src/component/{read-pagination.test.ts → products/read-pagination.test.ts} +2 -3
  56. package/src/component/{refund-history.test.ts → refundHistory/refund-history.test.ts} +2 -3
  57. package/src/component/{affiliate-clawbacks.test.ts → settlement/affiliate-clawbacks.test.ts} +3 -4
  58. package/src/component/{settlement-claims.test.ts → settlement/settlement-claims.test.ts} +2 -3
  59. package/src/component/webhooks/events.test.ts +121 -0
  60. package/src/component/{triggers.test.ts → webhooks/triggers.test.ts} +2 -4
  61. package/src/component/public.test.ts +0 -1858
@@ -0,0 +1,174 @@
1
+ import { afterEach, expect, it, vi } from "vitest";
2
+ import { BetterStripe } from "../index.js";
3
+ import { getStripeClient } from "../helpers.js";
4
+
5
+ afterEach(() => vi.restoreAllMocks());
6
+ function fixture() {
7
+ const key = `sk_test_invoice_page_${crypto.randomUUID()}`;
8
+ const client = new BetterStripe({} as never, { STRIPE_SECRET_KEY: key });
9
+ const list = vi.spyOn(getStripeClient(key).invoices, "list");
10
+ const ctx = { runQuery: vi.fn() };
11
+ const invoice = (id: string, customerAccount = "acct_buyer") => ({
12
+ id,
13
+ object: "invoice",
14
+ customer_account: customerAccount,
15
+ status: "paid",
16
+ currency: "jpy",
17
+ amount_paid: 1234,
18
+ status_transitions: { paid_at: 100 },
19
+ parent: {
20
+ type: "subscription_details",
21
+ subscription_details: { subscription: "sub_buyer" },
22
+ },
23
+ lines: { data: [{ id: "il_first" }], has_more: true },
24
+ });
25
+ return {
26
+ client,
27
+ list,
28
+ ctx,
29
+ invoice,
30
+ opts: { customerAccount: "acct_buyer" },
31
+ };
32
+ }
33
+
34
+ it("reads one bounded V2 buyer provider page preserving exact invoice evidence", async () => {
35
+ const f = fixture();
36
+ const row = f.invoice("in_first");
37
+ f.list.mockResolvedValue({ data: [row], has_more: false } as never);
38
+ const result = await f.client.getInvoicePageFromStripe(f.ctx, f.opts);
39
+ expect(f.list).toHaveBeenCalledExactlyOnceWith({
40
+ customer_account: "acct_buyer",
41
+ limit: 25,
42
+ });
43
+ expect(result).toEqual({ page: [row], hasMore: false, continueCursor: null });
44
+ expect(result.page[0]?.lines.has_more).toBe(true);
45
+ expect(f.ctx.runQuery).not.toHaveBeenCalled();
46
+ });
47
+
48
+ it("resumes provider pages with the original account and filter scope", async () => {
49
+ const f = fixture();
50
+ f.list
51
+ .mockResolvedValueOnce({
52
+ data: [f.invoice("in_newer")],
53
+ has_more: true,
54
+ } as never)
55
+ .mockResolvedValueOnce({
56
+ data: [f.invoice("in_older")],
57
+ has_more: false,
58
+ } as never);
59
+ const opts = {
60
+ ...f.opts,
61
+ status: "paid" as const,
62
+ created: { gte: 0, lte: 200 },
63
+ limit: 1,
64
+ };
65
+ const first = await f.client.getInvoicePageFromStripe(f.ctx, opts);
66
+ expect(first.hasMore).toBe(true);
67
+ expect(first.continueCursor).toEqual(expect.any(String));
68
+ const second = await f.client.getInvoicePageFromStripe(f.ctx, {
69
+ ...opts,
70
+ cursor: first.continueCursor,
71
+ });
72
+ expect(f.list).toHaveBeenLastCalledWith({
73
+ customer_account: "acct_buyer",
74
+ status: "paid",
75
+ created: { gte: 0, lte: 200 },
76
+ limit: 1,
77
+ starting_after: "in_newer",
78
+ });
79
+ expect(second.page.map((row) => row.id)).toEqual(["in_older"]);
80
+ expect(second.continueCursor).toBeNull();
81
+ });
82
+
83
+ it("rejects a continuation reused with a different buyer, status or window", async () => {
84
+ const f = fixture();
85
+ f.list.mockResolvedValue({
86
+ data: [f.invoice("in_first")],
87
+ has_more: true,
88
+ } as never);
89
+ const opts = { ...f.opts, status: "paid" as const, created: { lte: 200 } };
90
+ const first = await f.client.getInvoicePageFromStripe(f.ctx, opts);
91
+ for (const change of [
92
+ { customerAccount: "acct_other" },
93
+ { status: "open" as const },
94
+ { created: { lte: 201 } },
95
+ ]) {
96
+ await expect(
97
+ f.client.getInvoicePageFromStripe(f.ctx, {
98
+ ...opts,
99
+ ...change,
100
+ cursor: first.continueCursor,
101
+ }),
102
+ ).rejects.toThrow(/cursor|scope/i);
103
+ }
104
+ expect(f.list).toHaveBeenCalledTimes(1);
105
+ });
106
+
107
+ it.each([
108
+ { customerAccount: "cus_wrong" },
109
+ { limit: 0 },
110
+ { limit: 101 },
111
+ { limit: 1.5 },
112
+ { cursor: "not-json" },
113
+ { created: { gte: 20, lte: 10 } },
114
+ ])("rejects invalid selectors before provider reads %#", async (change) => {
115
+ const f = fixture();
116
+ await expect(
117
+ f.client.getInvoicePageFromStripe(f.ctx, { ...f.opts, ...change }),
118
+ ).rejects.toThrow();
119
+ expect(f.list).not.toHaveBeenCalled();
120
+ });
121
+
122
+ it("preserves provider failure identity instead of returning an empty completed page", async () => {
123
+ const f = fixture();
124
+ const failure = Object.assign(new Error("provider unavailable"), {
125
+ code: "api_error",
126
+ });
127
+ f.list.mockRejectedValue(failure);
128
+ await expect(f.client.getInvoicePageFromStripe(f.ctx, f.opts)).rejects.toBe(
129
+ failure,
130
+ );
131
+ });
132
+
133
+ it("rejects foreign buyer rows instead of exposing mismatched invoice evidence", async () => {
134
+ const f = fixture();
135
+ f.list.mockResolvedValue({
136
+ data: [f.invoice("in_foreign", "acct_other")],
137
+ has_more: false,
138
+ } as never);
139
+ await expect(
140
+ f.client.getInvoicePageFromStripe(f.ctx, f.opts),
141
+ ).rejects.toThrow(/scope|buyer/i);
142
+ });
143
+
144
+ it("rejects an empty has-more page rather than inventing a terminal cursor", async () => {
145
+ const f = fixture();
146
+ f.list.mockResolvedValue({ data: [], has_more: true } as never);
147
+ await expect(
148
+ f.client.getInvoicePageFromStripe(f.ctx, f.opts),
149
+ ).rejects.toThrow(/continuation|page/i);
150
+ });
151
+
152
+ it("preserves repeated observations across pages without asserting immutable payment state", async () => {
153
+ const f = fixture();
154
+ f.list
155
+ .mockResolvedValueOnce({
156
+ data: [f.invoice("in_first")],
157
+ has_more: true,
158
+ } as never)
159
+ .mockResolvedValueOnce({
160
+ data: [
161
+ { ...f.invoice("in_first"), amount_paid: 1200 },
162
+ f.invoice("in_next"),
163
+ ],
164
+ has_more: true,
165
+ } as never);
166
+ const first = await f.client.getInvoicePageFromStripe(f.ctx, f.opts);
167
+ const second = await f.client.getInvoicePageFromStripe(f.ctx, {
168
+ ...f.opts,
169
+ cursor: first.continueCursor,
170
+ });
171
+ expect(second.page.map((row) => row.id)).toEqual(["in_first", "in_next"]);
172
+ expect(second.page[0]?.amount_paid).toBe(1200);
173
+ expect(second.hasMore).toBe(true);
174
+ });
@@ -0,0 +1,110 @@
1
+ import type Stripe from "stripe";
2
+ import { z } from "zod";
3
+
4
+ const time = z.number().int().nonnegative().safe();
5
+ const scopeSchema = z
6
+ .object({
7
+ customerAccount: z
8
+ .string()
9
+ .max(128)
10
+ .regex(/^acct_[A-Za-z0-9_]+$/),
11
+ status: z
12
+ .enum(["draft", "open", "paid", "uncollectible", "void"])
13
+ .optional(),
14
+ created: z
15
+ .object({ gte: time.optional(), lte: time.optional() })
16
+ .strict()
17
+ .optional(),
18
+ })
19
+ .strict();
20
+ const optionsSchema = scopeSchema
21
+ .extend({
22
+ limit: z.number().int().min(1).max(100).default(25),
23
+ cursor: z.string().min(1).max(2048).nullable().optional(),
24
+ })
25
+ .strict();
26
+ const cursorSchema = z
27
+ .object({
28
+ version: z.literal(1),
29
+ scope: scopeSchema,
30
+ after: z
31
+ .string()
32
+ .max(128)
33
+ .regex(/^in_[A-Za-z0-9_]+$/),
34
+ })
35
+ .strict();
36
+
37
+ export type InvoicePageOptions = z.input<typeof optionsSchema>;
38
+ export type ProviderInvoicePage = {
39
+ page: Stripe.Invoice[];
40
+ hasMore: boolean;
41
+ continueCursor: string | null;
42
+ };
43
+
44
+ function encodeCursor(scope: z.infer<typeof scopeSchema>, after: string) {
45
+ return btoa(JSON.stringify({ version: 1, scope, after }))
46
+ .replaceAll("+", "-")
47
+ .replaceAll("/", "_")
48
+ .replace(/=+$/, "");
49
+ }
50
+ function decodeCursor(cursor: string, scope: z.infer<typeof scopeSchema>) {
51
+ try {
52
+ if (!/^[A-Za-z0-9_-]+$/.test(cursor)) throw new Error();
53
+ const parsed = cursorSchema.parse(
54
+ JSON.parse(atob(cursor.replaceAll("-", "+").replaceAll("_", "/"))),
55
+ );
56
+ if (
57
+ JSON.stringify(parsed.scope) !== JSON.stringify(scope) ||
58
+ encodeCursor(parsed.scope, parsed.after) !== cursor
59
+ )
60
+ throw new Error();
61
+ return parsed.after;
62
+ } catch {
63
+ throw new Error("Invalid invoice page cursor or scope");
64
+ }
65
+ }
66
+
67
+ /** Provider enumeration only. The host authorizes the buyer and reconciles mutable history. */
68
+ export async function getInvoicePageFromStripe(
69
+ stripe: Stripe,
70
+ input: InvoicePageOptions,
71
+ ): Promise<ProviderInvoicePage> {
72
+ const { limit, cursor, ...scope } = optionsSchema.parse(input);
73
+ if (
74
+ scope.created?.gte !== undefined &&
75
+ scope.created.lte !== undefined &&
76
+ scope.created.gte > scope.created.lte
77
+ )
78
+ throw new Error("Invalid invoice page time window");
79
+ if (
80
+ scope.created &&
81
+ scope.created.gte === undefined &&
82
+ scope.created.lte === undefined
83
+ )
84
+ delete scope.created;
85
+ const after = cursor ? decodeCursor(cursor, scope) : undefined;
86
+ const response = await stripe.invoices.list({
87
+ customer_account: scope.customerAccount,
88
+ limit,
89
+ ...(scope.status ? { status: scope.status } : {}),
90
+ ...(scope.created ? { created: scope.created } : {}),
91
+ ...(after ? { starting_after: after } : {}),
92
+ });
93
+ if (
94
+ response.data.length > limit ||
95
+ response.data.some(
96
+ (invoice) =>
97
+ invoice.customer_account !== scope.customerAccount ||
98
+ !/^in_[A-Za-z0-9_]+$/.test(invoice.id),
99
+ )
100
+ )
101
+ throw new Error("Invalid provider invoice page buyer scope");
102
+ const last = response.data[response.data.length - 1]?.id;
103
+ if (response.has_more && (!last || last === after))
104
+ throw new Error("Provider invoice page has no advancing continuation");
105
+ return {
106
+ page: response.data,
107
+ hasMore: response.has_more,
108
+ continueCursor: response.has_more ? encodeCursor(scope, last!) : null,
109
+ };
110
+ }
@@ -55,6 +55,11 @@ export type {
55
55
  CouponReadOptions,
56
56
  } from "./billing/providerReads.js";
57
57
  import * as providerReads from "./billing/providerReads.js";
58
+ import * as invoicePages from "./billing/invoicePages.js";
59
+ export type {
60
+ InvoicePageOptions,
61
+ ProviderInvoicePage,
62
+ } from "./billing/invoicePages.js";
58
63
  export type { CreateAccountOptions } from "./core/accounts.js";
59
64
  import { buildAsyncHookRoutes } from "./webhooks/asyncHooks.js";
60
65
  import * as saleContextImpl from "./settlement/verifiedSale.js";
@@ -1017,6 +1022,14 @@ export class BetterStripe extends ReadContractClient {
1017
1022
  return invoicePreviewImpl.getUpcomingInvoicePreview(this.stripe(), opts);
1018
1023
  }
1019
1024
 
1025
+ /** Provider page only; the host authorizes scope and verifies historical completeness. */
1026
+ async getInvoicePageFromStripe(
1027
+ _ctx: RunCtx,
1028
+ opts: invoicePages.InvoicePageOptions,
1029
+ ) {
1030
+ return invoicePages.getInvoicePageFromStripe(this.stripe(), opts);
1031
+ }
1032
+
1020
1033
  async getInvoiceFromStripe(ctx: RunCtx, opts: { stripeInvoiceId: string }) {
1021
1034
  return invoicesImpl.getInvoiceFromStripe(this.stripe(), ctx, opts);
1022
1035
  }
@@ -2,13 +2,12 @@
2
2
  import { convexTest } from "convex-test";
3
3
  import { expect, it, vi } from "vitest";
4
4
  import type Stripe from "stripe";
5
- import { api } from "./_generated/api.js";
6
- import schema from "./schema.js";
7
- import { changeBalance } from "./affiliateRecovery/accounting.js";
8
- import { createPayout } from "../client/connect/payouts.js";
9
- import { AffiliateRecoveryClient } from "../client/affiliateRecovery.js";
10
- import type { Component, RunCtx } from "../client/helpers.js";
11
- const modules = import.meta.glob("./**/*.*s");
5
+ import { api } from "../_generated/api.js";
6
+ import { schema, modules } from "../../test.js";
7
+ import { changeBalance } from "../affiliateRecovery/accounting.js";
8
+ import { createPayout } from "../../client/connect/payouts.js";
9
+ import { AffiliateRecoveryClient } from "../../client/affiliateRecovery.js";
10
+ import type { Component, RunCtx } from "../../client/helpers.js";
12
11
  const symbol = Symbol.for("toReferencePath");
13
12
  function reference(path = "betterStripe"): Component {
14
13
  return new Proxy(
@@ -1,20 +1,17 @@
1
1
  // @vitest-environment edge-runtime
2
2
  import { convexTest } from "convex-test";
3
- import { componentDb } from "../testing/component-db.js";
3
+ import { componentDb } from "../../testing/component-db.js";
4
4
  import { expect, it } from "vitest";
5
5
  import type {
6
6
  RegisteredQuery,
7
7
  RegisteredMutation,
8
8
  DefaultFunctionArgs,
9
9
  } from "convex/server";
10
- import type { MutationCtx } from "./_generated/server.js";
11
- import schema from "./schema.js";
12
- import {
13
- recoverySnapshot,
14
- pendingOperations,
15
- } from "./affiliateRecovery/queries.js";
16
- import { listAffiliateObligations } from "./settlement/queries.js";
17
- import { migrateAffiliateObligations } from "./settlement/mutations.js";
10
+ import type { MutationCtx } from "../_generated/server.js";
11
+ import { schema, modules } from "../../test.js";
12
+ import { recoverySnapshot, pendingOperations } from "./queries.js";
13
+ import { listAffiliateObligations } from "../settlement/queries.js";
14
+ import { migrateAffiliateObligations } from "../settlement/mutations.js";
18
15
 
19
16
  function handler<Args extends DefaultFunctionArgs, Result>(
20
17
  fn:
@@ -27,7 +24,7 @@ function handler<Args extends DefaultFunctionArgs, Result>(
27
24
  }
28
25
 
29
26
  it("reads recovery pages and migrates inside the deployed component pagination boundary", async () => {
30
- const t = convexTest(schema, import.meta.glob("./**/*.*s"));
27
+ const t = convexTest(schema, modules);
31
28
  await t.run(async (ctx) => {
32
29
  const componentCtx = { ...ctx, db: componentDb(ctx.db) };
33
30
  const paginationOpts = { numItems: 10, cursor: null };
@@ -2,18 +2,17 @@
2
2
  import type Stripe from "stripe";
3
3
  import { convexTest } from "convex-test";
4
4
  import { describe, expect, it } from "vitest";
5
- import { api } from "./_generated/api.js";
6
- import schema from "./schema.js";
7
- import type { Component, RunCtx } from "../client/helpers.js";
5
+ import { api } from "../_generated/api.js";
6
+ import { schema, modules } from "../../test.js";
7
+ import type { Component, RunCtx } from "../../client/helpers.js";
8
8
  import {
9
9
  reverseTransfers,
10
10
  reclaimReversalClaim,
11
11
  reverseTransfersForRefund,
12
12
  reverseTransfersForDispute,
13
- } from "../client/connect/transfers.js";
14
- import { executeResolvedTransfers } from "../client/settlement/execution.js";
15
- import { reconcileObligation } from "../client/affiliateRecovery/engine.js";
16
- const modules = import.meta.glob("./**/*.*s");
13
+ } from "../../client/connect/transfers.js";
14
+ import { executeResolvedTransfers } from "../../client/settlement/execution.js";
15
+ import { reconcileObligation } from "../../client/affiliateRecovery/engine.js";
17
16
  const REF = Symbol.for("toReferencePath");
18
17
  function component(path = "betterStripe"): Component {
19
18
  return new Proxy(
@@ -0,0 +1,89 @@
1
+ // @vitest-environment edge-runtime
2
+ import { convexTest } from "convex-test";
3
+ import { describe, expect, it } from "vitest";
4
+ import { api } from "../_generated/api.js";
5
+ import { schema, modules } from "../../test.js";
6
+
7
+ describe("billing — checkout session mutations and queries", () => {
8
+ it("upsertCheckoutSession + getCheckoutSessionByStripeId", async () => {
9
+ const t = convexTest(schema, modules);
10
+
11
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
12
+ stripeSessionId: "cs_001",
13
+ userId: "user_020",
14
+ mode: "subscription",
15
+ status: "open",
16
+ });
17
+
18
+ const session = await t.query(
19
+ api.billing.queries.getCheckoutSessionByStripeId,
20
+ {
21
+ stripeSessionId: "cs_001",
22
+ },
23
+ );
24
+
25
+ expect(session).not.toBeNull();
26
+ expect(session!.mode).toBe("subscription");
27
+ expect(session!.status).toBe("open");
28
+ });
29
+ });
30
+
31
+ describe("billing — listCheckoutSessionsByUser", () => {
32
+ it("lists sessions for the given user", async () => {
33
+ const t = convexTest(schema, modules);
34
+
35
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
36
+ stripeSessionId: "cs_u1_a",
37
+ userId: "user_cs_1",
38
+ mode: "subscription",
39
+ status: "complete",
40
+ });
41
+
42
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
43
+ stripeSessionId: "cs_u1_b",
44
+ userId: "user_cs_1",
45
+ mode: "payment",
46
+ status: "open",
47
+ });
48
+
49
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
50
+ stripeSessionId: "cs_u2",
51
+ userId: "user_cs_2",
52
+ mode: "subscription",
53
+ status: "open",
54
+ });
55
+
56
+ const sessions = await t.query(
57
+ api.billing.queries.listCheckoutSessionsByUser,
58
+ { userId: "user_cs_1" },
59
+ );
60
+
61
+ expect(sessions).toHaveLength(2);
62
+ });
63
+
64
+ it("filters by status", async () => {
65
+ const t = convexTest(schema, modules);
66
+
67
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
68
+ stripeSessionId: "cs_filter_open",
69
+ userId: "user_filter",
70
+ mode: "subscription",
71
+ status: "open",
72
+ });
73
+
74
+ await t.mutation(api.billing.mutations.upsertCheckoutSession, {
75
+ stripeSessionId: "cs_filter_complete",
76
+ userId: "user_filter",
77
+ mode: "subscription",
78
+ status: "complete",
79
+ });
80
+
81
+ const open = await t.query(api.billing.queries.listCheckoutSessionsByUser, {
82
+ userId: "user_filter",
83
+ status: "open",
84
+ });
85
+
86
+ expect(open).toHaveLength(1);
87
+ expect(open[0].status).toBe("open");
88
+ });
89
+ });