Skip to content

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

feat(mentions): take the Mentions page's changes on the same prompts as Insights (#1230)

Cihan20e8ba81de65
diff --git a/supabase/migrations/00195_mentions_same_prompt_changes.sql b/supabase/migrations/00195_mentions_same_prompt_changes.sql
new file mode 100644
index 000000000..03aa02fa8
--- /dev/null
+++ b/supabase/migrations/00195_mentions_same_prompt_changes.sql
@@ -0,0 +1,262 @@
+-- ============================================================================
+-- 00195: the Mentions page takes its changes on the same prompts as Insights
+-- ============================================================================
+-- After 00191 both pages show the same mentions and net sentiment, but their
+-- "vs the previous period" changes still differed: Insights compares only the
+-- prompts answered in both windows (insights_same_prompt_compare_daily,
+-- 00164), so adding or removing prompts doesn't read as a rise or a fall; the
+-- Mentions page compared all of them.
+--
+-- mentions_overview (00191's definition) now also returns `same`: how many
+-- prompts both windows answered, how many are new or dropped, and both
+-- windows' totals over the shared ones; each platform row gains the same
+-- counts on them (same_*, same_prev_*). The page takes every change from
+-- these. Existing fields are unchanged, so either deploy order works; the
+-- platforms keep 00191's order by occurrences.
+
+create or replace function public.mentions_overview(
+ p_brand_id uuid,
+ p_date_from timestamptz,
+ p_date_to timestamptz default null,
+ p_platform text default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_search 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_to timestamptz := coalesce(p_date_to, now());
+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));
+ v_span interval;
+ -- Whole days the window spans, at least one, with an hour of slack: a
+ -- rolling 7 days ends at now(), a moment after the browser started it.
+ v_days integer;
+ -- Under two days the answers are read directly.
+ v_raw boolean;
+ v_day_to date;
+ v_day_from date;
+ v_prev_from date;
+ v_search text := nullif(btrim(lower(coalesce(p_search, ''))), '');
+ 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;
+
+ v_span := v_to - v_from;
+ v_days := greatest(1, ceil(extract(epoch from v_span) / 86400.0 - 1.0 / 24)::integer);
+ v_raw := v_days < 2;
+ v_day_to := (v_to at time zone 'utc')::date;
+ v_day_from := v_day_to - (v_days - 1);
+ v_prev_from := v_day_from - v_days;
+
+ with
+ prompts_in as (
+ select p.id
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ and (p_topic_id is null or p.topic_id = p_topic_id)
+ and (v_search is null or position(v_search in lower(p.text)) > 0)
+ ),
+ facts as (
+ select (d.day >= v_day_from) as cur,
+ d.day,
+ d.prompt_id,
+ d.platform,
+ d.answer_count::bigint as answers,
+ d.mention_answers::bigint as mentions,
+ d.mention_occurrences as occurrences,
+ d.positive_answers::bigint as positive,
+ d.negative_answers::bigint as negative,
+ d.position_sum,
+ d.position_count::bigint as position_count,
+ d.last_answer_at
+ from public.mentions_prompt_daily d
+ join prompts_in pi on pi.id = d.prompt_id
+ where not v_raw
+ and d.brand_id = p_brand_id
+ and d.day between v_prev_from and v_day_to
+ and (p_platform is null or d.platform = p_platform)
+ and (p_region is null or d.region = p_region)
+ union all
+ select (pr.created_at >= v_from),
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id,
+ pr.platform,
+ 1,
+ (pr.mention_count > 0)::int,
+ coalesce(pr.mention_count, 0),
+ (pr.mention_count > 0 and pr.sentiment = 'positive')::int,
+ (pr.mention_count > 0 and pr.sentiment = 'negative')::int,
+ case when pr.mention_count > 0 then coalesce(pr.mention_position, 0) else 0 end,
+ (pr.mention_count > 0 and pr.mention_position is not null)::int,
+ pr.created_at
+ from public.prompt_results pr
+ join prompts_in pi on pi.id = pr.prompt_id
+ where v_raw
+ and pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from - v_span
+ and pr.created_at <= v_to
+ and (p_platform is null or pr.platform = p_platform)
+ and (p_region is null or pr.region = p_region)
+ ),
+ -- Prompts answered in both windows: every change is taken on them, as
+ -- Insights takes its changes (insights_same_prompt_compare_daily, 00164),
+ -- so adding or removing prompts doesn't read as a rise or a fall.
+ presence as (
+ select prompt_id,
+ bool_or(cur and answers > 0) as in_cur,
+ bool_or(not cur and answers > 0) as in_prev
+ from facts
+ group by prompt_id
+ ),
+ flagged as (
+ select f.*, (p.in_cur and p.in_prev) as shared
+ from facts f
+ join presence p using (prompt_id)
+ ),
+ same_totals as (
+ select cur,
+ sum(answers)::bigint as answers,
+ sum(mentions)::bigint as mentions,
+ sum(occurrences)::bigint as occurrences,
+ sum(positive)::bigint as positive,
+ sum(negative)::bigint as negative,
+ count(distinct prompt_id) as prompts,
+ count(distinct prompt_id) filter (where mentions > 0) as prompts_with_mentions
+ from flagged
+ where shared
+ group by cur
+ ),
+ totals as (
+ select cur,
+ sum(answers)::bigint as answers,
+ sum(mentions)::bigint as mentions,
+ sum(occurrences)::bigint as occurrences,
+ sum(positive)::bigint as positive,
+ sum(negative)::bigint as negative,
+ sum(position_sum)::bigint as position_sum,
+ sum(position_count)::bigint as position_count,
+ count(distinct prompt_id) as prompts,
+ count(distinct prompt_id) filter (where mentions > 0) as prompts_with_mentions,
+ max(last_answer_at) as last_answer_at
+ from facts
+ group by cur
+ ),
+ platforms as (
+ select platform,
+ coalesce(sum(answers) filter (where cur), 0)::bigint as answers,
+ coalesce(sum(mentions) filter (where cur), 0)::bigint as mentions,
+ coalesce(sum(occurrences) filter (where cur), 0)::bigint as occurrences,
+ coalesce(sum(positive) filter (where cur), 0)::bigint as positive,
+ coalesce(sum(negative) filter (where cur), 0)::bigint as negative,
+ coalesce(sum(answers) filter (where not cur), 0)::bigint as prev_answers,
+ coalesce(sum(mentions) filter (where not cur), 0)::bigint as prev_mentions,
+ coalesce(sum(positive) filter (where not cur), 0)::bigint as prev_positive,
+ coalesce(sum(negative) filter (where not cur), 0)::bigint as prev_negative,
+ -- The same on the shared prompts, for the platform's change.
+ coalesce(sum(answers) filter (where cur and shared), 0)::bigint as same_answers,
+ coalesce(sum(mentions) filter (where cur and shared), 0)::bigint as same_mentions,
+ coalesce(sum(positive) filter (where cur and shared), 0)::bigint as same_positive,
+ coalesce(sum(negative) filter (where cur and shared), 0)::bigint as same_negative,
+ coalesce(sum(answers) filter (where not cur and shared), 0)::bigint as same_prev_answers,
+ coalesce(sum(mentions) filter (where not cur and shared), 0)::bigint as same_prev_mentions,
+ coalesce(sum(positive) filter (where not cur and shared), 0)::bigint as same_prev_positive,
+ coalesce(sum(negative) filter (where not cur and shared), 0)::bigint as same_prev_negative
+ from flagged
+ group by platform
+ ),
+ daily as (
+ select day,
+ sum(answers)::bigint as answers,
+ sum(mentions)::bigint as mentions,
+ sum(occurrences)::bigint as occurrences,
+ sum(positive)::bigint as positive,
+ sum(negative)::bigint as negative
+ from facts
+ where cur
+ group by day
+ ),
+ comp_facts as (
+ select (c.day >= v_day_from) as cur,
+ c.competitor_id,
+ c.mention_answers::bigint as mentions,
+ c.co_mention_answers::bigint as co_mentions
+ from public.mentions_competitor_daily c
+ join prompts_in pi on pi.id = c.prompt_id
+ where not v_raw
+ and c.brand_id = p_brand_id
+ and c.day between v_prev_from and v_day_to
+ and (p_platform is null or c.platform = p_platform)
+ and (p_region is null or c.region = p_region)
+ union all
+ select (pr.created_at >= v_from),
+ cm.value->>'competitor_id',
+ 1,
+ (pr.mention_count > 0)::int
+ from public.prompt_results pr
+ join prompts_in pi on pi.id = pr.prompt_id
+ cross join lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where v_raw
+ and pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from - v_span
+ and pr.created_at <= v_to
+ and (p_platform is null or pr.platform = p_platform)
+ and (p_region is null or pr.region = p_region)
+ and cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0
+ ),
+ competitors as (
+ select co.id::text as competitor_id,
+ co.name,
+ coalesce(sum(f.mentions) filter (where f.cur), 0)::bigint as mentions,
+ coalesce(sum(f.co_mentions) filter (where f.cur), 0)::bigint as co_mentions,
+ coalesce(sum(f.mentions) filter (where not f.cur), 0)::bigint as prev_mentions
+ from public.competitors co
+ left join comp_facts f on f.competitor_id = co.id::text
+ where co.brand_id = p_brand_id
+ group by co.id, co.name
+ )
+ select jsonb_build_object(
+ 'window', jsonb_build_object(
+ 'from', v_from, 'to', v_to, 'days', v_days,
+ 'source', case when v_raw then 'answers' else 'days' end,
+ 'day_from', v_day_from, 'day_to', v_day_to),
+ 'current', (select to_jsonb(t) - 'cur' from totals t where t.cur),
+ 'previous', (select to_jsonb(t) - 'cur' from totals t where not t.cur),
+ 'same', jsonb_build_object(
+ 'prompts', (select count(*) from presence where in_cur and in_prev),
+ '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),
+ 'current', (select to_jsonb(t) - 'cur' from same_totals t where t.cur),
+ 'previous', (select to_jsonb(t) - 'cur' from same_totals t where not t.cur)),
+ -- In the order of the column the table shows: occurrences, then responses.
+ 'platforms', coalesce((select jsonb_agg(to_jsonb(p)
+ order by p.occurrences desc, p.mentions desc, p.platform)
+ from platforms p), '[]'::jsonb),
+ 'daily', coalesce((select jsonb_agg(to_jsonb(d) order by d.day) from daily d),
+ '[]'::jsonb),
+ 'competitors', coalesce((select jsonb_agg(to_jsonb(c) order by c.mentions desc, c.name)
+ from competitors c), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+notify pgrst, 'reload schema';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 2afce6e4f..15637edac 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -28007,6 +28007,272 @@ comment on function public.ai_traffic_known_pages(uuid, text[]) is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00195_mentions_same_prompt_changes.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00195: the Mentions page takes its changes on the same prompts as Insights
+-- ============================================================================
+-- After 00191 both pages show the same mentions and net sentiment, but their
+-- "vs the previous period" changes still differed: Insights compares only the
+-- prompts answered in both windows (insights_same_prompt_compare_daily,
+-- 00164), so adding or removing prompts doesn't read as a rise or a fall; the
+-- Mentions page compared all of them.
+--
+-- mentions_overview (00191's definition) now also returns `same`: how many
+-- prompts both windows answered, how many are new or dropped, and both
+-- windows' totals over the shared ones; each platform row gains the same
+-- counts on them (same_*, same_prev_*). The page takes every change from
+-- these. Existing fields are unchanged, so either deploy order works; the
+-- platforms keep 00191's order by occurrences.
+
+create or replace function public.mentions_overview(
+ p_brand_id uuid,
+ p_date_from timestamptz,
+ p_date_to timestamptz default null,
+ p_platform text default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_search 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_to timestamptz := coalesce(p_date_to, now());
+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));
+ v_span interval;
+ -- Whole days the window spans, at least one, with an hour of slack: a
+ -- rolling 7 days ends at now(), a moment after the browser started it.
+ v_days integer;
+ -- Under two days the answers are read directly.
+ v_raw boolean;
+ v_day_to date;
+ v_day_from date;
+ v_prev_from date;
+ v_search text := nullif(btrim(lower(coalesce(p_search, ''))), '');
+ 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;
+
+ v_span := v_to - v_from;
+ v_days := greatest(1, ceil(extract(epoch from v_span) / 86400.0 - 1.0 / 24)::integer);
+ v_raw := v_days < 2;
+ v_day_to := (v_to at time zone 'utc')::date;
+ v_day_from := v_day_to - (v_days - 1);
+ v_prev_from := v_day_from - v_days;
+
+ with
+ prompts_in as (
+ select p.id
+ from public.prompts p
+ join public.prompt_sets ps on ps.id = p.prompt_set_id
+ where ps.brand_id = p_brand_id
+ and (p_topic_id is null or p.topic_id = p_topic_id)
+ and (v_search is null or position(v_search in lower(p.text)) > 0)
+ ),
+ facts as (
+ select (d.day >= v_day_from) as cur,
+ d.day,
+ d.prompt_id,
+ d.platform,
+ d.answer_count::bigint as answers,
+ d.mention_answers::bigint as mentions,
+ d.mention_occurrences as occurrences,
+ d.positive_answers::bigint as positive,
+ d.negative_answers::bigint as negative,
+ d.position_sum,
+ d.position_count::bigint as position_count,
+ d.last_answer_at
+ from public.mentions_prompt_daily d
+ join prompts_in pi on pi.id = d.prompt_id
+ where not v_raw
+ and d.brand_id = p_brand_id
+ and d.day between v_prev_from and v_day_to
+ and (p_platform is null or d.platform = p_platform)
+ and (p_region is null or d.region = p_region)
+ union all
+ select (pr.created_at >= v_from),
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id,
+ pr.platform,
+ 1,
+ (pr.mention_count > 0)::int,
+ coalesce(pr.mention_count, 0),
+ (pr.mention_count > 0 and pr.sentiment = 'positive')::int,
+ (pr.mention_count > 0 and pr.sentiment = 'negative')::int,
+ case when pr.mention_count > 0 then coalesce(pr.mention_position, 0) else 0 end,
+ (pr.mention_count > 0 and pr.mention_position is not null)::int,
+ pr.created_at
+ from public.prompt_results pr
+ join prompts_in pi on pi.id = pr.prompt_id
+ where v_raw
+ and pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from - v_span
+ and pr.created_at <= v_to
+ and (p_platform is null or pr.platform = p_platform)
+ and (p_region is null or pr.region = p_region)
+ ),
+ -- Prompts answered in both windows: every change is taken on them, as
+ -- Insights takes its changes (insights_same_prompt_compare_daily, 00164),
+ -- so adding or removing prompts doesn't read as a rise or a fall.
+ presence as (
+ select prompt_id,
+ bool_or(cur and answers > 0) as in_cur,
+ bool_or(not cur and answers > 0) as in_prev
+ from facts
+ group by prompt_id
+ ),
+ flagged as (
+ select f.*, (p.in_cur and p.in_prev) as shared
+ from facts f
+ join presence p using (prompt_id)
+ ),
+ same_totals as (
+ select cur,
+ sum(answers)::bigint as answers,
+ sum(mentions)::bigint as mentions,
+ sum(occurrences)::bigint as occurrences,
+ sum(positive)::bigint as positive,
+ sum(negative)::bigint as negative,
+ count(distinct prompt_id) as prompts,
+ count(distinct prompt_id) filter (where mentions > 0) as prompts_with_mentions
+ from flagged
+ where shared
+ group by cur
+ ),
+ totals as (
+ select cur,
+ sum(answers)::bigint as answers,
+ sum(mentions)::bigint as mentions,
+ sum(occurrences)::bigint as occurrences,
+ sum(positive)::bigint as positive,
+ sum(negative)::bigint as negative,
+ sum(position_sum)::bigint as position_sum,
+ sum(position_count)::bigint as position_count,
+ count(distinct prompt_id) as prompts,
+ count(distinct prompt_id) filter (where mentions > 0) as prompts_with_mentions,
+ max(last_answer_at) as last_answer_at
+ from facts
+ group by cur
+ ),
+ platforms as (
+ select platform,
+ coalesce(sum(answers) filter (where cur), 0)::bigint as answers,
+ coalesce(sum(mentions) filter (where cur), 0)::bigint as mentions,
+ coalesce(sum(occurrences) filter (where cur), 0)::bigint as occurrences,
+ coalesce(sum(positive) filter (where cur), 0)::bigint as positive,
+ coalesce(sum(negative) filter (where cur), 0)::bigint as negative,
+ coalesce(sum(answers) filter (where not cur), 0)::bigint as prev_answers,
+ coalesce(sum(mentions) filter (where not cur), 0)::bigint as prev_mentions,
+ coalesce(sum(positive) filter (where not cur), 0)::bigint as prev_positive,
+ coalesce(sum(negative) filter (where not cur), 0)::bigint as prev_negative,
+ -- The same on the shared prompts, for the platform's change.
+ coalesce(sum(answers) filter (where cur and shared), 0)::bigint as same_answers,
+ coalesce(sum(mentions) filter (where cur and shared), 0)::bigint as same_mentions,
+ coalesce(sum(positive) filter (where cur and shared), 0)::bigint as same_positive,
+ coalesce(sum(negative) filter (where cur and shared), 0)::bigint as same_negative,
+ coalesce(sum(answers) filter (where not cur and shared), 0)::bigint as same_prev_answers,
+ coalesce(sum(mentions) filter (where not cur and shared), 0)::bigint as same_prev_mentions,
+ coalesce(sum(positive) filter (where not cur and shared), 0)::bigint as same_prev_positive,
+ coalesce(sum(negative) filter (where not cur and shared), 0)::bigint as same_prev_negative
+ from flagged
+ group by platform
+ ),
+ daily as (
+ select day,
+ sum(answers)::bigint as answers,
+ sum(mentions)::bigint as mentions,
+ sum(occurrences)::bigint as occurrences,
+ sum(positive)::bigint as positive,
+ sum(negative)::bigint as negative
+ from facts
+ where cur
+ group by day
+ ),
+ comp_facts as (
+ select (c.day >= v_day_from) as cur,
+ c.competitor_id,
+ c.mention_answers::bigint as mentions,
+ c.co_mention_answers::bigint as co_mentions
+ from public.mentions_competitor_daily c
+ join prompts_in pi on pi.id = c.prompt_id
+ where not v_raw
+ and c.brand_id = p_brand_id
+ and c.day between v_prev_from and v_day_to
+ and (p_platform is null or c.platform = p_platform)
+ and (p_region is null or c.region = p_region)
+ union all
+ select (pr.created_at >= v_from),
+ cm.value->>'competitor_id',
+ 1,
+ (pr.mention_count > 0)::int
+ from public.prompt_results pr
+ join prompts_in pi on pi.id = pr.prompt_id
+ cross join lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where v_raw
+ and pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from - v_span
+ and pr.created_at <= v_to
+ and (p_platform is null or pr.platform = p_platform)
+ and (p_region is null or pr.region = p_region)
+ and cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0
+ ),
+ competitors as (
+ select co.id::text as competitor_id,
+ co.name,
+ coalesce(sum(f.mentions) filter (where f.cur), 0)::bigint as mentions,
+ coalesce(sum(f.co_mentions) filter (where f.cur), 0)::bigint as co_mentions,
+ coalesce(sum(f.mentions) filter (where not f.cur), 0)::bigint as prev_mentions
+ from public.competitors co
+ left join comp_facts f on f.competitor_id = co.id::text
+ where co.brand_id = p_brand_id
+ group by co.id, co.name
+ )
+ select jsonb_build_object(
+ 'window', jsonb_build_object(
+ 'from', v_from, 'to', v_to, 'days', v_days,
+ 'source', case when v_raw then 'answers' else 'days' end,
+ 'day_from', v_day_from, 'day_to', v_day_to),
+ 'current', (select to_jsonb(t) - 'cur' from totals t where t.cur),
+ 'previous', (select to_jsonb(t) - 'cur' from totals t where not t.cur),
+ 'same', jsonb_build_object(
+ 'prompts', (select count(*) from presence where in_cur and in_prev),
+ '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),
+ 'current', (select to_jsonb(t) - 'cur' from same_totals t where t.cur),
+ 'previous', (select to_jsonb(t) - 'cur' from same_totals t where not t.cur)),
+ -- In the order of the column the table shows: occurrences, then responses.
+ 'platforms', coalesce((select jsonb_agg(to_jsonb(p)
+ order by p.occurrences desc, p.mentions desc, p.platform)
+ from platforms p), '[]'::jsonb),
+ 'daily', coalesce((select jsonb_agg(to_jsonb(d) order by d.day) from daily d),
+ '[]'::jsonb),
+ 'competitors', coalesce((select jsonb_agg(to_jsonb(c) order by c.mentions desc, c.name)
+ from competitors c), '[]'::jsonb)
+ )
+ into v_result;
+
+ return v_result;
+end;
+$$;
+
+notify pgrst, 'reload schema';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00196_getting_started.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx
index aff1cf7fd..bffc71ec7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx
@@ -5,6 +5,7 @@ import { Layers, MessageCircle, Percent, Smile } from 'lucide-react';
import { numberFormat } from '@/lib/number-format';
import { wholeNet } from '@/lib/mentions-headline';
import {
+ changeBasis,
isLowSample,
LOW_SAMPLE_MENTIONS,
mentionRate,
@@ -41,15 +42,26 @@ export function OverviewKpis({ overview, brand }: { overview: MentionsOverview;
const t = useTranslations('mentions.overview.kpi');
const locale = useLocale();
const f = numberFormat(locale);
- const { current: cur, previous: prev } = overview;
+ const { current: cur } = overview;
+ // Every change is taken on the prompts both windows answered, as Insights
+ // takes its changes (changeBasis); the values are the whole window's.
+ const { current: base, previous: prev } = changeBasis(overview);
const trend = mentionTrend(overview);
const round = (n: number | null, digits = 0) =>
n === null ? null : Math.round(n * 10 ** digits) / 10 ** digits;
const rate = mentionRate(cur);
+ const baseRate = mentionRate(base);
const prevRate = mentionRate(prev);
const lowAnswers = cur.answers < LOW_SAMPLE_MENTIONS;
+ // A change also needs both shared windows to clear the floor, as the
+ // summary line's does (mentions-headline.ts), each over its own sample:
+ // the rate's is the responses, the net's the responses naming the brand.
+ const rateChangeLow =
+ lowAnswers || base.answers < LOW_SAMPLE_MENTIONS || prev.answers < LOW_SAMPLE_MENTIONS;
+ const netChangeLow = isLowSample(cur) || isLowSample(base) || isLowSample(prev);
const net = wholeNet(cur);
+ const baseNet = wholeNet(base);
const prevNet = wholeNet(prev);
const split = sentimentSplit(cur);
const promptShare = cur.prompts > 0 ? (cur.promptsWithMentions * 100) / cur.prompts : 0;
@@ -62,7 +74,7 @@ export function OverviewKpis({ overview, brand }: { overview: MentionsOverview;
icon={MessageCircle}
// Every time a response names the brand, as Insights counts mentions.
value={f.number(cur.occurrences)}
- delta={upIsGood(round(relativeChange(cur.occurrences, prev.occurrences)), {
+ delta={upIsGood(round(relativeChange(base.occurrences, prev.occurrences)), {
percent: true,
locale,
})}
@@ -75,9 +87,9 @@ export function OverviewKpis({ overview, brand }: { overview: MentionsOverview;
icon={Percent}
value={rate === null ? '—' : f.percent(rate, 1)}
delta={
- lowAnswers || rate === null || prevRate === null
+ rateChangeLow || rate === null || baseRate === null || prevRate === null
? null
- : upIsGood(round(rate - prevRate, 1), { locale })
+ : upIsGood(round(baseRate - prevRate, 1), { locale })
}
sub={
rate !== null && lowAnswers
@@ -91,7 +103,7 @@ export function OverviewKpis({ overview, brand }: { overview: MentionsOverview;
tooltip={t('promptsWithMentionsTip', { brand })}
icon={Layers}
value={f.number(cur.promptsWithMentions)}
- delta={upIsGood(round(relativeChange(cur.promptsWithMentions, prev.promptsWithMentions)), {
+ delta={upIsGood(round(relativeChange(base.promptsWithMentions, prev.promptsWithMentions)), {
percent: true,
locale,
})}
@@ -114,9 +126,9 @@ export function OverviewKpis({ overview, brand }: { overview: MentionsOverview;
icon={Smile}
value={net === null ? '—' : signedValue(net, locale)}
delta={
- isLowSample(cur) || net === null || prevNet === null
+ netChangeLow || net === null || baseNet === null || prevNet === null
? null
- : upIsGood(net - prevNet, { locale })
+ : upIsGood(baseNet - prevNet, { locale })
}
sub={
split === null ? null : isLowSample(cur) ? (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx
index b539270a5..b2af61064 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx
@@ -177,6 +177,72 @@ describe('OverviewKpis', () => {
expect(text).toContain('n=100');
});
+ it('takes each change on the prompts both windows answered, as Insights does (00195)', () => {
+ render(
+ <OverviewKpis
+ overview={{
+ ...overview,
+ // Over all prompts, 260 vs 200; on the 12 shared ones, 240 vs 160.
+ same: {
+ prompts: 12,
+ newPrompts: 3,
+ droppedPrompts: 1,
+ current: totals({
+ answers: 360,
+ mentions: 90,
+ occurrences: 240,
+ positive: 45,
+ negative: 9,
+ promptsWithMentions: 12,
+ }),
+ previous: totals({
+ answers: 360,
+ mentions: 80,
+ occurrences: 160,
+ positive: 40,
+ negative: 8,
+ promptsWithMentions: 12,
+ }),
+ },
+ }}
+ brand="Ansvisor"
+ />,
+ );
+ const text = container.textContent;
+ // The values stay the whole window's; the changes are the shared prompts'.
+ expect(text).toContain('260+50%');
+ // Mention rate 90/360 vs 80/360: +2.8 points; prompts with mentions 12 vs 12.
+ expect(text).toContain('25.0%+2.8');
+ expect(text).toContain('15±0');
+ // Net +34 shown; its change is (50 − 10) − (50 − 10) = 0.
+ expect(text).toContain('+34±0');
+ });
+
+ // gkhngyk on #1230: the summary line also needs both shared windows to pass.
+ it('shows no rate or net change when a shared window is a low sample', () => {
+ render(
+ <OverviewKpis
+ overview={{
+ ...overview,
+ // The whole windows are large; the prompts both answered are few.
+ same: {
+ prompts: 2,
+ newPrompts: 13,
+ droppedPrompts: 10,
+ current: totals({ answers: 18, mentions: 9, positive: 6, negative: 1 }),
+ previous: totals({ answers: 30, mentions: 15, positive: 5, negative: 5 }),
+ },
+ }}
+ brand="Ansvisor"
+ />,
+ );
+ const text = container.textContent ?? '';
+ expect(text).toContain('25.0%');
+ expect(text).not.toMatch(/25\.0%[+−±]/);
+ expect(text).toContain('+34');
+ expect(text).not.toMatch(/\+34[+−±]/);
+ });
+
it('marks net sentiment over fewer than 20 mentions as a low sample, without a change', () => {
render(
<OverviewKpis
diff --git a/web/src/lib/mentions-headline.test.ts b/web/src/lib/mentions-headline.test.ts
index f2a212a73..3e338b8aa 100644
--- a/web/src/lib/mentions-headline.test.ts
+++ b/web/src/lib/mentions-headline.test.ts
@@ -112,6 +112,25 @@ describe('mentionsHeadline', () => {
});
});
+ it('takes the net change on the prompts both windows answered (00195)', () => {
+ const h = mentionsHeadline(
+ overview({
+ current: totals({ answers: 100, mentions: 100, positive: 50, negative: 10 }),
+ previous: totals({ answers: 100, mentions: 100, positive: 20, negative: 10 }),
+ same: {
+ prompts: 8,
+ newPrompts: 2,
+ droppedPrompts: 0,
+ current: totals({ answers: 60, mentions: 60, positive: 30, negative: 6 }),
+ previous: totals({ answers: 60, mentions: 60, positive: 24, negative: 6 }),
+ },
+ }),
+ );
+ // Net +40 now; on the shared prompts +40 vs +30, not +40 vs +10 on all.
+ expect(h.net).toBe(40);
+ expect(h.netChange).toBe(10);
+ });
+
it('gives no change from or to a low sample', () => {
const h = mentionsHeadline(
overview({
@@ -132,6 +151,18 @@ describe('mentionsHeadline', () => {
});
describe('platformNetChange', () => {
+ it('takes the change on the prompts both windows answered (00195)', () => {
+ const row = {
+ ...platform('claude', [40, 20, 0], [40, 10, 0]),
+ same: {
+ current: { answers: 30, mentions: 30, positive: 15, negative: 0 },
+ previous: { answers: 30, mentions: 30, positive: 12, negative: 0 },
+ },
+ };
+ // On all prompts +50 vs +25; on the shared ones +50 vs +40.
+ expect(platformNetChange(row)).toBe(10);
+ });
+
it('needs 20 mentions in both windows', () => {
expect(platformNetChange(platform('claude', [20, 10, 0], [20, 5, 0]))).toBe(25);
expect(platformNetChange(platform('claude', [19, 10, 0], [20, 5, 0]))).toBeNull();
diff --git a/web/src/lib/mentions-headline.ts b/web/src/lib/mentions-headline.ts
index 2a6b205e5..4d0e55e28 100644
--- a/web/src/lib/mentions-headline.ts
+++ b/web/src/lib/mentions-headline.ts
@@ -1,6 +1,7 @@
import { PLATFORM_LABELS } from '@/config/platform-labels';
import { POSITION_PLATFORMS } from '@/lib/prompt-positions';
import {
+ changeBasis,
isLowSample,
LOW_SAMPLE_MENTIONS,
netSentiment,
@@ -44,12 +45,20 @@ export interface MentionsHeadline {
export function mentionsHeadline(o: MentionsOverview): MentionsHeadline {
const net = wholeNet(o.current);
- const previous = wholeNet(o.previous);
const lowSample = isLowSample(o.current);
- // Like the KPI cards: no change from or to a low sample.
+ // Like the KPI cards: taken on the prompts both windows answered, and no
+ // change from or to a low sample.
+ const basis = changeBasis(o);
+ const now = wholeNet(basis.current);
+ const previous = wholeNet(basis.previous);
const netChange =
- net !== null && previous !== null && !lowSample && !isLowSample(o.previous)
- ? net - previous
+ net !== null &&
+ now !== null &&
+ previous !== null &&
+ !lowSample &&
+ !isLowSample(basis.current) &&
+ !isLowSample(basis.previous)
+ ? now - previous
: null;
let mover: MentionsHeadline['mover'] = null;
@@ -77,15 +86,18 @@ export function mentionsHeadline(o: MentionsOverview): MentionsHeadline {
}
/**
- * A platform's net sentiment change against the window before, only when both
- * windows have enough mentions to say so (fewer than 20 is a low sample).
+ * A platform's net sentiment change against the window before, on the prompts
+ * both windows answered (00195; all of them before it), only when both have
+ * enough mentions to say so (fewer than 20 is a low sample).
*/
export function platformNetChange(row: MentionPlatformRow): number | null {
- if (row.mentions < LOW_SAMPLE_MENTIONS || row.previous.mentions < LOW_SAMPLE_MENTIONS) {
+ const current = row.same?.current ?? row;
+ const previous = row.same?.previous ?? row.previous;
+ if (current.mentions < LOW_SAMPLE_MENTIONS || previous.mentions < LOW_SAMPLE_MENTIONS) {
return null;
}
- const now = wholeNet(row);
- const before = wholeNet(row.previous);
+ const now = wholeNet(current);
+ const before = wholeNet(previous);
return now !== null && before !== null ? now - before : null;
}
diff --git a/web/src/lib/mentions-overview.test.ts b/web/src/lib/mentions-overview.test.ts
index 5fed83ed9..8e0e0e023 100644
--- a/web/src/lib/mentions-overview.test.ts
+++ b/web/src/lib/mentions-overview.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
averagePosition,
+ changeBasis,
isLowSample,
mentionRate,
mentionTrend,
@@ -44,8 +45,24 @@ const raw = {
prev_mentions: 7,
prev_positive: 2,
prev_negative: 2,
+ // On the prompts both windows answered (00195).
+ same_answers: 5,
+ same_mentions: 5,
+ same_positive: 2,
+ same_negative: 1,
+ same_prev_answers: 6,
+ same_prev_mentions: 6,
+ same_prev_positive: 1,
+ same_prev_negative: 2,
},
],
+ same: {
+ prompts: 4,
+ new_prompts: 1,
+ dropped_prompts: 2,
+ current: { answers: 90, mentions: 90, occurrences: 250, positive: 40, negative: 20 },
+ previous: { answers: 80, mentions: 80, occurrences: 200, positive: 30, negative: 30 },
+ },
daily: [{ day: '2026-10-16', answers: 4, mentions: 4, occurrences: 9, positive: 2, negative: 1 }],
competitors: [
{
@@ -85,6 +102,17 @@ describe('parseMentionsOverview', () => {
positive: 2,
negative: 2,
previous: { answers: 7, mentions: 7, positive: 2, negative: 2 },
+ same: {
+ current: { answers: 5, mentions: 5, positive: 2, negative: 1 },
+ previous: { answers: 6, mentions: 6, positive: 1, negative: 2 },
+ },
+ });
+ expect(o.same).toMatchObject({
+ prompts: 4,
+ newPrompts: 1,
+ droppedPrompts: 2,
+ current: { occurrences: 250, positive: 40 },
+ previous: { occurrences: 200, negative: 30 },
});
expect(o.daily).toEqual([
{ day: '2026-10-16', answers: 4, mentions: 4, occurrences: 9, positive: 2, negative: 1 },
@@ -175,3 +203,29 @@ describe('mentionTrend', () => {
]);
});
});
+
+describe('changeBasis', () => {
+ it('takes the changes on the prompts both windows answered, or on all before 00195', () => {
+ const all = { answers: 10, mentions: 5, occurrences: 9 } as never;
+ const prevAll = { answers: 12, mentions: 8, occurrences: 20 } as never;
+ const shared = { answers: 6, mentions: 4, occurrences: 8 } as never;
+ const prevShared = { answers: 6, mentions: 3, occurrences: 5 } as never;
+ expect(
+ changeBasis({
+ current: all,
+ previous: prevAll,
+ same: {
+ prompts: 3,
+ newPrompts: 1,
+ droppedPrompts: 2,
+ current: shared,
+ previous: prevShared,
+ },
+ }),
+ ).toEqual({ current: shared, previous: prevShared });
+ expect(changeBasis({ current: all, previous: prevAll, same: null })).toEqual({
+ current: all,
+ previous: prevAll,
+ });
+ });
+});
diff --git a/web/src/lib/mentions-overview.ts b/web/src/lib/mentions-overview.ts
index ca4554222..70bf6694a 100644
--- a/web/src/lib/mentions-overview.ts
+++ b/web/src/lib/mentions-overview.ts
@@ -28,6 +28,8 @@ export interface MentionTotals {
lastAnswerAt: string | null;
}
+type PlatformCounts = Pick<MentionTotals, 'answers' | 'mentions' | 'positive' | 'negative'>;
+
export interface MentionPlatformRow {
platform: string;
answers: number;
@@ -36,7 +38,19 @@ export interface MentionPlatformRow {
occurrences: number;
positive: number;
negative: number;
- previous: Pick<MentionTotals, 'answers' | 'mentions' | 'positive' | 'negative'>;
+ previous: PlatformCounts;
+ /** The platform on the prompts both windows answered, for its change (00195; absent before it). */
+ same?: { current: PlatformCounts; previous: PlatformCounts } | null;
+}
+
+/** The prompts both windows answered, and each window's totals on them (00195). */
+export interface MentionComparison {
+ prompts: number;
+ /** Answered now but not before, and before but not now: left out of every change. */
+ newPrompts: number;
+ droppedPrompts: number;
+ current: MentionTotals;
+ previous: MentionTotals;
}
export interface MentionDay {
@@ -73,6 +87,8 @@ export interface MentionsOverview {
};
current: MentionTotals;
previous: MentionTotals;
+ /** What every change is taken on (00195; absent before it). */
+ same?: MentionComparison | null;
platforms: MentionPlatformRow[];
daily: MentionDay[];
competitors: MentionCompetitorRow[];
@@ -111,6 +127,27 @@ function totals(r: Raw | null | undefined): MentionTotals {
};
}
+function platformCounts(r: Raw, prefix: string): PlatformCounts {
+ return {
+ answers: num(r, `${prefix}answers`),
+ mentions: num(r, `${prefix}mentions`),
+ positive: num(r, `${prefix}positive`),
+ negative: num(r, `${prefix}negative`),
+ };
+}
+
+function comparison(raw: unknown): MentionComparison | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const s = raw as Raw;
+ return {
+ prompts: num(s, 'prompts'),
+ newPrompts: num(s, 'new_prompts'),
+ droppedPrompts: num(s, 'dropped_prompts'),
+ current: totals(s.current as Raw | null),
+ previous: totals(s.previous as Raw | null),
+ };
+}
+
/**
* The function's jsonb as the page's shape; null when there is nothing to
* read (the caller isn't in the brand's organization).
@@ -130,6 +167,7 @@ export function parseMentionsOverview(raw: unknown): MentionsOverview | null {
},
current: totals(r.current as Raw | null),
previous: totals(r.previous as Raw | null),
+ same: comparison(r.same),
platforms: rows(r.platforms).map((p) => ({
platform: String(p.platform ?? ''),
answers: num(p, 'answers'),
@@ -143,6 +181,10 @@ export function parseMentionsOverview(raw: unknown): MentionsOverview | null {
positive: num(p, 'prev_positive'),
negative: num(p, 'prev_negative'),
},
+ same:
+ 'same_answers' in p
+ ? { current: platformCounts(p, 'same_'), previous: platformCounts(p, 'same_prev_') }
+ : null,
})),
daily: rows(r.daily).map((d) => ({
day: String(d.day ?? ''),
@@ -207,6 +249,20 @@ export function averagePosition(t: Pick<MentionTotals, 'positionSum' | 'position
}
/** A count's change against the window before, in percent; null when there was nothing before. */
+/**
+ * The two windows every change is taken on: the prompts both answered (00195),
+ * as Insights takes its changes, so adding or removing prompts doesn't read as
+ * a rise or a fall; before 00195, all of each window's.
+ */
+export function changeBasis(o: Pick<MentionsOverview, 'current' | 'previous' | 'same'>): {
+ current: MentionTotals;
+ previous: MentionTotals;
+} {
+ return o.same
+ ? { current: o.same.current, previous: o.same.previous }
+ : { current: o.current, previous: o.previous };
+}
+
export function relativeChange(current: number, previous: number): number | null {
return previous > 0 ? ((current - previous) * 100) / previous : null;
}