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(insights): period-aware Tracked Prompts KPI card with plan quota (#471)
Gökhan Geyik9a5bb6a334ee
diff --git a/supabase/migrations/00024_tracked_prompt_count.sql b/supabase/migrations/00024_tracked_prompt_count.sqlnew file mode 100644index 000000000..debd2408c--- /dev/null+++ b/supabase/migrations/00024_tracked_prompt_count.sql@@ -0,0 +1,45 @@+-- ── Tracked Prompts KPI (#457) ────────────────────────────────────────────────+--+-- Distinct prompts that produced tracked results in a filtered window — the+-- period-aware main value of the Insights "Tracked Prompts" KPI card. A plain+-- "total tracked prompts" number was rejected because every card in that row+-- recomputes with the date preset; this count follows the same filters as+-- `insights_aggregates` (00012), including the #155 chatgpt-shopping+-- exclusion, so the KPI row stays internally consistent.+--+-- SECURITY INVOKER (00014 convention): RLS on prompt_results/prompts scopes+-- the caller to their own org's data.++CREATE OR REPLACE FUNCTION public.tracked_prompt_count(+ p_brand_id uuid,+ p_platform text DEFAULT NULL,+ p_models text[] DEFAULT NULL,+ p_region text DEFAULT NULL,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_topic_id uuid DEFAULT NULL+)+RETURNS integer+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ SELECT COUNT(DISTINCT pr.prompt_id)::integer+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND pr.prompt_id IS NOT NULL+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ AND (p_platform IS NULL OR pr.platform = p_platform)+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))+ AND (p_region IS NULL OR pr.region = p_region)+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)+ AND (p_topic_id IS NULL OR EXISTS (+ SELECT 1 FROM public.prompts p+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))+$$;++GRANT EXECUTE ON FUNCTION public.tracked_prompt_count(+ uuid, text, text[], text, timestamptz, timestamptz, uuid+) TO authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex df608e2f1..0f5d860c0 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -3042,3 +3042,52 @@ CREATE POLICY reports_member_delete ON reports FOR DELETE));+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00024_tracked_prompt_count.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ── Tracked Prompts KPI (#457) ────────────────────────────────────────────────+--+-- Distinct prompts that produced tracked results in a filtered window — the+-- period-aware main value of the Insights "Tracked Prompts" KPI card. A plain+-- "total tracked prompts" number was rejected because every card in that row+-- recomputes with the date preset; this count follows the same filters as+-- `insights_aggregates` (00012), including the #155 chatgpt-shopping+-- exclusion, so the KPI row stays internally consistent.+--+-- SECURITY INVOKER (00014 convention): RLS on prompt_results/prompts scopes+-- the caller to their own org's data.++CREATE OR REPLACE FUNCTION public.tracked_prompt_count(+ p_brand_id uuid,+ p_platform text DEFAULT NULL,+ p_models text[] DEFAULT NULL,+ p_region text DEFAULT NULL,+ p_date_from timestamptz DEFAULT NULL,+ p_date_to timestamptz DEFAULT NULL,+ p_topic_id uuid DEFAULT NULL+)+RETURNS integer+LANGUAGE sql+STABLE+SECURITY INVOKER+SET search_path = public+AS $$+ SELECT COUNT(DISTINCT pr.prompt_id)::integer+ FROM public.prompt_results pr+ WHERE pr.brand_id = p_brand_id+ AND pr.prompt_id IS NOT NULL+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ AND (p_platform IS NULL OR pr.platform = p_platform)+ AND (p_models IS NULL OR pr.model_used = ANY (p_models))+ AND (p_region IS NULL OR pr.region = p_region)+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)+ AND (p_date_to IS NULL OR pr.created_at <= p_date_to)+ AND (p_topic_id IS NULL OR EXISTS (+ SELECT 1 FROM public.prompts p+ WHERE p.id = pr.prompt_id AND p.topic_id = p_topic_id))+$$;++GRANT EXECUTE ON FUNCTION public.tracked_prompt_count(+ uuid, text, text[], text, timestamptz, timestamptz, uuid+) TO authenticated;+diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 1af2f3ba0..d9e08ad79 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -48,6 +48,7 @@ import {exportPromptResults,type PromptResultWithText,type InsightsSummary,+ type TrackedPromptsKpi,type CompetitorComparisonData,type ShareOfVoiceData,type TrackingJobStatus,@@ -83,6 +84,7 @@ import {Tag,ArrowUpRight,Download,+ Layers,} from 'lucide-react';import {Select,@@ -1249,6 +1251,7 @@ export default function InsightsPage() {const { isCloud } = usePlanContext();const brand = useBrandStore((s) => s.getActiveBrand());const [summary, setSummary] = useState<InsightsSummary | null>(null);+ const [trackedPrompts, setTrackedPrompts] = useState<TrackedPromptsKpi | null>(null);const [results, setResults] = useState<PromptResultWithText[]>([]);const [totalResults, setTotalResults] = useState(0);const [isLoading, setIsLoading] = useState(true);@@ -1298,6 +1301,7 @@ export default function InsightsPage() {checkUnfiltered: hasFilters,});setSummary(insights.summary);+ setTrackedPrompts(insights.trackedPrompts);setResults(insights.results);setTotalResults(insights.total);setCompetitorData(insights.competitors.brands.length > 1 ? insights.competitors : null);@@ -1706,7 +1710,7 @@ export default function InsightsPage() {) : (<>{/* KPI Cards */}- <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-5"><KpiCardtitle="Visibility Score"tooltip="A composite score (0–100) reflecting how prominently your brand appears across AI engine responses. Combines mentions, citations, and sentiment."@@ -1720,6 +1724,36 @@ export default function InsightsPage() {}onClick={() => setBreakdownMetric('visibility')}/>+ <KpiCard+ title="Tracked Prompts"+ tooltip="Distinct prompts that produced tracked results in the selected period and filters. The quota below is current usage across your organization — it does not change with the date range."+ icon={Layers}+ value={trackedPrompts?.activeInPeriod ?? 0}+ sub={+ trackedPrompts && trackedPrompts.quotaLimit !== -1 ? (+ <>+ <span className="tabular-nums">+ {trackedPrompts.quotaUsed} / {trackedPrompts.quotaLimit} prompts+ </span>+ {trackedPrompts.quotaUsed >= trackedPrompts.quotaLimit * 0.9 && (+ <button+ type="button"+ onClick={(e) => {+ e.stopPropagation();+ router.push('/dashboard/settings');+ }}+ className="ml-1 underline underline-offset-2 hover:text-foreground"+ >+ Upgrade+ </button>+ )}+ </>+ ) : (+ `${trackedPrompts?.quotaUsed ?? 0} prompts tracked`+ )+ }+ onClick={() => router.push('/dashboard/prompts')}+ /><KpiCardtitle="Mentions"tooltip="How many times your brand was referenced by name in AI-generated responses."diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 9f81596f0..fa4961e36 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -13,6 +13,7 @@ import type {} from '@/types';import { API_BASE_URL } from '@/config/api';import { getTopicById } from '@/lib/actions/topic';+import { getOrgPlan } from '@/lib/guards/plan-guard';/** Round to one decimal place (keeps sub-1 averages visible instead of flooring to 0). */function roundTo1(n: number): number {@@ -320,6 +321,71 @@ export async function getPromptResults(return { results, total };}+export interface TrackedPromptsKpi {+ /** Distinct prompts with results in the filtered window (shopping excluded). */+ activeInPeriod: number;+ /** Org-wide prompt count — the number the plan limit is enforced against. */+ quotaUsed: number;+ /** Effective org limit with Enterprise plan_overrides merged; -1 = unlimited. */+ quotaLimit: number;+}++/**+ * Tracked Prompts KPI (#457). The main value is period-aware — distinct+ * prompts that produced results under the SAME filters as the other KPI+ * cards (the `tracked_prompt_count` RPC mirrors `insights_aggregates`,+ * shopping excluded) — because a static account-state number sitting in a+ * filter-reactive row would read as inconsistent. The quota sub-line is+ * deliberately a "now" fact: org-wide usage against the effective plan+ * limit, matching what `enforceLimit` counts on write.+ */+export async function getTrackedPromptsKpi(+ brandId: string,+ opts?: { model?: string; region?: string; dateFrom?: string; dateTo?: string; topicId?: string },+): Promise<TrackedPromptsKpi> {+ const supabase = await createClient();++ const { data: brand } = await supabase+ .from('brands')+ .select('organization_id')+ .eq('id', brandId)+ .single();+ const orgId = (brand?.organization_id as string | undefined) ?? null;++ const countOrgPrompts = async (): Promise<number> => {+ if (!orgId) return 0;+ const { count } = await supabase+ .from('prompts')+ .select('id, prompt_sets!inner(brand_id, brands!inner(organization_id))', {+ count: 'exact',+ head: true,+ })+ .eq('prompt_sets.brands.organization_id', orgId);+ return count ?? 0;+ };++ const [rpcResult, plan, quotaUsed] = await Promise.all([+ supabase.rpc('tracked_prompt_count', {+ p_brand_id: brandId,+ p_platform: null,+ p_models: modelFilterArray(opts?.model),+ p_region: opts?.region ?? null,+ p_date_from: opts?.dateFrom ?? null,+ p_date_to: expandDateToEndOfDay(opts?.dateTo) ?? null,+ p_topic_id: opts?.topicId ?? null,+ }),+ orgId ? getOrgPlan(orgId) : Promise.resolve(null),+ countOrgPrompts(),+ ]);+ if (rpcResult.error) throw new Error(rpcResult.error.message);++ return {+ activeInPeriod: (rpcResult.data as number | null) ?? 0,+ quotaUsed,+ quotaLimit: plan?.limits.maxPrompts ?? -1,+ };+}+/** Cheap existence check for a brand's (non-shopping) prompt_results — counts, no rows. */async function getBrandResultsTotal(brandId: string): Promise<number> {const supabase = await createClient();@@ -340,6 +406,7 @@ export interface InsightsData {total: number;competitors: CompetitorComparisonData;sov: ShareOfVoiceData;+ trackedPrompts: TrackedPromptsKpi;hasAnyData: boolean;}@@ -374,13 +441,15 @@ export async function getInsightsData(dateTo: opts.dateTo,};- const [summary, resultsData, competitors, sov, unfilteredTotal] = await Promise.all([- getInsightsSummary(brandId, filterOpts),- getPromptResults(brandId, { limit: opts.rowLimit ?? 50, ...filterOpts }),- getCompetitorComparison(brandId, filterOpts),- getShareOfVoiceData(brandId, filterOpts),- opts.checkUnfiltered ? getBrandResultsTotal(brandId) : Promise.resolve(null),- ]);+ const [summary, resultsData, competitors, sov, trackedPrompts, unfilteredTotal] =+ await Promise.all([+ getInsightsSummary(brandId, filterOpts),+ getPromptResults(brandId, { limit: opts.rowLimit ?? 50, ...filterOpts }),+ getCompetitorComparison(brandId, filterOpts),+ getShareOfVoiceData(brandId, filterOpts),+ getTrackedPromptsKpi(brandId, filterOpts),+ opts.checkUnfiltered ? getBrandResultsTotal(brandId) : Promise.resolve(null),+ ]);const hasAnyData = unfilteredTotal !== null ? unfilteredTotal > 0 : resultsData.total > 0;@@ -390,6 +459,7 @@ export async function getInsightsData(total: resultsData.total,competitors,sov,+ trackedPrompts,hasAnyData,};}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex eb80d98cf..48c6027bf 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -1192,6 +1192,18 @@ export type Database = {};Returns: Json;};+ tracked_prompt_count: {+ Args: {+ p_brand_id: string;+ p_platform?: string | null;+ p_models?: string[] | null;+ p_region?: string | null;+ p_date_from?: string | null;+ p_date_to?: string | null;+ p_topic_id?: string | null;+ };+ Returns: number;+ };competitor_aggregates: {Args: {p_brand_id: string;