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): count mentions and net sentiment the same way on Insights and Mentions (#1226)

Cihan4fb5151d4b0c
diff --git a/server/src/lib/pulse/metrics.js b/server/src/lib/pulse/metrics.js
index 670a14814..def721f3e 100644
--- a/server/src/lib/pulse/metrics.js
+++ b/server/src/lib/pulse/metrics.js
@@ -174,14 +174,23 @@ async function visibilityRate(brandId, from, to, days = null) {
return { visible, total, rate: score };
}
+/**
+ * Positive answers over the answers that name the brand (00191's
+ * `mention_results`), the base Insights and Action Center use. Before 00191
+ * the aggregates carry only answers that name or cite it, so fall back.
+ */
+export function positiveSentimentPct(agg) {
+ const named = agg?.mention_results ?? agg?.mentioning_results ?? 0;
+ return named > 0 ? Math.round(((agg?.positive_count ?? 0) / named) * 100) : 0;
+}
+
async function insightsWindow(brandId, from, to, days = null) {
const agg = await rpc(daily('insights_aggregates', days), windowParams(brandId, from, to, days));
- const mentioning = agg?.mentioning_results ?? 0;
return {
totalResults: agg?.total_results ?? 0,
mentions: agg?.total_mentions ?? 0,
citations: agg?.total_citations ?? 0,
- sentimentPct: mentioning > 0 ? Math.round(((agg?.positive_count ?? 0) / mentioning) * 100) : 0,
+ sentimentPct: positiveSentimentPct(agg),
};
}
diff --git a/server/src/lib/pulse/metrics.test.js b/server/src/lib/pulse/metrics.test.js
index 4aea362c3..8f6b84e44 100644
--- a/server/src/lib/pulse/metrics.test.js
+++ b/server/src/lib/pulse/metrics.test.js
@@ -4,7 +4,14 @@ import { describe, expect, it, vi } from 'vitest';
// SUPABASE_* env is absent (as in CI) — stub it before the import chain.
vi.mock('../../config/supabase.js', () => ({ default: {} }));
-import { daily, isTransientDbError, series, trailingDayWindows, windowParams } from './metrics.js';
+import {
+ daily,
+ isTransientDbError,
+ positiveSentimentPct,
+ series,
+ trailingDayWindows,
+ windowParams,
+} from './metrics.js';
/**
* Pulse metric execution shape (#687).
@@ -144,3 +151,27 @@ describe('rollup routing', () => {
});
});
});
+
+/**
+ * The e-mail's positive sentiment uses the base Insights and Action Center
+ * use (00191, gkhngyk on #1226): answers that name the brand. Cited-only
+ * answers are always neutral, so counting them pulled the share down.
+ */
+describe('positiveSentimentPct', () => {
+ it('divides by the answers that name the brand', () => {
+ expect(
+ positiveSentimentPct({ positive_count: 3, mentioning_results: 6, mention_results: 4 }),
+ ).toBe(75);
+ });
+
+ it('falls back to answers that name or cite it before 00191', () => {
+ expect(positiveSentimentPct({ positive_count: 3, mentioning_results: 6 })).toBe(50);
+ });
+
+ it('reads 0 without named answers or a row', () => {
+ expect(
+ positiveSentimentPct({ positive_count: 0, mentioning_results: 2, mention_results: 0 }),
+ ).toBe(0);
+ expect(positiveSentimentPct(null)).toBe(0);
+ });
+});
diff --git a/supabase/migrations/00191_same_mentions_kpis.sql b/supabase/migrations/00191_same_mentions_kpis.sql
new file mode 100644
index 000000000..1e8afb967
--- /dev/null
+++ b/supabase/migrations/00191_same_mentions_kpis.sql
@@ -0,0 +1,495 @@
+-- ============================================================================
+-- 00191: Insights and Mentions count mentions and net sentiment the same way
+-- ============================================================================
+-- The two pages showed different "Mentions" and "Net sentiment" for the same
+-- days. The product decision (2026-10-20):
+--
+-- * Mentions are every time an answer names the brand (an answer naming it
+-- three times counts three), as Insights counted them. The Mentions
+-- page's Total mentions card, its trend and its platform table now read
+-- occurrences; its RPC gains them per day and per platform
+-- (`daily[].occurrences`, `platforms[].occurrences`).
+-- * Net sentiment is (positive − negative) over the answers that name the
+-- brand, as the Mentions page computed it. Insights divided by answers
+-- that name OR cite it (#508); cited-only answers are always neutral, so
+-- they pulled its net toward zero. The Insights aggregates (the daily
+-- rollup read and the raw window read) gain the answers that name the
+-- brand (`mention_results`) and the sparkline series gains them per day
+-- (`days[].mention_answers`).
+--
+-- Each function is the latest definition (00164, 00131, 00157) with only
+-- those fields added, and Mentions' platforms ordered by occurrences, the
+-- column they show; existing fields are unchanged, so a web build from
+-- before this migration keeps working.
+
+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,
+ p_topic_id uuid default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with topic_prompts as (
+ select array(select p.id from public.prompts p where p.topic_id = p_topic_id) as ids
+ ),
+ filtered as (
+ select d.model_used, d.answer_count, d.sum_visibility, d.total_mentions,
+ d.total_citations, d.positive_count, d.mentioning_answers, d.max_created_at,
+ d.citation_answers, d.negative_count, d.sum_position, d.position_count,
+ d.mention_answers
+ from public.insights_brand_daily d
+ where p_topic_id is null
+ and 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)
+ union all
+ select d.model_used, d.answer_count, d.sum_visibility, d.total_mentions,
+ d.total_citations, d.positive_count, d.mentioning_answers, d.max_created_at,
+ d.citation_answers, d.negative_count, d.sum_position, d.position_count,
+ d.mention_answers
+ from public.insights_prompt_daily d, topic_prompts tp
+ where p_topic_id is not null
+ and d.brand_id = p_brand_id
+ and d.prompt_id = any (tp.ids)
+ 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,
+ -- Answers naming the brand: Net sentiment's base, as on the Mentions page.
+ coalesce(sum(mention_answers), 0) as mention_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,
+ 'mention_results', t.mention_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;
+$$;
+
+-- The raw window read (00131's definition, still security invoker) gains the
+-- same base: reports (no `days`), the 24h window and the Daily Pulse read it,
+-- and without it they'd fall back to answers that name or cite the brand.
+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,
+ COUNT(*) FILTER (WHERE mention_count > 0) AS mention_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,
+ 'mention_results', t.mention_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_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.mention_answers) as mention_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,
+ 'mention_answers', d.mention_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)
+ );
+$$;
+
+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)
+ ),
+ 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
+ from facts
+ 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),
+ -- 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 b17992bca..2afce6e4f 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -27148,6 +27148,505 @@ comment on function public.ai_bot_report(uuid, date, date, integer) is
notify pgrst, 'reload schema';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00191_same_mentions_kpis.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ============================================================================
+-- 00191: Insights and Mentions count mentions and net sentiment the same way
+-- ============================================================================
+-- The two pages showed different "Mentions" and "Net sentiment" for the same
+-- days. The product decision (2026-10-20):
+--
+-- * Mentions are every time an answer names the brand (an answer naming it
+-- three times counts three), as Insights counted them. The Mentions
+-- page's Total mentions card, its trend and its platform table now read
+-- occurrences; its RPC gains them per day and per platform
+-- (`daily[].occurrences`, `platforms[].occurrences`).
+-- * Net sentiment is (positive − negative) over the answers that name the
+-- brand, as the Mentions page computed it. Insights divided by answers
+-- that name OR cite it (#508); cited-only answers are always neutral, so
+-- they pulled its net toward zero. The Insights aggregates (the daily
+-- rollup read and the raw window read) gain the answers that name the
+-- brand (`mention_results`) and the sparkline series gains them per day
+-- (`days[].mention_answers`).
+--
+-- Each function is the latest definition (00164, 00131, 00157) with only
+-- those fields added, and Mentions' platforms ordered by occurrences, the
+-- column they show; existing fields are unchanged, so a web build from
+-- before this migration keeps working.
+
+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,
+ p_topic_id uuid default null
+) returns jsonb
+language sql
+stable
+set search_path to 'public'
+as $$
+ with topic_prompts as (
+ select array(select p.id from public.prompts p where p.topic_id = p_topic_id) as ids
+ ),
+ filtered as (
+ select d.model_used, d.answer_count, d.sum_visibility, d.total_mentions,
+ d.total_citations, d.positive_count, d.mentioning_answers, d.max_created_at,
+ d.citation_answers, d.negative_count, d.sum_position, d.position_count,
+ d.mention_answers
+ from public.insights_brand_daily d
+ where p_topic_id is null
+ and 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)
+ union all
+ select d.model_used, d.answer_count, d.sum_visibility, d.total_mentions,
+ d.total_citations, d.positive_count, d.mentioning_answers, d.max_created_at,
+ d.citation_answers, d.negative_count, d.sum_position, d.position_count,
+ d.mention_answers
+ from public.insights_prompt_daily d, topic_prompts tp
+ where p_topic_id is not null
+ and d.brand_id = p_brand_id
+ and d.prompt_id = any (tp.ids)
+ 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,
+ -- Answers naming the brand: Net sentiment's base, as on the Mentions page.
+ coalesce(sum(mention_answers), 0) as mention_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,
+ 'mention_results', t.mention_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;
+$$;
+
+-- The raw window read (00131's definition, still security invoker) gains the
+-- same base: reports (no `days`), the 24h window and the Daily Pulse read it,
+-- and without it they'd fall back to answers that name or cite the brand.
+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,
+ COUNT(*) FILTER (WHERE mention_count > 0) AS mention_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,
+ 'mention_results', t.mention_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_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.mention_answers) as mention_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,
+ 'mention_answers', d.mention_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)
+ );
+$$;
+
+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)
+ ),
+ 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
+ from facts
+ 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),
+ -- 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/00192_rollup_integrity.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index 71751d159..2319640e3 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -2849,6 +2849,7 @@
"openPrompts": "Tracked prompts: open Prompts",
"openCitations": "Citations: open Citations",
"openMentions": "Mentions: open Mentions",
+ "openSentiment": "Net sentiment: open Mentions",
"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",
@@ -2867,7 +2868,7 @@
"citationsTip": "Times answers cited your pages. The change is against the previous period.",
"vsPrevious": "vs previous period",
"netSentiment": "Net sentiment",
- "netSentimentTip": "Positive minus negative share of the answers that name or cite your brand.",
+ "netSentimentTip": "Positive minus negative share of the answers that name your brand, as on the Mentions page.",
"sentimentSplit": "{positive} pos · {negative} neg",
"sampleTip": {
"all": "{count, plural, one {Based on # answer} other {Based on # answers}} in this period.",
@@ -5218,7 +5219,7 @@
"label": "Summary",
"net": "Net sentiment is <b>{net}</b>.",
"netChange": "Net sentiment is <b>{net}</b> (<tone>{change}</tone> vs the previous {period}).",
- "netLowSample": "Net sentiment is <b>{net}</b> (low sample: {count, plural, one {# mention} other {# mentions}}).",
+ "netLowSample": "Net sentiment is <b>{net}</b> (low sample: {count, plural, one {# response naming you} other {# responses naming you}}).",
"noMentions": "AI didn't name {brand} in the tracked responses of this period.",
"moverDown": "Most of the drop is on <b>{platform} ({change})</b>.",
"moverUp": "Most of the rise is on <b>{platform} ({change})</b>.",
@@ -5230,8 +5231,8 @@
},
"kpi": {
"totalMentions": "Total mentions",
- "totalMentionsTip": "Responses that name {brand} at least once. A response naming you twice counts once.",
- "totalMentionsSub": "responses naming {brand}",
+ "totalMentionsTip": "Every time the responses name {brand}: a response naming you three times counts three, as on the Insights page.",
+ "totalMentionsSub": "times responses named {brand}",
"mentionRate": "Mention rate",
"mentionRateTip": "The share of tracked responses that name {brand}.",
"mentionRateSub": "of {count} tracked responses",
@@ -5278,7 +5279,7 @@
"description": "How often AI names each brand, and how often in the same responses as you.",
"tableLabel": "Mentions of your brand and competitors",
"brand": "Brand",
- "mentions": "Mentions",
+ "mentions": "Responses",
"rate": "Rate",
"alsoNamesYou": "Also names you",
"alsoNamesYouTip": "Of the responses naming this competitor, how many name {brand} too, and what share of its mentions that is.",
@@ -5303,7 +5304,7 @@
"sortOldest": "Oldest",
"sortCoMentions": "Most co-mentions",
"sortNegative": "Most negative",
- "summary": "{mentions, plural, one {# mention} other {# mentions}} · {prompts, plural, one {# prompt} other {# prompts}}",
+ "summary": "{responses, plural, one {# response} other {# responses}} · {prompts, plural, one {# prompt} other {# prompts}}",
"columns": {
"prompt": "Prompt",
"platform": "Platform",
@@ -5401,7 +5402,7 @@
"copyBlocked": "Your browser didn't allow copying here. Allow clipboard access for this site and try again.",
"exportFailed": "Couldn't export the mentions. Try again in a moment.",
"nothing": "No mentions to export for these filters.",
- "capped": "The file holds {shown} of {total} mentions. Narrow the filters to export the rest.",
+ "capped": "The file holds {shown} of {total} responses. Narrow the filters to export the rest.",
"pickDates": "Choose a start or end date first.",
"reports": "Reports",
"exportSelected": "Export",
@@ -5410,11 +5411,12 @@
"periodDays": "{from} – {to} ({days, plural, one {# day} other {# days}}, UTC)",
"periodMoments": "{from} – {to} UTC",
"responses": "Tracked responses (n)",
- "mentions": "Mentions (n)",
+ "totalMentions": "Total mentions (n)",
+ "namedResponses": "Responses naming the brand (n)",
"prompts": "Prompts with mentions (n)",
- "inFile": "Mentions in this file (n)",
+ "inFile": "Responses in this file (n)",
"note": "Note",
- "capped": "Only the first {shown} of {total} mentions, in the table's order. Narrow the filters to export the rest.",
+ "capped": "Only the first {shown} of {total} responses, in the table's order. Narrow the filters to export the rest.",
"exported": "Exported (UTC)"
},
"summary": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx
index a707f5d8a..575efa9c7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_formula-dialog.tsx
@@ -120,7 +120,8 @@ export function FormulaDialog() {
of the score.
</p>
<Formula>
- Net sentiment = positive answers % − negative answers % (of answers mentioning you)
+ Net sentiment = positive answers % − negative answers % (of answers naming you, as
+ on the Mentions page)
</Formula>
</Section>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.test.tsx
index f85bebeef..2e9615158 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.test.tsx
@@ -38,7 +38,11 @@ let root: Root;
const onBreakdown = vi.fn();
const onNavigate = vi.fn();
-function render(trackedPrompts: TrackedPromptsKpi, over: Partial<InsightsSummary> = {}) {
+function render(
+ trackedPrompts: TrackedPromptsKpi,
+ over: Partial<InsightsSummary> = {},
+ props: { mentionsHref?: string } = {},
+) {
act(() => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
@@ -53,6 +57,7 @@ function render(trackedPrompts: TrackedPromptsKpi, over: Partial<InsightsSummary
series={null}
onBreakdown={onBreakdown}
onNavigate={onNavigate}
+ {...props}
/>
</NextIntlClientProvider>,
);
@@ -118,6 +123,17 @@ describe('the Mentions and Citations cards', () => {
expect(onBreakdown).not.toHaveBeenCalled();
});
+ it('opens Mentions on the same range from Mentions and Net sentiment', () => {
+ render(plan(47, 50), {}, { mentionsHref: '/dashboard/mentions?range=7d' });
+ const card = (label: string) =>
+ container.querySelector(`[role=button][aria-label="${label}"]`) as HTMLElement;
+ act(() => card('Mentions: open Mentions').click());
+ expect(onNavigate).toHaveBeenLastCalledWith('/dashboard/mentions?range=7d');
+ onNavigate.mockClear();
+ act(() => card('Net sentiment: open Mentions').click());
+ expect(onNavigate).toHaveBeenLastCalledWith('/dashboard/mentions?range=7d');
+ });
+
it('say nothing of a change they do not have', () => {
render(plan(47, 50), { mentionsChange: null, citationsChange: null });
expect(container.textContent).not.toContain('vs previous period');
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
index 30e63b4cf..fda6b478b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
@@ -279,6 +279,8 @@ interface KpiRowsProps {
/** Visibility's breakdown; Mentions opens its own page. */
onBreakdown: (metric: 'visibility') => void;
onNavigate: (path: string) => void;
+ /** The Mentions page on the same range and filters, for the Mentions and Net sentiment cards. */
+ mentionsHref?: string;
}
/**
@@ -297,6 +299,7 @@ export function KpiRows({
series,
onBreakdown,
onNavigate,
+ mentionsHref = '/dashboard/mentions',
}: KpiRowsProps) {
const t = useTranslations('insights.kpi');
const locale = useLocale();
@@ -409,7 +412,7 @@ export function KpiRows({
delta={upIsGood(summary.mentionsChange, { percent: true, locale })}
sub={vsPrevious(summary.mentionsChange)}
spark={daily('mentions')}
- onClick={() => onNavigate('/dashboard/mentions')}
+ onClick={() => onNavigate(mentionsHref)}
clickLabel={t('openMentions')}
/>
<MetricCard
@@ -440,6 +443,8 @@ export function KpiRows({
summary.netSentiment !== null,
)}
spark={daily('netSentiment')}
+ onClick={() => onNavigate(mentionsHref)}
+ clickLabel={t('openSentiment')}
/>
</div>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index dc175250d..c526bae6f 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -31,6 +31,7 @@ import {
import { getTopics } from '@/lib/actions/topic';
import { MODEL_PROVIDER_LABELS, PLATFORM_LABELS } from '@/config/platform-labels';
import { formatRegionDisplay } from '@/lib/region';
+import { mentionsHref } from '@/lib/mentions-filters';
import type { Topic } from '@/types';
import {
ALL_DATE_PRESETS,
@@ -1251,6 +1252,13 @@ export default function InsightsPage() {
setBreakdownMetric(metric);
}}
onNavigate={(path) => router.push(path)}
+ mentionsHref={mentionsHref({
+ range: filters.datePreset,
+ from: filters.dateFrom,
+ to: filters.dateTo,
+ region: filters.region,
+ topic: filters.topic,
+ })}
/>
{/* Competitor Comparison */}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx
index 94bebc021..368ac8ae3 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_header-actions.test.tsx
@@ -67,12 +67,20 @@ const overview: MentionsOverview = {
current: totals({
answers: 400,
mentions: 100,
+ occurrences: 130,
positive: 48,
negative: 14,
prompts: 20,
promptsWithMentions: 15,
}),
- previous: totals({ answers: 400, mentions: 80, positive: 40, negative: 8, prompts: 20 }),
+ previous: totals({
+ answers: 400,
+ mentions: 80,
+ occurrences: 100,
+ positive: 40,
+ negative: 8,
+ prompts: 20,
+ }),
platforms: [],
daily: [],
competitors: [
@@ -198,12 +206,13 @@ describe('MentionsHeaderActions', () => {
'Mentions & Sentiment · Acme Coffee',
'All platforms · All countries · All topics',
'Net sentiment is +34 (↓ 6 vs the previous 30 days). AI usually names Acme Coffee next to Crema Club.',
- 'Total mentions: 100 (+25%)',
+ // Total mentions counts every time a response names the brand, as the card does.
+ 'Total mentions: 130 (+30%)',
'Mention rate: 25.0% of 400 tracked responses',
'Prompts with mentions: 15 of 20 tracked prompts',
'Net sentiment: +34 · 48% positive, 38% neutral, 14% negative (n=100)',
'Built from aggregates with a fixed template, no LLM call · Sep 18 – Oct 17 · ' +
- '400 tracked responses · 100 mentions',
+ '400 tracked responses · 130 mentions',
].join('\n'),
);
expect(toast.success).toHaveBeenCalledWith('Summary copied');
@@ -215,6 +224,7 @@ describe('MentionsHeaderActions', () => {
current: totals({
answers: 12,
mentions: 3,
+ occurrences: 4,
positive: 2,
prompts: 2,
promptsWithMentions: 1,
@@ -233,7 +243,7 @@ describe('MentionsHeaderActions', () => {
const lines = (writeText.mock.calls[0][0] as string).split('\n');
expect(lines[1]).toBe('Gemini · Germany · Beans · Search: “espresso”');
expect(lines.slice(3, 7)).toEqual([
- 'Total mentions: 3',
+ 'Total mentions: 4',
'Mention rate: 25.0% · Low sample · 12 responses',
'Prompts with mentions: 1 of 2 tracked prompts',
'Net sentiment: +67 · Low sample · 3 responses',
@@ -269,21 +279,22 @@ describe('MentionsHeaderActions', () => {
);
expect(saved[0].name).toMatch(/^ansvisor_acme-coffee_mentions_\d{4}-\d{2}-\d{2}\.csv$/);
const lines = (await savedText()).split('\n');
- expect(lines.slice(0, 10)).toEqual([
+ expect(lines.slice(0, 11)).toEqual([
'Mentions & Sentiment,Acme Coffee',
'Period,"2026-09-18 – 2026-10-17 (30 days, UTC)"',
'Platform,All platforms',
'Country,All countries',
'Topic,All topics',
'Tracked responses (n),400',
- 'Mentions (n),2',
+ 'Total mentions (n),130',
+ 'Responses naming the brand (n),2',
'Prompts with mentions (n),1',
- 'Mentions in this file (n),2',
+ 'Responses in this file (n),2',
expect.stringMatching(/^Exported \(UTC\),\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/),
]);
- expect(lines[10]).toBe('');
- expect(lines[11]).toMatch(/^date_utc,prompt,topic,platform/);
- expect(lines).toHaveLength(14);
+ expect(lines[11]).toBe('');
+ expect(lines[12]).toMatch(/^date_utc,prompt,topic,platform/);
+ expect(lines).toHaveLength(15);
});
it("takes the table's filters from the Mentions tab, and notes a file cut at the cap", async () => {
@@ -304,10 +315,10 @@ describe('MentionsHeaderActions', () => {
const text = await savedText();
expect(text).toContain('Sentiment,Negative\nCo-mentioned,Crema Club\n');
expect(text).toContain(
- 'Note,"Only the first 2 of 12,345 mentions, in the table\'s order. Narrow the filters to export the rest."',
+ 'Note,"Only the first 2 of 12,345 responses, in the table\'s order. Narrow the filters to export the rest."',
);
expect(toast.warning).toHaveBeenCalledWith(
- 'The file holds 2 of 12,345 mentions. Narrow the filters to export the rest.',
+ 'The file holds 2 of 12,345 responses. Narrow the filters to export the rest.',
);
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx
index 50c819ced..113032da6 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_headline.tsx
@@ -126,7 +126,8 @@ export function Headline({ overview, brand }: { overview: MentionsOverview; bran
{t('basis', {
range: windowRange(overview.window, locale),
answers: overview.current.answers,
- mentions: overview.current.mentions,
+ // As Total mentions counts them: every time a response names the brand.
+ mentions: overview.current.occurrences,
})}
</p>
</section>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
index ffa7fc489..7ef437db1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx
@@ -158,7 +158,7 @@ describe('MentionsListTab', () => {
{ sentiment: 'negative', competitor: 'c1', sort: 'newest', group: '' },
0,
]);
- expect(container.textContent).toContain('2 mentions · 1 prompt');
+ expect(container.textContent).toContain('2 responses · 1 prompt');
const rows = container.querySelectorAll('tbody tr[tabindex]');
expect(rows).toHaveLength(2);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
index 8fc4bd8f7..4b27ec40c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx
@@ -250,7 +250,7 @@ export function MentionsListTab({
/>
{loaded?.status === 'ok' && loaded.list && (
<span className="ml-auto pb-1.5 text-xs text-muted-foreground tabular-nums">
- {t('summary', { mentions: loaded.list.total, prompts: loaded.list.prompts })}
+ {t('summary', { responses: loaded.list.total, prompts: loaded.list.prompts })}
</span>
)}
</div>
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 dfdd135eb..aff1cf7fd 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview-kpis.tsx
@@ -31,8 +31,9 @@ function ShareBar({ value, label }: { value: number; label: string }) {
}
/**
- * The Overview's KPI cards (MS-06), as in the mockup: Total mentions, Mention
- * rate, Prompts with mentions and Net sentiment with its split and n. Each
+ * The Overview's KPI cards (MS-06), as in the mockup: Total mentions (every
+ * time a response names the brand, as on Insights), Mention rate, Prompts with
+ * mentions and Net sentiment with its split and n. Each
* change is against the window of the same length before; a rate taken over
* fewer than 20 responses is a "Low sample" and shows no change.
*/
@@ -59,13 +60,14 @@ export function OverviewKpis({ overview, brand }: { overview: MentionsOverview;
label={t('totalMentions')}
tooltip={t('totalMentionsTip', { brand })}
icon={MessageCircle}
- value={f.number(cur.mentions)}
- delta={upIsGood(round(relativeChange(cur.mentions, prev.mentions)), {
+ // Every time a response names the brand, as Insights counts mentions.
+ value={f.number(cur.occurrences)}
+ delta={upIsGood(round(relativeChange(cur.occurrences, prev.occurrences)), {
percent: true,
locale,
})}
sub={t('totalMentionsSub', { brand })}
- spark={trend.map((d) => d.mentions)}
+ spark={trend.map((d) => d.occurrences)}
/>
<MetricCard
label={t('mentionRate')}
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 b84491ee0..b539270a5 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_overview.test.tsx
@@ -46,6 +46,8 @@ const platform = (
platform: id,
answers: now[0],
mentions: now[1],
+ // Each response naming the brand names it twice here.
+ occurrences: now[1] * 2,
positive: now[2],
negative: now[3],
previous: { answers: before[0], mentions: before[1], positive: before[2], negative: before[3] },
@@ -65,6 +67,7 @@ const overview: MentionsOverview = {
current: totals({
answers: 400,
mentions: 100,
+ occurrences: 260,
positive: 48,
negative: 14,
prompts: 20,
@@ -73,6 +76,7 @@ const overview: MentionsOverview = {
previous: totals({
answers: 400,
mentions: 80,
+ occurrences: 200,
positive: 40,
negative: 8,
prompts: 20,
@@ -128,7 +132,7 @@ describe('Headline', () => {
);
expect(basis.textContent).toBe(
'Built from aggregates with a fixed template, no LLM call · Sep 18 – Oct 17 · ' +
- '400 tracked responses · 100 mentions',
+ '400 tracked responses · 260 mentions',
);
});
@@ -144,7 +148,7 @@ describe('Headline', () => {
/>,
);
expect(container.querySelector('p')?.textContent).toBe(
- 'Net sentiment is −50 (low sample: 2 mentions).',
+ 'Net sentiment is −50 (low sample: 2 responses naming you).',
);
});
@@ -162,8 +166,9 @@ describe('OverviewKpis', () => {
it('shows each figure with its change and context', () => {
render(<OverviewKpis overview={overview} brand="Ansvisor" />);
const text = container.textContent;
- expect(text).toContain('100+25%');
- expect(text).toContain('responses naming Ansvisor');
+ // Every time a response names the brand, as on Insights: 260 vs 200.
+ expect(text).toContain('260+30%');
+ expect(text).toContain('times responses named Ansvisor');
expect(text).toContain('25.0%+5');
expect(text).toContain('of 400 tracked responses');
expect(text).toContain('15+25%');
@@ -209,7 +214,8 @@ describe('CompetitorTable', () => {
it('puts you first, then competitors by mentions and how often they name you too', () => {
render(<CompetitorTable overview={overview} brand="Ansvisor" />);
const headers = [...container.querySelectorAll('th')].map((th) => th.textContent);
- expect(headers).toEqual(['Brand', 'Mentions', 'Rate', 'Also names you']);
+ // Responses naming each brand: occurrences aren't kept for competitors.
+ expect(headers).toEqual(['Brand', 'Responses', 'Rate', 'Also names you']);
const rows = [...container.querySelectorAll('tbody tr')].map((r) =>
[...r.querySelectorAll('td')].map((td) => td.textContent),
);
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsx
index 17eab0c4b..19100ce15 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_platform-table.tsx
@@ -82,7 +82,10 @@ export function PlatformTable({
</span>
{negative && <span className="sr-only"> ({t('negativeNet')})</span>}
</td>
- <td className="px-2 py-2.5 text-right tabular-nums">{f.number(row.mentions)}</td>
+ {/* Every time it names the brand, as Total mentions counts them. */}
+ <td className="px-2 py-2.5 text-right tabular-nums">
+ {f.number(row.occurrences)}
+ </td>
<td className="px-2 py-2.5 text-right tabular-nums">
{rate === null ? '—' : f.percent(rate, 0)}
</td>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsx
index 42039ad94..275333741 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_trend-chart.tsx
@@ -57,6 +57,9 @@ export function MentionTrendChart({
const t = useTranslations('mentions.overview.trend');
const locale = useLocale();
const f = numberFormat(locale);
+ // Mentions are every time a response names the brand, as Total mentions
+ // (and Insights) count them; the rates keep their own field.
+ const key = metric === 'mentions' ? 'occurrences' : metric;
const value = (n: number) =>
metric === 'net'
? signedValue(Math.round(n), locale)
@@ -118,7 +121,7 @@ export function MentionTrendChart({
content={({ active, payload }) => {
const d = active ? (payload?.[0]?.payload as MentionTrendDay | undefined) : undefined;
if (!d) return null;
- const v = d[metric];
+ const v = d[key];
// A rate is taken over the day's responses, net sentiment over its mentions.
const n = metric === 'net' ? d.mentions : d.answers;
return (
@@ -141,7 +144,7 @@ export function MentionTrendChart({
/>
<Area
type="monotone"
- dataKey={metric}
+ dataKey={key}
stroke={STROKE}
strokeWidth={2}
fill={metric === 'net' ? 'none' : 'url(#mentionsTrendFill)'}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts
index 05acd28ec..e39644919 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_use-mentions-export.ts
@@ -151,7 +151,10 @@ export function useMentionsExport({
: []),
...(table.competitor ? [{ label: tTable('coMentioned'), value: competitor }] : []),
{ label: t('facts.responses'), value: overview.current.answers },
- { label: t('facts.mentions'), value: list.total },
+ // The card's Total mentions (every time a response names the brand),
+ // then the responses the rows below are.
+ { label: t('facts.totalMentions'), value: overview.current.occurrences },
+ { label: t('facts.namedResponses'), value: list.total },
{ label: t('facts.prompts'), value: list.prompts },
{ label: t('facts.inFile'), value: list.rows.length },
...(capped ? [{ label: t('facts.note'), value: t('facts.capped', shown) }] : []),
@@ -182,7 +185,8 @@ export function useMentionsExport({
: t('summary.kpi', { label, value });
const values = filterValues();
- const change = relativeChange(cur.mentions, prev.mentions);
+ // As the Total mentions card counts them: every time a response names the brand.
+ const change = relativeChange(cur.occurrences, prev.occurrences);
const total = upIsGood(change === null ? null : Math.round(change), { percent: true, locale });
const rate = mentionRate(cur);
const net = wholeNet(cur);
@@ -199,7 +203,7 @@ export function useMentionsExport({
headlineSentences(overview, brand, locale, tHeadline)
.map((s) => plain(s.key, s.values))
.join(' '),
- line(tKpi('totalMentions'), f.number(cur.mentions), total?.text),
+ line(tKpi('totalMentions'), f.number(cur.occurrences), total?.text),
line(
tKpi('mentionRate'),
rate === null
@@ -233,7 +237,7 @@ export function useMentionsExport({
tHeadline('basis', {
range: windowRange(overview.window, locale),
answers: cur.answers,
- mentions: cur.mentions,
+ mentions: cur.occurrences,
}),
].join('\n');
};
diff --git a/web/src/lib/actions/kpis.test.ts b/web/src/lib/actions/kpis.test.ts
index b6b2ae245..5bc10f384 100644
--- a/web/src/lib/actions/kpis.test.ts
+++ b/web/src/lib/actions/kpis.test.ts
@@ -106,9 +106,11 @@ describe('the Positive Sentiment KPI', () => {
totalCitations: 0,
});
dailyRows = {
- [daysAgo(6)]: { positive_count: 3, mentioning_results: 4 },
+ // Over the answers naming the brand (00191), not those only citing it.
+ [daysAgo(6)]: { positive_count: 3, mentioning_results: 6, mention_results: 4 },
// daysAgo(5): no answer named the brand.
- [daysAgo(4)]: { positive_count: 1, mentioning_results: 3 },
+ [daysAgo(4)]: { positive_count: 1, mentioning_results: 3, mention_results: 3 },
+ // Before 00191 the day has only the old base.
[daysAgo(0)]: { positive_count: 0, mentioning_results: 2 },
};
diff --git a/web/src/lib/actions/kpis.ts b/web/src/lib/actions/kpis.ts
index a84dbe519..4cfa1c0c8 100644
--- a/web/src/lib/actions/kpis.ts
+++ b/web/src/lib/actions/kpis.ts
@@ -173,13 +173,16 @@ async function fetchDailyInsightTotals(brandId: string) {
total_citations?: number;
positive_count?: number;
mentioning_results?: number;
+ mention_results?: number;
};
return {
date: day,
mentions: Number(agg.total_mentions ?? 0),
citations: Number(agg.total_citations ?? 0),
positive: Number(agg.positive_count ?? 0),
- mentioning: Number(agg.mentioning_results ?? 0),
+ // Answers naming the brand, the card's base (00191; before it, the
+ // answers naming or citing it).
+ named: Number(agg.mention_results ?? agg.mentioning_results ?? 0),
};
}),
);
@@ -236,8 +239,8 @@ function buildSnapshot(
// A day without an answer naming the brand has no share; it is left
// out rather than drawn as 0%.
trend = metrics.dailyTotals
- .filter((d) => d.mentioning > 0)
- .map((d) => ({ date: d.date, value: Math.round((d.positive * 100) / d.mentioning) }));
+ .filter((d) => d.named > 0)
+ .map((d) => ({ date: d.date, value: Math.round((d.positive * 100) / d.named) }));
break;
}
case 'share_of_voice': {
diff --git a/web/src/lib/actions/tracking.test.ts b/web/src/lib/actions/tracking.test.ts
index c43152fae..cf7acda8f 100644
--- a/web/src/lib/actions/tracking.test.ts
+++ b/web/src/lib/actions/tracking.test.ts
@@ -336,6 +336,30 @@ describe('getInsightsSummary', () => {
});
});
+ it('takes sentiment over the answers naming the brand, as the Mentions page (00191)', async () => {
+ rpcMock = vi.fn(async () => ({
+ data: {
+ ...insightsAggregatesRow,
+ // 17 of the 127 answers only cite the brand: always neutral.
+ mention_results: 110,
+ negative_count: 13,
+ kpi_complete: true,
+ },
+ error: null,
+ }));
+ const { getInsightsSummary } = await import('./tracking');
+
+ const summary = await getInsightsSummary('brand-id');
+
+ // 51 and 13 of 110: +46% / 12%, net (51 − 13)/110 = 34.5 → 35, rounded once.
+ expect(summary).toMatchObject({
+ positiveSentimentPct: 46,
+ negativeSentimentPct: 12,
+ netSentiment: 35,
+ mentioningResults: 110,
+ });
+ });
+
it('leaves Net sentiment and Avg. position empty until the rollups are backfilled', async () => {
rpcMock = vi.fn(async () => ({
data: {
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index fe6d260df..0cb65429f 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -273,6 +273,8 @@ interface InsightsAggregates {
total_citations: number;
positive_count: number;
mentioning_results: number;
+ /** 00191: answers naming the brand, Net sentiment's base. */
+ mention_results?: number;
last_checked_at: string | null;
by_model: Array<{
model_used: string;
@@ -1911,14 +1913,11 @@ export async function getInsightsSummary(
const avgVisibilityScore = roundTo1(cur.sum_visibility / totalResults);
const totalMentions = cur.total_mentions;
const totalCitations = cur.total_citations;
- // Denominator is answers that mention/cite the brand, not all results —
- // sentiment analysis is skipped entirely for brand-absent answers, so
- // dividing by totalResults dilutes the score with rows that can never
- // be positive (#508).
- const positiveSentimentPct =
- cur.mentioning_results > 0
- ? Math.round((cur.positive_count / cur.mentioning_results) * 100)
- : 0;
+ // Denominator is answers that name the brand, not all results — sentiment
+ // is only read where the brand is named, so dividing by totalResults (or by
+ // answers that only cite it, #508) dilutes it with rows that can never be
+ // positive. The same base as the Mentions page (00191).
+ const positiveSentimentPct = positivePctOf(cur);
const lastCheckedAt = cur.last_checked_at;
const platformBreakdown = cur.by_model.map((m) => ({
@@ -1996,18 +1995,12 @@ export async function getInsightsSummary(
const curAvgVis = roundTo1(curWin.sum_visibility / curWin.total_results);
const curMentions = curWin.total_mentions;
const curCitations = curWin.total_citations;
- const curSentimentPct =
- curWin.mentioning_results > 0
- ? Math.round((curWin.positive_count / curWin.mentioning_results) * 100)
- : 0;
+ const curSentimentPct = positivePctOf(curWin);
const prevAvgVis = roundTo1(prevWin.sum_visibility / prevWin.total_results);
prevMentions = prevWin.total_mentions;
prevCitations = prevWin.total_citations;
- const prevSentimentPct =
- prevWin.mentioning_results > 0
- ? Math.round((prevWin.positive_count / prevWin.mentioning_results) * 100)
- : 0;
+ const prevSentimentPct = positivePctOf(prevWin);
visibilityChange = roundTo1(curAvgVis - prevAvgVis);
mentionsChange = percentageChange(curMentions, prevMentions);
@@ -2043,11 +2036,25 @@ export async function getInsightsSummary(
netSentimentChange,
avgPosition: curRates.avgPosition,
avgPositionChange,
- mentioningResults: Number(cur.mentioning_results ?? 0),
+ mentioningResults: namedAnswers(cur),
positionedResults: Number(cur.position_count ?? 0),
};
}
+/**
+ * Answers naming the brand in a window: Net sentiment's base (00191). Before
+ * that migration the aggregates have only answers naming or citing it.
+ */
+function namedAnswers(a: InsightsAggregates): number {
+ return Number(a.mention_results ?? a.mentioning_results ?? 0);
+}
+
+/** Positive answers as a whole % of those naming the brand; 0 without any. */
+function positivePctOf(a: InsightsAggregates): number {
+ const named = namedAnswers(a);
+ return named > 0 ? Math.round((a.positive_count * 100) / named) : 0;
+}
+
/**
* The KPI cards' rates from one insights_aggregates window (00131). Before
* the rollups behind it are backfilled, negatives and positions are missing:
@@ -2059,7 +2066,7 @@ 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),
+ named: namedAnswers(a),
positive: Number(a.positive_count ?? 0),
negative: Number(a.negative_count ?? 0),
sumPosition:
diff --git a/web/src/lib/insights-kpis.test.ts b/web/src/lib/insights-kpis.test.ts
index b0e96d23d..a6a724035 100644
--- a/web/src/lib/insights-kpis.test.ts
+++ b/web/src/lib/insights-kpis.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import { coverage, kpiRates, parseKpiSeries, rateChange, shareOfVoice } from './insights-kpis';
+import { wholeNet } from './mentions-headline';
describe('kpiRates', () => {
it('works out every card rate from the components', () => {
@@ -7,7 +8,7 @@ describe('kpiRates', () => {
kpiRates({
answers: 200,
citationAnswers: 76,
- mentioning: 100,
+ named: 100,
positive: 48,
negative: 14,
sumPosition: 240,
@@ -22,12 +23,43 @@ describe('kpiRates', () => {
});
});
+ it('gives the same Net sentiment as the Mentions page, rounded once', () => {
+ for (let named = 1; named <= 40; named++) {
+ for (let positive = 0; positive <= named; positive++) {
+ for (let negative = 0; positive + negative <= named; negative += 3) {
+ const rates = kpiRates({
+ answers: named,
+ citationAnswers: 0,
+ named,
+ positive,
+ negative,
+ sumPosition: null,
+ positionCount: 0,
+ });
+ expect(rates.netSentiment).toBe(wholeNet({ mentions: named, positive, negative }));
+ }
+ }
+ }
+ // Rounded separately, 7/15 − 2/15 read 47 − 13 = 34; once, 33.
+ expect(
+ kpiRates({
+ answers: 15,
+ citationAnswers: 0,
+ named: 15,
+ positive: 7,
+ negative: 2,
+ sumPosition: null,
+ positionCount: 0,
+ }).netSentiment,
+ ).toBe(33);
+ });
+
it('has no rate without the answers it needs', () => {
expect(
kpiRates({
answers: 0,
citationAnswers: 0,
- mentioning: 0,
+ named: 0,
positive: 0,
negative: 0,
sumPosition: null,
@@ -94,6 +126,20 @@ describe('parseKpiSeries', () => {
]);
});
+ it("takes each day's net sentiment over the answers naming the brand (00191)", () => {
+ const day = {
+ day: '2026-10-13',
+ answers: 10,
+ citation_answers: 4,
+ positive_count: 3,
+ negative_count: 1,
+ // Two answers only cite the brand: they don't dilute the net.
+ mentioning_answers: 6,
+ mention_answers: 4,
+ };
+ expect(parseKpiSeries({ complete: true, days: [day] })?.[0].netSentiment).toBe(50);
+ });
+
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.ts
index c0ca321d1..c16364069 100644
--- a/web/src/lib/insights-kpis.ts
+++ b/web/src/lib/insights-kpis.ts
@@ -11,8 +11,12 @@ const round1 = (n: number) => Math.round(n * 10) / 10;
export interface KpiComponents {
answers: number;
citationAnswers: number;
- /** Answers naming or citing the brand: the sentiment denominator (#508). */
- mentioning: number;
+ /**
+ * Answers naming the brand: the sentiment denominator, as on the Mentions
+ * page (00191). Answers that only cite it are always neutral, so counting
+ * them (#508) pulled Net sentiment toward zero.
+ */
+ named: number;
positive: number;
negative: number;
/** Sum of the brand's position over answers naming it; null without positions. */
@@ -33,13 +37,16 @@ export interface KpiRates {
}
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;
+ // As the Mentions page does it (sentimentSplit and wholeNet in
+ // mentions-overview.ts / mentions-headline.ts): the shares multiplied
+ // first, and the net rounded once, so the two pages show the same number.
+ const share = (count: number) => (count * 100) / c.named;
+ const named = c.named > 0;
return {
citationRate: c.answers > 0 ? round1((c.citationAnswers / c.answers) * 100) : null,
- positivePct,
- negativePct,
- netSentiment: positivePct !== null && negativePct !== null ? positivePct - negativePct : null,
+ positivePct: named ? Math.round(share(c.positive)) : null,
+ negativePct: named ? Math.round(share(c.negative)) : null,
+ netSentiment: named ? Math.round(share(c.positive) - share(c.negative)) : null,
avgPosition:
c.positionCount > 0 && c.sumPosition !== null
? round1(c.sumPosition / c.positionCount)
@@ -89,7 +96,8 @@ export function parseKpiSeries(raw: unknown): KpiSeriesDay[] | null {
const rates = kpiRates({
answers: num(d.answers),
citationAnswers: num(d.citation_answers),
- mentioning: num(d.mentioning_answers),
+ // Before 00191 the series has no mention_answers: the old base.
+ named: num(d.mention_answers ?? d.mentioning_answers),
positive: num(d.positive_count),
negative: num(d.negative_count),
sumPosition:
diff --git a/web/src/lib/insights-same-prompts.test.ts b/web/src/lib/insights-same-prompts.test.ts
index dc586ef06..9c3d2c2f5 100644
--- a/web/src/lib/insights-same-prompts.test.ts
+++ b/web/src/lib/insights-same-prompts.test.ts
@@ -117,8 +117,9 @@ describe('samePromptChanges', () => {
// 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);
+ // Net sentiment over the answers naming the brand (00191): (44% − 11%)
+ // vs (30% − 10%); the 10 answers that only cite it don't dilute it.
+ expect(changes.netSentimentChange).toBe(13);
// Avg. position: 1.8 vs 2.0, an improvement.
expect(changes.avgPositionChange).toBe(-0.2);
// Citation rate: 15% vs 10%.
diff --git a/web/src/lib/insights-same-prompts.ts b/web/src/lib/insights-same-prompts.ts
index 0cce405e3..1f9ee412b 100644
--- a/web/src/lib/insights-same-prompts.ts
+++ b/web/src/lib/insights-same-prompts.ts
@@ -131,8 +131,9 @@ function competitorScore(t: SamePromptTotals, id: string): number | null {
});
}
+// Of the answers naming the brand, as Net sentiment (00191).
const sentimentPct = (t: SamePromptTotals) =>
- t.mentioning_answers > 0 ? Math.round((t.positive_count / t.mentioning_answers) * 100) : 0;
+ t.mention_answers > 0 ? Math.round((t.positive_count * 100) / t.mention_answers) : 0;
export interface SamePromptChanges {
/** Visibility on the shared prompts in each window, and the change in points. */
@@ -163,7 +164,7 @@ export function samePromptChanges(same: SamePromptComparison): SamePromptChanges
kpiRates({
answers: t.answers,
citationAnswers: t.citation_answers,
- mentioning: t.mentioning_answers,
+ named: t.mention_answers,
positive: t.positive_count,
negative: t.negative_count,
sumPosition: t.sum_position,
diff --git a/web/src/lib/mentions-filters.test.ts b/web/src/lib/mentions-filters.test.ts
index a8cce317c..1ef47f0e2 100644
--- a/web/src/lib/mentions-filters.test.ts
+++ b/web/src/lib/mentions-filters.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from 'vitest';
import {
DEFAULT_MENTIONS_FILTERS,
+ mentionsHref,
mentionsQuery,
mentionsStateParams,
readMentionsState,
@@ -111,18 +112,43 @@ describe('mentionsQuery', () => {
});
});
- it('reads a custom range as whole days in the given time zone', () => {
- const q = at('2026-10-17T12:00:00.000Z')(() =>
- mentionsQuery(
- { ...DEFAULT_MENTIONS_FILTERS, range: 'custom', from: '2026-10-01', to: '2026-10-14' },
- 'UTC',
- ),
- );
- expect(q?.from).toBe('2026-10-01T00:00:00.000Z');
- expect(q?.to).toBe('2026-10-14T23:59:59.999Z');
+ // The days Insights reads and mentions_overview reads, wherever the viewer is.
+ it('reads a custom range as whole UTC days, west of UTC too', () => {
+ const zone = process.env.TZ;
+ process.env.TZ = 'America/New_York';
+ try {
+ const q = at('2026-10-17T12:00:00.000Z')(() =>
+ mentionsQuery({
+ ...DEFAULT_MENTIONS_FILTERS,
+ range: 'custom',
+ from: '2026-10-01',
+ to: '2026-10-14',
+ }),
+ );
+ expect(q?.from).toBe('2026-10-01T00:00:00.000Z');
+ expect(q?.to).toBe('2026-10-14T23:59:59.999Z');
+ } finally {
+ process.env.TZ = zone;
+ }
});
it('is null for a custom range with no dates yet', () => {
expect(mentionsQuery({ ...DEFAULT_MENTIONS_FILTERS, range: 'custom' })).toBeNull();
});
});
+
+describe('mentionsHref', () => {
+ it("opens Mentions on another page's range and filters", () => {
+ expect(mentionsHref({ range: '7d', region: 'us', topic: 't1' })).toBe(
+ '/dashboard/mentions?range=7d&region=us&topic=t1',
+ );
+ expect(mentionsHref({ range: 'custom', from: '2026-10-01', to: '2026-10-14' })).toBe(
+ '/dashboard/mentions?range=custom&from=2026-10-01&to=2026-10-14',
+ );
+ });
+
+ it("leaves Mentions' default range out, and opens it for a range it lacks", () => {
+ expect(mentionsHref({ range: '30d' })).toBe('/dashboard/mentions');
+ expect(mentionsHref({ range: 'all', region: 'us' })).toBe('/dashboard/mentions?region=us');
+ });
+});
diff --git a/web/src/lib/mentions-filters.ts b/web/src/lib/mentions-filters.ts
index 7936f972f..0d70f71a9 100644
--- a/web/src/lib/mentions-filters.ts
+++ b/web/src/lib/mentions-filters.ts
@@ -86,6 +86,36 @@ export function mentionsStateParams(
};
}
+/**
+ * The Mentions page's address for a range and filters another page holds
+ * (Insights' Mentions and Net sentiment cards link here), so the numbers it
+ * opens on are taken over the same days. A range Mentions doesn't offer (All
+ * time) opens its default.
+ */
+export function mentionsHref(f: {
+ range: string;
+ from?: string;
+ to?: string;
+ region?: string;
+ topic?: string;
+}): string {
+ const range = (PROMPT_RANGE_PRESETS as readonly string[]).includes(f.range)
+ ? (f.range as PromptRangePreset)
+ : DEFAULT_MENTIONS_FILTERS.range;
+ const params = mentionsStateParams(DEFAULT_MENTIONS_TAB, {
+ ...DEFAULT_MENTIONS_FILTERS,
+ range,
+ from: f.from ?? '',
+ to: f.to ?? '',
+ region: f.region ?? '',
+ topic: f.topic ?? '',
+ });
+ const search = new URLSearchParams();
+ for (const [key, value] of Object.entries(params)) if (value !== null) search.set(key, value);
+ const query = search.toString();
+ return query ? `/dashboard/mentions?${query}` : '/dashboard/mentions';
+}
+
/** What the page's reads take: the window's bounds and the filters. */
export interface MentionsQuery {
from: string;
@@ -97,13 +127,15 @@ export interface MentionsQuery {
}
/**
- * The filters as a read: the range resolved to bounds in the viewer's time
- * zone, as on the Prompts page, and empty filters left out. Null for a custom
- * range with no dates yet, which is not a window to read.
+ * The filters as a read, empty filters left out. A custom range's days are
+ * UTC days: mentions_overview reads whole UTC days, as Insights does, so in
+ * the viewer's zone a viewer west of UTC who picked Oct 1–7 read Oct 2–8,
+ * and Insights' card link opened another window (gkhngyk on #1226). Null for
+ * a custom range with no dates yet, which is not a window to read.
*/
-export function mentionsQuery(filters: MentionsFilters, timeZone?: string): MentionsQuery | null {
+export function mentionsQuery(filters: MentionsFilters): MentionsQuery | null {
if (filters.range === 'custom' && !filters.from && !filters.to) return null;
- const range = resolvePromptRange(filters.range, { from: filters.from, to: filters.to }, timeZone);
+ const range = resolvePromptRange(filters.range, { from: filters.from, to: filters.to }, 'UTC');
const query: MentionsQuery = { from: range.from };
if (range.to) query.to = range.to;
if (filters.platform) query.platform = filters.platform;
diff --git a/web/src/lib/mentions-headline.test.ts b/web/src/lib/mentions-headline.test.ts
index 68aee0be8..f2a212a73 100644
--- a/web/src/lib/mentions-headline.test.ts
+++ b/web/src/lib/mentions-headline.test.ts
@@ -29,6 +29,7 @@ const platform = (
platform: id,
answers: now[0],
mentions: now[0],
+ occurrences: now[0],
positive: now[1],
negative: now[2],
previous: { answers: before[0], mentions: before[0], positive: before[1], negative: before[2] },
diff --git a/web/src/lib/mentions-overview.test.ts b/web/src/lib/mentions-overview.test.ts
index 09d6090e4..5fed83ed9 100644
--- a/web/src/lib/mentions-overview.test.ts
+++ b/web/src/lib/mentions-overview.test.ts
@@ -37,6 +37,7 @@ const raw = {
platform: 'gemini-web',
answers: 7,
mentions: 7,
+ occurrences: 15,
positive: 2,
negative: 2,
prev_answers: 7,
@@ -45,7 +46,7 @@ const raw = {
prev_negative: 2,
},
],
- daily: [{ day: '2026-10-16', answers: 4, mentions: 4, positive: 2, negative: 1 }],
+ daily: [{ day: '2026-10-16', answers: 4, mentions: 4, occurrences: 9, positive: 2, negative: 1 }],
competitors: [
{
competitor_id: 'c1',
@@ -80,12 +81,13 @@ describe('parseMentionsOverview', () => {
platform: 'gemini-web',
answers: 7,
mentions: 7,
+ occurrences: 15,
positive: 2,
negative: 2,
previous: { answers: 7, mentions: 7, positive: 2, negative: 2 },
});
expect(o.daily).toEqual([
- { day: '2026-10-16', answers: 4, mentions: 4, positive: 2, negative: 1 },
+ { day: '2026-10-16', answers: 4, mentions: 4, occurrences: 9, positive: 2, negative: 1 },
]);
expect(o.competitors).toEqual([
{
@@ -162,14 +164,14 @@ describe('mentionTrend', () => {
dayTo: '2026-10-17',
},
daily: [
- { day: '2026-10-15', answers: 10, mentions: 4, positive: 2, negative: 1 },
- { day: '2026-10-17', answers: 5, mentions: 0, positive: 0, negative: 0 },
+ { day: '2026-10-15', answers: 10, mentions: 4, occurrences: 7, positive: 2, negative: 1 },
+ { day: '2026-10-17', answers: 5, mentions: 0, occurrences: 0, positive: 0, negative: 0 },
],
});
expect(trend).toEqual([
- { day: '2026-10-15', answers: 10, mentions: 4, rate: 40, net: 25 },
- { day: '2026-10-16', answers: 0, mentions: 0, rate: null, net: null },
- { day: '2026-10-17', answers: 5, mentions: 0, rate: 0, net: null },
+ { day: '2026-10-15', answers: 10, mentions: 4, occurrences: 7, rate: 40, net: 25 },
+ { day: '2026-10-16', answers: 0, mentions: 0, occurrences: 0, rate: null, net: null },
+ { day: '2026-10-17', answers: 5, mentions: 0, occurrences: 0, rate: 0, net: null },
]);
});
});
diff --git a/web/src/lib/mentions-overview.ts b/web/src/lib/mentions-overview.ts
index 780c52de6..ca4554222 100644
--- a/web/src/lib/mentions-overview.ts
+++ b/web/src/lib/mentions-overview.ts
@@ -32,6 +32,8 @@ export interface MentionPlatformRow {
platform: string;
answers: number;
mentions: number;
+ /** Times the brand is named on the platform (00191; 0 before it). */
+ occurrences: number;
positive: number;
negative: number;
previous: Pick<MentionTotals, 'answers' | 'mentions' | 'positive' | 'negative'>;
@@ -42,6 +44,8 @@ export interface MentionDay {
day: string;
answers: number;
mentions: number;
+ /** Times the brand is named that day (00191; 0 before it). */
+ occurrences: number;
positive: number;
negative: number;
}
@@ -130,6 +134,7 @@ export function parseMentionsOverview(raw: unknown): MentionsOverview | null {
platform: String(p.platform ?? ''),
answers: num(p, 'answers'),
mentions: num(p, 'mentions'),
+ occurrences: num(p, 'occurrences'),
positive: num(p, 'positive'),
negative: num(p, 'negative'),
previous: {
@@ -143,6 +148,7 @@ export function parseMentionsOverview(raw: unknown): MentionsOverview | null {
day: String(d.day ?? ''),
answers: num(d, 'answers'),
mentions: num(d, 'mentions'),
+ occurrences: num(d, 'occurrences'),
positive: num(d, 'positive'),
negative: num(d, 'negative'),
})),
@@ -209,7 +215,10 @@ export function relativeChange(current: number, previous: number): number | null
export interface MentionTrendDay {
day: string;
answers: number;
+ /** Responses naming the brand: the base of the day's rate and net sentiment. */
mentions: number;
+ /** Times the brand is named: the Mentions line, as Total mentions counts them. */
+ occurrences: number;
/** Null on a day without answers. */
rate: number | null;
/** Null on a day without mentions. */
@@ -231,11 +240,19 @@ export function mentionTrend(o: Pick<MentionsOverview, 'window' | 'daily'>): Men
days.push(...byDay.keys());
}
return days.map((day) => {
- const d = byDay.get(day) ?? { day, answers: 0, mentions: 0, positive: 0, negative: 0 };
+ const d = byDay.get(day) ?? {
+ day,
+ answers: 0,
+ mentions: 0,
+ occurrences: 0,
+ positive: 0,
+ negative: 0,
+ };
return {
day,
answers: d.answers,
mentions: d.mentions,
+ occurrences: d.occurrences,
rate: mentionRate(d),
net: netSentiment(d),
};