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): show the KPI cards in two rows, as in the v2 mockup (#1037)
Cihan5c10f7a489d2
diff --git a/supabase/migrations/00131_insights_kpi_cards.sql b/supabase/migrations/00131_insights_kpi_cards.sqlnew file mode 100644index 000000000..18a743f58--- /dev/null+++ b/supabase/migrations/00131_insights_kpi_cards.sql@@ -0,0 +1,696 @@+-- Insights KPI cards v2 (VIS-003).+--+-- The v2 mockup's KPI rows add Net sentiment (positive share minus negative+-- share of the answers naming the brand), Avg. position (mean position when+-- named), Citation rate, Coverage and Share of voice, each with a sparkline+-- and a change that follows "Compare: Same prompts" (00130).+--+-- The rollups had no negative count and no position sum (only the 1/position+-- sum behind the Visibility score), so both day-grain and prompt-grain brand+-- tables gain them. Like 00130, the columns are nullable: a day not rewritten+-- by refresh_insights_daily since this migration reads NULL, the functions+-- below report it (kpi_complete / complete = false) and the app shows those+-- two cards without a value instead of a partial one. After deploying, run+-- the backfill once (it covers 00130 too):+--+-- cd server && node src/scripts/backfill-insights-daily.js+--+-- Also here:+-- insights_aggregates[_daily] + citation, negative and position totals+-- insights_same_prompt_compare[_daily] + the same, the shared prompts that+-- appeared, and competitor mentions for+-- share of voice+-- insights_kpi_series (new) one row of components per day, for the+-- cards' sparklines++-- ─── Columns ────────────────────────────────────────────────────────────────++alter table public.insights_brand_daily+ add column if not exists negative_count integer,+ add column if not exists sum_position numeric;++alter table public.insights_prompt_daily+ add column if not exists negative_count integer,+ add column if not exists sum_position numeric;++comment on column public.insights_brand_daily.sum_position is+ 'Sum of mention_position over answers naming the brand (00131); with position_count gives the mean position. NULL until refresh_insights_daily rewrites the day.';++-- ─── Refresh: 00130 plus the new columns ────────────────────────────────────++create or replace function public.refresh_insights_daily(+ p_brand_id uuid,+ p_day_from date,+ p_day_to date+) returns void+language plpgsql+set search_path to 'public'+as $$+begin+ delete from public.insights_brand_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;++ insert into public.insights_brand_daily (+ brand_id, day, model_used, platform, region,+ answer_count, mention_answers, citation_answers, mentioning_answers,+ sum_visibility, sum_visibility_visible, total_mentions, total_citations,+ positive_count, sum_inv_position, position_count, max_created_at,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.model_used, pr.platform, pr.region,+ count(*),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ coalesce(sum(pr.visibility_score), 0),+ coalesce(sum(pr.visibility_score)+ filter (where pr.mention_count > 0 or pr.citation_count > 0), 0),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ count(*) filter (where pr.sentiment = 'positive'),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ max(pr.created_at),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ group by 2, pr.model_used, pr.platform, pr.region;++ insert into public.insights_prompt_daily (+ brand_id, day, prompt_id, model_used, platform, region,+ answer_count, has_mention, has_citation,+ mention_answers, citation_answers, mentioning_answers, positive_count,+ total_mentions, total_citations, sum_inv_position, position_count,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ count(*),+ bool_or(pr.mention_count > 0),+ bool_or(pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ count(*) filter (where pr.sentiment = 'positive'),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ group by 2, pr.prompt_id, pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_daily (+ brand_id, day, competitor_id, model_used, platform, region,+ answer_count, sum_visibility, total_mentions, total_citations,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.model_used, pr.platform, pr.region,+ count(*),+ sum((cm.value->>'visibility_score')::numeric),+ coalesce(sum(coalesce((cm.value->>'mention_count')::int, 0)), 0),+ coalesce(sum(coalesce((cm.value->>'citation_count')::int, 0)), 0),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ and cm.value ? 'competitor_id'+ group by 2, cm.value->>'competitor_id', pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_prompt_daily (+ brand_id, day, competitor_id, prompt_id, model_used, platform, region, mention_count,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ sum(coalesce((cm.value->>'mention_count')::int, 0)),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ and cm.value ? 'competitor_id'+ and (coalesce((cm.value->>'mention_count')::int, 0) > 0+ or coalesce((cm.value->>'citation_count')::int, 0) > 0+ or coalesce((cm.value->>'visibility_score')::numeric, 0) > 0)+ group by 2, cm.value->>'competitor_id', pr.prompt_id, pr.model_used, pr.platform, pr.region;+end;+$$;++revoke execute on function public.refresh_insights_daily(uuid, date, date)+ from public, anon, authenticated;++-- ─── Window totals: the cards' new components ──────────────────────────────++CREATE OR REPLACE FUNCTION public.insights_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.visibility_score, pr.mention_count, pr.citation_count,+ pr.sentiment, pr.model_used, pr.created_at, pr.mention_position+ 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))+ ),+ totals AS (+ SELECT+ COUNT(*) AS total_results,+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,+ COALESCE(SUM(mention_count), 0) AS total_mentions,+ COALESCE(SUM(citation_count), 0) AS total_citations,+ COUNT(*) FILTER (WHERE sentiment = 'positive') AS positive_count,+ COUNT(*) FILTER (WHERE mention_count > 0+ OR citation_count > 0) AS mentioning_results,+ MAX(created_at) AS last_checked_at,+ COUNT(*) FILTER (WHERE citation_count > 0) AS citation_answers,+ COUNT(*) FILTER (WHERE sentiment = 'negative') AS negative_count,+ SUM(mention_position)+ FILTER (WHERE mention_position IS NOT NULL) AS sum_position,+ COUNT(*) FILTER (WHERE mention_position IS NOT NULL) AS position_count+ FROM filtered+ ),+ by_model AS (+ SELECT+ COALESCE(model_used, 'unknown') AS model_used,+ SUM(visibility_score) AS sum_visibility,+ COUNT(*) AS result_count+ FROM filtered+ GROUP BY COALESCE(model_used, 'unknown')+ )+ SELECT jsonb_build_object(+ 'total_results', t.total_results,+ 'sum_visibility', t.sum_visibility,+ 'total_mentions', t.total_mentions,+ 'total_citations', t.total_citations,+ 'positive_count', t.positive_count,+ 'mentioning_results', t.mentioning_results,+ 'last_checked_at', t.last_checked_at,+ 'citation_answers', t.citation_answers,+ 'negative_count', t.negative_count,+ 'sum_position', t.sum_position,+ 'position_count', t.position_count,+ 'kpi_complete', true,+ 'by_model', COALESCE(+ (SELECT jsonb_agg(jsonb_build_object(+ 'model_used', bm.model_used,+ 'sum_visibility', bm.sum_visibility,+ 'result_count', bm.result_count)+ ORDER BY bm.result_count DESC, bm.model_used)+ FROM by_model bm),+ '[]'::jsonb)+ )+ FROM totals t;+$$;++create or replace function public.insights_aggregates_daily(+ p_brand_id uuid,+ p_platform text default null,+ p_models text[] default null,+ p_region text default null,+ p_day_from date default null,+ p_day_to date default null+) returns jsonb+language sql+stable+set search_path to 'public'+as $$+ with filtered as (+ select * from public.insights_brand_daily d+ where d.brand_id = p_brand_id+ and (p_platform is null or d.platform = p_platform)+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (p_day_from is null or d.day >= p_day_from)+ and (p_day_to is null or d.day <= p_day_to)+ ),+ totals as (+ select+ coalesce(sum(answer_count), 0) as total_results,+ coalesce(sum(sum_visibility), 0) as sum_visibility,+ coalesce(sum(total_mentions), 0) as total_mentions,+ coalesce(sum(total_citations), 0) as total_citations,+ coalesce(sum(positive_count), 0) as positive_count,+ coalesce(sum(mentioning_answers), 0) as mentioning_results,+ max(max_created_at) as last_checked_at,+ coalesce(sum(citation_answers), 0) as citation_answers,+ coalesce(sum(negative_count), 0) as negative_count,+ sum(sum_position) as sum_position,+ coalesce(sum(position_count), 0) as position_count,+ -- A day not rewritten since 00131 has no negative or position totals.+ not exists (select 1 from filtered where negative_count is null) as kpi_complete+ from filtered+ ),+ by_model as (+ select+ coalesce(model_used, 'unknown') as model_used,+ sum(sum_visibility) as sum_visibility,+ sum(answer_count) as result_count+ from filtered+ group by coalesce(model_used, 'unknown')+ )+ select jsonb_build_object(+ 'total_results', t.total_results,+ 'sum_visibility', t.sum_visibility,+ 'total_mentions', t.total_mentions,+ 'total_citations', t.total_citations,+ 'positive_count', t.positive_count,+ 'mentioning_results', t.mentioning_results,+ 'last_checked_at', t.last_checked_at,+ 'citation_answers', t.citation_answers,+ 'negative_count', t.negative_count,+ 'sum_position', t.sum_position,+ 'position_count', t.position_count,+ 'kpi_complete', t.kpi_complete,+ 'by_model', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', bm.model_used,+ 'sum_visibility', bm.sum_visibility,+ 'result_count', bm.result_count)+ order by bm.result_count desc, bm.model_used)+ from by_model bm),+ '[]'::jsonb)+ )+ from totals t;+$$;++-- ─── Same prompts: the new components too ──────────────────────────────────++create or replace function public.insights_same_prompt_compare_daily(+ p_brand_id uuid,+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_models text[] default null,+ p_region text default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*,+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur' and answer_count > 0) as in_cur,+ bool_or(win = 'prev' and answer_count > 0) as in_prev+ from prompt_rows+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ brand_agg as (+ select r.win,+ sum(r.answer_count) as answers,+ sum(r.mention_answers) as mention_answers,+ sum(r.citation_answers) as citation_answers,+ sum(r.sum_inv_position) / nullif(sum(r.position_count), 0) as position_factor,+ sum(r.total_mentions) as total_mentions,+ sum(r.total_citations) as total_citations,+ sum(r.positive_count) as positive_count,+ sum(r.mentioning_answers) as mentioning_answers,+ sum(r.negative_count) as negative_count,+ sum(r.sum_position) as sum_position,+ sum(r.position_count) as position_count,+ count(distinct r.prompt_id) filter (where r.has_mention or r.has_citation)+ as visible_prompts+ from prompt_rows r+ join same_prompts s using (prompt_id)+ group by r.win+ ),+ comp_rows as (+ select cd.*,+ case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win+ from public.insights_competitor_prompt_daily cd+ join same_prompts s using (prompt_id)+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ ),+ -- Competitors tracked in each window, from the dense day-grain table: the+ -- prompt-grain one only records sightings, so it can't tell a competitor+ -- never named from one not tracked yet. A competitor added during the+ -- period then has no previous value, as on all prompts, instead of a gain+ -- from 0.+ tracked as (+ select distinct+ case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ cd.competitor_id+ from public.insights_competitor_daily cd+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ ),+ comp_agg as (+ select t.win,+ t.competitor_id,+ max(c.name) as name,+ coalesce(sum(cr.mention_answers), 0) as mention_answers,+ coalesce(sum(cr.citation_answers), 0) as citation_answers,+ sum(cr.sum_inv_position) / nullif(sum(cr.position_count), 0) as position_factor+ from tracked t+ join public.competitors c+ on c.id::text = t.competitor_id and c.brand_id = p_brand_id+ left join comp_rows cr+ on cr.win = t.win and cr.competitor_id = t.competitor_id+ group by t.win, t.competitor_id+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice+ -- (which counts all competitors, as share_of_voice_aggregates does).+ comp_mentions as (+ select win, sum(mention_count) as mentions from comp_rows group by win+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', not exists (+ select 1 from prompt_rows+ where mention_answers is null or negative_count is null)+ and not exists (select 1 from comp_rows where mention_answers is null),+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ );+$$;++create or replace function public.insights_same_prompt_compare(+ p_brand_id uuid,+ p_cur_from timestamptz,+ p_cur_to timestamptz,+ p_prev_from timestamptz,+ p_prev_to timestamptz,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with filtered as (+ select pr.prompt_id, pr.created_at, pr.mention_count, pr.citation_count,+ pr.mention_position, pr.sentiment, pr.competitor_mentions+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (p_models is null or pr.model_used = any (p_models))+ and (p_region is null or pr.region = p_region)+ and pr.created_at >= p_prev_from+ and pr.created_at <= p_cur_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))+ ),+ windowed as (+ select 'cur' as win, f.* from filtered f+ where f.created_at >= p_cur_from and f.created_at <= p_cur_to+ union all+ select 'prev' as win, f.* from filtered f+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur') as in_cur,+ bool_or(win = 'prev') as in_prev+ from windowed+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ same_rows as (+ select w.* from windowed w join same_prompts s using (prompt_id)+ ),+ brand_agg as (+ select win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ avg(1.0 / mention_position) filter (where mention_position is not null)+ as position_factor,+ coalesce(sum(mention_count), 0) as total_mentions,+ coalesce(sum(citation_count), 0) as total_citations,+ count(*) filter (where sentiment = 'positive') as positive_count,+ count(*) filter (where mention_count > 0 or citation_count > 0)+ as mentioning_answers,+ count(*) filter (where sentiment = 'negative') as negative_count,+ sum(mention_position) filter (where mention_position is not null)+ as sum_position,+ count(*) filter (where mention_position is not null) as position_count,+ count(distinct prompt_id) filter (where mention_count > 0 or citation_count > 0)+ as visible_prompts+ from same_rows+ group by win+ ),+ comp_agg as (+ select r.win,+ cm.value->>'competitor_id' as competitor_id,+ max(c.name) as name,+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0)+ as mention_answers,+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0)+ as citation_answers,+ avg(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null)+ as position_factor+ from same_rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ join public.competitors c+ on c.id::text = cm.value->>'competitor_id' and c.brand_id = p_brand_id+ where cm.value ? 'competitor_id'+ group by r.win, cm.value->>'competitor_id'+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice.+ comp_mentions as (+ select r.win, sum(coalesce((cm.value->>'mention_count')::int, 0)) as mentions+ from same_rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ where cm.value ? 'competitor_id'+ group by r.win+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', true,+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ );+$$;++-- ─── Sparklines: one row of components per day ────────────────────────────+--+-- From the prompt-grain rollups, so a topic filter works too (a topic is a+-- set of prompts). Each day's values are that day's own, for the cards'+-- sparklines; the card values themselves come from the window aggregates.++create or replace function public.insights_kpi_series(+ p_brand_id uuid,+ p_day_from date default null,+ p_day_to date default null,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (p_day_from is null or d.day >= p_day_from)+ and (p_day_to is null or d.day <= p_day_to)+ and (p_topic_id is null or exists (+ select 1 from public.prompts p+ where p.id = d.prompt_id and p.topic_id = p_topic_id))+ ),+ comp_days as (+ select cd.day, sum(cd.mention_count) as competitor_mentions+ from public.insights_competitor_prompt_daily cd+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (p_day_from is null or cd.day >= p_day_from)+ and (p_day_to is null or cd.day <= p_day_to)+ and (p_topic_id is null or exists (+ select 1 from public.prompts p+ where p.id = cd.prompt_id and p.topic_id = p_topic_id))+ group by cd.day+ ),+ days as (+ select r.day,+ sum(r.answer_count) as answers,+ sum(r.citation_answers) as citation_answers,+ sum(r.total_mentions) as total_mentions,+ sum(r.total_citations) as total_citations,+ sum(r.positive_count) as positive_count,+ sum(r.negative_count) as negative_count,+ sum(r.mentioning_answers) as mentioning_answers,+ sum(r.sum_position) as sum_position,+ sum(r.position_count) as position_count,+ count(distinct r.prompt_id) filter (where r.has_mention or r.has_citation)+ as visible_prompts,+ count(distinct r.prompt_id) as active_prompts+ from prompt_rows r+ group by r.day+ )+ select jsonb_build_object(+ 'complete', not exists (+ select 1 from prompt_rows+ where mention_answers is null or negative_count is null),+ 'days', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'day', d.day,+ 'answers', d.answers,+ 'citation_answers', d.citation_answers,+ 'total_mentions', d.total_mentions,+ 'total_citations', d.total_citations,+ 'positive_count', d.positive_count,+ 'negative_count', d.negative_count,+ 'mentioning_answers', d.mentioning_answers,+ 'sum_position', d.sum_position,+ 'position_count', d.position_count,+ 'visible_prompts', d.visible_prompts,+ 'active_prompts', d.active_prompts,+ 'competitor_mentions', coalesce(c.competitor_mentions, 0))+ order by d.day)+ from days d+ left join comp_days c using (day)),+ '[]'::jsonb)+ );+$$;++revoke all on function public.insights_kpi_series(uuid, date, date, text[], text, uuid) from public;+grant execute on function public.insights_kpi_series(uuid, date, date, text[], text, uuid)+ to authenticated, service_role;++comment on function public.insights_kpi_series(uuid, date, date, text[], text, uuid) is+ 'Insights KPI sparklines (VIS-003, 00131): the cards'' components per day from the prompt-grain rollups, topic filter included. complete=false until the rows are rewritten by refresh_insights_daily.';diff --git a/supabase/migrations/00149_insights_kpi_same_prompts_definer.sql b/supabase/migrations/00149_insights_kpi_same_prompts_definer.sqlnew file mode 100644index 000000000..b26ed99df--- /dev/null+++ b/supabase/migrations/00149_insights_kpi_same_prompts_definer.sql@@ -0,0 +1,353 @@+-- The KPI cards' "Same prompts" read, made fast again (#1036 review).+--+-- 00147 (#1036) rewrote insights_same_prompt_compare[_daily] as plpgsql,+-- security definer, with the organization check made explicit, because the+-- SQL-language version timed out on the largest brand: 4.5 s as the table+-- owner, over 30 s for a signed-in member against the authenticated role's+-- 8 s statement_timeout. It carries 00130's output, so on this branch it+-- would drop the components 00131 added (negative count, position sum and+-- count, visible prompts, competitor mentions). This is 00131's output with+-- 00147's shape: planned per call with its real arguments+-- (force_custom_plan), no RLS inside the scan, the rollup rows folded to one+-- row per prompt and window first, and the raw rows kept once. The service+-- role still reads, for the cached 24h view (cachedAnchoredInsights).++-- ─── Over the rollups (whole-day windows) ──────────────────────────────────++create or replace function public.insights_same_prompt_compare_daily(+ p_brand_id uuid,+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_models text[] default null,+ p_region text default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ with per_prompt as (+ -- One row per prompt and window: nothing below reads the per-day rows.+ select d.prompt_id,+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ sum(d.answer_count) as answers,+ sum(d.mention_answers) as mention_answers,+ sum(d.citation_answers) as citation_answers,+ sum(d.sum_inv_position) as sum_inv_position,+ sum(d.position_count) as position_count,+ sum(d.total_mentions) as total_mentions,+ sum(d.total_citations) as total_citations,+ sum(d.positive_count) as positive_count,+ sum(d.mentioning_answers) as mentioning_answers,+ sum(d.negative_count) as negative_count,+ sum(d.sum_position) as sum_position,+ bool_or(d.has_mention or d.has_citation) as visible,+ bool_or(d.mention_answers is null or d.negative_count is null) as stale+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)+ group by 1, 2+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur' and answers > 0) as in_cur,+ bool_or(win = 'prev' and answers > 0) as in_prev+ from per_prompt+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ brand_agg as (+ select p.win,+ sum(p.answers) as answers,+ sum(p.mention_answers) as mention_answers,+ sum(p.citation_answers) as citation_answers,+ sum(p.sum_inv_position) / nullif(sum(p.position_count), 0) as position_factor,+ sum(p.total_mentions) as total_mentions,+ sum(p.total_citations) as total_citations,+ sum(p.positive_count) as positive_count,+ sum(p.mentioning_answers) as mentioning_answers,+ sum(p.negative_count) as negative_count,+ sum(p.sum_position) as sum_position,+ sum(p.position_count) as position_count,+ count(*) filter (where p.visible) as visible_prompts+ from per_prompt p+ join same_prompts s using (prompt_id)+ group by p.win+ ),+ comp_sums as (+ select case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ cd.competitor_id,+ sum(cd.mention_answers) as mention_answers,+ sum(cd.citation_answers) as citation_answers,+ sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor,+ sum(cd.mention_count) as mentions,+ bool_or(cd.mention_answers is null) as stale+ from public.insights_competitor_prompt_daily cd+ where cd.brand_id = p_brand_id+ and cd.prompt_id in (select prompt_id from same_prompts)+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ group by 1, 2+ ),+ -- Competitors tracked in each window, from the dense day-grain table (see+ -- 00130): one added during the period then has no previous value.+ tracked as (+ select distinct+ case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ cd.competitor_id+ from public.insights_competitor_daily cd+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ ),+ comp_agg as (+ select t.win,+ t.competitor_id,+ c.name,+ coalesce(cs.mention_answers, 0) as mention_answers,+ coalesce(cs.citation_answers, 0) as citation_answers,+ cs.position_factor+ from tracked t+ join public.competitors c+ on c.id::text = t.competitor_id and c.brand_id = p_brand_id+ left join comp_sums cs+ on cs.win = t.win and cs.competitor_id = t.competitor_id+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice+ -- (which counts all competitors, as share_of_voice_aggregates does).+ comp_mentions as (+ select win, sum(mentions) as mentions from comp_sums group by win+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', not exists (select 1 from per_prompt where stale)+ and not exists (select 1 from comp_sums where stale),+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ )+ into v_result;++ return v_result;+end;+$$;++-- ─── Over the raw rows (24h and topic views) ───────────────────────────────++create or replace function public.insights_same_prompt_compare(+ p_brand_id uuid,+ p_cur_from timestamptz,+ p_cur_to timestamptz,+ p_prev_from timestamptz,+ p_prev_to timestamptz,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ with filtered as (+ select pr.prompt_id, pr.mention_count, pr.citation_count,+ pr.mention_position, pr.sentiment, pr.competitor_mentions,+ pr.created_at >= p_cur_from and pr.created_at <= p_cur_to as in_cur,+ pr.created_at >= p_prev_from and pr.created_at <= p_prev_to as in_prev+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (p_models is null or pr.model_used = any (p_models))+ and (p_region is null or pr.region = p_region)+ and pr.created_at >= p_prev_from+ and pr.created_at <= p_cur_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))+ ),+ presence as (+ select prompt_id,+ bool_or(in_cur) as in_cur,+ bool_or(in_prev) as in_prev+ from filtered+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ -- Each window selected on its own, inclusive at both ends like+ -- ai_visibility_aggregates: an answer exactly on the boundary counts in+ -- both, as it does on the card.+ same_rows as not materialized (+ select w.win, f.*+ from filtered f+ join same_prompts s using (prompt_id)+ cross join lateral (values ('cur', f.in_cur), ('prev', f.in_prev)) w(win, inside)+ where w.inside+ ),+ brand_agg as (+ select win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ avg(1.0 / mention_position) filter (where mention_position is not null)+ as position_factor,+ coalesce(sum(mention_count), 0) as total_mentions,+ coalesce(sum(citation_count), 0) as total_citations,+ count(*) filter (where sentiment = 'positive') as positive_count,+ count(*) filter (where mention_count > 0 or citation_count > 0)+ as mentioning_answers,+ count(*) filter (where sentiment = 'negative') as negative_count,+ sum(mention_position) filter (where mention_position is not null)+ as sum_position,+ count(*) filter (where mention_position is not null) as position_count,+ count(distinct prompt_id) filter (where mention_count > 0 or citation_count > 0)+ as visible_prompts+ from same_rows+ group by win+ ),+ -- The competitor entries of the shared prompts' answers, unpacked once.+ comp_entries as materialized (+ select r.win, cm.value as entry+ from same_rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ where cm.value ? 'competitor_id'+ ),+ comp_agg as (+ select e.win,+ e.entry->>'competitor_id' as competitor_id,+ max(c.name) as name,+ count(*) filter (where coalesce((e.entry->>'mention_count')::int, 0) > 0)+ as mention_answers,+ count(*) filter (where coalesce((e.entry->>'citation_count')::int, 0) > 0)+ as citation_answers,+ avg(1.0 / (e.entry->>'mention_position')::numeric)+ filter (where (e.entry->>'mention_position') is not null)+ as position_factor+ from comp_entries e+ join public.competitors c+ on c.id::text = e.entry->>'competitor_id' and c.brand_id = p_brand_id+ group by e.win, e.entry->>'competitor_id'+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice.+ comp_mentions as (+ select win, sum(coalesce((entry->>'mention_count')::int, 0)) as mentions+ from comp_entries+ group by win+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', true,+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ )+ into v_result;++ return v_result;+end;+$$;++revoke execute on function public.insights_same_prompt_compare_daily(+ uuid, date, date, date, date, text[], text+) from public, anon;+grant execute on function public.insights_same_prompt_compare_daily(+ uuid, date, date, date, date, text[], text+) to authenticated, service_role;++revoke execute on function public.insights_same_prompt_compare(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid+) from public, anon;+grant execute on function public.insights_same_prompt_compare(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid+) to authenticated, service_role;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 5095ac277..4b60df96c 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -15416,35 +15416,1052 @@ comment on function public.insights_same_prompt_compare() is'Insights "Same prompts" (VIS-002, 00130) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_same_prompt_compare_daily.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00131_insights_kpi_cards.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Insights KPI cards v2 (VIS-003).+--+-- The v2 mockup's KPI rows add Net sentiment (positive share minus negative+-- share of the answers naming the brand), Avg. position (mean position when+-- named), Citation rate, Coverage and Share of voice, each with a sparkline+-- and a change that follows "Compare: Same prompts" (00130).+--+-- The rollups had no negative count and no position sum (only the 1/position+-- sum behind the Visibility score), so both day-grain and prompt-grain brand+-- tables gain them. Like 00130, the columns are nullable: a day not rewritten+-- by refresh_insights_daily since this migration reads NULL, the functions+-- below report it (kpi_complete / complete = false) and the app shows those+-- two cards without a value instead of a partial one. After deploying, run+-- the backfill once (it covers 00130 too):+--+-- cd server && node src/scripts/backfill-insights-daily.js+--+-- Also here:+-- insights_aggregates[_daily] + citation, negative and position totals+-- insights_same_prompt_compare[_daily] + the same, the shared prompts that+-- appeared, and competitor mentions for+-- share of voice+-- insights_kpi_series (new) one row of components per day, for the+-- cards' sparklines++-- ─── Columns ────────────────────────────────────────────────────────────────++alter table public.insights_brand_daily+ add column if not exists negative_count integer,+ add column if not exists sum_position numeric;++alter table public.insights_prompt_daily+ add column if not exists negative_count integer,+ add column if not exists sum_position numeric;++comment on column public.insights_brand_daily.sum_position is+ 'Sum of mention_position over answers naming the brand (00131); with position_count gives the mean position. NULL until refresh_insights_daily rewrites the day.';++-- ─── Refresh: 00130 plus the new columns ────────────────────────────────────++create or replace function public.refresh_insights_daily(+ p_brand_id uuid,+ p_day_from date,+ p_day_to date+) returns void+language plpgsql+set search_path to 'public'+as $$+begin+ delete from public.insights_brand_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;++ insert into public.insights_brand_daily (+ brand_id, day, model_used, platform, region,+ answer_count, mention_answers, citation_answers, mentioning_answers,+ sum_visibility, sum_visibility_visible, total_mentions, total_citations,+ positive_count, sum_inv_position, position_count, max_created_at,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.model_used, pr.platform, pr.region,+ count(*),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ coalesce(sum(pr.visibility_score), 0),+ coalesce(sum(pr.visibility_score)+ filter (where pr.mention_count > 0 or pr.citation_count > 0), 0),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ count(*) filter (where pr.sentiment = 'positive'),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ max(pr.created_at),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ group by 2, pr.model_used, pr.platform, pr.region;++ insert into public.insights_prompt_daily (+ brand_id, day, prompt_id, model_used, platform, region,+ answer_count, has_mention, has_citation,+ mention_answers, citation_answers, mentioning_answers, positive_count,+ total_mentions, total_citations, sum_inv_position, position_count,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ count(*),+ bool_or(pr.mention_count > 0),+ bool_or(pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ count(*) filter (where pr.sentiment = 'positive'),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ group by 2, pr.prompt_id, pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_daily (+ brand_id, day, competitor_id, model_used, platform, region,+ answer_count, sum_visibility, total_mentions, total_citations,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.model_used, pr.platform, pr.region,+ count(*),+ sum((cm.value->>'visibility_score')::numeric),+ coalesce(sum(coalesce((cm.value->>'mention_count')::int, 0)), 0),+ coalesce(sum(coalesce((cm.value->>'citation_count')::int, 0)), 0),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ and cm.value ? 'competitor_id'+ group by 2, cm.value->>'competitor_id', pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_prompt_daily (+ brand_id, day, competitor_id, prompt_id, model_used, platform, region, mention_count,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ sum(coalesce((cm.value->>'mention_count')::int, 0)),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and (pr.created_at at time zone 'utc')::date between p_day_from and p_day_to+ and cm.value ? 'competitor_id'+ and (coalesce((cm.value->>'mention_count')::int, 0) > 0+ or coalesce((cm.value->>'citation_count')::int, 0) > 0+ or coalesce((cm.value->>'visibility_score')::numeric, 0) > 0)+ group by 2, cm.value->>'competitor_id', pr.prompt_id, pr.model_used, pr.platform, pr.region;+end;+$$;++revoke execute on function public.refresh_insights_daily(uuid, date, date)+ from public, anon, authenticated;++-- ─── Window totals: the cards' new components ──────────────────────────────++CREATE OR REPLACE FUNCTION public.insights_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.visibility_score, pr.mention_count, pr.citation_count,+ pr.sentiment, pr.model_used, pr.created_at, pr.mention_position+ 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))+ ),+ totals AS (+ SELECT+ COUNT(*) AS total_results,+ COALESCE(SUM(visibility_score), 0) AS sum_visibility,+ COALESCE(SUM(mention_count), 0) AS total_mentions,+ COALESCE(SUM(citation_count), 0) AS total_citations,+ COUNT(*) FILTER (WHERE sentiment = 'positive') AS positive_count,+ COUNT(*) FILTER (WHERE mention_count > 0+ OR citation_count > 0) AS mentioning_results,+ MAX(created_at) AS last_checked_at,+ COUNT(*) FILTER (WHERE citation_count > 0) AS citation_answers,+ COUNT(*) FILTER (WHERE sentiment = 'negative') AS negative_count,+ SUM(mention_position)+ FILTER (WHERE mention_position IS NOT NULL) AS sum_position,+ COUNT(*) FILTER (WHERE mention_position IS NOT NULL) AS position_count+ FROM filtered+ ),+ by_model AS (+ SELECT+ COALESCE(model_used, 'unknown') AS model_used,+ SUM(visibility_score) AS sum_visibility,+ COUNT(*) AS result_count+ FROM filtered+ GROUP BY COALESCE(model_used, 'unknown')+ )+ SELECT jsonb_build_object(+ 'total_results', t.total_results,+ 'sum_visibility', t.sum_visibility,+ 'total_mentions', t.total_mentions,+ 'total_citations', t.total_citations,+ 'positive_count', t.positive_count,+ 'mentioning_results', t.mentioning_results,+ 'last_checked_at', t.last_checked_at,+ 'citation_answers', t.citation_answers,+ 'negative_count', t.negative_count,+ 'sum_position', t.sum_position,+ 'position_count', t.position_count,+ 'kpi_complete', true,+ 'by_model', COALESCE(+ (SELECT jsonb_agg(jsonb_build_object(+ 'model_used', bm.model_used,+ 'sum_visibility', bm.sum_visibility,+ 'result_count', bm.result_count)+ ORDER BY bm.result_count DESC, bm.model_used)+ FROM by_model bm),+ '[]'::jsonb)+ )+ FROM totals t;+$$;++create or replace function public.insights_aggregates_daily(+ p_brand_id uuid,+ p_platform text default null,+ p_models text[] default null,+ p_region text default null,+ p_day_from date default null,+ p_day_to date default null+) returns jsonb+language sql+stable+set search_path to 'public'+as $$+ with filtered as (+ select * from public.insights_brand_daily d+ where d.brand_id = p_brand_id+ and (p_platform is null or d.platform = p_platform)+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (p_day_from is null or d.day >= p_day_from)+ and (p_day_to is null or d.day <= p_day_to)+ ),+ totals as (+ select+ coalesce(sum(answer_count), 0) as total_results,+ coalesce(sum(sum_visibility), 0) as sum_visibility,+ coalesce(sum(total_mentions), 0) as total_mentions,+ coalesce(sum(total_citations), 0) as total_citations,+ coalesce(sum(positive_count), 0) as positive_count,+ coalesce(sum(mentioning_answers), 0) as mentioning_results,+ max(max_created_at) as last_checked_at,+ coalesce(sum(citation_answers), 0) as citation_answers,+ coalesce(sum(negative_count), 0) as negative_count,+ sum(sum_position) as sum_position,+ coalesce(sum(position_count), 0) as position_count,+ -- A day not rewritten since 00131 has no negative or position totals.+ not exists (select 1 from filtered where negative_count is null) as kpi_complete+ from filtered+ ),+ by_model as (+ select+ coalesce(model_used, 'unknown') as model_used,+ sum(sum_visibility) as sum_visibility,+ sum(answer_count) as result_count+ from filtered+ group by coalesce(model_used, 'unknown')+ )+ select jsonb_build_object(+ 'total_results', t.total_results,+ 'sum_visibility', t.sum_visibility,+ 'total_mentions', t.total_mentions,+ 'total_citations', t.total_citations,+ 'positive_count', t.positive_count,+ 'mentioning_results', t.mentioning_results,+ 'last_checked_at', t.last_checked_at,+ 'citation_answers', t.citation_answers,+ 'negative_count', t.negative_count,+ 'sum_position', t.sum_position,+ 'position_count', t.position_count,+ 'kpi_complete', t.kpi_complete,+ 'by_model', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'model_used', bm.model_used,+ 'sum_visibility', bm.sum_visibility,+ 'result_count', bm.result_count)+ order by bm.result_count desc, bm.model_used)+ from by_model bm),+ '[]'::jsonb)+ )+ from totals t;+$$;++-- ─── Same prompts: the new components too ──────────────────────────────────++create or replace function public.insights_same_prompt_compare_daily(+ p_brand_id uuid,+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_models text[] default null,+ p_region text default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*,+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur' and answer_count > 0) as in_cur,+ bool_or(win = 'prev' and answer_count > 0) as in_prev+ from prompt_rows+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ brand_agg as (+ select r.win,+ sum(r.answer_count) as answers,+ sum(r.mention_answers) as mention_answers,+ sum(r.citation_answers) as citation_answers,+ sum(r.sum_inv_position) / nullif(sum(r.position_count), 0) as position_factor,+ sum(r.total_mentions) as total_mentions,+ sum(r.total_citations) as total_citations,+ sum(r.positive_count) as positive_count,+ sum(r.mentioning_answers) as mentioning_answers,+ sum(r.negative_count) as negative_count,+ sum(r.sum_position) as sum_position,+ sum(r.position_count) as position_count,+ count(distinct r.prompt_id) filter (where r.has_mention or r.has_citation)+ as visible_prompts+ from prompt_rows r+ join same_prompts s using (prompt_id)+ group by r.win+ ),+ comp_rows as (+ select cd.*,+ case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win+ from public.insights_competitor_prompt_daily cd+ join same_prompts s using (prompt_id)+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ ),+ -- Competitors tracked in each window, from the dense day-grain table: the+ -- prompt-grain one only records sightings, so it can't tell a competitor+ -- never named from one not tracked yet. A competitor added during the+ -- period then has no previous value, as on all prompts, instead of a gain+ -- from 0.+ tracked as (+ select distinct+ case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ cd.competitor_id+ from public.insights_competitor_daily cd+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ ),+ comp_agg as (+ select t.win,+ t.competitor_id,+ max(c.name) as name,+ coalesce(sum(cr.mention_answers), 0) as mention_answers,+ coalesce(sum(cr.citation_answers), 0) as citation_answers,+ sum(cr.sum_inv_position) / nullif(sum(cr.position_count), 0) as position_factor+ from tracked t+ join public.competitors c+ on c.id::text = t.competitor_id and c.brand_id = p_brand_id+ left join comp_rows cr+ on cr.win = t.win and cr.competitor_id = t.competitor_id+ group by t.win, t.competitor_id+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice+ -- (which counts all competitors, as share_of_voice_aggregates does).+ comp_mentions as (+ select win, sum(mention_count) as mentions from comp_rows group by win+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', not exists (+ select 1 from prompt_rows+ where mention_answers is null or negative_count is null)+ and not exists (select 1 from comp_rows where mention_answers is null),+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ );+$$;++create or replace function public.insights_same_prompt_compare(+ p_brand_id uuid,+ p_cur_from timestamptz,+ p_cur_to timestamptz,+ p_prev_from timestamptz,+ p_prev_to timestamptz,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with filtered as (+ select pr.prompt_id, pr.created_at, pr.mention_count, pr.citation_count,+ pr.mention_position, pr.sentiment, pr.competitor_mentions+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (p_models is null or pr.model_used = any (p_models))+ and (p_region is null or pr.region = p_region)+ and pr.created_at >= p_prev_from+ and pr.created_at <= p_cur_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))+ ),+ windowed as (+ select 'cur' as win, f.* from filtered f+ where f.created_at >= p_cur_from and f.created_at <= p_cur_to+ union all+ select 'prev' as win, f.* from filtered f+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur') as in_cur,+ bool_or(win = 'prev') as in_prev+ from windowed+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ same_rows as (+ select w.* from windowed w join same_prompts s using (prompt_id)+ ),+ brand_agg as (+ select win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ avg(1.0 / mention_position) filter (where mention_position is not null)+ as position_factor,+ coalesce(sum(mention_count), 0) as total_mentions,+ coalesce(sum(citation_count), 0) as total_citations,+ count(*) filter (where sentiment = 'positive') as positive_count,+ count(*) filter (where mention_count > 0 or citation_count > 0)+ as mentioning_answers,+ count(*) filter (where sentiment = 'negative') as negative_count,+ sum(mention_position) filter (where mention_position is not null)+ as sum_position,+ count(*) filter (where mention_position is not null) as position_count,+ count(distinct prompt_id) filter (where mention_count > 0 or citation_count > 0)+ as visible_prompts+ from same_rows+ group by win+ ),+ comp_agg as (+ select r.win,+ cm.value->>'competitor_id' as competitor_id,+ max(c.name) as name,+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0)+ as mention_answers,+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0)+ as citation_answers,+ avg(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null)+ as position_factor+ from same_rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ join public.competitors c+ on c.id::text = cm.value->>'competitor_id' and c.brand_id = p_brand_id+ where cm.value ? 'competitor_id'+ group by r.win, cm.value->>'competitor_id'+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice.+ comp_mentions as (+ select r.win, sum(coalesce((cm.value->>'mention_count')::int, 0)) as mentions+ from same_rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ where cm.value ? 'competitor_id'+ group by r.win+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', true,+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ );+$$;++-- ─── Sparklines: one row of components per day ────────────────────────────+--+-- From the prompt-grain rollups, so a topic filter works too (a topic is a+-- set of prompts). Each day's values are that day's own, for the cards'+-- sparklines; the card values themselves come from the window aggregates.++create or replace function public.insights_kpi_series(+ p_brand_id uuid,+ p_day_from date default null,+ p_day_to date default null,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with prompt_rows as (+ select d.*+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (p_day_from is null or d.day >= p_day_from)+ and (p_day_to is null or d.day <= p_day_to)+ and (p_topic_id is null or exists (+ select 1 from public.prompts p+ where p.id = d.prompt_id and p.topic_id = p_topic_id))+ ),+ comp_days as (+ select cd.day, sum(cd.mention_count) as competitor_mentions+ from public.insights_competitor_prompt_daily cd+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (p_day_from is null or cd.day >= p_day_from)+ and (p_day_to is null or cd.day <= p_day_to)+ and (p_topic_id is null or exists (+ select 1 from public.prompts p+ where p.id = cd.prompt_id and p.topic_id = p_topic_id))+ group by cd.day+ ),+ days as (+ select r.day,+ sum(r.answer_count) as answers,+ sum(r.citation_answers) as citation_answers,+ sum(r.total_mentions) as total_mentions,+ sum(r.total_citations) as total_citations,+ sum(r.positive_count) as positive_count,+ sum(r.negative_count) as negative_count,+ sum(r.mentioning_answers) as mentioning_answers,+ sum(r.sum_position) as sum_position,+ sum(r.position_count) as position_count,+ count(distinct r.prompt_id) filter (where r.has_mention or r.has_citation)+ as visible_prompts,+ count(distinct r.prompt_id) as active_prompts+ from prompt_rows r+ group by r.day+ )+ select jsonb_build_object(+ 'complete', not exists (+ select 1 from prompt_rows+ where mention_answers is null or negative_count is null),+ 'days', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'day', d.day,+ 'answers', d.answers,+ 'citation_answers', d.citation_answers,+ 'total_mentions', d.total_mentions,+ 'total_citations', d.total_citations,+ 'positive_count', d.positive_count,+ 'negative_count', d.negative_count,+ 'mentioning_answers', d.mentioning_answers,+ 'sum_position', d.sum_position,+ 'position_count', d.position_count,+ 'visible_prompts', d.visible_prompts,+ 'active_prompts', d.active_prompts,+ 'competitor_mentions', coalesce(c.competitor_mentions, 0))+ order by d.day)+ from days d+ left join comp_days c using (day)),+ '[]'::jsonb)+ );+$$;++revoke all on function public.insights_kpi_series(uuid, date, date, text[], text, uuid) from public;+grant execute on function public.insights_kpi_series(uuid, date, date, text[], text, uuid)+ to authenticated, service_role;++comment on function public.insights_kpi_series(uuid, date, date, text[], text, uuid) is+ 'Insights KPI sparklines (VIS-003, 00131): the cards'' components per day from the prompt-grain rollups, topic filter included. complete=false until the rows are rewritten by refresh_insights_daily.';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00147_insights_same_prompts_definer.sql-- ─────────────────────────────────────────────────────────────────────────--- "Compare: Same prompts" timed out on the largest brand (#1036 review).------ insights_same_prompt_compare_daily (00130) took 4.5 s as the table owner--- and over 30 s for a signed-in member on the largest brand (~219k answers,--- 30 days against the 30 before). The authenticated role's statement_timeout--- is 8 s, so every Insights open fell back to comparing all prompts. Two--- causes:------ * A SQL-language function is planned without its argument values--- (PostgreSQL 17 and older), so the brand and both day ranges were--- guesses: a range between unknown bounds is estimated at 0.5% of the--- rows. The plan, and the RLS membership subquery planned into it, were--- built for a few hundred rows and got ~200k. plan_cache_mode does not--- reach SQL functions, which is why force_custom_plan did not help.--- * The per-day rollup rows were joined to the shared prompts again for--- the totals, after being grouped once for the presence check.+-- "Compare: Same prompts" timed out on the largest brand (#1036 review).+--+-- insights_same_prompt_compare_daily (00130) took 4.5 s as the table owner+-- and over 30 s for a signed-in member on the largest brand (~219k answers,+-- 30 days against the 30 before). The authenticated role's statement_timeout+-- is 8 s, so every Insights open fell back to comparing all prompts. Two+-- causes:+--+-- * A SQL-language function is planned without its argument values+-- (PostgreSQL 17 and older), so the brand and both day ranges were+-- guesses: a range between unknown bounds is estimated at 0.5% of the+-- rows. The plan, and the RLS membership subquery planned into it, were+-- built for a few hundred rows and got ~200k. plan_cache_mode does not+-- reach SQL functions, which is why force_custom_plan did not help.+-- * The per-day rollup rows were joined to the shared prompts again for+-- the totals, after being grouped once for the presence check.+--+-- Both functions become plpgsql with force_custom_plan, so every call is+-- planned with its real arguments, and security definer with the+-- organization check made explicit, as citations_urls_daily does (00119), so+-- RLS no longer runs inside the scan. The service role still reads: the+-- cached 24h view (cachedAnchoredInsights) calls the raw variant with it,+-- after checking the caller's access to the brand. The rollup rows are now+-- folded to one row per prompt and window first, and the raw variant keeps+-- one copy of its rows instead of three. Output and counting rules are+-- 00130's.++-- ─── Over the rollups (whole-day windows) ──────────────────────────────────++create or replace function public.insights_same_prompt_compare_daily(+ p_brand_id uuid,+ p_cur_from date,+ p_cur_to date,+ p_prev_from date,+ p_prev_to date,+ p_models text[] default null,+ p_region text default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ with per_prompt as (+ -- One row per prompt and window: nothing below reads the per-day rows.+ select d.prompt_id,+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ sum(d.answer_count) as answers,+ sum(d.mention_answers) as mention_answers,+ sum(d.citation_answers) as citation_answers,+ sum(d.sum_inv_position) as sum_inv_position,+ sum(d.position_count) as position_count,+ sum(d.total_mentions) as total_mentions,+ sum(d.total_citations) as total_citations,+ sum(d.positive_count) as positive_count,+ sum(d.mentioning_answers) as mentioning_answers,+ bool_or(d.mention_answers is null) as stale+ from public.insights_prompt_daily d+ where d.brand_id = p_brand_id+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)+ group by 1, 2+ ),+ presence as (+ select prompt_id,+ bool_or(win = 'cur' and answers > 0) as in_cur,+ bool_or(win = 'prev' and answers > 0) as in_prev+ from per_prompt+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ brand_agg as (+ select p.win,+ sum(p.answers) as answers,+ sum(p.mention_answers) as mention_answers,+ sum(p.citation_answers) as citation_answers,+ sum(p.sum_inv_position) / nullif(sum(p.position_count), 0) as position_factor,+ sum(p.total_mentions) as total_mentions,+ sum(p.total_citations) as total_citations,+ sum(p.positive_count) as positive_count,+ sum(p.mentioning_answers) as mentioning_answers+ from per_prompt p+ join same_prompts s using (prompt_id)+ group by p.win+ ),+ comp_sums as (+ select case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ cd.competitor_id,+ sum(cd.mention_answers) as mention_answers,+ sum(cd.citation_answers) as citation_answers,+ sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor,+ bool_or(cd.mention_answers is null) as stale+ from public.insights_competitor_prompt_daily cd+ where cd.brand_id = p_brand_id+ and cd.prompt_id in (select prompt_id from same_prompts)+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ group by 1, 2+ ),+ -- Competitors tracked in each window, from the dense day-grain table (see+ -- 00130): one added during the period then has no previous value.+ tracked as (+ select distinct+ case when cd.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win,+ cd.competitor_id+ from public.insights_competitor_daily cd+ where cd.brand_id = p_brand_id+ and (p_models is null or cd.model_used = any (p_models))+ and (p_region is null or cd.region = p_region)+ and (cd.day between p_cur_from and p_cur_to or cd.day between p_prev_from and p_prev_to)+ ),+ comp_agg as (+ select t.win,+ t.competitor_id,+ c.name,+ coalesce(cs.mention_answers, 0) as mention_answers,+ coalesce(cs.citation_answers, 0) as citation_answers,+ cs.position_factor+ from tracked t+ join public.competitors c+ on c.id::text = t.competitor_id and c.brand_id = p_brand_id+ left join comp_sums cs+ on cs.win = t.win and cs.competitor_id = t.competitor_id+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', not exists (select 1 from per_prompt where stale)+ and not exists (select 1 from comp_sums where stale),+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ )+ into v_result;++ return v_result;+end;+$$;++-- ─── Over the raw rows (24h and topic views) ───────────────────────────────++create or replace function public.insights_same_prompt_compare(+ p_brand_id uuid,+ p_cur_from timestamptz,+ p_cur_to timestamptz,+ p_prev_from timestamptz,+ p_prev_to timestamptz,+ p_models text[] default null,+ p_region text default null,+ p_topic_id uuid default null+)+returns jsonb+language plpgsql+stable+security definer+set search_path to 'public'+set work_mem to '64MB'+set plan_cache_mode to 'force_custom_plan'+as $$+declare+ v_result jsonb;+begin+ if auth.role() is distinct from 'service_role' and not exists (+ select 1 from public.brands b+ join public.profiles pf on pf.organization_id = b.organization_id+ where b.id = p_brand_id and pf.id = auth.uid()+ ) then+ return null;+ end if;++ with filtered as (+ select pr.prompt_id, pr.mention_count, pr.citation_count,+ pr.mention_position, pr.sentiment, pr.competitor_mentions,+ pr.created_at >= p_cur_from and pr.created_at <= p_cur_to as in_cur,+ pr.created_at >= p_prev_from and pr.created_at <= p_prev_to as in_prev+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and (p_models is null or pr.model_used = any (p_models))+ and (p_region is null or pr.region = p_region)+ and pr.created_at >= p_prev_from+ and pr.created_at <= p_cur_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))+ ),+ presence as (+ select prompt_id,+ bool_or(in_cur) as in_cur,+ bool_or(in_prev) as in_prev+ from filtered+ group by prompt_id+ ),+ same_prompts as (+ select prompt_id from presence where in_cur and in_prev+ ),+ -- Each window selected on its own, inclusive at both ends like+ -- ai_visibility_aggregates: an answer exactly on the boundary counts in+ -- both, as it does on the card.+ same_rows as not materialized (+ select w.win, f.*+ from filtered f+ join same_prompts s using (prompt_id)+ cross join lateral (values ('cur', f.in_cur), ('prev', f.in_prev)) w(win, inside)+ where w.inside+ ),+ brand_agg as (+ select win,+ count(*) as answers,+ count(*) filter (where mention_count > 0) as mention_answers,+ count(*) filter (where citation_count > 0) as citation_answers,+ avg(1.0 / mention_position) filter (where mention_position is not null)+ as position_factor,+ coalesce(sum(mention_count), 0) as total_mentions,+ coalesce(sum(citation_count), 0) as total_citations,+ count(*) filter (where sentiment = 'positive') as positive_count,+ count(*) filter (where mention_count > 0 or citation_count > 0)+ as mentioning_answers+ from same_rows+ group by win+ ),+ comp_agg as (+ select r.win,+ cm.value->>'competitor_id' as competitor_id,+ max(c.name) as name,+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0)+ as mention_answers,+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0)+ as citation_answers,+ avg(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null)+ as position_factor+ from same_rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ join public.competitors c+ on c.id::text = cm.value->>'competitor_id' and c.brand_id = p_brand_id+ where cm.value ? 'competitor_id'+ group by r.win, cm.value->>'competitor_id'+ ),+ windows(win) as (values ('cur'), ('prev'))+ select jsonb_build_object(+ 'complete', true,+ 'same_prompts', (select count(*) from same_prompts),+ 'new_prompts', (select count(*) from presence where in_cur and not in_prev),+ 'dropped_prompts', (select count(*) from presence where in_prev and not in_cur)+ ) || (+ select jsonb_object_agg(w.win, jsonb_build_object(+ 'answers', coalesce(b.answers, 0),+ 'mention_answers', coalesce(b.mention_answers, 0),+ 'citation_answers', coalesce(b.citation_answers, 0),+ 'position_factor', b.position_factor,+ 'total_mentions', coalesce(b.total_mentions, 0),+ 'total_citations', coalesce(b.total_citations, 0),+ 'positive_count', coalesce(b.positive_count, 0),+ 'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'by_competitor', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', ca.competitor_id,+ 'name', ca.name,+ 'mention_answers', ca.mention_answers,+ 'citation_answers', ca.citation_answers,+ 'position_factor', ca.position_factor)+ order by ca.mention_answers desc, ca.competitor_id)+ from comp_agg ca where ca.win = w.win),+ '[]'::jsonb)))+ from windows w+ left join brand_agg b on b.win = w.win+ )+ into v_result;++ return v_result;+end;+$$;++revoke execute on function public.insights_same_prompt_compare_daily(+ uuid, date, date, date, date, text[], text+) from public, anon;+grant execute on function public.insights_same_prompt_compare_daily(+ uuid, date, date, date, date, text[], text+) to authenticated, service_role;++revoke execute on function public.insights_same_prompt_compare(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid+) from public, anon;+grant execute on function public.insights_same_prompt_compare(+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid+) to authenticated, service_role;++-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00149_insights_kpi_same_prompts_definer.sql+-- ─────────────────────────────────────────────────────────────────────────+-- The KPI cards' "Same prompts" read, made fast again (#1036 review).----- Both functions become plpgsql with force_custom_plan, so every call is--- planned with its real arguments, and security definer with the--- organization check made explicit, as citations_urls_daily does (00119), so--- RLS no longer runs inside the scan. The service role still reads: the--- cached 24h view (cachedAnchoredInsights) calls the raw variant with it,--- after checking the caller's access to the brand. The rollup rows are now--- folded to one row per prompt and window first, and the raw variant keeps--- one copy of its rows instead of three. Output and counting rules are--- 00130's.+-- 00147 (#1036) rewrote insights_same_prompt_compare[_daily] as plpgsql,+-- security definer, with the organization check made explicit, because the+-- SQL-language version timed out on the largest brand: 4.5 s as the table+-- owner, over 30 s for a signed-in member against the authenticated role's+-- 8 s statement_timeout. It carries 00130's output, so on this branch it+-- would drop the components 00131 added (negative count, position sum and+-- count, visible prompts, competitor mentions). This is 00131's output with+-- 00147's shape: planned per call with its real arguments+-- (force_custom_plan), no RLS inside the scan, the rollup rows folded to one+-- row per prompt and window first, and the raw rows kept once. The service+-- role still reads, for the cached 24h view (cachedAnchoredInsights).-- ─── Over the rollups (whole-day windows) ──────────────────────────────────@@ -15489,7 +16506,10 @@ beginsum(d.total_citations) as total_citations,sum(d.positive_count) as positive_count,sum(d.mentioning_answers) as mentioning_answers,- bool_or(d.mention_answers is null) as stale+ sum(d.negative_count) as negative_count,+ sum(d.sum_position) as sum_position,+ bool_or(d.has_mention or d.has_citation) as visible,+ bool_or(d.mention_answers is null or d.negative_count is null) as stalefrom public.insights_prompt_daily dwhere d.brand_id = p_brand_idand (p_models is null or d.model_used = any (p_models))@@ -15516,7 +16536,11 @@ beginsum(p.total_mentions) as total_mentions,sum(p.total_citations) as total_citations,sum(p.positive_count) as positive_count,- sum(p.mentioning_answers) as mentioning_answers+ sum(p.mentioning_answers) as mentioning_answers,+ sum(p.negative_count) as negative_count,+ sum(p.sum_position) as sum_position,+ sum(p.position_count) as position_count,+ count(*) filter (where p.visible) as visible_promptsfrom per_prompt pjoin same_prompts s using (prompt_id)group by p.win@@ -15527,6 +16551,7 @@ beginsum(cd.mention_answers) as mention_answers,sum(cd.citation_answers) as citation_answers,sum(cd.sum_inv_position) / nullif(sum(cd.position_count), 0) as position_factor,+ sum(cd.mention_count) as mentions,bool_or(cd.mention_answers is null) as stalefrom public.insights_competitor_prompt_daily cdwhere cd.brand_id = p_brand_id@@ -15561,6 +16586,11 @@ beginleft join comp_sums cson cs.win = t.win and cs.competitor_id = t.competitor_id),+ -- Every competitor's mentions on the shared prompts, for share of voice+ -- (which counts all competitors, as share_of_voice_aggregates does).+ comp_mentions as (+ select win, sum(mentions) as mentions from comp_sums group by win+ ),windows(win) as (values ('cur'), ('prev'))select jsonb_build_object('complete', not exists (select 1 from per_prompt where stale)@@ -15578,6 +16608,11 @@ begin'total_citations', coalesce(b.total_citations, 0),'positive_count', coalesce(b.positive_count, 0),'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),'by_competitor', coalesce((select jsonb_agg(jsonb_build_object('competitor_id', ca.competitor_id,@@ -15675,27 +16710,44 @@ begincoalesce(sum(citation_count), 0) as total_citations,count(*) filter (where sentiment = 'positive') as positive_count,count(*) filter (where mention_count > 0 or citation_count > 0)- as mentioning_answers+ as mentioning_answers,+ count(*) filter (where sentiment = 'negative') as negative_count,+ sum(mention_position) filter (where mention_position is not null)+ as sum_position,+ count(*) filter (where mention_position is not null) as position_count,+ count(distinct prompt_id) filter (where mention_count > 0 or citation_count > 0)+ as visible_promptsfrom same_rowsgroup by win),- comp_agg as (- select r.win,- cm.value->>'competitor_id' as competitor_id,- max(c.name) as name,- count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0)- as mention_answers,- count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0)- as citation_answers,- avg(1.0 / (cm.value->>'mention_position')::numeric)- filter (where (cm.value->>'mention_position') is not null)- as position_factor+ -- The competitor entries of the shared prompts' answers, unpacked once.+ comp_entries as materialized (+ select r.win, cm.value as entryfrom same_rows rcross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm- join public.competitors c- on c.id::text = cm.value->>'competitor_id' and c.brand_id = p_brand_idwhere cm.value ? 'competitor_id'- group by r.win, cm.value->>'competitor_id'+ ),+ comp_agg as (+ select e.win,+ e.entry->>'competitor_id' as competitor_id,+ max(c.name) as name,+ count(*) filter (where coalesce((e.entry->>'mention_count')::int, 0) > 0)+ as mention_answers,+ count(*) filter (where coalesce((e.entry->>'citation_count')::int, 0) > 0)+ as citation_answers,+ avg(1.0 / (e.entry->>'mention_position')::numeric)+ filter (where (e.entry->>'mention_position') is not null)+ as position_factor+ from comp_entries e+ join public.competitors c+ on c.id::text = e.entry->>'competitor_id' and c.brand_id = p_brand_id+ group by e.win, e.entry->>'competitor_id'+ ),+ -- Every competitor's mentions on the shared prompts, for share of voice.+ comp_mentions as (+ select win, sum(coalesce((entry->>'mention_count')::int, 0)) as mentions+ from comp_entries+ group by win),windows(win) as (values ('cur'), ('prev'))select jsonb_build_object(@@ -15713,6 +16765,11 @@ begin'total_citations', coalesce(b.total_citations, 0),'positive_count', coalesce(b.positive_count, 0),'mentioning_answers', coalesce(b.mentioning_answers, 0),+ 'negative_count', coalesce(b.negative_count, 0),+ 'sum_position', b.sum_position,+ 'position_count', coalesce(b.position_count, 0),+ 'visible_prompts', coalesce(b.visible_prompts, 0),+ 'competitor_mentions', coalesce((select cm.mentions from comp_mentions cm where cm.win = w.win), 0),'by_competitor', coalesce((select jsonb_agg(jsonb_build_object('competitor_id', ca.competitor_id,diff --git a/web/messages/en.json b/web/messages/en.jsonindex ee856c76e..e883bebeb 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1685,6 +1685,45 @@"hint": "Changes compare only prompts tracked in both periods","newExcluded": "{count, plural, one {# new prompt excluded} other {# new prompts excluded}}","newIncluded": "{count, plural, one {includes # new prompt} other {includes # new prompts}}"+ },+ "kpi": {+ "sectionLabel": "Key metrics",+ "noData": "No data",+ "viewBreakdown": "{metric}: view breakdown",+ "openPrompts": "Tracked prompts: open Prompts",+ "openCitations": "Citations: open Citations",+ "visibility": "Visibility",+ "visibilityTip": "AI Visibility Score (0–100) from how often answers name you, cite your site and how early you're named. See Formulas.",+ "rankOf": "#{rank} of {count} brands",+ "appearedIn": "appeared in {visible} of {active} prompts",+ "trackedPrompts": "Tracked prompts",+ "trackedPromptsTip": "Prompts answered in this period. The bar is your plan's prompt locations, shared by all brands and counting only active prompts (paused ones don't count): {used} of {limit} used.",+ "trackedPromptsTipUnlimited": "Prompts answered in this period. Your plan has no prompt location limit.",+ "slotsLeft": "{count, plural, one {# slot left} other {# slots left}} · all brands",+ "overLimit": "{count, plural, one {# location over your plan} other {# locations over your plan}} · all brands",+ "unlimited": "{count, plural, one {# active location} other {# active locations}} · Unlimited",+ "quotaLabel": "{used} of {limit} active prompt locations used",+ "mentions": "Mentions",+ "mentionsTip": "Times answers named your brand. With Same prompts, the change counts only prompts tracked in both periods.",+ "citations": "Citations",+ "citationsTip": "Times answers cited your pages. With Same prompts, the change counts only prompts tracked in both periods.",+ "samePrompts": "{count, plural, one {same # prompt} other {same # prompts}}",+ "allPrompts": "all prompts",+ "netSentiment": "Net sentiment",+ "netSentimentTip": "Positive minus negative share of the answers that name or cite your brand.",+ "sentimentSplit": "{positive}% pos · {negative}% neg",+ "coverage": "Coverage",+ "coverageTip": "Share of answered prompts where you appear at least once.",+ "coverageSub": "{visible} of {active} prompts",+ "shareOfVoice": "Share of voice",+ "shareOfVoiceTip": "Your mentions divided by mentions of all tracked brands.",+ "shareOfVoiceSub": "of brand mentions",+ "avgPosition": "Avg. position",+ "avgPositionTip": "Average position when you're named. Lower is better.",+ "avgPositionSub": "when mentioned",+ "citationRate": "Citation rate",+ "citationRateTip": "Share of answers that cite your domain.",+ "citationRateSub": "of answers cite you"}},"topics": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsxindex 805e03ae3..2ecc5f483 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx@@ -4,7 +4,7 @@ import { useState } from 'react';import { Sigma } from 'lucide-react';import { Button } from '@/components/ui/button';import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';-import { VISIBILITY_SCORE_WEIGHTS } from '@/lib/visibility-score';+import { POSITION_SUPPORT_ANSWERS, VISIBILITY_SCORE_WEIGHTS } from '@/lib/visibility-score';const PCT = {mention: Math.round(VISIBILITY_SCORE_WEIGHTS.mention * 100),@@ -61,7 +61,10 @@ export function FormulaDialog() {<Formula>Visibility = 100 × ({VISIBILITY_SCORE_WEIGHTS.mention} × mention rate +{' '}{VISIBILITY_SCORE_WEIGHTS.citation} × citation rate +{' '}- {VISIBILITY_SCORE_WEIGHTS.position} × position factor)+ {VISIBILITY_SCORE_WEIGHTS.position} × position factor × confidence)+ <br />+ confidence = answers mentioning you ÷ (answers mentioning you +{' '}+ {POSITION_SUPPORT_ANSWERS})</Formula><ul className="list-disc pl-5 space-y-1"><li>@@ -79,9 +82,9 @@ export function FormulaDialog() {Position factor ({PCT.position}%)</span>{' '}— how early you're named in the answers that mention you: named first = 1,- second = 0.5, third = 0.33, and so on, averaged. This term is weighted by how many- answers actually mention the brand, so a perfect position in a handful of answers- can't outrank brands that consistently show up.+ second = 0.5, third = 0.33, and so on, averaged. The confidence factor weights it+ by how many answers actually mention the brand, so a perfect position in a handful+ of answers can't outrank brands that consistently show up.</li></ul><p>@@ -110,16 +113,30 @@ export function FormulaDialog() {</p></Section>- <Section title="Positive sentiment">+ <Section title="Net sentiment"><p>- Share of brand-mentioning answers that describe you in a positive context. Sentiment- is shown alongside Visibility but is not part of the score.+ Of the answers that name or cite you, the share that is positive minus the share+ that is negative, in points. Sentiment is shown alongside Visibility but is not part+ of the score.</p><Formula>- Positive sentiment = positive answers ÷ answers mentioning you × 100+ Net sentiment = positive answers % − negative answers % (of answers mentioning you)</Formula></Section>+ <Section title="Avg. position">+ <p>+ Where you're named in the answers that mention you, averaged. Lower is better:+ #1 means you're usually named first.+ </p>+ <Formula>Avg. position = sum of your positions ÷ answers that name you</Formula>+ </Section>++ <Section title="Citation rate">+ <p>The share of AI answers that link to your website as a source.</p>+ <Formula>Citation rate = answers citing your domain ÷ all answers × 100</Formula>+ </Section>+<Section title="Share of Voice"><p>Your slice of the total brand conversation: of all brand mentions in AI answers —@@ -130,9 +147,19 @@ export function FormulaDialog() {<Section title="Coverage"><p>- The "appeared in X/Y prompts" line under the Visibility card: the number- of tracked prompts where you showed up at least once in the selected period, against- all prompts that produced results.+ The share of tracked prompts where you showed up (named or cited) at least once in+ the selected period, against all prompts that produced results.+ </p>+ <Formula>Coverage = prompts you appeared in ÷ prompts answered × 100</Formula>+ </Section>++ <Section title="Changes and “Same prompts”">+ <p>+ Each card's change compares the selected period with the period of the same+ length just before it. With "Compare: Same prompts" on, it compares only+ the prompts answered in both periods, so adding prompts doesn't inflate it; the+ numbers themselves still cover every prompt. With "All time" there is no+ earlier period, so no change is shown.</p></Section></div>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsxnew file mode 100644index 000000000..2b476330c--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx@@ -0,0 +1,445 @@+'use client';++import { useId, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { useTranslations } from 'next-intl';+import {+ ArrowUpRight,+ Eye,+ HelpCircle,+ Layers,+ Link2,+ ListOrdered,+ MessageCircle,+ PieChart,+ Quote,+ Smile,+ Target,+ type LucideIcon,+} from 'lucide-react';+import { Card } from '@/components/ui/card';+import { cn } from '@/lib/utils';+import { formatCompactNumber } from '@/lib/format';+import type {+ CompetitorComparisonData,+ CoverageKpi,+ InsightsSummary,+ ShareOfVoiceData,+ TrackedPromptsKpi,+ VisibilityRateTrendData,+} from '@/lib/actions/tracking';+import type { PromptComparison } from '@/lib/insights-same-prompts';+import type { KpiSeriesDay } from '@/lib/insights-kpis';+import {+ lowerIsGood,+ signedChange,+ signedValue,+ upIsGood,+ type Change,+ type Tone,+} from './kpi-format';++// ─── Info tooltip ─────────────────────────────────────────────────────────────++export function InfoTip({ content }: { content: string }) {+ const [pos, setPos] = useState<{ x: number; y: number } | null>(null);+ const ref = useRef<HTMLSpanElement>(null);+ const tooltipId = useId();++ function show() {+ const r = ref.current?.getBoundingClientRect();+ if (r) setPos({ x: r.left + r.width / 2, y: r.bottom + 6 });+ }++ function hide() {+ setPos(null);+ }++ return (+ <>+ <span+ ref={ref}+ tabIndex={0}+ aria-label="More information"+ aria-describedby={pos ? tooltipId : undefined}+ onMouseEnter={show}+ onMouseLeave={hide}+ onFocus={show}+ onBlur={hide}+ onKeyDown={(e) => {+ if (e.key === 'Escape') hide();+ }}+ className="inline-flex items-center cursor-help rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <HelpCircle className="h-3 w-3 text-muted-foreground/60 hover:text-muted-foreground transition-colors" />+ </span>+ {pos &&+ createPortal(+ <div+ id={tooltipId}+ role="tooltip"+ style={{ left: pos.x, top: pos.y, transform: 'translateX(-50%)' }}+ className="pointer-events-none fixed z-[9999] w-56 rounded-md border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md"+ >+ {content}+ </div>,+ document.body,+ )}+ </>+ );+}++// ─── Card parts ───────────────────────────────────────────────────────────────++const TONE_TEXT: Record<Tone, string> = {+ good: 'text-emerald-600 dark:text-emerald-400',+ bad: 'text-red-600 dark:text-red-400',+ neutral: 'text-muted-foreground',+};++/**+ * A daily sparkline. Days without a value are skipped; fewer than two+ * points draw nothing. Grey normally, red when the card's change is bad.+ */+function Sparkline({ values, bad }: { values: (number | null)[]; bad: boolean }) {+ const points = values+ .map((v, i) => (v === null ? null : { i, v }))+ .filter((p): p is { i: number; v: number } => p !== null);+ if (points.length < 2) return <div className="h-6" aria-hidden />;+ const min = Math.min(...points.map((p) => p.v));+ const max = Math.max(...points.map((p) => p.v));+ const last = values.length - 1 || 1;+ const coords = points+ .map(({ i, v }) => {+ const x = (i / last) * 100;+ const y = max === min ? 12 : 22 - ((v - min) / (max - min)) * 20;+ return `${x.toFixed(1)},${y.toFixed(1)}`;+ })+ .join(' ');+ return (+ <svg+ viewBox="0 0 100 24"+ preserveAspectRatio="none"+ className={cn(+ 'h-6 w-full',+ bad ? 'text-red-500 dark:text-red-400' : 'text-muted-foreground/50',+ )}+ aria-hidden+ >+ <polyline+ points={coords}+ fill="none"+ stroke="currentColor"+ strokeWidth={1.5}+ vectorEffect="non-scaling-stroke"+ />+ </svg>+ );+}++/** The plan's prompt locations as a fill bar: amber from 80%, red when full. */+function QuotaBar({ used, limit, label }: { used: number; limit: number; label: string }) {+ const pct = Math.min(100, Math.round((used / limit) * 100));+ return (+ <div+ role="img"+ aria-label={label}+ className="my-[9px] h-1.5 overflow-hidden rounded-full bg-muted"+ >+ <div+ className={cn(+ 'h-full rounded-full',+ used >= limit ? 'bg-red-500' : pct >= 80 ? 'bg-amber-500' : 'bg-foreground/60',+ )}+ style={{ width: `${pct}%` }}+ />+ </div>+ );+}++interface MetricCardProps {+ label: string;+ tooltip: string;+ icon: LucideIcon;+ value: string;+ delta?: Change | null;+ sub?: React.ReactNode;+ spark?: (number | null)[] | null;+ quota?: { used: number; limit: number; label: string } | null;+ onClick?: () => void;+ clickLabel?: string;+}++/** One KPI card, as in the v2 mockup: label, value with its change, a line of context, a sparkline. */+function MetricCard({+ label,+ tooltip,+ icon: Icon,+ value,+ delta,+ sub,+ spark,+ quota,+ onClick,+ clickLabel,+}: MetricCardProps) {+ const clickable = typeof onClick === 'function';+ return (+ <Card+ onClick={onClick}+ role={clickable ? 'button' : undefined}+ tabIndex={clickable ? 0 : undefined}+ aria-label={clickable ? clickLabel : undefined}+ onKeyDown={+ clickable+ ? (e) => {+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault();+ onClick?.();+ }+ }+ : undefined+ }+ className={cn(+ 'group flex min-w-0 flex-col gap-1.5 rounded-xl px-4 pt-3.5 pb-2.5',+ clickable &&+ 'cursor-pointer transition-colors hover:border-foreground/30 hover:bg-accent/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',+ )}+ >+ <div className="flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wider text-muted-foreground">+ <span className="truncate">{label}</span>+ <InfoTip content={tooltip} />+ <span className="flex-1" />+ <span className="relative flex h-4 w-4 items-center justify-center">+ <Icon+ className={cn(+ 'h-3.5 w-3.5 text-muted-foreground transition-opacity',+ clickable && 'group-hover:opacity-0',+ )}+ />+ {clickable && (+ <ArrowUpRight+ className="absolute h-4 w-4 text-foreground opacity-0 transition-opacity group-hover:opacity-100"+ aria-hidden+ />+ )}+ </span>+ </div>+ <div className="flex items-baseline gap-2">+ <span className="text-[28px] font-semibold leading-tight tracking-tight tabular-nums">+ {value}+ </span>+ {delta && (+ <span className={cn('text-xs font-medium tabular-nums', TONE_TEXT[delta.tone])}>+ {delta.text}+ </span>+ )}+ </div>+ <div className="truncate text-xs text-muted-foreground">{sub}</div>+ {quota ? (+ <QuotaBar used={quota.used} limit={quota.limit} label={quota.label} />+ ) : (+ <Sparkline values={spark ?? []} bad={delta?.tone === 'bad'} />+ )}+ </Card>+ );+}++const pct = (n: number | null) => (n === null ? null : `${n}%`);++// ─── The two rows ─────────────────────────────────────────────────────────────++interface KpiRowsProps {+ summary: InsightsSummary;+ trend: VisibilityRateTrendData | null;+ trackedPrompts: TrackedPromptsKpi | null;+ coverage: CoverageKpi | null;+ sov: ShareOfVoiceData | null;+ competitors: CompetitorComparisonData | null;+ comparison: PromptComparison | null;+ series: KpiSeriesDay[] | null;+ onBreakdown: (metric: 'visibility' | 'mentions') => void;+ onNavigate: (path: string) => void;+}++/**+ * The Insights KPI cards (VIS-003): today's five on the first row, the new+ * rates on the second, as in the v2 mockup. Changes follow "Compare: Same+ * prompts"; the values themselves cover every prompt in the window.+ */+export function KpiRows({+ summary,+ trend,+ trackedPrompts,+ coverage,+ sov,+ competitors,+ comparison,+ series,+ onBreakdown,+ onNavigate,+}: KpiRowsProps) {+ const t = useTranslations('insights.kpi');+ const none = t('noData');++ const own = competitors?.brands.findIndex((b) => b.isOwnBrand) ?? -1;+ const visibilitySub =+ competitors && own >= 0+ ? t('rankOf', { rank: own + 1, count: competitors.brands.length })+ : coverage+ ? t('appearedIn', { visible: coverage.visiblePrompts, active: coverage.activePrompts })+ : null;+ const basisSub =+ comparison?.basis === 'same'+ ? t('samePrompts', { count: comparison.samePrompts })+ : t('allPrompts');++ const quota =+ trackedPrompts && trackedPrompts.quotaLimit !== -1+ ? { used: trackedPrompts.quotaUsed, limit: trackedPrompts.quotaLimit }+ : null;+ const trackedSub = !trackedPrompts+ ? null+ : !quota+ ? t('unlimited', { count: trackedPrompts.quotaUsed })+ : quota.used > quota.limit+ ? t('overLimit', { count: quota.used - quota.limit })+ : t('slotsLeft', { count: quota.limit - quota.used });++ const daily = <K extends keyof KpiSeriesDay>(key: K) =>+ series ? series.map((d) => d[key] as number | null) : null;++ return (+ <section aria-label={t('sectionLabel')} className="flex flex-col gap-3">+ <div className="grid grid-cols-2 gap-3 md:grid-cols-3 xl:grid-cols-5">+ <MetricCard+ label={t('visibility')}+ tooltip={t('visibilityTip')}+ icon={Eye}+ value={String(trend?.summary.rate ?? 0)}+ delta={upIsGood(trend?.summary.change ?? null)}+ sub={visibilitySub}+ spark={trend ? trend.points.map((p) => p.values.you ?? null) : null}+ onClick={() => onBreakdown('visibility')}+ clickLabel={t('viewBreakdown', { metric: t('visibility') })}+ />+ <MetricCard+ label={t('trackedPrompts')}+ tooltip={+ quota+ ? t('trackedPromptsTip', {+ used: quota.used.toLocaleString('en-US'),+ limit: quota.limit.toLocaleString('en-US'),+ })+ : t('trackedPromptsTipUnlimited')+ }+ icon={Layers}+ value={(trackedPrompts?.activeInPeriod ?? 0).toLocaleString('en-US')}+ delta={+ comparison && comparison.newPrompts > 0+ ? { text: signedChange(comparison.newPrompts), tone: 'neutral' }+ : null+ }+ sub={trackedSub}+ quota={+ quota+ ? {+ ...quota,+ label: t('quotaLabel', {+ used: quota.used.toLocaleString('en-US'),+ limit: quota.limit.toLocaleString('en-US'),+ }),+ }+ : null+ }+ onClick={() => onNavigate('/dashboard/prompts')}+ clickLabel={t('openPrompts')}+ />+ <MetricCard+ label={t('mentions')}+ tooltip={t('mentionsTip')}+ icon={MessageCircle}+ value={formatCompactNumber(summary.totalMentions)}+ delta={upIsGood(summary.mentionsChange, '%')}+ sub={basisSub}+ spark={daily('mentions')}+ onClick={() => onBreakdown('mentions')}+ clickLabel={t('viewBreakdown', { metric: t('mentions') })}+ />+ <MetricCard+ label={t('citations')}+ tooltip={t('citationsTip')}+ icon={Quote}+ value={formatCompactNumber(summary.totalCitations)}+ delta={upIsGood(summary.citationsChange, '%')}+ sub={basisSub}+ spark={daily('citations')}+ onClick={() => onNavigate('/dashboard/citations')}+ clickLabel={t('openCitations')}+ />+ <MetricCard+ label={t('netSentiment')}+ tooltip={t('netSentimentTip')}+ icon={Smile}+ value={summary.netSentiment === null ? none : signedValue(summary.netSentiment)}+ delta={upIsGood(summary.netSentimentChange)}+ sub={+ summary.netSentiment === null+ ? null+ : t('sentimentSplit', {+ positive: summary.positiveSentimentPct,+ negative: summary.negativeSentimentPct ?? 0,+ })+ }+ spark={daily('netSentiment')}+ />+ </div>++ <div className="grid grid-cols-2 gap-3 lg:grid-cols-4">+ <MetricCard+ label={t('coverage')}+ tooltip={t('coverageTip')}+ icon={Target}+ value={pct(coverage?.value ?? null) ?? none}+ delta={upIsGood(coverage?.change ?? null)}+ sub={+ coverage+ ? t('coverageSub', {+ visible: coverage.visiblePrompts,+ active: coverage.activePrompts,+ })+ : null+ }+ spark={daily('coverage')}+ />+ <MetricCard+ label={t('shareOfVoice')}+ tooltip={t('shareOfVoiceTip')}+ icon={PieChart}+ value={pct(sov ? sov.overallSov : null) ?? none}+ delta={upIsGood(sov?.overallSovChange ?? null)}+ sub={t('shareOfVoiceSub')}+ spark={daily('shareOfVoice')}+ />+ <MetricCard+ label={t('avgPosition')}+ tooltip={t('avgPositionTip')}+ icon={ListOrdered}+ value={summary.avgPosition === null ? none : `#${summary.avgPosition}`}+ delta={lowerIsGood(summary.avgPositionChange)}+ sub={t('avgPositionSub')}+ spark={daily('avgPosition')}+ />+ <MetricCard+ label={t('citationRate')}+ tooltip={t('citationRateTip')}+ icon={Link2}+ value={pct(summary.citationRate) ?? none}+ delta={upIsGood(summary.citationRateChange)}+ sub={t('citationRateSub')}+ spark={daily('citationRate')}+ />+ </div>+ </section>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.tsnew file mode 100644index 000000000..c12bdbfe1--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest';+import { lowerIsGood, signedChange, signedValue, upIsGood } from './kpi-format';++describe('KPI card formatting', () => {+ it('writes changes with a sign, and no change as ±0', () => {+ expect(signedChange(1.5)).toBe('+1.5');+ expect(signedChange(-3.2)).toBe('−3.2');+ expect(signedChange(0)).toBe('±0');+ });++ it('writes a zero value as 0, not as a change', () => {+ expect(signedValue(34)).toBe('+34');+ expect(signedValue(-6)).toBe('−6');+ expect(signedValue(0)).toBe('0');+ });++ it('colours a rise good and a fall bad on most cards', () => {+ expect(upIsGood(18, '%')).toEqual({ text: '+18%', tone: 'good' });+ expect(upIsGood(-4)).toEqual({ text: '−4', tone: 'bad' });+ expect(upIsGood(0, '%')).toEqual({ text: '±0', tone: 'neutral' });+ expect(upIsGood(null)).toBeNull();+ });++ it('reads a lower Avg. position as an improvement', () => {+ expect(lowerIsGood(-0.3)).toEqual({ text: '↑0.3', tone: 'good' });+ expect(lowerIsGood(0.5)).toEqual({ text: '↓0.5', tone: 'bad' });+ expect(lowerIsGood(0)).toEqual({ text: '±0', tone: 'neutral' });+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.tsnew file mode 100644index 000000000..139591635--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts@@ -0,0 +1,45 @@+/**+ * How the Insights KPI cards (VIS-003) write their values and changes, and+ * whether a change is good news. Kept apart from the cards so the rules are+ * tested on their own.+ */++/** Whether a change is good news, bad news, or neither (counts like tracked prompts). */+export type Tone = 'good' | 'bad' | 'neutral';++export interface Change {+ text: string;+ tone: Tone;+}++const MINUS = '−';++/** A change: "+1.5", "−3.2", "±0". */+export function signedChange(n: number): string {+ if (n === 0) return '±0';+ return `${n > 0 ? '+' : MINUS}${Math.abs(n).toLocaleString('en-US')}`;+}++/** A value that can be negative, like Net sentiment: "+34", "−6", "0". */+export function signedValue(n: number): string {+ return n === 0 ? '0' : signedChange(n);+}++/** A change where up is good (most cards). */+export function upIsGood(change: number | null, suffix = ''): Change | null {+ if (change === null) return null;+ return {+ text: `${signedChange(change)}${change === 0 ? '' : suffix}`,+ tone: change > 0 ? 'good' : change < 0 ? 'bad' : 'neutral',+ };+}++/** Avg. position: a lower number is better, shown as an arrow up when it improves. */+export function lowerIsGood(change: number | null): Change | null {+ if (change === null) return null;+ if (change === 0) return { text: '±0', tone: 'neutral' };+ return {+ text: `${change < 0 ? '↑' : '↓'}${Math.abs(change)}`,+ tone: change < 0 ? 'good' : 'bad',+ };+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 41c1849ed..12ab4035f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -1,9 +1,8 @@'use client';-import { useState, useRef, useEffect, useCallback, useId } from 'react';+import { useState, useRef, useEffect, useCallback } from 'react';import { Link, useRouter } from '@/i18n/navigation';import { useSearchParams } from 'next/navigation';-import { createPortal } from 'react-dom';import { useTranslations } from 'next-intl';import dynamic from 'next/dynamic';import { Skeleton } from '@/components/ui/skeleton';@@ -53,13 +52,13 @@ import {exportPromptResults,type InsightsSummary,type TrackedPromptsKpi,- type VisibilityRateKpi,type CompetitorComparisonData,type ShareOfVoiceData,type InsightsRecommendations,type TrackingJobStatus,type BreakdownFilters,type BreakdownMetric,+ type CoverageKpi,} from '@/lib/actions/tracking';import { getTopics } from '@/lib/actions/topic';import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';@@ -78,24 +77,17 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/uimport {BarChart3,CalendarX2,- Eye,- HelpCircle,Play,TrendingUp,TrendingDown,- Quote,- Zap,- AlertCircle,Loader2,FlaskConical,PieChart,Users,StopCircle,ArrowRight,- ArrowUpRight,Download,FileText,- Layers,Lightbulb,Sparkles,Tag,@@ -114,6 +106,8 @@ import { formatCompactNumber } from '@/lib/format';import { toast } from 'sonner';import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';import type { PromptComparison } from '@/lib/insights-same-prompts';+import type { KpiSeriesDay } from '@/lib/insights-kpis';+import { KpiRows } from './_kpi-cards';// ─── Filter Types ─────────────────────────────────────────────────────────────@@ -250,56 +244,6 @@ function formatWindowBound(value: string): string {});}-// ─── Info Tooltip ─────────────────────────────────────────────────────────────--function InfoTip({ content }: { content: string }) {- const [pos, setPos] = useState<{ x: number; y: number } | null>(null);- const ref = useRef<HTMLSpanElement>(null);- const tooltipId = useId();-- function show() {- const r = ref.current?.getBoundingClientRect();- if (r) setPos({ x: r.left + r.width / 2, y: r.bottom + 6 });- }-- function hide() {- setPos(null);- }-- return (- <>- <span- ref={ref}- tabIndex={0}- aria-label="More information"- aria-describedby={pos ? tooltipId : undefined}- onMouseEnter={show}- onMouseLeave={hide}- onFocus={show}- onBlur={hide}- onKeyDown={(e) => {- if (e.key === 'Escape') hide();- }}- className="inline-flex items-center cursor-help rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- >- <HelpCircle className="h-3 w-3 text-muted-foreground/60 hover:text-muted-foreground transition-colors" />- </span>- {pos &&- createPortal(- <div- id={tooltipId}- role="tooltip"- style={{ left: pos.x, top: pos.y, transform: 'translateX(-50%)' }}- className="pointer-events-none fixed z-[9999] w-56 rounded-md border bg-popover px-3 py-2 text-xs text-popover-foreground shadow-md"- >- {content}- </div>,- document.body,- )}- </>- );-}-// ─── Sub-components ───────────────────────────────────────────────────────────// ─── Delta Badge ──────────────────────────────────────────────────────────────@@ -323,111 +267,6 @@ function DeltaBadge({ delta, suffix = '%' }: { delta: number | null; suffix?: st);}-function CountDeltaBadge({- current,- previous,- delta,-}: {- current: number;- previous: number | null;- delta: number | null;-}) {- if (previous === 0 && current > 0) {- return (- <span className="text-xs font-medium text-emerald-600 dark:text-emerald-400">- +{current.toLocaleString()} new- </span>- );- }- return <DeltaBadge delta={delta} />;-}--// ─── KPI Card ─────────────────────────────────────────────────────────────────--function KpiCard({- title,- tooltip,- icon: Icon,- value,- sub,- subVariant = 'muted',- onClick,-}: {- title: string;- tooltip: string;- icon: React.ElementType;- value: React.ReactNode;- sub: React.ReactNode;- subVariant?: 'muted' | 'positive';- onClick?: () => void;-}) {- const clickable = typeof onClick === 'function';- return (- <Card- onClick={clickable ? onClick : undefined}- role={clickable ? 'button' : undefined}- tabIndex={clickable ? 0 : undefined}- aria-label={clickable ? `${title} — view breakdown` : undefined}- title={clickable ? 'Click to see breakdown' : undefined}- onKeyDown={- clickable- ? (e) => {- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault();- onClick?.();- }- }- : undefined- }- className={cn(- 'group relative',- clickable &&- 'cursor-pointer transition-all duration-150 hover:border-foreground/30 hover:shadow-md hover:-translate-y-0.5 hover:bg-accent/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring',- )}- >- <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-1">- <CardTitle className="flex items-center gap-1 text-xs font-medium text-muted-foreground uppercase tracking-wide">- {title}- <InfoTip content={tooltip} />- </CardTitle>- <div className="relative flex h-4 w-4 items-center justify-center">- <Icon- className={cn(- 'h-3.5 w-3.5 text-muted-foreground transition-opacity',- clickable && 'group-hover:opacity-0',- )}- />- {clickable && (- <ArrowUpRight- className="absolute h-4 w-4 text-foreground opacity-0 transition-opacity group-hover:opacity-100"- aria-hidden- />- )}- </div>- </CardHeader>- <CardContent>- <div className="text-3xl font-bold">{value}</div>- <p- className={cn(- 'text-xs mt-1 flex items-center gap-0.5',- subVariant === 'positive'- ? 'text-green-600 dark:text-green-400'- : 'text-muted-foreground',- )}- >- {sub}- </p>- {clickable && (- <p className="mt-2 flex items-center gap-1 text-[10px] font-medium text-muted-foreground/70 opacity-0 transition-opacity group-hover:opacity-100">- View breakdown- <ArrowUpRight className="h-2.5 w-2.5" />- </p>- )}- </CardContent>- </Card>- );-}-// ─── Run Single Prompt Dialog ─────────────────────────────────────────────────function RunSinglePromptDialog({@@ -1056,7 +895,6 @@ 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);@@ -1072,6 +910,8 @@ export default function InsightsPage() {const [sovData, setSovData] = useState<ShareOfVoiceData | null>(null);const [recommendations, setRecommendations] = useState<InsightsRecommendations | null>(null);const [comparison, setComparison] = useState<PromptComparison | null>(null);+ const [coverage, setCoverage] = useState<CoverageKpi | null>(null);+ const [kpiSeries, setKpiSeries] = useState<KpiSeriesDay[] | null>(null);const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);// The window and filters the cards were last loaded with (the 24h view// anchored to its tracking run): the breakdown panel explains those exact@@ -1154,11 +994,12 @@ export default function InsightsPage() {setRateTrend(trend && trend.points.length > 0 ? trend : null);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);setComparison(insights.comparison);+ setCoverage(insights.coverage);+ setKpiSeries(insights.kpiSeries);setHasAnyData(insights.hasAnyData);// Group raw model slugs by their resolved display name so different@@ -1472,16 +1313,6 @@ export default function InsightsPage() {// content stays visible under the overlay instead of flashing a skeleton.const isRefetching = isLoading && summary !== null;- // Visibility Rate now IS the AI Visibility Score (0-100): 0.6×mention- // rate + 0.25×citation rate + 0.15×position factor over the filtered- // answers. Sourced from the trend action so this card, the trend card- // header and the leaderboard all read the exact same number. Coverage- // (appeared in X of Y prompts) survives as the sub-line.- const headlineScore = rateTrend?.summary.rate ?? 0;- const coveragePct =- visibilityRate && trackedPrompts && trackedPrompts.activeInPeriod > 0- ? Math.round((visibilityRate.visiblePrompts / trackedPrompts.activeInPeriod) * 1000) / 10- : 0;const trulyEmpty = noResults && !hasAnyData;// The localStorage-tracked job banner (with progress + Stop) wins when this@@ -1615,108 +1446,19 @@ export default function InsightsPage() {<NoDataForPeriod datePreset={filters.datePreset} onReset={handleResetFilters} />) : (<>- {/* 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"- tooltip="AI Visibility Score (0-100): how often AI answers mention you (60%), cite your site (25%) and how early you're named (15%), under the current filters."- icon={Eye}- value={headlineScore}- sub={- visibilityRate && trackedPrompts ? (- <span className="tabular-nums">- appeared in {visibilityRate.visiblePrompts}/{trackedPrompts.activeInPeriod}{' '}- prompts ({coveragePct}%)- </span>- ) : null- }- 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, counting one per location each active prompt targets (paused prompts don't count) — 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} active locations- </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} active prompt locations`- )- }- onClick={() => router.push('/dashboard/prompts')}- />- <KpiCard- title={t('mentions')}- tooltip="How many times your brand was referenced by name in AI-generated responses."- icon={Zap}- value={summary!.totalMentions.toLocaleString()}- sub={- <CountDeltaBadge- current={summary!.totalMentions}- previous={summary!.prevMentions}- delta={summary!.mentionsChange}- />- }- subVariant={- summary!.mentionsChange !== null && summary!.mentionsChange > 0- ? 'positive'- : 'muted'- }- onClick={() => setBreakdownMetric('mentions')}- />- <KpiCard- title={t('citations')}- tooltip="Times your brand's domain was cited as a source with a direct link in AI responses."- icon={Quote}- value={summary!.totalCitations.toLocaleString()}- sub={- <CountDeltaBadge- current={summary!.totalCitations}- previous={summary!.prevCitations}- delta={summary!.citationsChange}- />- }- subVariant={- summary!.citationsChange !== null && summary!.citationsChange > 0- ? 'positive'- : 'muted'- }- onClick={() => router.push('/dashboard/citations')}- />- <KpiCard- title={t('positiveSentiment')}- tooltip="Percentage of answers that mention your brand and describe it in a positive context."- icon={AlertCircle}- value={`${summary!.positiveSentimentPct}%`}- sub={<DeltaBadge delta={summary!.sentimentChange} suffix=" pts" />}- subVariant={- summary!.sentimentChange !== null && summary!.sentimentChange > 0- ? 'positive'- : 'muted'- }- />- </div>+ {/* KPI cards (VIS-003): today's five, then the new rates. */}+ <KpiRows+ summary={summary!}+ trend={rateTrend}+ trackedPrompts={trackedPrompts}+ coverage={coverage}+ sov={sovData}+ competitors={competitorData}+ comparison={comparison}+ series={kpiSeries}+ onBreakdown={setBreakdownMetric}+ onNavigate={(path) => router.push(path)}+ />{/* Competitor Comparison */}{competitorData ? (diff --git a/web/src/lib/actions/tracking-visibility-parity.test.ts b/web/src/lib/actions/tracking-visibility-parity.test.tsindex e6d843fba..96c53b37a 100644--- a/web/src/lib/actions/tracking-visibility-parity.test.ts+++ b/web/src/lib/actions/tracking-visibility-parity.test.ts@@ -268,7 +268,7 @@ describe('Same prompts parity (VIS-002)', () => {getCompetitorComparison('b1', thirtyDays),]);return withPromptComparison(- { trend, summary, competitors },+ { trend, summary, competitors, sov: { overallSovChange: null }, coverage: null },parseSamePromptComparison(SAME),samePrompts,);diff --git a/web/src/lib/actions/tracking.test.ts b/web/src/lib/actions/tracking.test.tsindex b2224d6f5..f385dca8e 100644--- a/web/src/lib/actions/tracking.test.ts+++ b/web/src/lib/actions/tracking.test.ts@@ -135,6 +135,59 @@ describe('getInsightsSummary', () => {expect(summary.positiveSentimentPct).toBe(0);});++ it('works out the v2 KPI card rates from the same aggregates (VIS-003)', async () => {+ rpcMock = vi.fn(async () => ({+ data: {+ ...insightsAggregatesRow,+ citation_answers: 171,+ negative_count: 13,+ sum_position: 305,+ position_count: 122,+ kpi_complete: true,+ },+ error: null,+ }));+ const { getInsightsSummary } = await import('./tracking');++ const summary = await getInsightsSummary('brand-id');++ // 171/427 answers cite the domain; 51 positive and 13 negative of 127.+ expect(summary).toMatchObject({+ citationRate: 40,+ negativeSentimentPct: 10,+ netSentiment: 30,+ avgPosition: 2.5,+ });+ });++ it('leaves Net sentiment and Avg. position empty until the rollups are backfilled', async () => {+ rpcMock = vi.fn(async () => ({+ data: {+ ...insightsAggregatesRow,+ citation_answers: 171,+ negative_count: 2,+ sum_position: null,+ position_count: 0,+ kpi_complete: false,+ },+ error: null,+ }));+ const { getInsightsSummary } = await import('./tracking');++ const summary = await getInsightsSummary('brand-id');++ expect(summary).toMatchObject({ netSentiment: null, avgPosition: null, citationRate: 40 });+ });++ it('shows the new rates as empty, not 0, if migration 00131 has not run', async () => {+ rpcMock = vi.fn(async () => ({ data: insightsAggregatesRow, error: null }));+ const { getInsightsSummary } = await import('./tracking');++ const summary = await getInsightsSummary('brand-id');++ expect(summary).toMatchObject({ netSentiment: null, avgPosition: null, citationRate: null });+ });});describe('analyzeNewPrompt', () => {diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex 079629ed8..f4c3084dd 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -45,6 +45,14 @@ import { getPromptVolumes } from '@/lib/actions/volumes';import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import { percentageChange } from '@/lib/metrics';+import {+ coverage as coverageRate,+ kpiRates,+ parseKpiSeries,+ rateChange,+ type KpiRates,+ type KpiSeriesDay,+} from '@/lib/insights-kpis';import {breakdownDelta,buildBreakdownRows,@@ -194,6 +202,19 @@ export interface InsightsSummary {/** Raw previous-period count, used to distinguish a zero base from unavailable comparison data. */prevCitations: number | null;sentimentChange: number | null;+ /**+ * The v2 KPI cards (VIS-003, 00131). Null without the answers they need,+ * and Net sentiment / Avg. position also while the rollups behind the+ * window are not backfilled. Changes are in points (positions for Avg.+ * position, where lower is better).+ */+ citationRate: number | null;+ citationRateChange: number | null;+ negativeSentimentPct: number | null;+ netSentiment: number | null;+ netSentimentChange: number | null;+ avgPosition: number | null;+ avgPositionChange: number | null;}/**@@ -218,6 +239,12 @@ export type { DayWindow } from '@/lib/insights-windows';// ── RPC return shapes (mirror supabase/migrations/00031_insights_sentiment_denominator.sql) ─interface InsightsAggregates {+ /** 00131: the KPI cards' components; kpi_complete is false before the backfill. */+ citation_answers?: number;+ negative_count?: number;+ sum_position?: number | null;+ position_count?: number;+ kpi_complete?: boolean;total_results: number;sum_visibility: number;total_mentions: number;@@ -675,7 +702,6 @@ export interface InsightsData {competitors: CompetitorComparisonData;sov: ShareOfVoiceData;trackedPrompts: TrackedPromptsKpi;- visibilityRate: VisibilityRateKpi;filterOptions: InsightsFilterOptions;recommendations: InsightsRecommendations;hasAnyData: boolean;@@ -687,6 +713,13 @@ export interface InsightsData {* window (All time) or before the rollups behind it are backfilled.*/comparison: PromptComparison | null;+ /** Coverage card (VIS-003); null when its read failed. */+ coverage: CoverageKpi | null;+ /**+ * The KPI cards' sparklines, one point per day (VIS-003). Null for the 24h+ * view (a single day), when the read failed, or before the backfill.+ */+ kpiSeries: KpiSeriesDay[] | null;/** The run ledger, when the 24h window was anchored to it (`anchor24h`). */trackingWindow: TrackingWindow | null;}@@ -773,7 +806,14 @@ export async function getTrackingWindow(brandId: string): Promise<TrackingWindow/** The part of the Insights page that depends only on the brand and the window. */type WindowedInsights = Pick<InsightsData,- 'summary' | 'competitors' | 'sov' | 'visibilityRate' | 'filterOptions' | 'trend' | 'comparison'+ | 'summary'+ | 'competitors'+ | 'sov'+ | 'filterOptions'+ | 'trend'+ | 'comparison'+ | 'coverage'+ | 'kpiSeries'>;type InsightsFilterArgs = {@@ -815,8 +855,8 @@ async function loadWindowedInsights(return fallback;});- const [summary, competitors, sov, visibilityRate, filterOptions, trend, same] = await Promise.all(- [+ const [summary, competitors, sov, filterOptions, trend, same, coverage, kpiSeries] =+ await Promise.all([getInsightsSummary(brandId, filterOpts),lenient(getCompetitorComparison(brandId, filterOpts),@@ -824,7 +864,6 @@ async function loadWindowedInsights('competitor comparison',),lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),- getVisibilityRateKpi(brandId, filterOpts),getInsightsFilterOptions(brandId),// The chart follows the same window as every other number on the page.lenient<VisibilityRateTrendData | null>(@@ -833,12 +872,110 @@ async function loadWindowedInsights('visibility trend',),lenient(getSamePromptComparison(brandId, filterOpts), null, 'same-prompt comparison'),- ],- );- const windowed = { summary, competitors, sov, visibilityRate, filterOptions, trend };+ lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),+ lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),+ ]);+ const windowed = {+ ...(comparisonWindows(filterOpts).prev ? { summary, sov } : withoutChanges(summary, sov)),+ competitors,+ filterOptions,+ trend,+ coverage,+ kpiSeries,+ };return withPromptComparison(windowed, same, filterOpts.samePrompts !== false);}+/** Coverage card (VIS-003): the answered prompts where the brand appeared. */+export interface CoverageKpi {+ visiblePrompts: number;+ activePrompts: number;+ /** %, one decimal; null without answered prompts. */+ value: number | null;+ /** Change in points vs the previous window; null without one. */+ change: number | null;+}++/**+ * Coverage over the card's windows: distinct prompts the brand appeared in+ * (visible_prompt_stats) over distinct prompts answered (tracked_prompt_count),+ * the same counts the Visibility card's "appeared in x/y" line shows.+ */+async function getCoverageKpi(brandId: string, opts?: InsightsFilterArgs): Promise<CoverageKpi> {+ const supabase = await dbClient();+ const windows = comparisonWindows(opts);+ const base = {+ p_brand_id: brandId,+ p_platform: undefined as string | undefined,+ p_models: modelFilterArray(opts?.model),+ p_region: opts?.region ?? undefined,+ };++ const countsFor = async (win: MetricWindow) => {+ let visible;+ let active;+ if (win.kind === 'days') {+ const days = { ...base, p_day_from: win.days.dayFrom, p_day_to: win.days.dayTo };+ [visible, active] = await Promise.all([+ supabase.rpc('visible_prompt_stats_daily', days),+ supabase.rpc('tracked_prompt_count_daily', days),+ ]);+ } else {+ const range = {+ ...base,+ p_date_from: win.from,+ p_date_to: win.to,+ p_topic_id: opts?.topicId ?? undefined,+ };+ [visible, active] = await Promise.all([+ supabase.rpc('visible_prompt_stats', range),+ supabase.rpc('tracked_prompt_count', range),+ ]);+ }+ if (visible.error) throw new Error(visible.error.message);+ if (active.error) throw new Error(active.error.message);+ return {+ visible: Number((visible.data as { visible_prompts?: number } | null)?.visible_prompts ?? 0),+ active: Number(active.data ?? 0),+ };+ };++ const [cur, prev] = await Promise.all([+ countsFor(windows.cur),+ windows.prev ? countsFor(windows.prev) : Promise.resolve(null),+ ]);+ const value = coverageRate(cur.visible, cur.active);+ return {+ visiblePrompts: cur.visible,+ activePrompts: cur.active,+ value,+ change: prev ? rateChange(value, coverageRate(prev.visible, prev.active)) : null,+ };+}++/**+ * The KPI cards' sparklines: one point per day of the window, from the+ * prompt-grain rollups (00131), topic filter included. Whole days only — the+ * 24h view is a single day, nothing to plot.+ */+async function getKpiSeries(+ brandId: string,+ opts?: InsightsFilterArgs,+): Promise<KpiSeriesDay[] | null> {+ if (!opts?.days) return null;+ const supabase = await dbClient();+ const { data, error } = await supabase.rpc('insights_kpi_series', {+ p_brand_id: brandId,+ p_day_from: opts.days.dayFrom,+ p_day_to: opts.days.dayTo,+ p_models: modelFilterArray(opts.model),+ p_region: opts.region ?? undefined,+ p_topic_id: opts.topicId ?? undefined,+ });+ if (error) throw new Error(error.message);+ return parseKpiSeries(data);+}+/*** The comparison windows' totals over the prompts answered in both* (VIS-002): the daily rollups for whole days, the raw rows for the 24h and@@ -1451,6 +1588,13 @@ export async function getInsightsSummary(prevMentions: null,prevCitations: null,sentimentChange: null,+ citationRate: null,+ citationRateChange: null,+ negativeSentimentPct: null,+ netSentiment: null,+ netSentimentChange: null,+ avgPosition: null,+ avgPositionChange: null,};}@@ -1486,6 +1630,10 @@ export async function getInsightsSummary(let prevMentions: number | null = null;let prevCitations: number | null = null;let sentimentChange: number | null = null;+ let citationRateChange: number | null = null;+ let netSentimentChange: number | null = null;+ let avgPositionChange: number | null = null;+ const curRates = aggregateRates(cur);{let currentFrom: Date;@@ -1561,6 +1709,12 @@ export async function getInsightsSummary(mentionsChange = percentageChange(curMentions, prevMentions);citationsChange = percentageChange(curCitations, prevCitations);sentimentChange = curSentimentPct - prevSentimentPct;++ const deltaCur = aggregateRates(curWin);+ const deltaPrev = aggregateRates(prevWin);+ citationRateChange = rateChange(deltaCur.citationRate, deltaPrev.citationRate);+ netSentimentChange = rateChange(deltaCur.netSentiment, deltaPrev.netSentiment);+ avgPositionChange = rateChange(deltaCur.avgPosition, deltaPrev.avgPosition);}}@@ -1578,6 +1732,64 @@ export async function getInsightsSummary(prevMentions,prevCitations,sentimentChange,+ citationRate: curRates.citationRate,+ citationRateChange,+ negativeSentimentPct: curRates.negativePct,+ netSentiment: curRates.netSentiment,+ netSentimentChange,+ avgPosition: curRates.avgPosition,+ avgPositionChange,+ };+}++/**+ * The KPI cards' rates from one insights_aggregates window (00131). Before+ * the rollups behind it are backfilled, negatives and positions are missing:+ * Net sentiment and Avg. position read null rather than a partial value. A+ * payload without the 00131 fields at all (migration not run) reads the same+ * way, and so does Citation rate, instead of counting what's missing as 0.+ */+function aggregateRates(a: InsightsAggregates): KpiRates {+ const rates = kpiRates({+ answers: Number(a.total_results ?? 0),+ citationAnswers: Number(a.citation_answers ?? 0),+ mentioning: Number(a.mentioning_results ?? 0),+ positive: Number(a.positive_count ?? 0),+ negative: Number(a.negative_count ?? 0),+ sumPosition:+ a.sum_position === null || a.sum_position === undefined ? null : Number(a.sum_position),+ positionCount: Number(a.position_count ?? 0),+ });+ return {+ ...rates,+ citationRate: a.citation_answers === undefined ? null : rates.citationRate,+ ...(a.kpi_complete === true+ ? {}+ : { negativePct: null, netSentiment: null, avgPosition: null }),+ };+}++/**+ * All time has no earlier period of the same length (VIS-001), so the cards+ * show no change. getInsightsSummary and getShareOfVoiceData keep comparing+ * the trailing 7 days there for their other callers (the topic page).+ */+function withoutChanges(+ summary: InsightsSummary,+ sov: ShareOfVoiceData,+): { summary: InsightsSummary; sov: ShareOfVoiceData } {+ return {+ summary: {+ ...summary,+ visibilityChange: null,+ mentionsChange: null,+ citationsChange: null,+ sentimentChange: null,+ citationRateChange: null,+ netSentimentChange: null,+ avgPositionChange: null,+ },+ sov: { ...sov, overallSovChange: null },};}diff --git a/web/src/lib/insights-kpis.test.ts b/web/src/lib/insights-kpis.test.tsnew file mode 100644index 000000000..b0e96d23d--- /dev/null+++ b/web/src/lib/insights-kpis.test.ts@@ -0,0 +1,101 @@+import { describe, expect, it } from 'vitest';+import { coverage, kpiRates, parseKpiSeries, rateChange, shareOfVoice } from './insights-kpis';++describe('kpiRates', () => {+ it('works out every card rate from the components', () => {+ expect(+ kpiRates({+ answers: 200,+ citationAnswers: 76,+ mentioning: 100,+ positive: 48,+ negative: 14,+ sumPosition: 240,+ positionCount: 100,+ }),+ ).toEqual({+ citationRate: 38,+ positivePct: 48,+ negativePct: 14,+ netSentiment: 34,+ avgPosition: 2.4,+ });+ });++ it('has no rate without the answers it needs', () => {+ expect(+ kpiRates({+ answers: 0,+ citationAnswers: 0,+ mentioning: 0,+ positive: 0,+ negative: 0,+ sumPosition: null,+ positionCount: 0,+ }),+ ).toEqual({+ citationRate: null,+ positivePct: null,+ negativePct: null,+ netSentiment: null,+ avgPosition: null,+ });+ });+});++describe('rates', () => {+ it('rounds changes to one decimal and needs both values', () => {+ expect(rateChange(64.3, 62.2)).toBe(2.1);+ expect(rateChange(64.3, null)).toBeNull();+ });++ it('matches share_of_voice_aggregates and the coverage line', () => {+ expect(shareOfVoice(46, 954)).toBe(4.6);+ expect(shareOfVoice(0, 0)).toBeNull();+ expect(coverage(456, 709)).toBe(64.3);+ expect(coverage(0, 0)).toBeNull();+ });+});++describe('parseKpiSeries', () => {+ it('turns each day into the cards’ values', () => {+ const series = parseKpiSeries({+ complete: true,+ days: [+ {+ day: '2026-10-13',+ answers: 10,+ citation_answers: 4,+ total_mentions: 12,+ total_citations: 5,+ positive_count: 3,+ negative_count: 1,+ mentioning_answers: 6,+ sum_position: 9,+ position_count: 6,+ visible_prompts: 3,+ active_prompts: 4,+ competitor_mentions: 36,+ },+ ],+ });++ expect(series).toEqual([+ {+ day: '2026-10-13',+ mentions: 12,+ citations: 5,+ netSentiment: 33,+ coverage: 75,+ shareOfVoice: 25,+ avgPosition: 1.5,+ citationRate: 40,+ },+ ]);+ });++ it('draws nothing before the rollups are backfilled', () => {+ expect(parseKpiSeries({ complete: false, days: [] })).toBeNull();+ expect(parseKpiSeries(null)).toBeNull();+ });+});diff --git a/web/src/lib/insights-kpis.ts b/web/src/lib/insights-kpis.tsnew file mode 100644index 000000000..c0ca321d1--- /dev/null+++ b/web/src/lib/insights-kpis.ts@@ -0,0 +1,110 @@+/**+ * The Insights KPI cards' rates (VIS-003): Net sentiment, Avg. position,+ * Citation rate, Coverage and Share of voice, from the components the+ * aggregates return (00131). One definition for the card values, their+ * changes and the sparklines, so the three always agree.+ */++const round1 = (n: number) => Math.round(n * 10) / 10;++/** Components behind the rates, for one window or one day. */+export interface KpiComponents {+ answers: number;+ citationAnswers: number;+ /** Answers naming or citing the brand: the sentiment denominator (#508). */+ mentioning: number;+ positive: number;+ negative: number;+ /** Sum of the brand's position over answers naming it; null without positions. */+ sumPosition: number | null;+ positionCount: number;+}++export interface KpiRates {+ /** % of answers citing the brand's domain, one decimal. */+ citationRate: number | null;+ /** % of brand-naming answers that are positive / negative, whole numbers. */+ positivePct: number | null;+ negativePct: number | null;+ /** positivePct − negativePct, in points. */+ netSentiment: number | null;+ /** Mean position when named, one decimal; lower is better. */+ avgPosition: number | null;+}++export function kpiRates(c: KpiComponents): KpiRates {+ const positivePct = c.mentioning > 0 ? Math.round((c.positive / c.mentioning) * 100) : null;+ const negativePct = c.mentioning > 0 ? Math.round((c.negative / c.mentioning) * 100) : null;+ return {+ citationRate: c.answers > 0 ? round1((c.citationAnswers / c.answers) * 100) : null,+ positivePct,+ negativePct,+ netSentiment: positivePct !== null && negativePct !== null ? positivePct - negativePct : null,+ avgPosition:+ c.positionCount > 0 && c.sumPosition !== null+ ? round1(c.sumPosition / c.positionCount)+ : null,+ };+}++/** Change in points (or positions) between two rates; null unless both exist. */+export function rateChange(cur: number | null, prev: number | null): number | null {+ return cur === null || prev === null ? null : round1(cur - prev);+}++/** % of all tracked brands' mentions that name this brand, one decimal (share_of_voice_aggregates). */+export function shareOfVoice(brandMentions: number, competitorMentions: number): number | null {+ const all = brandMentions + competitorMentions;+ return all > 0 ? round1((brandMentions / all) * 100) : null;+}++/** % of the answered prompts where the brand appeared at least once, one decimal. */+export function coverage(visiblePrompts: number, activePrompts: number): number | null {+ return activePrompts > 0 ? round1((visiblePrompts / activePrompts) * 100) : null;+}++/** One day of the cards' sparklines. */+export interface KpiSeriesDay {+ day: string;+ mentions: number;+ citations: number;+ netSentiment: number | null;+ coverage: number | null;+ shareOfVoice: number | null;+ avgPosition: number | null;+ citationRate: number | null;+}++const num = (v: unknown): number => Number(v ?? 0);++/**+ * The insights_kpi_series payload as sparkline points, or null when it+ * can't be used: missing, or read from rollup rows not yet rewritten since+ * 00131 — the cards then show no sparkline rather than a partial one.+ */+export function parseKpiSeries(raw: unknown): KpiSeriesDay[] | null {+ const r = raw as { complete?: boolean; days?: Record<string, unknown>[] } | null;+ if (!r || r.complete !== true) return null;+ return (r.days ?? []).map((d) => {+ const rates = kpiRates({+ answers: num(d.answers),+ citationAnswers: num(d.citation_answers),+ mentioning: num(d.mentioning_answers),+ positive: num(d.positive_count),+ negative: num(d.negative_count),+ sumPosition:+ d.sum_position === null || d.sum_position === undefined ? null : num(d.sum_position),+ positionCount: num(d.position_count),+ });+ return {+ day: String(d.day),+ mentions: num(d.total_mentions),+ citations: num(d.total_citations),+ netSentiment: rates.netSentiment,+ coverage: coverage(num(d.visible_prompts), num(d.active_prompts)),+ shareOfVoice: shareOfVoice(num(d.total_mentions), num(d.competitor_mentions)),+ avgPosition: rates.avgPosition,+ citationRate: rates.citationRate,+ };+ });+}diff --git a/web/src/lib/insights-same-prompts.test.ts b/web/src/lib/insights-same-prompts.test.tsindex 552564c88..dc586ef06 100644--- a/web/src/lib/insights-same-prompts.test.ts+++ b/web/src/lib/insights-same-prompts.test.ts@@ -17,6 +17,11 @@ const totals = (over: Partial<SamePromptTotals> = {}): SamePromptTotals => ({total_citations: 60,positive_count: 30,mentioning_answers: 110,+ negative_count: 10,+ sum_position: 200,+ position_count: 100,+ visible_prompts: 150,+ competitor_mentions: 450,by_competitor: [],...over,});@@ -91,6 +96,37 @@ describe('samePromptChanges', () => {expect(changes.competitorChange('new')).toBeNull();});+ it('measures the KPI card rates on the shared prompts', () => {+ const changes = samePromptChanges(+ same({+ samePrompts: 200,+ cur: totals({+ visible_prompts: 160,+ positive_count: 44,+ negative_count: 11,+ mentioning_answers: 110,+ sum_position: 180,+ position_count: 100,+ citation_answers: 60,+ total_mentions: 150,+ competitor_mentions: 350,+ }),+ prev: totals({ visible_prompts: 150 }),+ }),+ );++ // Coverage of the shared prompts: 160/200 = 80% vs 150/200 = 75%.+ expect(changes.coverageChange).toBe(5);+ // Net sentiment: (40% − 10%) vs (27% − 9%).+ expect(changes.netSentimentChange).toBe(12);+ // Avg. position: 1.8 vs 2.0, an improvement.+ expect(changes.avgPositionChange).toBe(-0.2);+ // Citation rate: 15% vs 10%.+ expect(changes.citationRateChange).toBe(5);+ // Share of voice: 150/500 = 30% vs 150/600 = 25%.+ expect(changes.shareOfVoiceChange).toBe(5);+ });+it('has no percentage changes without answers in both windows', () => {const changes = samePromptChanges(same({ samePrompts: 0, cur: totals({ answers: 0 }), prev: totals({ answers: 0 }) }),@@ -104,7 +140,17 @@ describe('samePromptChanges', () => {describe('withPromptComparison', () => {const insights = () => ({- summary: { totalResults: 709, mentionsChange: 203, citationsChange: 223, sentimentChange: 4 },+ summary: {+ totalResults: 709,+ mentionsChange: 203,+ citationsChange: 223,+ sentimentChange: 4,+ netSentimentChange: 9,+ avgPositionChange: -0.5,+ citationRateChange: 3,+ },+ sov: { overallSov: 4.6, overallSovChange: 2.2 },+ coverage: { visiblePrompts: 456, activePrompts: 709, value: 64.3, change: 8 },trend: { summary: { change: 7.9 } },competitors: {brands: [@@ -131,6 +177,12 @@ describe('withPromptComparison', () => {// The leaderboard's own row moves with the card.expect(out.competitors.brands[0].scoreChange).toBe(changes.visibility.change);expect(out.competitors.brands[1].scoreChange).toBe(changes.competitorChange('c1'));+ // Every KPI card's change moves too; the values stay.+ expect(out.summary.netSentimentChange).toBe(changes.netSentimentChange);+ expect(out.summary.avgPositionChange).toBe(changes.avgPositionChange);+ expect(out.summary.citationRateChange).toBe(changes.citationRateChange);+ expect(out.sov).toEqual({ overallSov: 4.6, overallSovChange: changes.shareOfVoiceChange });+ expect(out.coverage).toMatchObject({ value: 64.3, change: changes.coverageChange });expect(out.untouched).toBe('kept');});diff --git a/web/src/lib/insights-same-prompts.ts b/web/src/lib/insights-same-prompts.tsindex bca0b7b3a..0cce405e3 100644--- a/web/src/lib/insights-same-prompts.ts+++ b/web/src/lib/insights-same-prompts.ts@@ -1,5 +1,6 @@import { computeAiVisibilityScore } from '@/lib/visibility-score';import { percentageChange } from '@/lib/metrics';+import { coverage, kpiRates, rateChange, shareOfVoice } from '@/lib/insights-kpis';/*** Insights "Compare: Same prompts" (VIS-002). Adding prompts used to inflate@@ -27,6 +28,14 @@ export interface SamePromptTotals {total_citations: number;positive_count: number;mentioning_answers: number;+ /** 00131: the KPI cards' components on the shared prompts. */+ negative_count: number;+ sum_position: number | null;+ position_count: number;+ /** Shared prompts where the brand appeared (named or cited). */+ visible_prompts: number;+ /** Every competitor's mentions, for share of voice. */+ competitor_mentions: number;by_competitor: SamePromptCompetitor[];}@@ -64,6 +73,11 @@ function parseTotals(raw: unknown): SamePromptTotals {total_citations: num(t.total_citations),positive_count: num(t.positive_count),mentioning_answers: num(t.mentioning_answers),+ negative_count: num(t.negative_count),+ sum_position: numOrNull(t.sum_position),+ position_count: num(t.position_count),+ visible_prompts: num(t.visible_prompts),+ competitor_mentions: num(t.competitor_mentions),by_competitor: ((t.by_competitor as Record<string, unknown>[] | undefined) ?? []).map((c) => ({competitor_id: String(c.competitor_id),name: (c.name as string | null) ?? null,@@ -131,6 +145,12 @@ export interface SamePromptChanges {citationsChange: number | null;/** Positive-sentiment share change in points. */sentimentChange: number | null;+ /** The KPI cards' rate changes (VIS-003), in points (positions for Avg. position). */+ netSentimentChange: number | null;+ avgPositionChange: number | null;+ citationRateChange: number | null;+ coverageChange: number | null;+ shareOfVoiceChange: number | null;}/** Every change the Insights page shows, measured on the shared prompts. */@@ -139,6 +159,18 @@ export function samePromptChanges(same: SamePromptComparison): SamePromptChangesconst comparable = cur.answers > 0 && prev.answers > 0;const visCur = brandScore(cur);const visPrev = brandScore(prev);+ const rates = (t: SamePromptTotals) =>+ kpiRates({+ answers: t.answers,+ citationAnswers: t.citation_answers,+ mentioning: t.mentioning_answers,+ positive: t.positive_count,+ negative: t.negative_count,+ sumPosition: t.sum_position,+ positionCount: t.position_count,+ });+ const ratesCur = rates(cur);+ const ratesPrev = rates(prev);return {visibility: {cur: visCur,@@ -156,6 +188,17 @@ export function samePromptChanges(same: SamePromptComparison): SamePromptChanges? percentageChange(cur.total_citations, prev.total_citations): null,sentimentChange: comparable ? sentimentPct(cur) - sentimentPct(prev) : null,+ netSentimentChange: rateChange(ratesCur.netSentiment, ratesPrev.netSentiment),+ avgPositionChange: rateChange(ratesCur.avgPosition, ratesPrev.avgPosition),+ citationRateChange: rateChange(ratesCur.citationRate, ratesPrev.citationRate),+ coverageChange: rateChange(+ coverage(cur.visible_prompts, same.samePrompts),+ coverage(prev.visible_prompts, same.samePrompts),+ ),+ shareOfVoiceChange: rateChange(+ shareOfVoice(cur.total_mentions, cur.competitor_mentions),+ shareOfVoice(prev.total_mentions, prev.competitor_mentions),+ ),};}@@ -166,7 +209,12 @@ export interface ComparedInsights {mentionsChange: number | null;citationsChange: number | null;sentimentChange: number | null;+ netSentimentChange: number | null;+ avgPositionChange: number | null;+ citationRateChange: number | null;};+ sov: { overallSovChange: number | null };+ coverage: { change: number | null } | null;trend: { summary: { change: number | null } } | null;competitors: {brands: { isOwnBrand: boolean; competitorId?: string; scoreChange: number | null }[];@@ -177,8 +225,7 @@ export interface ComparedInsights {* Re-measure the page's changes on the prompts answered in both periods* when Same prompts is on. The numbers themselves still cover every prompt;* only the changes move: the Visibility change on the trend card, every- * leaderboard row's change, and the Mentions, Citations and Sentiment- * changes. Without a usable comparison the changes stay as they are,+ * leaderboard row's change, and every KPI card's change. Without a usable comparison the changes stay as they are,* measured on all prompts. With Same prompts off, the counts still come* back so the page can say how many new prompts the change includes.*/@@ -197,7 +244,7 @@ export function withPromptComparison<T extends ComparedInsights>(if (!samePrompts) return { ...insights, comparison };const changes = samePromptChanges(same);- const { summary, trend, competitors } = insights;+ const { summary, trend, competitors, sov, coverage: coverageKpi } = insights;return {...insights,comparison,@@ -208,8 +255,13 @@ export function withPromptComparison<T extends ComparedInsights>(mentionsChange: changes.mentionsChange,citationsChange: changes.citationsChange,sentimentChange: changes.sentimentChange,+ netSentimentChange: changes.netSentimentChange,+ avgPositionChange: changes.avgPositionChange,+ citationRateChange: changes.citationRateChange,}: summary,+ sov: { ...sov, overallSovChange: changes.shareOfVoiceChange },+ coverage: coverageKpi && { ...coverageKpi, change: changes.coverageChange },trend: trend && { ...trend, summary: { ...trend.summary, change: changes.visibility.change } },competitors: {...competitors,diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex de36ed8fd..37abb04dc 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3097,6 +3097,17 @@ export type Database = {regions: string[]}[]}+ insights_kpi_series: {+ Args: {+ p_brand_id: string+ p_day_from?: string+ p_day_to?: string+ p_models?: string[]+ p_region?: string+ p_topic_id?: string+ }+ Returns: Json+ }insights_same_prompt_compare: {Args: {p_brand_id: string