Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions lib/credits/__tests__/const.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { describe, expect, it } from "vitest";

import { DEFAULT_CREDITS, PRO_CREDITS } from "@/lib/credits/const";

describe("credit plan constants", () => {
it("keeps the free-tier allotment at 333 (matches chat/lib/consts.ts)", () => {
expect(DEFAULT_CREDITS).toBe(333);
});

it("gives pro accounts 9999 credits per month (matches chat/lib/consts.ts)", () => {
expect(PRO_CREDITS).toBe(9999);
});
});
32 changes: 32 additions & 0 deletions lib/credits/__tests__/getAccountSubscriptionState.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import { getAccountSubscriptionState } from "@/lib/credits/getAccountSubscriptionState";
import { getActiveSubscriptionDetails } from "@/lib/stripe/getActiveSubscriptionDetails";
import { getOrgSubscription } from "@/lib/stripe/getOrgSubscription";
import { isEnterpriseAccount } from "@/lib/enterprise/isEnterpriseAccount";

vi.mock("@/lib/stripe/getActiveSubscriptionDetails", () => ({
getActiveSubscriptionDetails: vi.fn(),
Expand All @@ -12,11 +13,16 @@ vi.mock("@/lib/stripe/getOrgSubscription", () => ({
getOrgSubscription: vi.fn(),
}));

vi.mock("@/lib/enterprise/isEnterpriseAccount", () => ({
isEnterpriseAccount: vi.fn(),
}));

const ACCOUNT = "123e4567-e89b-12d3-a456-426614174000";

describe("getAccountSubscriptionState", () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(isEnterpriseAccount).mockResolvedValue(false);
});

it("returns isPro=false / activeSubscription=null when neither subscription is active", async () => {
Expand Down Expand Up @@ -69,4 +75,30 @@ describe("getAccountSubscriptionState", () => {

expect(result).toEqual({ isPro: false, activeSubscription: null });
});

it("returns isPro=true with activeSubscription=null for an enterprise account without Stripe", async () => {
vi.mocked(getActiveSubscriptionDetails).mockResolvedValue(null);
vi.mocked(getOrgSubscription).mockResolvedValue(null);
vi.mocked(isEnterpriseAccount).mockResolvedValue(true);

const result = await getAccountSubscriptionState(ACCOUNT);

expect(result).toEqual({ isPro: true, activeSubscription: null });
expect(isEnterpriseAccount).toHaveBeenCalledWith(ACCOUNT);
});

it("keeps activeSubscription Stripe-only when both enterprise and a Stripe sub apply", async () => {
const accountSub = {
id: "sub_account",
status: "active",
canceled_at: null,
} as never;
vi.mocked(getActiveSubscriptionDetails).mockResolvedValue(accountSub);
vi.mocked(getOrgSubscription).mockResolvedValue(null);
vi.mocked(isEnterpriseAccount).mockResolvedValue(true);

const result = await getAccountSubscriptionState(ACCOUNT);

expect(result).toEqual({ isPro: true, activeSubscription: accountSub });
});
});
6 changes: 4 additions & 2 deletions lib/credits/const.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
export const DEFAULT_CREDITS = 333;

/**
* Monthly credit allotment for accounts on a pro plan (directly or via an organization).
* Monthly credit allotment for accounts on a pro plan (directly, via an
* organization, or via an enterprise email domain). Effectively "don't think
* about credits" for paying customers.
*/
export const PRO_CREDITS = 1000;
export const PRO_CREDITS = 9999;

/**
* Credits added per automatic top-up when a request would push an account below
Expand Down
20 changes: 12 additions & 8 deletions lib/credits/getAccountSubscriptionState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,32 +2,36 @@ import type Stripe from "stripe";
import isActiveSubscription from "@/lib/stripe/isActiveSubscription";
import { getActiveSubscriptionDetails } from "@/lib/stripe/getActiveSubscriptionDetails";
import { getOrgSubscription } from "@/lib/stripe/getOrgSubscription";
import { isEnterpriseAccount } from "@/lib/enterprise/isEnterpriseAccount";

export interface AccountSubscriptionState {
isPro: boolean;
activeSubscription: Stripe.Subscription | null;
}

/**
* Single source of truth for "what's this account's plan?" — checks both the
* account-level subscription and any org membership in parallel, then resolves
* the active subscription with account-wins-on-tie precedence.
* Single source of truth for "what's this account's plan?" — checks the
* account-level subscription, any org membership, and enterprise email-domain
* status in parallel. `isPro` is true if any of the three match; the active
* subscription resolves with account-wins-on-tie precedence.
*
* Returns the resolved Stripe.Subscription alongside the boolean so callers
* that need period-start timestamps (e.g. checkAndResetCredits) don't have to
* re-derive which one was active.
* `activeSubscription` stays Stripe-only on purpose: it feeds
* checkAndResetCredits's early-refill via `current_period_start`, and
* enterprise-domain accounts (no Stripe sub) must refill on the ≥1-month path
* only — so an enterprise match yields `isPro: true, activeSubscription: null`.
*/
export async function getAccountSubscriptionState(
accountId: string,
): Promise<AccountSubscriptionState> {
const [accountSub, orgSub] = await Promise.all([
const [accountSub, orgSub, isEnterprise] = await Promise.all([
getActiveSubscriptionDetails(accountId),
getOrgSubscription(accountId),
isEnterpriseAccount(accountId),

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Credits reads now add an unconditional enterprise-domain DB lookup, even when Stripe already proves the account is pro. This increases per-request load/latency on the hot path; consider running isEnterpriseAccount only when both Stripe checks are inactive.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At lib/credits/getAccountSubscriptionState.ts, line 29:

<comment>Credits reads now add an unconditional enterprise-domain DB lookup, even when Stripe already proves the account is pro. This increases per-request load/latency on the hot path; consider running `isEnterpriseAccount` only when both Stripe checks are inactive.</comment>

<file context>
@@ -2,32 +2,36 @@ import type Stripe from "stripe";
+  const [accountSub, orgSub, isEnterprise] = await Promise.all([
     getActiveSubscriptionDetails(accountId),
     getOrgSubscription(accountId),
+    isEnterpriseAccount(accountId),
   ]);
   const hasAccountSub = isActiveSubscription(accountSub);
</file context>

]);
const hasAccountSub = isActiveSubscription(accountSub);
const hasOrgSub = isActiveSubscription(orgSub);
return {
isPro: hasAccountSub || hasOrgSub,
isPro: hasAccountSub || hasOrgSub || isEnterprise,
activeSubscription: hasAccountSub ? accountSub : hasOrgSub ? orgSub : null,
};
}
60 changes: 60 additions & 0 deletions lib/enterprise/__tests__/isEnterpriseAccount.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { beforeEach, describe, expect, it, vi } from "vitest";

import { isEnterpriseAccount } from "@/lib/enterprise/isEnterpriseAccount";
import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails";

vi.mock("@/lib/supabase/account_emails/selectAccountEmails", () => ({
default: vi.fn(),
}));

const ACCOUNT = "123e4567-e89b-12d3-a456-426614174000";

function emailRow(email: string | null) {
return { account_id: ACCOUNT, email, id: "row-1" } as never;
}

describe("isEnterpriseAccount", () => {
beforeEach(() => {
vi.clearAllMocks();
});

it("returns true when an account email's domain is in ENTERPRISE_DOMAINS", async () => {
vi.mocked(selectAccountEmails).mockResolvedValue([emailRow("artist@seekermusic.com")]);

await expect(isEnterpriseAccount(ACCOUNT)).resolves.toBe(true);
expect(selectAccountEmails).toHaveBeenCalledWith({ accountIds: ACCOUNT });
});

it("matches domains case-insensitively", async () => {
vi.mocked(selectAccountEmails).mockResolvedValue([emailRow("Artist@SeekerMusic.com")]);

await expect(isEnterpriseAccount(ACCOUNT)).resolves.toBe(true);
});

it("returns true when any of multiple emails matches", async () => {
vi.mocked(selectAccountEmails).mockResolvedValue([
emailRow("personal@gmail.com"),
emailRow("work@rostrumrecords.com"),
]);

await expect(isEnterpriseAccount(ACCOUNT)).resolves.toBe(true);
});

it("returns false when no email domain is enterprise", async () => {
vi.mocked(selectAccountEmails).mockResolvedValue([emailRow("someone@gmail.com")]);

await expect(isEnterpriseAccount(ACCOUNT)).resolves.toBe(false);
});

it("returns false when the account has no emails", async () => {
vi.mocked(selectAccountEmails).mockResolvedValue([]);

await expect(isEnterpriseAccount(ACCOUNT)).resolves.toBe(false);
});

it("returns false for rows with null or malformed emails", async () => {
vi.mocked(selectAccountEmails).mockResolvedValue([emailRow(null), emailRow("not-an-email")]);

await expect(isEnterpriseAccount(ACCOUNT)).resolves.toBe(false);
});
});
16 changes: 16 additions & 0 deletions lib/enterprise/isEnterpriseAccount.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { ENTERPRISE_DOMAINS } from "@/lib/enterprise/consts";
import { extractDomain } from "@/lib/email/extractDomain";
import selectAccountEmails from "@/lib/supabase/account_emails/selectAccountEmails";

/**
* Resolves whether an account belongs to an enterprise customer: true when any
* of the account's emails has a domain in ENTERPRISE_DOMAINS. Used by the
* credits system to grant pro status without a Stripe subscription.
*/
export async function isEnterpriseAccount(accountId: string): Promise<boolean> {
const rows = await selectAccountEmails({ accountIds: accountId });
return rows.some(row => {
const domain = row.email ? extractDomain(row.email) : null;
return domain !== null && ENTERPRISE_DOMAINS.has(domain);
});
}
Loading