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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(prompts): keep per-brand usage counters for the tracked prompts cards (#1053)
Cihan6adc2c3aff67
diff --git a/docs/guides/mcp-server.mdx b/docs/guides/mcp-server.mdxindex 4754bf32f..ea2858a91 100644--- a/docs/guides/mcp-server.mdx+++ b/docs/guides/mcp-server.mdx@@ -220,7 +220,7 @@ instead.## Available tools-The MCP server exposes **29 tools**. Descriptions below match+The MCP server exposes **30 tools**. Descriptions below match[`web/src/lib/mcp/server.ts`](https://github.com/ansvisor/ansvisor/blob/main/web/src/lib/mcp/server.ts).Tools that change data are marked **writes** — only call them on explicit userintent, not during exploratory queries.@@ -252,6 +252,7 @@ intent, not during exploratory queries.| `accept_topic_suggestion` | Accept one pending suggestion: creates a topic and marks the suggestion added. | **yes** || `dismiss_topic_suggestion` | Dismiss one pending suggestion so it does not reappear in future batches. | **yes** || `get_prompt_volumes` | Per-prompt Google and estimated AI search demand and competition for prompts that already have analysis. | |+| `get_prompt_usage` | Tracked-prompt usage against the plan: the brand's active and paused prompts, and the account's active prompts, brands, prompt locations used and location limit. | |### Content opportunitiesdiff --git a/server/src/lib/prompt-usage-counters.js b/server/src/lib/prompt-usage-counters.jsnew file mode 100644index 000000000..1ea722693--- /dev/null+++ b/server/src/lib/prompt-usage-counters.js@@ -0,0 +1,27 @@+import supabaseAdmin from '../config/supabase.js';+import { logger } from './logger.js';++/**+ * Nightly consistency check for the Tracked Prompts usage counters+ * (PROMPT-012, 00139). Triggers rebuild a brand's row on every prompt write;+ * this recomputes every brand from `prompts`, rebuilds the rows that differ+ * and logs them, so a write path the triggers miss shows up instead of+ * leaving the usage cards wrong.+ *+ * Returns the drifted rows ({ brand_id, stored_*, actual_* }).+ */+export async function checkPromptUsageCounters(client = supabaseAdmin) {+ const { data, error } = await client.rpc('repair_prompt_usage_counters');+ if (error) throw new Error(error.message);++ const drifted = data ?? [];+ if (drifted.length > 0) {+ logger.warn(+ { drifted: drifted.length, rows: drifted.slice(0, 20) },+ '[prompt-usage] counters drifted from prompts and were rebuilt',+ );+ } else {+ logger.info('[prompt-usage] counters match prompts');+ }+ return drifted;+}diff --git a/server/src/lib/prompt-usage-counters.test.js b/server/src/lib/prompt-usage-counters.test.jsnew file mode 100644index 000000000..729dfaa6a--- /dev/null+++ b/server/src/lib/prompt-usage-counters.test.js@@ -0,0 +1,47 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+vi.mock('./logger.js', () => ({ default: logger, logger }));+vi.mock('../config/supabase.js', () => ({ default: {} }));++const { checkPromptUsageCounters } = await import('./prompt-usage-counters.js');++const client = (result) => ({ rpc: vi.fn(async () => result) });++beforeEach(() => {+ vi.clearAllMocks();+});++describe('checkPromptUsageCounters', () => {+ it('logs and returns the brands whose counters drifted', async () => {+ const row = {+ brand_id: 'b1',+ stored_active: 3,+ stored_paused: 0,+ stored_locations: 3,+ actual_active: 4,+ actual_paused: 0,+ actual_locations: 5,+ };+ const db = client({ data: [row], error: null });++ await expect(checkPromptUsageCounters(db)).resolves.toEqual([row]);+ expect(db.rpc).toHaveBeenCalledWith('repair_prompt_usage_counters');+ expect(logger.warn).toHaveBeenCalledWith(+ { drifted: 1, rows: [row] },+ expect.stringContaining('drifted'),+ );+ });++ it('says so when every counter matches', async () => {+ await expect(checkPromptUsageCounters(client({ data: [], error: null }))).resolves.toEqual([]);+ expect(logger.warn).not.toHaveBeenCalled();+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('match'));+ });++ it('fails loudly when the check itself fails', async () => {+ await expect(+ checkPromptUsageCounters(client({ data: null, error: { message: 'timeout' } })),+ ).rejects.toThrow('timeout');+ });+});diff --git a/server/src/server.js b/server/src/server.jsindex 9c2205105..5dd7942ec 100644--- a/server/src/server.js+++ b/server/src/server.js@@ -42,6 +42,7 @@ import { runPulseCatchUp } from './lib/pulse/engine.js';import { runSignalCatchUp } from './lib/signals/pass.js';import { sweepTaskExecution } from './lib/action-center/execution/run.js';import { sendHealthReport } from './lib/health/report.js';+import { checkPromptUsageCounters } from './lib/prompt-usage-counters.js';const app = express();app.set('trust proxy', 1);@@ -139,6 +140,12 @@ async function runDailyTracking() {logger.error({ err }, '[signals] catch-up sweep crashed');});+ // Check the Tracked Prompts usage counters against the prompts themselves+ // and rebuild any that drifted (PROMPT-012). Non-blocking, like the above.+ checkPromptUsageCounters().catch((err) => {+ logger.error({ err }, '[prompt-usage] counter check crashed');+ });+// Carry out the tasks the engine can carry out itself (#818 phase 7). Runs// after the catch-up above so tonight's actions exist before anything tries// to work on them. Bounded by a nightly ceiling; every attempt is recordeddiff --git a/supabase/migrations/00139_prompt_usage_counters.sql b/supabase/migrations/00139_prompt_usage_counters.sqlnew file mode 100644index 000000000..6ff775d03--- /dev/null+++ b/supabase/migrations/00139_prompt_usage_counters.sql@@ -0,0 +1,326 @@+-- Tracked Prompts usage counters (PROMPT-012).+--+-- The usage cards above the Tracked Prompts table show a brand's active and+-- paused prompts, and the account's active prompts, brands and active prompt+-- locations. Counting those from `prompts` on every page view is what the+-- spec rules out, so they're kept here, one row per brand, and the account+-- figures are the sum of the org's few brand rows.+--+-- A row is rebuilt from `prompts` by statement-level triggers, in the same+-- transaction as the change: a prompt added, paused, resumed, edited, moved+-- or deleted, and a prompt set deleted or moved to another brand. Rebuilding+-- the brand rather than adding deltas means a missed case can't leave a row+-- wrong for good, and a per-brand advisory lock taken before the rebuild+-- makes the last of two concurrent writers count both changes.+--+-- Locations follow org_prompt_location_usage (00128): an active prompt counts+-- greatest(array_length(regions), 1), a paused one counts none.+--+-- prompt_usage_actual() is the one place the counts are computed from+-- `prompts`; the rebuild, the backfill and the nightly check all read it.+-- repair_prompt_usage_counters() compares every row with it, rebuilds the rows+-- that differ and returns them; the server runs it nightly and logs drift.++-- The rebuild looks prompts up by brand; neither join had an index.+create index if not exists idx_prompts_prompt_set_id on public.prompts (prompt_set_id);+create index if not exists idx_prompt_sets_brand_id on public.prompt_sets (brand_id);++create table if not exists public.prompt_usage_counters (+ brand_id uuid primary key references public.brands(id) on delete cascade,+ organization_id uuid not null references public.organizations(id) on delete cascade,+ active_prompts integer not null default 0,+ paused_prompts integer not null default 0,+ active_locations integer not null default 0,+ updated_at timestamptz not null default now()+);++create index if not exists idx_prompt_usage_counters_org+ on public.prompt_usage_counters (organization_id);++alter table public.prompt_usage_counters enable row level security;++drop policy if exists "prompt_usage_counters: member select" on public.prompt_usage_counters;+create policy "prompt_usage_counters: member select" on public.prompt_usage_counters+ for select using (+ organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++grant select on table public.prompt_usage_counters to authenticated;+grant all on table public.prompt_usage_counters to service_role;++-- Each brand's counts as they are in `prompts` right now: all brands, or the+-- given ones. Brands without prompts come back with zeros.+create or replace function public.prompt_usage_actual(p_brand_ids uuid[] default null)+returns table (+ brand_id uuid,+ organization_id uuid,+ active_prompts integer,+ paused_prompts integer,+ active_locations integer+)+language sql+stable+set search_path = public+as $$+ select+ b.id,+ b.organization_id,+ count(p.id) filter (where p.is_active)::integer,+ count(p.id) filter (where not p.is_active)::integer,+ coalesce(+ sum(greatest(coalesce(array_length(p.regions, 1), 0), 1)) filter (where p.is_active),+ 0+ )::integer+ from public.brands b+ left join public.prompt_sets ps on ps.brand_id = b.id+ left join public.prompts p on p.prompt_set_id = ps.id+ where p_brand_ids is null or b.id = any(p_brand_ids)+ group by b.id, b.organization_id;+$$;++revoke all on function public.prompt_usage_actual(uuid[]) from public, anon, authenticated;+grant execute on function public.prompt_usage_actual(uuid[]) to service_role;++-- Rebuilds the counter rows of the given brands. Brands that no longer exist+-- (a brand deleted, its sets and prompts cascading) are skipped; their rows go+-- with them.+create or replace function public.refresh_prompt_usage_counters(p_brand_ids uuid[])+returns void+language plpgsql+security definer+set search_path = public+as $$+declare+ v_brand uuid;+begin+ -- Sorted, so two writers locking the same brands can't deadlock.+ for v_brand in+ select distinct id from unnest(p_brand_ids) as t(id) where id is not null order by id+ loop+ perform pg_advisory_xact_lock(hashtext('prompt_usage_counters:' || v_brand::text));++ -- A new statement after the lock, so it counts what a writer we waited+ -- for has committed.+ insert into public.prompt_usage_counters as c (+ brand_id, organization_id, active_prompts, paused_prompts, active_locations, updated_at+ )+ select a.brand_id, a.organization_id, a.active_prompts, a.paused_prompts, a.active_locations, now()+ from public.prompt_usage_actual(array[v_brand]) a+ on conflict (brand_id) do update set+ organization_id = excluded.organization_id,+ active_prompts = excluded.active_prompts,+ paused_prompts = excluded.paused_prompts,+ active_locations = excluded.active_locations,+ updated_at = excluded.updated_at;+ end loop;+end;+$$;++revoke all on function public.refresh_prompt_usage_counters(uuid[]) from public, anon, authenticated;+grant execute on function public.refresh_prompt_usage_counters(uuid[]) to service_role;++-- Statement-level, so a bulk import or a plan alignment that writes hundreds+-- of prompts in one statement rebuilds each brand once. Prompts whose set is+-- already gone (a set deleted, its prompts cascading) resolve to no brand; the+-- prompt_sets trigger below rebuilds that brand instead.+create or replace function public.prompts_refresh_usage_counters()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ v_brands uuid[];+begin+ if tg_op = 'INSERT' then+ select array_agg(distinct ps.brand_id) into v_brands+ from new_rows r join public.prompt_sets ps on ps.id = r.prompt_set_id;+ elsif tg_op = 'DELETE' then+ select array_agg(distinct ps.brand_id) into v_brands+ from old_rows r join public.prompt_sets ps on ps.id = r.prompt_set_id;+ else+ select array_agg(distinct ps.brand_id) into v_brands+ from (+ select prompt_set_id from new_rows+ union+ select prompt_set_id from old_rows+ ) r+ join public.prompt_sets ps on ps.id = r.prompt_set_id;+ end if;++ if v_brands is not null then+ perform public.refresh_prompt_usage_counters(v_brands);+ end if;+ return null;+end;+$$;++drop trigger if exists trg_prompts_usage_counters_insert on public.prompts;+create trigger trg_prompts_usage_counters_insert+ after insert on public.prompts+ referencing new table as new_rows+ for each statement execute function public.prompts_refresh_usage_counters();++drop trigger if exists trg_prompts_usage_counters_update on public.prompts;+create trigger trg_prompts_usage_counters_update+ after update on public.prompts+ referencing old table as old_rows new table as new_rows+ for each statement execute function public.prompts_refresh_usage_counters();++drop trigger if exists trg_prompts_usage_counters_delete on public.prompts;+create trigger trg_prompts_usage_counters_delete+ after delete on public.prompts+ referencing old table as old_rows+ for each statement execute function public.prompts_refresh_usage_counters();++-- A prompt set deleted (its prompts cascading first) or moved to another+-- brand: rebuild the brands it left and joined.+create or replace function public.prompt_sets_refresh_usage_counters()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ v_brands uuid[];+begin+ if tg_op = 'DELETE' then+ select array_agg(distinct brand_id) into v_brands from old_rows;+ else+ select array_agg(distinct brand_id) into v_brands+ from (+ select brand_id from new_rows+ union+ select brand_id from old_rows+ ) r;+ end if;++ if v_brands is not null then+ perform public.refresh_prompt_usage_counters(v_brands);+ end if;+ return null;+end;+$$;++drop trigger if exists trg_prompt_sets_usage_counters_update on public.prompt_sets;+create trigger trg_prompt_sets_usage_counters_update+ after update on public.prompt_sets+ referencing old table as old_rows new table as new_rows+ for each statement execute function public.prompt_sets_refresh_usage_counters();++drop trigger if exists trg_prompt_sets_usage_counters_delete on public.prompt_sets;+create trigger trg_prompt_sets_usage_counters_delete+ after delete on public.prompt_sets+ referencing old table as old_rows+ for each statement execute function public.prompt_sets_refresh_usage_counters();++-- What the usage cards read: one brand's counts plus its account's totals,+-- from the counter rows alone. Security invoker, so RLS returns no row for a+-- brand outside the caller's org.+create or replace function public.prompt_usage_summary(p_brand_id uuid)+returns table (+ brand_active integer,+ brand_paused integer,+ account_active integer,+ account_brands integer,+ account_locations integer+)+language sql+stable+set search_path = public+as $$+ select+ coalesce(bc.active_prompts, 0),+ coalesce(bc.paused_prompts, 0),+ coalesce(acct.active_prompts, 0)::integer,+ (select count(*) from public.brands b2 where b2.organization_id = b.organization_id)::integer,+ coalesce(acct.active_locations, 0)::integer+ from public.brands b+ left join public.prompt_usage_counters bc on bc.brand_id = b.id+ left join lateral (+ select sum(c.active_prompts) as active_prompts, sum(c.active_locations) as active_locations+ from public.prompt_usage_counters c+ where c.organization_id = b.organization_id+ ) acct on true+ where b.id = p_brand_id;+$$;++revoke all on function public.prompt_usage_summary(uuid) from public, anon;+grant execute on function public.prompt_usage_summary(uuid) to authenticated, service_role;++-- The nightly consistency check: compare every row with prompt_usage_actual(),+-- return the ones that differ (stored and actual counts) for the log, and+-- rebuild them. A brand moved to another organization counts as drift too. A+-- brand with no prompts and no row yet isn't drift.+create or replace function public.repair_prompt_usage_counters()+returns table (+ brand_id uuid,+ stored_active integer,+ stored_paused integer,+ stored_locations integer,+ actual_active integer,+ actual_paused integer,+ actual_locations integer+)+language plpgsql+security definer+set search_path = public+as $$+#variable_conflict use_column+declare+ v_ids uuid[] := '{}';+ r record;+begin+ for r in+ select+ a.brand_id as id,+ coalesce(c.active_prompts, 0) as s_active,+ coalesce(c.paused_prompts, 0) as s_paused,+ coalesce(c.active_locations, 0) as s_locations,+ a.active_prompts as a_active,+ a.paused_prompts as a_paused,+ a.active_locations as a_locations+ from public.prompt_usage_actual() a+ left join public.prompt_usage_counters c on c.brand_id = a.brand_id+ where coalesce(c.active_prompts, 0) <> a.active_prompts+ or coalesce(c.paused_prompts, 0) <> a.paused_prompts+ or coalesce(c.active_locations, 0) <> a.active_locations+ or (c.brand_id is not null and c.organization_id <> a.organization_id)+ loop+ brand_id := r.id;+ stored_active := r.s_active;+ stored_paused := r.s_paused;+ stored_locations := r.s_locations;+ actual_active := r.a_active;+ actual_paused := r.a_paused;+ actual_locations := r.a_locations;+ v_ids := v_ids || r.id;+ return next;+ end loop;++ if cardinality(v_ids) > 0 then+ perform public.refresh_prompt_usage_counters(v_ids);+ end if;+end;+$$;++revoke all on function public.repair_prompt_usage_counters() from public, anon, authenticated;+grant execute on function public.repair_prompt_usage_counters() to service_role;++-- Every existing brand starts with its current counts. One statement and no+-- advisory locks (one per brand could exhaust the lock table on a large+-- database): the CREATE TRIGGERs above already hold off writes to prompts and+-- prompt_sets until this migration commits.+insert into public.prompt_usage_counters (+ brand_id, organization_id, active_prompts, paused_prompts, active_locations+)+select brand_id, organization_id, active_prompts, paused_prompts, active_locations+from public.prompt_usage_actual()+on conflict (brand_id) do nothing;++comment on table public.prompt_usage_counters is+ 'Per-brand prompt counts for the Tracked Prompts usage cards (PROMPT-012, 00139): active, paused and active prompt locations. Rebuilt by triggers on prompts and prompt_sets; repair_prompt_usage_counters() checks them nightly.';+comment on function public.prompt_usage_summary(uuid) is+ 'One brand''s active/paused prompts and its account''s active prompts, brands and active prompt locations, from prompt_usage_counters only (PROMPT-012). Security invoker.';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 8b3c0216b..f58e5e7a5 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -17095,6 +17095,336 @@ grant execute on function public.reserve_suggestion_relevance(uuid, uuid, text,comment on function public.reserve_suggestion_relevance(uuid, uuid, text, timestamptz, numeric, numeric) is'Atomically reserves a suggestion refresh''s worst-case relevance cost against the organization''s monthly allowance (VIS-011). Returns the suggestion_relevance_usage id, or null when it does not fit.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00139_prompt_usage_counters.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Tracked Prompts usage counters (PROMPT-012).+--+-- The usage cards above the Tracked Prompts table show a brand's active and+-- paused prompts, and the account's active prompts, brands and active prompt+-- locations. Counting those from `prompts` on every page view is what the+-- spec rules out, so they're kept here, one row per brand, and the account+-- figures are the sum of the org's few brand rows.+--+-- A row is rebuilt from `prompts` by statement-level triggers, in the same+-- transaction as the change: a prompt added, paused, resumed, edited, moved+-- or deleted, and a prompt set deleted or moved to another brand. Rebuilding+-- the brand rather than adding deltas means a missed case can't leave a row+-- wrong for good, and a per-brand advisory lock taken before the rebuild+-- makes the last of two concurrent writers count both changes.+--+-- Locations follow org_prompt_location_usage (00128): an active prompt counts+-- greatest(array_length(regions), 1), a paused one counts none.+--+-- prompt_usage_actual() is the one place the counts are computed from+-- `prompts`; the rebuild, the backfill and the nightly check all read it.+-- repair_prompt_usage_counters() compares every row with it, rebuilds the rows+-- that differ and returns them; the server runs it nightly and logs drift.++-- The rebuild looks prompts up by brand; neither join had an index.+create index if not exists idx_prompts_prompt_set_id on public.prompts (prompt_set_id);+create index if not exists idx_prompt_sets_brand_id on public.prompt_sets (brand_id);++create table if not exists public.prompt_usage_counters (+ brand_id uuid primary key references public.brands(id) on delete cascade,+ organization_id uuid not null references public.organizations(id) on delete cascade,+ active_prompts integer not null default 0,+ paused_prompts integer not null default 0,+ active_locations integer not null default 0,+ updated_at timestamptz not null default now()+);++create index if not exists idx_prompt_usage_counters_org+ on public.prompt_usage_counters (organization_id);++alter table public.prompt_usage_counters enable row level security;++drop policy if exists "prompt_usage_counters: member select" on public.prompt_usage_counters;+create policy "prompt_usage_counters: member select" on public.prompt_usage_counters+ for select using (+ organization_id in (+ select p.organization_id from public.profiles p where p.id = auth.uid()+ )+ );++grant select on table public.prompt_usage_counters to authenticated;+grant all on table public.prompt_usage_counters to service_role;++-- Each brand's counts as they are in `prompts` right now: all brands, or the+-- given ones. Brands without prompts come back with zeros.+create or replace function public.prompt_usage_actual(p_brand_ids uuid[] default null)+returns table (+ brand_id uuid,+ organization_id uuid,+ active_prompts integer,+ paused_prompts integer,+ active_locations integer+)+language sql+stable+set search_path = public+as $$+ select+ b.id,+ b.organization_id,+ count(p.id) filter (where p.is_active)::integer,+ count(p.id) filter (where not p.is_active)::integer,+ coalesce(+ sum(greatest(coalesce(array_length(p.regions, 1), 0), 1)) filter (where p.is_active),+ 0+ )::integer+ from public.brands b+ left join public.prompt_sets ps on ps.brand_id = b.id+ left join public.prompts p on p.prompt_set_id = ps.id+ where p_brand_ids is null or b.id = any(p_brand_ids)+ group by b.id, b.organization_id;+$$;++revoke all on function public.prompt_usage_actual(uuid[]) from public, anon, authenticated;+grant execute on function public.prompt_usage_actual(uuid[]) to service_role;++-- Rebuilds the counter rows of the given brands. Brands that no longer exist+-- (a brand deleted, its sets and prompts cascading) are skipped; their rows go+-- with them.+create or replace function public.refresh_prompt_usage_counters(p_brand_ids uuid[])+returns void+language plpgsql+security definer+set search_path = public+as $$+declare+ v_brand uuid;+begin+ -- Sorted, so two writers locking the same brands can't deadlock.+ for v_brand in+ select distinct id from unnest(p_brand_ids) as t(id) where id is not null order by id+ loop+ perform pg_advisory_xact_lock(hashtext('prompt_usage_counters:' || v_brand::text));++ -- A new statement after the lock, so it counts what a writer we waited+ -- for has committed.+ insert into public.prompt_usage_counters as c (+ brand_id, organization_id, active_prompts, paused_prompts, active_locations, updated_at+ )+ select a.brand_id, a.organization_id, a.active_prompts, a.paused_prompts, a.active_locations, now()+ from public.prompt_usage_actual(array[v_brand]) a+ on conflict (brand_id) do update set+ organization_id = excluded.organization_id,+ active_prompts = excluded.active_prompts,+ paused_prompts = excluded.paused_prompts,+ active_locations = excluded.active_locations,+ updated_at = excluded.updated_at;+ end loop;+end;+$$;++revoke all on function public.refresh_prompt_usage_counters(uuid[]) from public, anon, authenticated;+grant execute on function public.refresh_prompt_usage_counters(uuid[]) to service_role;++-- Statement-level, so a bulk import or a plan alignment that writes hundreds+-- of prompts in one statement rebuilds each brand once. Prompts whose set is+-- already gone (a set deleted, its prompts cascading) resolve to no brand; the+-- prompt_sets trigger below rebuilds that brand instead.+create or replace function public.prompts_refresh_usage_counters()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ v_brands uuid[];+begin+ if tg_op = 'INSERT' then+ select array_agg(distinct ps.brand_id) into v_brands+ from new_rows r join public.prompt_sets ps on ps.id = r.prompt_set_id;+ elsif tg_op = 'DELETE' then+ select array_agg(distinct ps.brand_id) into v_brands+ from old_rows r join public.prompt_sets ps on ps.id = r.prompt_set_id;+ else+ select array_agg(distinct ps.brand_id) into v_brands+ from (+ select prompt_set_id from new_rows+ union+ select prompt_set_id from old_rows+ ) r+ join public.prompt_sets ps on ps.id = r.prompt_set_id;+ end if;++ if v_brands is not null then+ perform public.refresh_prompt_usage_counters(v_brands);+ end if;+ return null;+end;+$$;++drop trigger if exists trg_prompts_usage_counters_insert on public.prompts;+create trigger trg_prompts_usage_counters_insert+ after insert on public.prompts+ referencing new table as new_rows+ for each statement execute function public.prompts_refresh_usage_counters();++drop trigger if exists trg_prompts_usage_counters_update on public.prompts;+create trigger trg_prompts_usage_counters_update+ after update on public.prompts+ referencing old table as old_rows new table as new_rows+ for each statement execute function public.prompts_refresh_usage_counters();++drop trigger if exists trg_prompts_usage_counters_delete on public.prompts;+create trigger trg_prompts_usage_counters_delete+ after delete on public.prompts+ referencing old table as old_rows+ for each statement execute function public.prompts_refresh_usage_counters();++-- A prompt set deleted (its prompts cascading first) or moved to another+-- brand: rebuild the brands it left and joined.+create or replace function public.prompt_sets_refresh_usage_counters()+returns trigger+language plpgsql+security definer+set search_path = public+as $$+declare+ v_brands uuid[];+begin+ if tg_op = 'DELETE' then+ select array_agg(distinct brand_id) into v_brands from old_rows;+ else+ select array_agg(distinct brand_id) into v_brands+ from (+ select brand_id from new_rows+ union+ select brand_id from old_rows+ ) r;+ end if;++ if v_brands is not null then+ perform public.refresh_prompt_usage_counters(v_brands);+ end if;+ return null;+end;+$$;++drop trigger if exists trg_prompt_sets_usage_counters_update on public.prompt_sets;+create trigger trg_prompt_sets_usage_counters_update+ after update on public.prompt_sets+ referencing old table as old_rows new table as new_rows+ for each statement execute function public.prompt_sets_refresh_usage_counters();++drop trigger if exists trg_prompt_sets_usage_counters_delete on public.prompt_sets;+create trigger trg_prompt_sets_usage_counters_delete+ after delete on public.prompt_sets+ referencing old table as old_rows+ for each statement execute function public.prompt_sets_refresh_usage_counters();++-- What the usage cards read: one brand's counts plus its account's totals,+-- from the counter rows alone. Security invoker, so RLS returns no row for a+-- brand outside the caller's org.+create or replace function public.prompt_usage_summary(p_brand_id uuid)+returns table (+ brand_active integer,+ brand_paused integer,+ account_active integer,+ account_brands integer,+ account_locations integer+)+language sql+stable+set search_path = public+as $$+ select+ coalesce(bc.active_prompts, 0),+ coalesce(bc.paused_prompts, 0),+ coalesce(acct.active_prompts, 0)::integer,+ (select count(*) from public.brands b2 where b2.organization_id = b.organization_id)::integer,+ coalesce(acct.active_locations, 0)::integer+ from public.brands b+ left join public.prompt_usage_counters bc on bc.brand_id = b.id+ left join lateral (+ select sum(c.active_prompts) as active_prompts, sum(c.active_locations) as active_locations+ from public.prompt_usage_counters c+ where c.organization_id = b.organization_id+ ) acct on true+ where b.id = p_brand_id;+$$;++revoke all on function public.prompt_usage_summary(uuid) from public, anon;+grant execute on function public.prompt_usage_summary(uuid) to authenticated, service_role;++-- The nightly consistency check: compare every row with prompt_usage_actual(),+-- return the ones that differ (stored and actual counts) for the log, and+-- rebuild them. A brand moved to another organization counts as drift too. A+-- brand with no prompts and no row yet isn't drift.+create or replace function public.repair_prompt_usage_counters()+returns table (+ brand_id uuid,+ stored_active integer,+ stored_paused integer,+ stored_locations integer,+ actual_active integer,+ actual_paused integer,+ actual_locations integer+)+language plpgsql+security definer+set search_path = public+as $$+#variable_conflict use_column+declare+ v_ids uuid[] := '{}';+ r record;+begin+ for r in+ select+ a.brand_id as id,+ coalesce(c.active_prompts, 0) as s_active,+ coalesce(c.paused_prompts, 0) as s_paused,+ coalesce(c.active_locations, 0) as s_locations,+ a.active_prompts as a_active,+ a.paused_prompts as a_paused,+ a.active_locations as a_locations+ from public.prompt_usage_actual() a+ left join public.prompt_usage_counters c on c.brand_id = a.brand_id+ where coalesce(c.active_prompts, 0) <> a.active_prompts+ or coalesce(c.paused_prompts, 0) <> a.paused_prompts+ or coalesce(c.active_locations, 0) <> a.active_locations+ or (c.brand_id is not null and c.organization_id <> a.organization_id)+ loop+ brand_id := r.id;+ stored_active := r.s_active;+ stored_paused := r.s_paused;+ stored_locations := r.s_locations;+ actual_active := r.a_active;+ actual_paused := r.a_paused;+ actual_locations := r.a_locations;+ v_ids := v_ids || r.id;+ return next;+ end loop;++ if cardinality(v_ids) > 0 then+ perform public.refresh_prompt_usage_counters(v_ids);+ end if;+end;+$$;++revoke all on function public.repair_prompt_usage_counters() from public, anon, authenticated;+grant execute on function public.repair_prompt_usage_counters() to service_role;++-- Every existing brand starts with its current counts. One statement and no+-- advisory locks (one per brand could exhaust the lock table on a large+-- database): the CREATE TRIGGERs above already hold off writes to prompts and+-- prompt_sets until this migration commits.+insert into public.prompt_usage_counters (+ brand_id, organization_id, active_prompts, paused_prompts, active_locations+)+select brand_id, organization_id, active_prompts, paused_prompts, active_locations+from public.prompt_usage_actual()+on conflict (brand_id) do nothing;++comment on table public.prompt_usage_counters is+ 'Per-brand prompt counts for the Tracked Prompts usage cards (PROMPT-012, 00139): active, paused and active prompt locations. Rebuilt by triggers on prompts and prompt_sets; repair_prompt_usage_counters() checks them nightly.';+comment on function public.prompt_usage_summary(uuid) is+ 'One brand''s active/paused prompts and its account''s active prompts, brands and active prompt locations, from prompt_usage_counters only (PROMPT-012). Security invoker.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00147_insights_same_prompts_definer.sql-- ─────────────────────────────────────────────────────────────────────────diff --git a/web/src/app/api/mcp/prompt-usage/route.ts b/web/src/app/api/mcp/prompt-usage/route.tsnew file mode 100644index 000000000..97b08abf4--- /dev/null+++ b/web/src/app/api/mcp/prompt-usage/route.ts@@ -0,0 +1,31 @@+import { NextResponse } from 'next/server';+import { authenticateMcpRequest } from '@/lib/mcp-auth';+import { getPromptUsageFor } from '@/lib/mcp/data';++/**+ * GET /api/mcp/prompt-usage?brand_id=…+ *+ * Parallel REST surface for the `get_prompt_usage` MCP tool — the Tracked+ * Prompts usage cards (PROMPT-012): the brand's active and paused prompts, the+ * account's active prompts, brands and prompt locations, and the plan limit.+ */+export async function GET(req: Request) {+ const auth = await authenticateMcpRequest(req);+ if (auth instanceof NextResponse) return auth;++ const brandId = new URL(req.url).searchParams.get('brand_id');+ if (!brandId) {+ return NextResponse.json({ error: 'brand_id is required' }, { status: 400 });+ }++ try {+ const usage = await getPromptUsageFor(auth, brandId);+ if (!usage) {+ return NextResponse.json({ error: 'Brand not found' }, { status: 404 });+ }+ return NextResponse.json(usage);+ } catch (err) {+ const message = err instanceof Error ? err.message : 'Failed';+ return NextResponse.json({ error: message }, { status: 500 });+ }+}diff --git a/web/src/app/api/prompts/usage/route.test.ts b/web/src/app/api/prompts/usage/route.test.tsnew file mode 100644index 000000000..3174dba6b--- /dev/null+++ b/web/src/app/api/prompts/usage/route.test.ts@@ -0,0 +1,123 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * GET /api/prompts/usage (PROMPT-012): who may read a brand's usage, and the+ * plan the cards are measured against — the organization's own, read with the+ * brand in the same round trip as the counts.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';++let user: { id: string } | null;+let brand: { data: unknown; error: { message: string } | null };+let usage: { data: unknown; error: { message: string } | null };+const rpc = vi.fn(async () => usage);++vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getUser: async () => ({ data: { user } }) },+ from: () => ({+ select: () => ({ eq: () => ({ maybeSingle: async () => brand }) }),+ }),+ rpc,+ }),+}));++const { GET } = await import('./route');++const get = (query: string) => GET(new Request(`http://localhost/api/prompts/usage${query}`));++const counts = {+ brand_active: 46,+ brand_paused: 2,+ account_active: 46,+ account_brands: 1,+ account_locations: 46,+};++beforeEach(() => {+ vi.clearAllMocks();+ user = { id: 'u1' };+ brand = {+ data: {+ organization_id: 'org1',+ organizations: { plan: 'starter', subscription_status: 'active', plan_overrides: null },+ },+ error: null,+ };+ usage = { data: [counts], error: null };+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('GET /api/prompts/usage', () => {+ it("returns the brand's counts against its organization's plan", async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');++ const res = await get(`?brandId=${BRAND}`);++ expect(res.status).toBe(200);+ expect(res.headers.get('Cache-Control')).toBe('private, no-store');+ expect(await res.json()).toMatchObject({+ plan: { key: 'starter', name: 'Starter plan', locationLimit: 50, cta: 'upgrade_growth' },+ brand: { active: 46, paused: 2, total: 48 },+ account: { activePrompts: 46, brands: 1, locationsUsed: 46 },+ });+ expect(rpc).toHaveBeenCalledWith('prompt_usage_summary', { p_brand_id: BRAND });+ });++ it('measures an Enterprise account against the limit set for it', async () => {+ vi.stubEnv('NEXT_PUBLIC_IS_CLOUD', 'true');+ brand.data = {+ organization_id: 'org1',+ organizations: {+ plan: 'enterprise',+ subscription_status: 'active',+ plan_overrides: { maxPrompts: 1000 },+ },+ };++ const body = await (await get(`?brandId=${BRAND}`)).json();++ expect(body.plan).toEqual({+ key: 'enterprise',+ name: 'Enterprise plan',+ locationLimit: 1000,+ cta: 'contact',+ });+ });++ it('is unlimited on a self-hosted install', async () => {+ const body = await (await get(`?brandId=${BRAND}`)).json();+ expect(body.plan).toEqual({+ key: 'self_hosted',+ name: 'Self-Hosted plan',+ locationLimit: null,+ cta: null,+ });+ });++ it('rejects a missing or malformed brand id', async () => {+ expect((await get('')).status).toBe(400);+ expect((await get('?brandId=nope')).status).toBe(400);+ });++ it('needs a signed-in user', async () => {+ user = null;+ expect((await get(`?brandId=${BRAND}`)).status).toBe(401);+ });++ it("is not found for a brand outside the caller's organization", async () => {+ brand = { data: null, error: null };+ usage = { data: [], error: null };+ expect((await get(`?brandId=${BRAND}`)).status).toBe(404);+ });++ it('reports a database failure as an error, not as a missing brand', async () => {+ brand = { data: null, error: { message: 'statement timeout' } };+ vi.spyOn(console, 'error').mockImplementation(() => {});+ expect((await get(`?brandId=${BRAND}`)).status).toBe(500);+ });+});diff --git a/web/src/app/api/prompts/usage/route.ts b/web/src/app/api/prompts/usage/route.tsnew file mode 100644index 000000000..5cc625ae0--- /dev/null+++ b/web/src/app/api/prompts/usage/route.ts@@ -0,0 +1,63 @@+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 { fetchPromptUsageRow, toPromptUsageSummary } from '@/lib/prompt-usage-summary';++/**+ * GET /api/prompts/usage?brandId=…+ *+ * The Tracked Prompts usage cards (PROMPT-012): the brand's active and paused+ * prompts, the account's active prompts, brands and active prompt locations,+ * and the plan's limit. A route rather than a server action, so the page can+ * fire it alongside its table load: Next.js runs a client's server actions+ * one at a time, and this request must never hold the table up.+ *+ * Not cached: the counters are rebuilt on every prompt write, and the cards+ * refresh right after the user's own changes.+ */+// Any 8-4-4-4-12 hex id, like the MCP server's relaxedUuid: zod 4's uuid()+// rejects ids without a version digit, such as the seeded demo brands'.+const query = z.object({+ brandId: z+ .string()+ .regex(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/),+});++export async function GET(req: Request) {+ const parsed = query.safeParse(Object.fromEntries(new URL(req.url).searchParams));+ if (!parsed.success) {+ return NextResponse.json({ error: 'brandId must be a brand id' }, { status: 400 });+ }+ const { brandId } = parsed.data;++ const supabase = await createClient();+ const {+ data: { user },+ } = await supabase.auth.getUser();+ if (!user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });++ try {+ // The brand with its organization's plan columns, and the counts, in one+ // round trip. RLS: only a brand of the caller's own organization comes+ // back, and the RPC returns no row for any other.+ const [{ data: brand, error: brandError }, row] = await Promise.all([+ supabase+ .from('brands')+ .select(`organization_id, organizations(${ORG_PLAN_COLUMNS})`)+ .eq('id', brandId)+ .maybeSingle(),+ fetchPromptUsageRow(supabase, brandId),+ ]);+ 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), {+ headers: { 'Cache-Control': 'private, no-store' },+ });+ } catch (err) {+ console.error('[prompts/usage]', err);+ return NextResponse.json({ error: 'Internal error' }, { status: 500 });+ }+}diff --git a/web/src/lib/guards/plan-guard.ts b/web/src/lib/guards/plan-guard.tsindex 52082119b..f1e765f85 100644--- a/web/src/lib/guards/plan-guard.ts+++ b/web/src/lib/guards/plan-guard.ts@@ -20,14 +20,30 @@ export async function getOrgPlan(organizationId: string): Promise<Plan> {.eq('id', organizationId).single();+ return planFromOrgRow(data);+}++/** The organization columns {@link planFromOrgRow} reads. */+export const ORG_PLAN_COLUMNS = 'plan, subscription_status, plan_overrides';++/**+ * The plan an organization row is entitled to, for callers that read the row+ * themselves (the MCP server has no user session, so it reads with the+ * service role).+ */+export function planFromOrgRow(+ data: { plan?: unknown; subscription_status?: unknown; plan_overrides?: unknown } | null,+): Plan {+ if (!isCloud()) return getPlan('self_hosted');+// `trialing` is a paid plan in its trial window — treat it as active so// trial customers get their actual plan's limits (seats, brands, prompts…)// instead of being silently dropped to starter.- if (!isSubscriptionActive(data?.subscription_status)) {+ if (!isSubscriptionActive(data?.subscription_status as string | null | undefined)) {return getPlan('starter');}- const plan = getPlan(data?.plan);+ const plan = getPlan(data?.plan as string | null | undefined);// Enterprise orgs can have custom limit overridesif (data?.plan === 'enterprise' && data.plan_overrides) {diff --git a/web/src/lib/mcp/data.ts b/web/src/lib/mcp/data.tsindex 645a570f4..dfe507a50 100644--- a/web/src/lib/mcp/data.ts+++ b/web/src/lib/mcp/data.ts@@ -12,6 +12,12 @@ import { classifyArticleType } from '@/lib/citations/article-type';import { expandDateToEndOfDay } from '@/lib/dates';import { computeAiVisibilityScore } from '@/lib/visibility-score';import { API_BASE_URL } from '@/config/api';+import { ORG_PLAN_COLUMNS, planFromOrgRow } from '@/lib/guards/plan-guard';+import {+ fetchPromptUsageRow,+ toPromptUsageSummary,+ type PromptUsageSummary,+} from '@/lib/prompt-usage-summary';/*** Pure data-fetch functions shared by the MCP route and the parallel REST@@ -866,6 +872,31 @@ export async function getSiteAuditQuotaFor(auth: McpAuthContext): Promise<SiteAureturn body.quota;}+/**+ * The Tracked Prompts usage cards for a brand (PROMPT-012), so the Agent Chat+ * can answer "how many prompt slots do we have left?" with the page's own+ * numbers: prompt_usage_counters for the counts, the organization's effective+ * plan (Enterprise overrides merged) for the limit.+ */+export async function getPromptUsageFor(+ auth: McpAuthContext,+ brandId: string,+): Promise<PromptUsageSummary | null> {+ if (!auth.organizationId || !(await brandInOrg(auth, brandId))) return null;++ const [{ data: org, error: orgError }, row] = await Promise.all([+ supabaseAdmin+ .from('organizations')+ .select(ORG_PLAN_COLUMNS)+ .eq('id', auth.organizationId)+ .maybeSingle(),+ fetchPromptUsageRow(supabaseAdmin, brandId),+ ]);+ if (orgError) throw new Error(orgError.message);+ if (!row) return null;+ return toPromptUsageSummary(row, planFromOrgRow(org));+}+/*** Start a Site Audit for a brand + URL via MCP.*diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.tsindex 30fbc5668..2c82ebc80 100644--- a/web/src/lib/mcp/server.ts+++ b/web/src/lib/mcp/server.ts@@ -27,6 +27,7 @@ import {getSiteAuditFor,listSiteAuditsFor,getSiteAuditQuotaFor,+ getPromptUsageFor,MCP_TASK_STATUSES,getActionFor,listActionHistoryFor,@@ -455,6 +456,35 @@ export function createMcpServer(auth: McpAuthContext): McpServer {},);+ server.registerTool(+ 'get_prompt_usage',+ {+ 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 }, ' ++ '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.',+ inputSchema: {+ brand_id: relaxedUuid.describe('Brand UUID, from list_brands.'),+ },+ },+ async (args) => {+ const usage = await getPromptUsageFor(auth, args.brand_id);+ if (!usage) {+ return {+ content: [{ type: 'text', text: 'Brand not found' }],+ isError: true,+ };+ }+ return {+ content: [{ type: 'text', text: JSON.stringify(usage, null, 2) }],+ };+ },+ );+server.registerTool('update_opportunity_status',{diff --git a/web/src/lib/prompt-usage-summary.test.ts b/web/src/lib/prompt-usage-summary.test.tsnew file mode 100644index 000000000..d22c04f0a--- /dev/null+++ b/web/src/lib/prompt-usage-summary.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it, vi } from 'vitest';+import { PLANS, type Plan } from '@/config/plans';+import { fetchPromptUsageRow, toPromptUsageSummary, usagePlan } from './prompt-usage-summary';++const withLimit = (plan: Plan, maxPrompts: number): Plan => ({+ ...plan,+ limits: { ...plan.limits, maxPrompts },+});++describe('usagePlan', () => {+ it('names each plan with its limit and where the Slots left card points', () => {+ expect(usagePlan(PLANS.starter)).toEqual({+ key: 'starter',+ name: 'Starter plan',+ locationLimit: 50,+ cta: 'upgrade_growth',+ });+ expect(usagePlan(PLANS.growth)).toEqual({+ key: 'growth',+ name: 'Growth plan',+ locationLimit: 200,+ cta: 'upgrade',+ });+ });++ it('shows the limit Ansvisor set for an Enterprise customer, and asks them to contact us', () => {+ expect(usagePlan(withLimit(PLANS.enterprise, 1000))).toEqual({+ key: 'enterprise',+ name: 'Enterprise plan',+ locationLimit: 1000,+ cta: 'contact',+ });+ });++ it('reports no limit, rather than -1, while none is set', () => {+ expect(usagePlan(PLANS.enterprise).locationLimit).toBeNull();+ expect(usagePlan(PLANS.self_hosted)).toEqual({+ key: 'self_hosted',+ name: 'Self-Hosted plan',+ locationLimit: null,+ cta: null,+ });+ });+});++describe('toPromptUsageSummary', () => {+ it('shapes the counters row as the usage cards read it', () => {+ const now = new Date('2026-10-15T09:12:00Z');+ const summary = toPromptUsageSummary(+ {+ brand_active: 702,+ brand_paused: 7,+ account_active: 1248,+ account_brands: 3,+ account_locations: 781,+ },+ withLimit(PLANS.enterprise, 1000),+ now,+ );++ expect(summary).toEqual({+ plan: { key: 'enterprise', name: 'Enterprise plan', locationLimit: 1000, cta: 'contact' },+ brand: { active: 702, paused: 7, total: 709 },+ account: { activePrompts: 1248, brands: 3, locationsUsed: 781 },+ updatedAt: '2026-10-15T09:12:00.000Z',+ });+ });+});++describe('fetchPromptUsageRow', () => {+ it("reads the brand's row from the counters RPC", async () => {+ const row = {+ brand_active: 1,+ brand_paused: 0,+ account_active: 1,+ account_brands: 1,+ account_locations: 2,+ };+ const rpc = vi.fn(async () => ({ data: [row], error: null }));++ await expect(fetchPromptUsageRow({ rpc } as never, 'b1')).resolves.toEqual(row);+ expect(rpc).toHaveBeenCalledWith('prompt_usage_summary', { p_brand_id: 'b1' });+ });++ it('is null for a brand the caller cannot see', async () => {+ const rpc = vi.fn(async () => ({ data: [], error: null }));+ await expect(fetchPromptUsageRow({ rpc } as never, 'b2')).resolves.toBeNull();+ });++ it('throws when the RPC fails', async () => {+ const rpc = vi.fn(async () => ({ data: null, error: { message: 'boom' } }));+ await expect(fetchPromptUsageRow({ rpc } as never, 'b1')).rejects.toThrow('boom');+ });+});diff --git a/web/src/lib/prompt-usage-summary.ts b/web/src/lib/prompt-usage-summary.tsnew file mode 100644index 000000000..902760d7b--- /dev/null+++ b/web/src/lib/prompt-usage-summary.ts@@ -0,0 +1,94 @@+import type { SupabaseClient } from '@supabase/supabase-js';+import type { Plan, PlanId } from '@/config/plans';+import type { Database } from '@/types/supabase';++/**+ * The Tracked Prompts usage cards (PROMPT-012): a brand's active and paused+ * prompts, and its account's active prompts, brands and active prompt+ * locations against the plan's limit. The counts come from the+ * prompt_usage_counters rows (00139), kept current by triggers on every+ * prompt write, so a page view never counts `prompts` itself.+ */++/** Where the Slots left card sends the user: billing to upgrade, or sales. */+export type PromptUsageCta = 'upgrade_growth' | 'upgrade' | 'contact';++export interface PromptUsageSummary {+ plan: {+ key: PlanId;+ /** "Starter plan", "Enterprise plan"… */+ name: string;+ /** Active prompt locations the plan allows; null = unlimited. */+ locationLimit: number | null;+ /** null on self-hosted, where there is no plan to change. */+ cta: PromptUsageCta | null;+ };+ brand: { active: number; paused: number; total: number };+ account: { activePrompts: number; brands: number; locationsUsed: number };+ /** When the counts were read. */+ updatedAt: string;+}++const PLAN_CTA: Record<PlanId, PromptUsageCta | null> = {+ self_hosted: null,+ starter: 'upgrade_growth',+ growth: 'upgrade',+ // Ansvisor sets each Enterprise customer's limit (plan_overrides).+ enterprise: 'contact',+};++/**+ * The plan half of the summary. `plan` is the effective plan (getOrgPlan /+ * planFromOrgRow), so the limit is the one the plan-limit guard enforces,+ * Enterprise overrides included.+ */+export function usagePlan(plan: Plan): 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],+ };+}++/** One row of the prompt_usage_summary RPC. */+export type PromptUsageRow =+ Database['public']['Functions']['prompt_usage_summary']['Returns'][number];++/**+ * The RPC's row for one brand, or null when the brand doesn't exist or the+ * caller can't see it (the RPC is security invoker, so a session client only+ * sees its own organization's brands). Takes the session client on the page+ * and the service-role client in the MCP server, which checks the brand's+ * organization itself.+ */+export async function fetchPromptUsageRow(+ client: Pick<SupabaseClient, 'rpc'>,+ brandId: string,+): Promise<PromptUsageRow | null> {+ const { data, error } = await client.rpc('prompt_usage_summary', { p_brand_id: brandId });+ if (error) throw new Error(error.message);+ return ((data as PromptUsageRow[] | null) ?? [])[0] ?? null;+}++export function toPromptUsageSummary(+ row: PromptUsageRow,+ plan: Plan,+ now: Date = new Date(),+): PromptUsageSummary {+ return {+ plan: usagePlan(plan),+ brand: {+ active: row.brand_active,+ paused: row.brand_paused,+ total: row.brand_active + row.brand_paused,+ },+ account: {+ activePrompts: row.account_active,+ brands: row.account_brands,+ locationsUsed: row.account_locations,+ },+ updatedAt: now.toISOString(),+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex eba3ad95a..89075e5ba 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3258,6 +3258,16 @@ export type Database = {runs: number}[]}+ prompt_usage_summary: {+ Args: { p_brand_id: string }+ Returns: {+ brand_active: number+ brand_paused: number+ account_active: number+ account_brands: number+ account_locations: number+ }[]+ }prompt_visibility_summaries: {Args: {p_brand_id: string