Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

fix(prompts): show an organization whose plan ended its own plan in Plan & usage, not Starter's (#1671)

Cihan7ada1f6edd67
diff --git a/web/messages/en.json b/web/messages/en.json
index 4a7a4015f..be4f418df 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -6999,6 +6999,8 @@
"show": "Show",
"hide": "Hide",
"planPill": "{plan} plan",
+ "planPillEnded": "{plan} plan · ended",
+ "ended": "Your {plan} plan has ended",
"planLabel": {
"self_hosted": "Self-Hosted",
"starter": "Starter",
@@ -7025,7 +7027,8 @@
"cta": {
"upgrade_growth": "Upgrade to Growth",
"upgrade": "Upgrade plan",
- "contact": "Contact us"
+ "contact": "Contact us",
+ "choose_plan": "Choose a plan"
},
"footer": "Click a card to filter the table (Active · Paused · All).",
"updated": "Counts updated {when}",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsx
index b3896e6c5..7e342d0a5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.test.tsx
@@ -4,6 +4,7 @@ import { NextIntlClientProvider } from 'next-intl';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import messages from '../../../../../../messages/en.json';
import type { PromptUsageSummary } from '@/lib/prompt-usage-summary';
+import { getPromptUsage, isPromptLimitReached } from '@/lib/prompt-usage';
import {
PromptUsageCards,
countByStatus,
@@ -110,6 +111,30 @@ describe('PromptUsageCards', () => {
expect(container.textContent).toContain('over limit');
});
+ it('says an ended plan has ended, with no slots left and Choose a plan', () => {
+ render({
+ status: 'ready',
+ usage: summary({
+ plan: {
+ key: 'growth',
+ name: 'Growth plan',
+ locationLimit: 200,
+ cta: 'choose_plan',
+ ended: true,
+ },
+ }),
+ });
+
+ expect(values().slice(3)).toEqual(['46 / 200', '0']);
+ expect(container.textContent).toContain('Growth plan · ended');
+ expect(container.textContent).toContain('Your Growth plan has ended · Choose a plan');
+ expect(container.textContent).not.toContain('Starter');
+ const choose = [...container.querySelectorAll('a')].find(
+ (a) => a.textContent === 'Choose a plan',
+ );
+ expect(choose).toBeDefined();
+ });
+
it('asks an Enterprise account to contact us, against the limit set for it', () => {
render({
status: 'ready',
@@ -290,6 +315,29 @@ describe('locationQuotaFromUsage', () => {
).maxPrompts,
).toBe(-1);
});
+
+ it('leaves no slot to the Add Prompt dialog and bulk import once the plan has ended', () => {
+ const ended = (locationLimit: number | null) =>
+ locationQuotaFromUsage(
+ summary({
+ plan: {
+ key: 'growth',
+ name: 'Growth plan',
+ locationLimit,
+ cta: 'choose_plan',
+ ended: true,
+ },
+ }),
+ );
+
+ // Limited or not, nothing can be added until a plan is chosen again.
+ for (const quota of [ended(200), ended(null)]) {
+ expect(quota).toMatchObject({ used: 46, planId: 'growth', planName: 'Growth' });
+ const usage = getPromptUsage(quota.used, quota.maxPrompts);
+ expect(usage.remaining).toBe(0);
+ expect(isPromptLimitReached(usage)).toBe(true);
+ }
+ });
});
describe('the table status filter', () => {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsx
index ee1524273..1ddd61fc4 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_usage-cards.tsx
@@ -151,9 +151,12 @@ export function usePromptUsage(
/** The plan-limit numbers the Add Prompt dialog and bulk import bound themselves by. */
export function locationQuotaFromUsage(usage: PromptUsageSummary): LocationQuota {
+ const used = usage.account.locationsUsed;
return {
- maxPrompts: usage.plan.locationLimit ?? -1,
- used: usage.account.locationsUsed,
+ // An ended plan takes nothing new until a plan is chosen again: the quota
+ // reads as full, as the Slots left card's 0 does.
+ maxPrompts: usage.plan.ended ? used : (usage.plan.locationLimit ?? -1),
+ used,
planId: usage.plan.key,
planName: isKnownPlan(usage.plan.key) ? PLANS[usage.plan.key].name : usage.plan.name,
};
@@ -203,8 +206,11 @@ export function PromptUsageCards({
const usage = state.status === 'ready' ? state.usage : null;
const plan = usage?.plan;
const planShort = !plan ? '' : isKnownPlan(plan.key) ? t(`planLabel.${plan.key}`) : plan.name;
- const planPill =
- plan && isKnownPlan(plan.key) ? t('planPill', { plan: planShort }) : (plan?.name ?? '');
+ const planPill = plan?.ended
+ ? t('planPillEnded', { plan: planShort })
+ : plan && isKnownPlan(plan.key)
+ ? t('planPill', { plan: planShort })
+ : (plan?.name ?? '');
// Self-hosted has no plan page to go to.
const planHref = plan?.cta ? PLAN_PAGE : undefined;
@@ -448,12 +454,18 @@ export function PromptUsageCards({
)}
</UsageCard>
<UsageCard label={t('slotsLeft')} href={planHref}>
- {value(limit === null ? t('unlimited') : n(meter?.remaining ?? 0), TONE_TEXT[tone])}
+ {/* Nothing can be added until a plan is chosen again. */}
+ {value(
+ plan?.ended ? n(0) : limit === null ? t('unlimited') : n(meter?.remaining ?? 0),
+ TONE_TEXT[tone],
+ )}
{sub(
<>
- {limit === null
- ? t('onPlan', { plan: planShort })
- : t('ofLimit', { limit: n(limit), plan: planShort })}
+ {plan?.ended
+ ? t('ended', { plan: planShort })
+ : limit === null
+ ? t('onPlan', { plan: planShort })
+ : t('ofLimit', { limit: n(limit), plan: planShort })}
{cta && <> · {cta}</>}
</>,
)}
diff --git a/web/src/app/api/prompts/usage/route.test.ts b/web/src/app/api/prompts/usage/route.test.ts
index 3174dba6b..aa1911c91 100644
--- a/web/src/app/api/prompts/usage/route.test.ts
+++ b/web/src/app/api/prompts/usage/route.test.ts
@@ -89,6 +89,24 @@ describe('GET /api/prompts/usage', () => {
});
});
+ it('counts an organization whose plan ended against the plan it was on, not Starter', async () => {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ brand.data = {
+ organization_id: 'org1',
+ organizations: { plan: 'growth', subscription_status: 'canceled', plan_overrides: null },
+ };
+
+ const body = await (await get(`?brandId=${BRAND}`)).json();
+
+ expect(body.plan).toEqual({
+ key: 'growth',
+ name: 'Growth plan',
+ locationLimit: 200,
+ cta: 'choose_plan',
+ ended: true,
+ });
+ });
+
it('is unlimited on a self-hosted install', async () => {
const body = await (await get(`?brandId=${BRAND}`)).json();
expect(body.plan).toEqual({
diff --git a/web/src/app/api/prompts/usage/route.ts b/web/src/app/api/prompts/usage/route.ts
index 5cc625ae0..273f14863 100644
--- a/web/src/app/api/prompts/usage/route.ts
+++ b/web/src/app/api/prompts/usage/route.ts
@@ -1,7 +1,7 @@
import { NextResponse } from 'next/server';
import { z } from 'zod';
import { createClient } from '@/lib/supabase/server';
-import { ORG_PLAN_COLUMNS, planFromOrgRow } from '@/lib/guards/plan-guard';
+import { ORG_PLAN_COLUMNS, usagePlanFromOrgRow } from '@/lib/guards/plan-guard';
import { fetchPromptUsageRow, toPromptUsageSummary } from '@/lib/prompt-usage-summary';
/**
@@ -52,8 +52,9 @@ export async function GET(req: Request) {
if (brandError) throw new Error(brandError.message);
if (!brand || !row) return NextResponse.json({ error: 'Brand not found' }, { status: 404 });
- const plan = planFromOrgRow(brand.organizations);
- return NextResponse.json(toPromptUsageSummary(row, plan), {
+ // An organization whose plan ended counts against the plan it was on.
+ const { plan, ended } = usagePlanFromOrgRow(brand.organizations);
+ return NextResponse.json(toPromptUsageSummary(row, plan, new Date(), { ended }), {
headers: { 'Cache-Control': 'private, no-store' },
});
} catch (err) {
diff --git a/web/src/lib/guards/plan-guard.test.ts b/web/src/lib/guards/plan-guard.test.ts
new file mode 100644
index 000000000..a4d44c8cc
--- /dev/null
+++ b/web/src/lib/guards/plan-guard.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/lib/supabase/server', () => ({ createClient: vi.fn() }));
+
+const { planFromOrgRow, usagePlanFromOrgRow } = await import('./plan-guard');
+
+/** The plan an organization's usage is shown against, while it's on one and once it has ended. */
+
+afterEach(() => vi.unstubAllEnvs());
+
+describe('usagePlanFromOrgRow', () => {
+ it('is the plan it is entitled to while its subscription is active or in trial', () => {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ for (const status of ['active', 'trialing']) {
+ const { plan, ended } = usagePlanFromOrgRow({ plan: 'growth', subscription_status: status });
+ expect([plan.id, ended]).toEqual(['growth', false]);
+ }
+ });
+
+ it('is the plan it was on once that has ended, marked ended, where entitlement reads Starter', () => {
+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');
+ const org = {
+ plan: 'enterprise',
+ subscription_status: 'canceled',
+ plan_overrides: { maxPrompts: 1000 },
+ };
+ expect(planFromOrgRow(org).id).toBe('starter');
+ const { plan, ended } = usagePlanFromOrgRow(org);
+ expect([plan.id, plan.limits.maxPrompts, ended]).toEqual(['enterprise', 1000, true]);
+ });
+
+ it('never ends on a self-hosted install', () => {
+ const { plan, ended } = usagePlanFromOrgRow({ plan: 'growth', subscription_status: null });
+ expect([plan.id, ended]).toEqual(['self_hosted', false]);
+ });
+});
diff --git a/web/src/lib/guards/plan-guard.ts b/web/src/lib/guards/plan-guard.ts
index f1e765f85..1dd6203f3 100644
--- a/web/src/lib/guards/plan-guard.ts
+++ b/web/src/lib/guards/plan-guard.ts
@@ -43,6 +43,11 @@ export function planFromOrgRow(
return getPlan('starter');
}
+ return ownPlan(data);
+}
+
+/** The plan the organization's row names, Enterprise's overrides merged. */
+function ownPlan(data: { plan?: unknown; plan_overrides?: unknown } | null): Plan {
const plan = getPlan(data?.plan as string | null | undefined);
// Enterprise orgs can have custom limit overrides
@@ -57,6 +62,21 @@ export function planFromOrgRow(
return plan;
}
+/**
+ * The plan to show an organization's usage against: while its subscription
+ * is active, the one it's entitled to; once it has ended (read-only, the
+ * Choose a plan step), the plan it was on, marked ended, not Starter's,
+ * which it never chose. What choosing a plan again gives it back.
+ */
+export function usagePlanFromOrgRow(
+ data: { plan?: unknown; subscription_status?: unknown; plan_overrides?: unknown } | null,
+): { plan: Plan; ended: boolean } {
+ if (isCloud() && !isSubscriptionActive(data?.subscription_status as string | null | undefined)) {
+ return { plan: ownPlan(data), ended: true };
+ }
+ return { plan: planFromOrgRow(data), ended: false };
+}
+
export class PlanLimitError extends Error {
public readonly requiredPlan: string;
diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.ts
index 6d2a7df4a..55873f3a9 100644
--- a/web/src/lib/mcp/data.ts
+++ b/web/src/lib/mcp/data.ts
@@ -15,7 +15,7 @@ import { expandDateToEndOfDay } from '@/lib/dates';
import { countTrafficLogs, scanTrafficLogs } from '@/lib/traffic-scan';
import { computeAiVisibilityScore } from '@/lib/visibility-score';
import { API_BASE_URL } from '@/config/api';
-import { ORG_PLAN_COLUMNS, planFromOrgRow } from '@/lib/guards/plan-guard';
+import { ORG_PLAN_COLUMNS, planFromOrgRow, usagePlanFromOrgRow } from '@/lib/guards/plan-guard';
import {
fetchPromptUsageRow,
toPromptUsageSummary,
@@ -1171,7 +1171,8 @@ export async function getPromptUsageFor(
]);
if (orgError) throw new Error(orgError.message);
if (!row) return null;
- return toPromptUsageSummary(row, planFromOrgRow(org));
+ const { plan, ended } = usagePlanFromOrgRow(org);
+ return toPromptUsageSummary(row, plan, new Date(), { ended });
}
/**
diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts
index 0d1c0145c..b6d6a4b38 100644
--- a/web/src/lib/mcp/server.ts
+++ b/web/src/lib/mcp/server.ts
@@ -703,12 +703,15 @@ export function createMcpServer(auth: McpAuthContext): McpServer {
{
description:
'Check tracked-prompt usage against the plan — the numbers on the Tracked Prompts usage cards. ' +
- 'Returns { plan: { key, name, locationLimit, cta }, brand: { active, paused, total }, ' +
+ 'Returns { plan: { key, name, locationLimit, cta, ended? }, brand: { active, paused, total }, ' +
'account: { activePrompts, brands, locationsUsed }, updatedAt }. The plan limit counts ' +
'prompt LOCATIONS across every brand of the account: each active prompt uses one slot per ' +
'location it targets, and paused prompts use none. Slots left = locationLimit − ' +
- 'locationsUsed (never below 0); locationLimit null means unlimited. Use this for "how many ' +
- 'prompts can we still add?" / "how close are we to the limit?". This is a read.',
+ 'locationsUsed (never below 0); locationLimit null means unlimited. When plan.ended is ' +
+ 'true the organization\'s plan has ended (plan is the one it was on, cta is "choose_plan"): ' +
+ '0 slots are left, whatever the limit says, and a plan must be chosen before any prompt ' +
+ 'can be added. Use this for "how many prompts can we still add?" / "how close are we to ' +
+ 'the limit?". This is a read.',
inputSchema: {
brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),
},
diff --git a/web/src/lib/prompt-usage-summary.ts b/web/src/lib/prompt-usage-summary.ts
index 902760d7b..af5cb5ec4 100644
--- a/web/src/lib/prompt-usage-summary.ts
+++ b/web/src/lib/prompt-usage-summary.ts
@@ -11,7 +11,7 @@ import type { Database } from '@/types/supabase';
*/
/** Where the Slots left card sends the user: billing to upgrade, or sales. */
-export type PromptUsageCta = 'upgrade_growth' | 'upgrade' | 'contact';
+export type PromptUsageCta = 'upgrade_growth' | 'upgrade' | 'contact' | 'choose_plan';
export interface PromptUsageSummary {
plan: {
@@ -22,6 +22,8 @@ export interface PromptUsageSummary {
locationLimit: number | null;
/** null on self-hosted, where there is no plan to change. */
cta: PromptUsageCta | null;
+ /** The organization's plan has ended: it's the plan it was on, to choose again. */
+ ended?: true;
};
brand: { active: number; paused: number; total: number };
account: { activePrompts: number; brands: number; locationsUsed: number };
@@ -42,13 +44,14 @@ const PLAN_CTA: Record<PlanId, PromptUsageCta | null> = {
* planFromOrgRow), so the limit is the one the plan-limit guard enforces,
* Enterprise overrides included.
*/
-export function usagePlan(plan: Plan): PromptUsageSummary['plan'] {
+export function usagePlan(plan: Plan, ended = false): PromptUsageSummary['plan'] {
const max = plan.limits.maxPrompts;
return {
key: plan.id,
name: `${plan.name} plan`,
locationLimit: max === -1 ? null : max,
- cta: PLAN_CTA[plan.id],
+ cta: ended ? 'choose_plan' : PLAN_CTA[plan.id],
+ ...(ended ? { ended: true as const } : {}),
};
}
@@ -76,9 +79,10 @@ export function toPromptUsageSummary(
row: PromptUsageRow,
plan: Plan,
now: Date = new Date(),
+ { ended = false }: { ended?: boolean } = {},
): PromptUsageSummary {
return {
- plan: usagePlan(plan),
+ plan: usagePlan(plan, ended),
brand: {
active: row.brand_active,
paused: row.brand_paused,