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.

feat(insights): visibility rate as the headline metric across Insights (#490)

Gökhan Geyikde5030d41c74
diff --git a/supabase/migrations/00027_visible_prompt_stats.sql b/supabase/migrations/00027_visible_prompt_stats.sql
new file mode 100644
index 000000000..6bbbe227c
--- /dev/null
+++ b/supabase/migrations/00027_visible_prompt_stats.sql
@@ -0,0 +1,64 @@
+-- ── Visibility Rate KPI ───────────────────────────────────────────────────────
+--
+-- Headline metric change on Insights: the raw average visibility score over
+-- ALL results reads near zero for most brands (every answer the brand does
+-- not appear in contributes a 0), which buries the two numbers users act on:
+-- how OFTEN the brand shows up, and how GOOD it looks when it does. This RPC
+-- returns the "appeared" side of that split for the filtered window:
+--
+-- visible_prompts distinct prompts with >= 1 answer mentioning or
+-- citing the brand (numerator of Visibility Rate;
+-- the denominator is tracked_prompt_count, 00024)
+-- visible_results result rows where the brand appeared
+-- sum_visibility_visible sum of visibility_score over those rows, so the
+-- caller derives "avg score when visible"
+--
+-- Filters mirror tracked_prompt_count / insights_aggregates exactly — same
+-- window, same #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.visible_prompt_stats(
+ 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 jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ SELECT jsonb_build_object(
+ 'visible_prompts',
+ COUNT(DISTINCT pr.prompt_id)
+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0),
+ 'visible_results',
+ COUNT(*) FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0),
+ 'sum_visibility_visible',
+ COALESCE(SUM(pr.visibility_score)
+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0), 0)
+ )
+ 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.visible_prompt_stats(
+ uuid, text, text[], text, timestamptz, timestamptz, uuid
+) TO authenticated;
diff --git a/supabase/migrations/00028_competitor_visible_prompts.sql b/supabase/migrations/00028_competitor_visible_prompts.sql
new file mode 100644
index 000000000..15b4c07df
--- /dev/null
+++ b/supabase/migrations/00028_competitor_visible_prompts.sql
@@ -0,0 +1,156 @@
+-- ── Prompt-level visibility counts in competitor_aggregates ──────────────────
+--
+-- The Brand vs Competitors leaderboard moves from the all-rows score average
+-- (which reads "1%" for a brand that appears in a third of its prompts —
+-- every absent answer contributes a 0) to the same prompt-level Visibility
+-- Rate the Insights headline now uses: distinct prompts an entity appeared
+-- in ÷ distinct prompts that produced results, identical denominator for the
+-- brand and every competitor.
+--
+-- Adds to the existing payload (shape is additive, old readers unaffected):
+-- brand_prompt_count distinct prompts in the filtered window
+-- brand_visible_prompts distinct prompts with >= 1 answer mentioning or
+-- citing the brand
+-- by_competitor[].visible_prompts
+-- distinct prompts with >= 1 answer where that
+-- competitor scored (mention, citation or score)
+--
+-- SECURITY INVOKER kept from 00014.
+
+CREATE OR REPLACE FUNCTION public.competitor_aggregates(
+ 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_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.prompt_id, pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.model_used, pr.platform, pr.competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ 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_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ 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))
+ ),
+ brand_totals AS (
+ SELECT
+ COUNT(*) AS row_count,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(citation_count), 0)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ ),
+ by_brand_provider AS (
+ SELECT
+ model_used,
+ platform,
+ SUM(visibility_score) AS sum_visibility,
+ COUNT(*) AS row_count
+ FROM filtered
+ GROUP BY model_used, platform
+ ),
+ mentions_flat AS (
+ SELECT
+ f.prompt_id,
+ f.model_used,
+ f.platform,
+ cm.value->>'competitor_id' AS competitor_id,
+ cm.value->>'name' AS competitor_name,
+ (cm.value->>'visibility_score')::numeric AS cm_visibility,
+ COALESCE((cm.value->>'mention_count')::int, 0) AS cm_mention_count,
+ COALESCE((cm.value->>'citation_count')::int, 0) AS cm_citation_count
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ ),
+ by_competitor AS (
+ SELECT
+ competitor_id,
+ MAX(competitor_name) AS name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ SUM(cm_mention_count)::bigint AS total_mentions,
+ SUM(cm_citation_count)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE cm_mention_count > 0
+ OR cm_citation_count > 0
+ OR COALESCE(cm_visibility, 0) > 0)
+ AS visible_prompts
+ FROM mentions_flat
+ GROUP BY competitor_id
+ ),
+ by_competitor_provider AS (
+ SELECT
+ model_used,
+ platform,
+ competitor_id,
+ MAX(competitor_name) AS competitor_name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count
+ FROM mentions_flat
+ GROUP BY model_used, platform, competitor_id
+ )
+ SELECT jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'brand_prompt_count', b.prompt_count,
+ 'brand_visible_prompts', b.visible_prompts,
+ 'by_competitor', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations,
+ 'visible_prompts', bc.visible_prompts)
+ ORDER BY bc.row_count DESC, bc.competitor_id)
+ FROM by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count)
+ ORDER BY bbp.platform NULLS LAST, bbp.model_used NULLS LAST)
+ FROM by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count)
+ ORDER BY bcp.platform NULLS LAST, bcp.model_used NULLS LAST, bcp.competitor_id)
+ FROM by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ FROM brand_totals b;
+$$;
diff --git a/supabase/migrations/00029_provider_visible_prompts.sql b/supabase/migrations/00029_provider_visible_prompts.sql
new file mode 100644
index 000000000..87c0e11b8
--- /dev/null
+++ b/supabase/migrations/00029_provider_visible_prompts.sql
@@ -0,0 +1,169 @@
+-- ── Per-provider prompt counts in competitor_aggregates ──────────────────────
+--
+-- Second half of the visibility-rate leaderboard switch (00028): the
+-- "AI Visibility — Brand vs Competitors" provider chart still plotted the
+-- all-rows score average per provider, so its bars contradicted the rate
+-- numbers in the leaderboard next to it. The provider groups now also carry
+-- distinct-prompt counts so the chart can plot the same prompt-level rate:
+--
+-- by_brand_provider[].prompt_count distinct prompts in the group
+-- by_brand_provider[].visible_prompts …with >= 1 brand mention/citation
+-- by_competitor_provider[].visible_prompts
+-- …where that competitor scored
+--
+-- Groups stay keyed by (model_used, platform) — the provider mapping lives
+-- in JS on purpose. Summing DISTINCT counts across two engines of the same
+-- provider counts a shared prompt once per engine, in the numerator and the
+-- denominator alike, so the folded rate stays unbiased.
+--
+-- SECURITY INVOKER kept from 00014.
+
+CREATE OR REPLACE FUNCTION public.competitor_aggregates(
+ 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_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.prompt_id, pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.model_used, pr.platform, pr.competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ 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_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ 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))
+ ),
+ brand_totals AS (
+ SELECT
+ COUNT(*) AS row_count,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(citation_count), 0)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ ),
+ by_brand_provider AS (
+ SELECT
+ model_used,
+ platform,
+ SUM(visibility_score) AS sum_visibility,
+ COUNT(*) AS row_count,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ GROUP BY model_used, platform
+ ),
+ mentions_flat AS (
+ SELECT
+ f.prompt_id,
+ f.model_used,
+ f.platform,
+ cm.value->>'competitor_id' AS competitor_id,
+ cm.value->>'name' AS competitor_name,
+ (cm.value->>'visibility_score')::numeric AS cm_visibility,
+ COALESCE((cm.value->>'mention_count')::int, 0) AS cm_mention_count,
+ COALESCE((cm.value->>'citation_count')::int, 0) AS cm_citation_count
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ ),
+ by_competitor AS (
+ SELECT
+ competitor_id,
+ MAX(competitor_name) AS name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ SUM(cm_mention_count)::bigint AS total_mentions,
+ SUM(cm_citation_count)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE cm_mention_count > 0
+ OR cm_citation_count > 0
+ OR COALESCE(cm_visibility, 0) > 0)
+ AS visible_prompts
+ FROM mentions_flat
+ GROUP BY competitor_id
+ ),
+ by_competitor_provider AS (
+ SELECT
+ model_used,
+ platform,
+ competitor_id,
+ MAX(competitor_name) AS competitor_name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE cm_mention_count > 0
+ OR cm_citation_count > 0
+ OR COALESCE(cm_visibility, 0) > 0)
+ AS visible_prompts
+ FROM mentions_flat
+ GROUP BY model_used, platform, competitor_id
+ )
+ SELECT jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'brand_prompt_count', b.prompt_count,
+ 'brand_visible_prompts', b.visible_prompts,
+ 'by_competitor', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations,
+ 'visible_prompts', bc.visible_prompts)
+ ORDER BY bc.row_count DESC, bc.competitor_id)
+ FROM by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count,
+ 'prompt_count', bbp.prompt_count,
+ 'visible_prompts', bbp.visible_prompts)
+ ORDER BY bbp.platform NULLS LAST, bbp.model_used NULLS LAST)
+ FROM by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count,
+ 'visible_prompts', bcp.visible_prompts)
+ ORDER BY bcp.platform NULLS LAST, bcp.model_used NULLS LAST, bcp.competitor_id)
+ FROM by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ FROM brand_totals b;
+$$;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index cc5abb03c..b480c7d48 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -3181,3 +3181,404 @@ $$;
GRANT EXECUTE ON FUNCTION public.insights_filter_options(uuid)
TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00027_visible_prompt_stats.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ── Visibility Rate KPI ───────────────────────────────────────────────────────
+--
+-- Headline metric change on Insights: the raw average visibility score over
+-- ALL results reads near zero for most brands (every answer the brand does
+-- not appear in contributes a 0), which buries the two numbers users act on:
+-- how OFTEN the brand shows up, and how GOOD it looks when it does. This RPC
+-- returns the "appeared" side of that split for the filtered window:
+--
+-- visible_prompts distinct prompts with >= 1 answer mentioning or
+-- citing the brand (numerator of Visibility Rate;
+-- the denominator is tracked_prompt_count, 00024)
+-- visible_results result rows where the brand appeared
+-- sum_visibility_visible sum of visibility_score over those rows, so the
+-- caller derives "avg score when visible"
+--
+-- Filters mirror tracked_prompt_count / insights_aggregates exactly — same
+-- window, same #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.visible_prompt_stats(
+ 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 jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ SELECT jsonb_build_object(
+ 'visible_prompts',
+ COUNT(DISTINCT pr.prompt_id)
+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0),
+ 'visible_results',
+ COUNT(*) FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0),
+ 'sum_visibility_visible',
+ COALESCE(SUM(pr.visibility_score)
+ FILTER (WHERE pr.mention_count > 0 OR pr.citation_count > 0), 0)
+ )
+ 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.visible_prompt_stats(
+ uuid, text, text[], text, timestamptz, timestamptz, uuid
+) TO authenticated;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00028_competitor_visible_prompts.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ── Prompt-level visibility counts in competitor_aggregates ──────────────────
+--
+-- The Brand vs Competitors leaderboard moves from the all-rows score average
+-- (which reads "1%" for a brand that appears in a third of its prompts —
+-- every absent answer contributes a 0) to the same prompt-level Visibility
+-- Rate the Insights headline now uses: distinct prompts an entity appeared
+-- in ÷ distinct prompts that produced results, identical denominator for the
+-- brand and every competitor.
+--
+-- Adds to the existing payload (shape is additive, old readers unaffected):
+-- brand_prompt_count distinct prompts in the filtered window
+-- brand_visible_prompts distinct prompts with >= 1 answer mentioning or
+-- citing the brand
+-- by_competitor[].visible_prompts
+-- distinct prompts with >= 1 answer where that
+-- competitor scored (mention, citation or score)
+--
+-- SECURITY INVOKER kept from 00014.
+
+CREATE OR REPLACE FUNCTION public.competitor_aggregates(
+ 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_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.prompt_id, pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.model_used, pr.platform, pr.competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ 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_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ 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))
+ ),
+ brand_totals AS (
+ SELECT
+ COUNT(*) AS row_count,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(citation_count), 0)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ ),
+ by_brand_provider AS (
+ SELECT
+ model_used,
+ platform,
+ SUM(visibility_score) AS sum_visibility,
+ COUNT(*) AS row_count
+ FROM filtered
+ GROUP BY model_used, platform
+ ),
+ mentions_flat AS (
+ SELECT
+ f.prompt_id,
+ f.model_used,
+ f.platform,
+ cm.value->>'competitor_id' AS competitor_id,
+ cm.value->>'name' AS competitor_name,
+ (cm.value->>'visibility_score')::numeric AS cm_visibility,
+ COALESCE((cm.value->>'mention_count')::int, 0) AS cm_mention_count,
+ COALESCE((cm.value->>'citation_count')::int, 0) AS cm_citation_count
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ ),
+ by_competitor AS (
+ SELECT
+ competitor_id,
+ MAX(competitor_name) AS name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ SUM(cm_mention_count)::bigint AS total_mentions,
+ SUM(cm_citation_count)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE cm_mention_count > 0
+ OR cm_citation_count > 0
+ OR COALESCE(cm_visibility, 0) > 0)
+ AS visible_prompts
+ FROM mentions_flat
+ GROUP BY competitor_id
+ ),
+ by_competitor_provider AS (
+ SELECT
+ model_used,
+ platform,
+ competitor_id,
+ MAX(competitor_name) AS competitor_name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count
+ FROM mentions_flat
+ GROUP BY model_used, platform, competitor_id
+ )
+ SELECT jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'brand_prompt_count', b.prompt_count,
+ 'brand_visible_prompts', b.visible_prompts,
+ 'by_competitor', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations,
+ 'visible_prompts', bc.visible_prompts)
+ ORDER BY bc.row_count DESC, bc.competitor_id)
+ FROM by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count)
+ ORDER BY bbp.platform NULLS LAST, bbp.model_used NULLS LAST)
+ FROM by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count)
+ ORDER BY bcp.platform NULLS LAST, bcp.model_used NULLS LAST, bcp.competitor_id)
+ FROM by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ FROM brand_totals b;
+$$;
+
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00029_provider_visible_prompts.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ── Per-provider prompt counts in competitor_aggregates ──────────────────────
+--
+-- Second half of the visibility-rate leaderboard switch (00028): the
+-- "AI Visibility — Brand vs Competitors" provider chart still plotted the
+-- all-rows score average per provider, so its bars contradicted the rate
+-- numbers in the leaderboard next to it. The provider groups now also carry
+-- distinct-prompt counts so the chart can plot the same prompt-level rate:
+--
+-- by_brand_provider[].prompt_count distinct prompts in the group
+-- by_brand_provider[].visible_prompts …with >= 1 brand mention/citation
+-- by_competitor_provider[].visible_prompts
+-- …where that competitor scored
+--
+-- Groups stay keyed by (model_used, platform) — the provider mapping lives
+-- in JS on purpose. Summing DISTINCT counts across two engines of the same
+-- provider counts a shared prompt once per engine, in the numerator and the
+-- denominator alike, so the folded rate stays unbiased.
+--
+-- SECURITY INVOKER kept from 00014.
+
+CREATE OR REPLACE FUNCTION public.competitor_aggregates(
+ 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_prompt_id uuid DEFAULT NULL,
+ p_topic_id uuid DEFAULT NULL
+)
+RETURNS jsonb
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ WITH filtered AS (
+ SELECT pr.prompt_id, pr.visibility_score, pr.mention_count, pr.citation_count,
+ pr.model_used, pr.platform, pr.competitor_mentions
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ 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_prompt_id IS NULL OR pr.prompt_id = p_prompt_id)
+ 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))
+ ),
+ brand_totals AS (
+ SELECT
+ COUNT(*) AS row_count,
+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,
+ COALESCE(SUM(mention_count), 0)::bigint AS total_mentions,
+ COALESCE(SUM(citation_count), 0)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ ),
+ by_brand_provider AS (
+ SELECT
+ model_used,
+ platform,
+ SUM(visibility_score) AS sum_visibility,
+ COUNT(*) AS row_count,
+ COUNT(DISTINCT prompt_id) AS prompt_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE mention_count > 0 OR citation_count > 0)
+ AS visible_prompts
+ FROM filtered
+ GROUP BY model_used, platform
+ ),
+ mentions_flat AS (
+ SELECT
+ f.prompt_id,
+ f.model_used,
+ f.platform,
+ cm.value->>'competitor_id' AS competitor_id,
+ cm.value->>'name' AS competitor_name,
+ (cm.value->>'visibility_score')::numeric AS cm_visibility,
+ COALESCE((cm.value->>'mention_count')::int, 0) AS cm_mention_count,
+ COALESCE((cm.value->>'citation_count')::int, 0) AS cm_citation_count
+ FROM filtered f,
+ LATERAL jsonb_array_elements(
+ COALESCE(f.competitor_mentions, '[]'::jsonb)) cm
+ WHERE cm.value ? 'competitor_id'
+ ),
+ by_competitor AS (
+ SELECT
+ competitor_id,
+ MAX(competitor_name) AS name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ SUM(cm_mention_count)::bigint AS total_mentions,
+ SUM(cm_citation_count)::bigint AS total_citations,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE cm_mention_count > 0
+ OR cm_citation_count > 0
+ OR COALESCE(cm_visibility, 0) > 0)
+ AS visible_prompts
+ FROM mentions_flat
+ GROUP BY competitor_id
+ ),
+ by_competitor_provider AS (
+ SELECT
+ model_used,
+ platform,
+ competitor_id,
+ MAX(competitor_name) AS competitor_name,
+ SUM(cm_visibility) AS sum_visibility,
+ COUNT(*) AS row_count,
+ COUNT(DISTINCT prompt_id)
+ FILTER (WHERE cm_mention_count > 0
+ OR cm_citation_count > 0
+ OR COALESCE(cm_visibility, 0) > 0)
+ AS visible_prompts
+ FROM mentions_flat
+ GROUP BY model_used, platform, competitor_id
+ )
+ SELECT jsonb_build_object(
+ 'brand_row_count', b.row_count,
+ 'brand_sum_visibility', b.sum_visibility,
+ 'brand_total_mentions', b.total_mentions,
+ 'brand_total_citations', b.total_citations,
+ 'brand_prompt_count', b.prompt_count,
+ 'brand_visible_prompts', b.visible_prompts,
+ 'by_competitor', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'competitor_id', bc.competitor_id,
+ 'name', bc.name,
+ 'sum_visibility', bc.sum_visibility,
+ 'row_count', bc.row_count,
+ 'total_mentions', bc.total_mentions,
+ 'total_citations', bc.total_citations,
+ 'visible_prompts', bc.visible_prompts)
+ ORDER BY bc.row_count DESC, bc.competitor_id)
+ FROM by_competitor bc),
+ '[]'::jsonb),
+ 'by_brand_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bbp.model_used,
+ 'platform', bbp.platform,
+ 'sum_visibility', bbp.sum_visibility,
+ 'row_count', bbp.row_count,
+ 'prompt_count', bbp.prompt_count,
+ 'visible_prompts', bbp.visible_prompts)
+ ORDER BY bbp.platform NULLS LAST, bbp.model_used NULLS LAST)
+ FROM by_brand_provider bbp),
+ '[]'::jsonb),
+ 'by_competitor_provider', COALESCE(
+ (SELECT jsonb_agg(jsonb_build_object(
+ 'model_used', bcp.model_used,
+ 'platform', bcp.platform,
+ 'competitor_id', bcp.competitor_id,
+ 'competitor_name', bcp.competitor_name,
+ 'sum_visibility', bcp.sum_visibility,
+ 'row_count', bcp.row_count,
+ 'visible_prompts', bcp.visible_prompts)
+ ORDER BY bcp.platform NULLS LAST, bcp.model_used NULLS LAST, bcp.competitor_id)
+ FROM by_competitor_provider bcp),
+ '[]'::jsonb)
+ )
+ FROM brand_totals b;
+$$;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
index 186671c1c..392a1ec9a 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_charts.tsx
@@ -467,20 +467,25 @@ function LeaderboardEntry({ entry, rank }: { entry: CompetitorComparisonEntry; r
<span>{entry.totalMentions} mentions</span>
<span>{entry.totalCitations} citations</span>
</div>
+ <div className="flex items-center gap-3 text-xs text-muted-foreground mt-0.5">
+ <span className="tabular-nums">
+ appeared in {entry.visiblePrompts}/{entry.promptCount} prompts
+ </span>
+ </div>
</div>
<div className="flex flex-col items-end gap-0.5 shrink-0">
- <span className="text-sm font-semibold tabular-nums">{entry.avgVisibilityScore}%</span>
+ <span className="text-sm font-semibold tabular-nums">{entry.visibilityRate}%</span>
{entry.change !== null && entry.change !== 0 && (
<span
className={`text-[10px] font-medium tabular-nums ${
entry.change > 0 ? 'text-green-500' : 'text-red-500'
}`}
>
- {entry.change > 0 ? '↑' : '↓'} {Math.abs(entry.change).toFixed(1)}%
+ {entry.change > 0 ? '↑' : '↓'} {Math.abs(entry.change).toFixed(1)} pts
</span>
)}
{entry.change === 0 && (
- <span className="text-[10px] font-medium tabular-nums text-muted-foreground">— 0%</span>
+ <span className="text-[10px] font-medium tabular-nums text-muted-foreground">— 0</span>
)}
</div>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 8c112f2f3..2dac7bc76 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -46,6 +46,7 @@ import {
exportPromptResults,
type InsightsSummary,
type TrackedPromptsKpi,
+ type VisibilityRateKpi,
type CompetitorComparisonData,
type ShareOfVoiceData,
type InsightsRecommendations,
@@ -63,6 +64,7 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/u
import {
BarChart3,
CalendarX2,
+ Eye,
HelpCircle,
Play,
TrendingUp,
@@ -596,8 +598,8 @@ function InsightsSkeleton() {
</div>
<Skeleton className="h-10 w-32" />
</div>
- <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
- {Array.from({ length: 4 }).map((_, i) => (
+ <div className="grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-5">
+ {Array.from({ length: 5 }).map((_, i) => (
<Card key={i}>
<CardContent className="pt-6 space-y-2">
<Skeleton className="h-4 w-24" />
@@ -891,6 +893,7 @@ export default function InsightsPage() {
const brand = useBrandStore((s) => s.getActiveBrand());
const [summary, setSummary] = useState<InsightsSummary | null>(null);
const [trackedPrompts, setTrackedPrompts] = useState<TrackedPromptsKpi | null>(null);
+ const [visibilityRate, setVisibilityRate] = useState<VisibilityRateKpi | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [isRunning, setIsRunning] = useState(false);
const [activeJobId, setActiveJobId] = useState<string | null>(null);
@@ -939,6 +942,7 @@ export default function InsightsPage() {
});
setSummary(insights.summary);
setTrackedPrompts(insights.trackedPrompts);
+ setVisibilityRate(insights.visibilityRate);
setCompetitorData(insights.competitors.brands.length > 1 ? insights.competitors : null);
setSovData(insights.sov.byPlatform.length > 0 ? insights.sov : null);
setRecommendations(insights.recommendations);
@@ -1209,6 +1213,14 @@ export default function InsightsPage() {
if (!brand || (isLoading && !summary)) return <InsightsSkeleton />;
const noResults = !summary || summary.totalResults === 0;
+
+ // Visibility Rate = prompts the brand appeared in ÷ prompts that produced
+ // results, both under the same filters (the Tracked Prompts KPI is the
+ // denominator on purpose — the two cards must agree).
+ const visibilityRatePct =
+ visibilityRate && trackedPrompts && trackedPrompts.activeInPeriod > 0
+ ? Math.round((visibilityRate.visiblePrompts / trackedPrompts.activeInPeriod) * 1000) / 10
+ : 0;
const trulyEmpty = noResults && !hasAnyData;
if (trulyEmpty) {
@@ -1313,19 +1325,18 @@ export default function InsightsPage() {
<NoDataForPeriod datePreset={filters.datePreset} onReset={handleResetFilters} />
) : (
<>
- {/* KPI Cards */}
+ {/* KPI Cards — Visibility Rate leads the row: the raw all-results
+ score average reads near zero for most brands (absent answers
+ each contribute 0) and buried the number users act on. The old
+ average survives in the breakdown sheet; Share of Voice has its
+ own chart section below. */}
<div className="grid grid-cols-2 gap-4 sm:grid-cols-3 xl:grid-cols-5">
<KpiCard
- title="Visibility Score"
- tooltip="A composite score (0–100) reflecting how prominently your brand appears across AI engine responses. Combines mentions, citations, and sentiment."
- icon={BarChart3}
- value={summary!.avgVisibilityScore}
- sub={<DeltaBadge delta={summary!.visibilityChange} suffix=" pts" />}
- subVariant={
- summary!.visibilityChange !== null && summary!.visibilityChange > 0
- ? 'positive'
- : 'muted'
- }
+ title="Visibility Rate"
+ tooltip="Share of tracked prompts where your brand appeared in at least one AI answer under the current filters."
+ icon={Eye}
+ value={`${visibilityRatePct}%`}
+ sub={null}
onClick={() => setBreakdownMetric('visibility')}
/>
<KpiCard
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index 2198b30a7..52bfe9a79 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -146,6 +146,8 @@ interface CompetitorAggregatesRow {
brand_sum_visibility: number;
brand_total_mentions: number;
brand_total_citations: number;
+ brand_prompt_count: number;
+ brand_visible_prompts: number;
by_competitor: Array<{
competitor_id: string;
name: string | null;
@@ -153,12 +155,15 @@ interface CompetitorAggregatesRow {
row_count: number;
total_mentions: number;
total_citations: number;
+ visible_prompts: number;
}>;
by_brand_provider: Array<{
model_used: string | null;
platform: string | null;
sum_visibility: number;
row_count: number;
+ prompt_count: number;
+ visible_prompts: number;
}>;
by_competitor_provider: Array<{
model_used: string | null;
@@ -167,6 +172,7 @@ interface CompetitorAggregatesRow {
competitor_name: string | null;
sum_visibility: number;
row_count: number;
+ visible_prompts: number;
}>;
}
@@ -333,6 +339,54 @@ export interface TrackedPromptsKpi {
quotaLimit: number;
}
+export interface VisibilityRateKpi {
+ /** Distinct prompts with >= 1 answer mentioning or citing the brand. */
+ visiblePrompts: number;
+ /** Result rows where the brand appeared. */
+ visibleResults: number;
+ /** Average visibility score over only the rows the brand appeared in. */
+ avgScoreWhenVisible: number;
+}
+
+/**
+ * Visibility Rate KPI — the "appeared" side of the how-often ⁄ how-good
+ * split. Averaging visibility over ALL results reads near zero for most
+ * brands (absent answers contribute 0 each), so the headline shows how many
+ * tracked prompts the brand actually surfaced in, and the average score of
+ * only those appearances. Same filters and shopping exclusion as the rest of
+ * the KPI row; the rate's denominator is TrackedPromptsKpi.activeInPeriod.
+ */
+export async function getVisibilityRateKpi(
+ brandId: string,
+ opts?: { model?: string; region?: string; dateFrom?: string; dateTo?: string; topicId?: string },
+): Promise<VisibilityRateKpi> {
+ const supabase = await createClient();
+
+ const { data, error } = await supabase.rpc('visible_prompt_stats', {
+ 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,
+ });
+ if (error) throw new Error(error.message);
+
+ const row = (data ?? {}) as {
+ visible_prompts?: number;
+ visible_results?: number;
+ sum_visibility_visible?: number;
+ };
+ const visibleResults = Number(row.visible_results ?? 0);
+ return {
+ visiblePrompts: Number(row.visible_prompts ?? 0),
+ visibleResults,
+ avgScoreWhenVisible:
+ visibleResults > 0 ? Math.round(Number(row.sum_visibility_visible ?? 0) / visibleResults) : 0,
+ };
+}
+
/**
* Tracked Prompts KPI (#457). The main value is period-aware — distinct
* prompts that produced results under the SAME filters as the other KPI
@@ -489,6 +543,7 @@ export interface InsightsData {
competitors: CompetitorComparisonData;
sov: ShareOfVoiceData;
trackedPrompts: TrackedPromptsKpi;
+ visibilityRate: VisibilityRateKpi;
filterOptions: InsightsFilterOptions;
recommendations: InsightsRecommendations;
hasAnyData: boolean;
@@ -530,6 +585,7 @@ export async function getInsightsData(
competitors,
sov,
trackedPrompts,
+ visibilityRate,
filterOptions,
recommendations,
unfilteredTotal,
@@ -538,6 +594,7 @@ export async function getInsightsData(
getCompetitorComparison(brandId, filterOpts),
getShareOfVoiceData(brandId, filterOpts),
getTrackedPromptsKpi(brandId, filterOpts),
+ getVisibilityRateKpi(brandId, filterOpts),
getInsightsFilterOptions(brandId),
getInsightsRecommendations(brandId),
opts.checkUnfiltered ? getBrandResultsTotal(brandId) : Promise.resolve(null),
@@ -552,6 +609,7 @@ export async function getInsightsData(
competitors,
sov,
trackedPrompts,
+ visibilityRate,
filterOptions,
recommendations,
hasAnyData,
@@ -1165,8 +1223,18 @@ export interface CompetitorComparisonEntry {
name: string;
avgVisibilityScore: number;
/**
- * Percentage change of the average visibility score versus the previous
- * comparable window (e.g. last 7 days vs the 7 days before that).
+ * Prompt-level visibility rate (%): distinct prompts this entity appeared
+ * in ÷ distinct prompts that produced results in the window. Same
+ * denominator for the brand and every competitor — the leaderboard metric.
+ */
+ visibilityRate: number;
+ /** Distinct prompts this entity appeared in (the rate's numerator). */
+ visiblePrompts: number;
+ /** Distinct prompts that produced results in the window (shared denominator). */
+ promptCount: number;
+ /**
+ * Point change of the visibility rate versus the previous comparable
+ * window (e.g. last 7 days vs the 7 days before that).
* `null` when there is no comparable previous-period value.
*/
change: number | null;
@@ -1304,43 +1372,44 @@ export async function getCompetitorComparison(
const curWin = curRes.data as unknown as CompetitorAggregatesRow | null;
const prevWin = prevRes.data as unknown as CompetitorAggregatesRow | null;
- const curBrandAvg =
- curWin && curWin.brand_row_count > 0
- ? curWin.brand_sum_visibility / curWin.brand_row_count
- : null;
- const prevBrandAvg =
- prevWin && prevWin.brand_row_count > 0
- ? prevWin.brand_sum_visibility / prevWin.brand_row_count
- : null;
-
- // Competitor averages use the SAME denominator as the brand's — every
- // filtered result row, not just the rows where the competitor happened to
- // appear. A competitor absent from a response scores 0 for it, exactly
- // like the brand does. Dividing by the appearance count instead graded
- // competitors only on their best runs and could rank a rarely-seen
- // competitor above a frequently-mentioned brand.
- const curCompAvg = new Map<string, number>();
- if (curWin && curWin.brand_row_count > 0) {
+ // The leaderboard metric is the prompt-level visibility rate: distinct
+ // prompts an entity appeared in ÷ distinct prompts that produced results.
+ // Same-denominator rule as before (#478) — the brand and every competitor
+ // divide by the same prompt count, so absence still costs; but a prompt
+ // counts once no matter how many platforms answered it, which keeps the
+ // number readable instead of the near-zero all-rows score average.
+ const rateOf = (visible: number, prompts: number): number | null =>
+ prompts > 0 ? Math.round((visible / prompts) * 1000) / 10 : null;
+
+ const curBrandRate = curWin
+ ? rateOf(curWin.brand_visible_prompts, curWin.brand_prompt_count)
+ : null;
+ const prevBrandRate = prevWin
+ ? rateOf(prevWin.brand_visible_prompts, prevWin.brand_prompt_count)
+ : null;
+
+ const curCompRate = new Map<string, number | null>();
+ if (curWin) {
for (const c of curWin.by_competitor) {
- curCompAvg.set(c.competitor_id, c.sum_visibility / curWin.brand_row_count);
+ curCompRate.set(c.competitor_id, rateOf(c.visible_prompts, curWin.brand_prompt_count));
}
}
- const prevCompAvg = new Map<string, number>();
- if (prevWin && prevWin.brand_row_count > 0) {
+ const prevCompRate = new Map<string, number | null>();
+ if (prevWin) {
for (const c of prevWin.by_competitor) {
- prevCompAvg.set(c.competitor_id, c.sum_visibility / prevWin.brand_row_count);
+ prevCompRate.set(c.competitor_id, rateOf(c.visible_prompts, prevWin.brand_prompt_count));
}
}
const brandName = (brand?.name as string) ?? 'Your Brand';
const brandAvg = Math.round(agg.brand_sum_visibility / agg.brand_row_count);
+ const brandRate = rateOf(agg.brand_visible_prompts, agg.brand_prompt_count) ?? 0;
- // Percentage change relative to the previous-period value.
- // Null when no comparable previous value exists (or growth from 0 → x is undefined).
- const pctChange = (cur: number | null, prev: number | null): number | null => {
+ // Point change of the rate relative to the previous-period value.
+ // Null when no comparable previous value exists.
+ const rateDiff = (cur: number | null, prev: number | null): number | null => {
if (cur === null || prev === null) return null;
- if (prev === 0) return cur === 0 ? 0 : null;
- return Math.round(((cur - prev) / prev) * 1000) / 10;
+ return Math.round((cur - prev) * 10) / 10;
};
// Falls back to the competitor id when the name is null/empty so two
@@ -1354,7 +1423,10 @@ export async function getCompetitorComparison(
{
name: brandName,
avgVisibilityScore: brandAvg,
- change: pctChange(curBrandAvg, prevBrandAvg),
+ visibilityRate: brandRate,
+ visiblePrompts: agg.brand_visible_prompts,
+ promptCount: agg.brand_prompt_count,
+ change: rateDiff(curBrandRate, prevBrandRate),
totalMentions: agg.brand_total_mentions,
totalCitations: agg.brand_total_citations,
resultCount: agg.brand_row_count,
@@ -1363,15 +1435,18 @@ export async function getCompetitorComparison(
];
for (const c of agg.by_competitor) {
- // Same-denominator rule as the window averages above (agg.brand_row_count
+ // Same-denominator rule as the window rates above (agg.brand_row_count
// is guaranteed > 0 by the early return).
const avg = Math.round(c.sum_visibility / agg.brand_row_count);
entries.push({
name: competitorDisplayName(c.name, c.competitor_id),
avgVisibilityScore: avg,
- change: pctChange(
- curCompAvg.get(c.competitor_id) ?? null,
- prevCompAvg.get(c.competitor_id) ?? null,
+ visibilityRate: rateOf(c.visible_prompts, agg.brand_prompt_count) ?? 0,
+ visiblePrompts: c.visible_prompts,
+ promptCount: agg.brand_prompt_count,
+ change: rateDiff(
+ curCompRate.get(c.competitor_id) ?? null,
+ prevCompRate.get(c.competitor_id) ?? null,
),
totalMentions: c.total_mentions,
totalCitations: c.total_citations,
@@ -1380,35 +1455,36 @@ export async function getCompetitorComparison(
});
}
- entries.sort((a, b) => b.avgVisibilityScore - a.avgVisibilityScore);
+ entries.sort((a, b) => b.visibilityRate - a.visibilityRate || b.totalMentions - a.totalMentions);
// --- Per-provider breakdown ---
// resolveProvider stays in JS so we don't keep a SQL copy of the mapping
// table in sync — fold the (model_used, platform) groups into provider
- // buckets here.
- type Agg = { totalScore: number; count: number };
+ // buckets here. The chart plots the same prompt-level rate as the
+ // leaderboard; summing DISTINCT counts across two engines of one provider
+ // counts a shared prompt once per engine in numerator and denominator
+ // alike, so the folded rate stays unbiased.
+ type Agg = { visiblePrompts: number; promptCount: number };
const brandByProvider = new Map<string, Agg>();
for (const bp of agg.by_brand_provider) {
const provider = resolveProvider(bp.model_used, bp.platform);
- const ex = brandByProvider.get(provider) ?? { totalScore: 0, count: 0 };
- ex.totalScore += Number(bp.sum_visibility);
- ex.count += bp.row_count;
+ const ex = brandByProvider.get(provider) ?? { visiblePrompts: 0, promptCount: 0 };
+ ex.visiblePrompts += bp.visible_prompts;
+ ex.promptCount += bp.prompt_count;
brandByProvider.set(provider, ex);
}
- // compName -> provider -> agg. Keyed by the same display name used in
- // entries[] above so the providerRows column headers line up with the
- // table rows (empty/null names fall back to competitor_id).
- const compByProvider = new Map<string, Map<string, Agg>>();
+ // compName -> provider -> visible prompt count. Keyed by the same display
+ // name used in entries[] above so the providerRows column headers line up
+ // with the table rows (empty/null names fall back to competitor_id). No
+ // denominator here — competitors divide by the brand's provider bucket.
+ const compByProvider = new Map<string, Map<string, number>>();
for (const cp of agg.by_competitor_provider) {
const provider = resolveProvider(cp.model_used, cp.platform);
const name = competitorDisplayName(cp.competitor_name, cp.competitor_id);
if (!compByProvider.has(name)) compByProvider.set(name, new Map());
const pm = compByProvider.get(name)!;
- const ex = pm.get(provider) ?? { totalScore: 0, count: 0 };
- ex.totalScore += Number(cp.sum_visibility);
- ex.count += cp.row_count;
- pm.set(provider, ex);
+ pm.set(provider, (pm.get(provider) ?? 0) + cp.visible_prompts);
}
const allProviders = new Set<string>();
@@ -1420,15 +1496,15 @@ export async function getCompetitorComparison(
const providerRows: ProviderComparisonRow[] = [...allProviders].sort().map((provider) => {
const row: ProviderComparisonRow = { provider };
const bp = brandByProvider.get(provider);
- row[brandName] = bp && bp.count > 0 ? Math.round(bp.totalScore / bp.count) : 0;
+ // Same-denominator rule: everyone divides by the brand bucket's prompt
+ // count (which spans every filtered prompt for the provider), not their
+ // own appearance count. Competitor rows are a subset of the brand's, so
+ // bp always exists when a competitor has data for the provider.
+ const denom = bp?.promptCount ?? 0;
+ row[brandName] = bp && denom > 0 ? Math.round((bp.visiblePrompts / denom) * 1000) / 10 : 0;
for (const [compName, pm] of compByProvider) {
- const cp = pm.get(provider);
- // Same-denominator rule: divide by the provider bucket's total run
- // count (the brand's, which spans every filtered row), not the
- // competitor's appearance count. Competitor rows are a subset of the
- // brand's, so bp always exists when cp does.
- const denom = bp?.count ?? 0;
- row[compName] = cp && denom > 0 ? Math.round(cp.totalScore / denom) : 0;
+ const visible = pm.get(provider) ?? 0;
+ row[compName] = denom > 0 ? Math.round((visible / denom) * 1000) / 10 : 0;
}
return row;
});
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 8ba309131..09bd6da48 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1204,6 +1204,18 @@ export type Database = {
};
Returns: number;
};
+ visible_prompt_stats: {
+ 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: Json;
+ };
prompt_visibility_summaries: {
Args: {
p_brand_id: string;