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): add daily mention rollups and the Mentions overview read (#1115)

Cihanf422c043ddd7
diff --git a/server/src/lib/citations-rollups.js b/server/src/lib/citations-rollups.js
index 0f1e351d8..78f2a9657 100644
--- a/server/src/lib/citations-rollups.js
+++ b/server/src/lib/citations-rollups.js
@@ -58,7 +58,7 @@ export async function refreshCitationsDaily(brandId, dayFrom, dayTo) {
}
/** UTC day of a brand's first or last result, or null when it has none. */
-async function resultDayBound(brandId, ascending) {
+export async function resultDayBound(brandId, ascending) {
const { data, error } = await supabaseAdmin
.from('prompt_results')
.select('created_at')
diff --git a/server/src/lib/insights-rollups.js b/server/src/lib/insights-rollups.js
index 9633e1c73..49ca8a0bc 100644
--- a/server/src/lib/insights-rollups.js
+++ b/server/src/lib/insights-rollups.js
@@ -20,6 +20,7 @@
import supabaseAdmin from '../config/supabase.js';
import { logger } from './logger.js';
import { rebuildQueuedCitationRollups, refreshCitationsDaily } from './citations-rollups.js';
+import { refreshMentionsDaily } from './mentions-rollups.js';
/** How many trailing days the daily sweep recomputes, today included. */
export const SWEEP_DAYS = 3;
@@ -50,19 +51,22 @@ export async function refreshInsightsDaily(brandId, dayFrom, dayTo) {
/**
* Refresh the days a completed tracking run touched: from the run's start
* day through today (a run crossing UTC midnight lands rows on two days).
- * The Citations rollups (00118) are refreshed for the same days.
+ * The Citations (00118) and Mentions (00157) rollups are refreshed for the
+ * same days.
*/
export async function refreshForCompletedRun(brandId, runStartedAtIso) {
const dayFrom = utcDay(runStartedAtIso);
const dayTo = utcDay();
const ok = await refreshInsightsDaily(brandId, dayFrom, dayTo);
await refreshCitationsDaily(brandId, dayFrom, dayTo);
+ await refreshMentionsDaily(brandId, dayFrom, dayTo);
return ok;
}
/**
- * Daily backstop: refresh the trailing SWEEP_DAYS for every brand, Insights
- * and Citations rollups alike, then rebuild the brands queued by topic moves.
+ * Daily backstop: refresh the trailing SWEEP_DAYS for every brand, Insights,
+ * Citations and Mentions rollups alike, then rebuild the brands queued by
+ * topic moves.
*
* Deliberately every brand rather than "brands with recent results" — a
* refresh over days with no rows deletes nothing and inserts nothing, so the
@@ -88,7 +92,8 @@ export async function sweepInsightsRollups({ days = SWEEP_DAYS } = {}) {
for (const brand of brands ?? []) {
const ok = await refreshInsightsDaily(brand.id, dayFrom, dayTo);
const citationsOk = await refreshCitationsDaily(brand.id, dayFrom, dayTo);
- if (ok && citationsOk) refreshed++;
+ const mentionsOk = await refreshMentionsDaily(brand.id, dayFrom, dayTo);
+ if (ok && citationsOk && mentionsOk) refreshed++;
else failed++;
}
diff --git a/server/src/lib/insights-rollups.test.js b/server/src/lib/insights-rollups.test.js
index fa5ed8be7..bba4c6724 100644
--- a/server/src/lib/insights-rollups.test.js
+++ b/server/src/lib/insights-rollups.test.js
@@ -17,6 +17,12 @@ vi.mock('./citations-rollups.js', () => ({
rebuildQueuedCitationRollups: (...a) => rebuildQueuedCitationRollups(...a),
}));
+// The Mentions rollups ride on them too (mentions-rollups.test.js).
+const refreshMentionsDaily = vi.fn();
+vi.mock('./mentions-rollups.js', () => ({
+ refreshMentionsDaily: (...a) => refreshMentionsDaily(...a),
+}));
+
import {
refreshInsightsDaily,
refreshForCompletedRun,
@@ -29,6 +35,7 @@ beforeEach(() => {
rpc.mockReset();
from.mockReset();
refreshCitationsDaily.mockReset().mockResolvedValue(true);
+ refreshMentionsDaily.mockReset().mockResolvedValue(true);
rebuildQueuedCitationRollups.mockReset().mockResolvedValue({ rebuilt: 0, failed: 0 });
vi.useFakeTimers();
vi.setSystemTime(new Date('2026-08-21T05:30:00Z'));
@@ -99,10 +106,11 @@ describe('refreshForCompletedRun', () => {
});
});
- it('refreshes the Citations rollups for the same days', async () => {
+ it('refreshes the Citations and Mentions rollups for the same days', async () => {
rpc.mockResolvedValue({ error: null });
await refreshForCompletedRun('brand-1', '2026-08-20T23:45:00Z');
expect(refreshCitationsDaily).toHaveBeenCalledWith('brand-1', '2026-08-20', '2026-08-21');
+ expect(refreshMentionsDaily).toHaveBeenCalledWith('brand-1', '2026-08-20', '2026-08-21');
});
});
@@ -127,6 +135,7 @@ describe('sweepInsightsRollups', () => {
});
expect(SWEEP_DAYS).toBe(3);
expect(refreshCitationsDaily).toHaveBeenCalledWith('b', '2026-08-19', '2026-08-21');
+ expect(refreshMentionsDaily).toHaveBeenCalledWith('b', '2026-08-19', '2026-08-21');
expect(rebuildQueuedCitationRollups).toHaveBeenCalledTimes(1);
});
@@ -140,6 +149,16 @@ describe('sweepInsightsRollups', () => {
expect(res).toEqual({ refreshed: 1, failed: 1 });
});
+ it('counts a brand whose Mentions refresh failed', async () => {
+ brandsList([{ id: 'a' }, { id: 'b' }]);
+ rpc.mockResolvedValue({ error: null });
+ refreshMentionsDaily.mockResolvedValueOnce(false);
+
+ const res = await sweepInsightsRollups();
+
+ expect(res).toEqual({ refreshed: 1, failed: 1 });
+ });
+
// One brand's failure must not stop the sweep — the whole point of the
// backstop is that no brand silently stays stale.
it('keeps sweeping past a failing brand and counts it', async () => {
diff --git a/server/src/lib/mentions-rollups.js b/server/src/lib/mentions-rollups.js
new file mode 100644
index 000000000..36b5fc728
--- /dev/null
+++ b/server/src/lib/mentions-rollups.js
@@ -0,0 +1,54 @@
+/**
+ * Mentions daily-rollup maintenance (00157).
+ *
+ * The Mentions & Sentiment page reads per-day mention rows instead of
+ * re-reading a window of answers per load; this module is the only thing
+ * that writes them, through the `refresh_mentions_daily` SQL function. It
+ * rides on the Insights rollup callers (insights-rollups.js), as the Citations
+ * rollups do: a run's days are refreshed when the run stamps, and the daily
+ * sweep re-refreshes the trailing days.
+ *
+ * Best-effort like the other rollups: the rows are derived state, always
+ * recomputable from prompt_results, so a failure costs freshness until the
+ * next sweep and never throws into a tracking run.
+ */
+
+import supabaseAdmin from '../config/supabase.js';
+import { logger } from './logger.js';
+import { dayChunks, resultDayBound } from './citations-rollups.js';
+
+/**
+ * Recompute one brand's mention rollups for an inclusive UTC day range.
+ * Resolves to true on success, false otherwise; never throws.
+ */
+export async function refreshMentionsDaily(brandId, dayFrom, dayTo) {
+ const { error } = await supabaseAdmin.rpc('refresh_mentions_daily', {
+ p_brand_id: brandId,
+ p_day_from: dayFrom,
+ p_day_to: dayTo,
+ });
+ if (error) {
+ logger.error({ err: error, brandId, dayFrom, dayTo }, '[mentions-rollups] refresh failed');
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Recompute a brand's whole mention history, a chunk at a time so no call
+ * nears the service role's statement timeout. Resolves to the number of
+ * chunks written; throws when a chunk fails, so the caller can retry later.
+ */
+export async function refreshMentionHistory(brandId, { pauseMs = 0 } = {}) {
+ const firstDay = await resultDayBound(brandId, true);
+ if (!firstDay) return 0;
+ const lastDay = await resultDayBound(brandId, false);
+
+ const chunks = dayChunks(firstDay, lastDay);
+ for (const [from, to] of chunks) {
+ const ok = await refreshMentionsDaily(brandId, from, to);
+ if (!ok) throw new Error(`mention rollup refresh failed for ${brandId} ${from}..${to}`);
+ if (pauseMs > 0) await new Promise((resolve) => setTimeout(resolve, pauseMs));
+ }
+ return chunks.length;
+}
diff --git a/server/src/lib/mentions-rollups.test.js b/server/src/lib/mentions-rollups.test.js
new file mode 100644
index 000000000..c9cb35a70
--- /dev/null
+++ b/server/src/lib/mentions-rollups.test.js
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// The module reaches the supabase admin client at import time, whose config
+// hard-exits when SUPABASE_* env is absent (as in CI).
+const rpc = vi.fn();
+const from = vi.fn();
+vi.mock('../config/supabase.js', () => ({
+ default: { rpc: (...a) => rpc(...a), from: (...a) => from(...a) },
+}));
+
+import { refreshMentionHistory, refreshMentionsDaily } from './mentions-rollups.js';
+
+/** A prompt_results bound query: first call ascending (first day), then descending. */
+function resultBounds(first, last) {
+ const days = [first, last];
+ from.mockImplementation((table) => {
+ if (table !== 'prompt_results') throw new Error(`unexpected table ${table}`);
+ const day = days.shift();
+ const q = {
+ select: () => q,
+ eq: () => q,
+ order: () => q,
+ limit: () =>
+ Promise.resolve({ data: day ? [{ created_at: `${day}T04:00:00Z` }] : [], error: null }),
+ };
+ return q;
+ });
+}
+
+beforeEach(() => {
+ rpc.mockReset();
+ from.mockReset();
+});
+
+describe('refreshMentionsDaily', () => {
+ it('calls the refresh function with the brand and inclusive day range', async () => {
+ rpc.mockResolvedValue({ error: null });
+ await expect(refreshMentionsDaily('brand-1', '2026-10-15', '2026-10-17')).resolves.toBe(true);
+ expect(rpc).toHaveBeenCalledWith('refresh_mentions_daily', {
+ p_brand_id: 'brand-1',
+ p_day_from: '2026-10-15',
+ p_day_to: '2026-10-17',
+ });
+ });
+
+ // Derived state: a failed refresh costs freshness until the next sweep and
+ // must never throw into a tracking run's finalize path.
+ it('reports failure without throwing', async () => {
+ rpc.mockResolvedValue({ error: { message: 'boom' } });
+ await expect(refreshMentionsDaily('brand-1', '2026-10-17', '2026-10-17')).resolves.toBe(false);
+ });
+});
+
+describe('refreshMentionHistory', () => {
+ it('recomputes the whole history in two-week chunks', async () => {
+ resultBounds('2026-09-01', '2026-10-17');
+ rpc.mockResolvedValue({ error: null });
+
+ await expect(refreshMentionHistory('brand-1')).resolves.toBe(4);
+ expect(rpc.mock.calls.map(([, args]) => [args.p_day_from, args.p_day_to])).toEqual([
+ ['2026-09-01', '2026-09-14'],
+ ['2026-09-15', '2026-09-28'],
+ ['2026-09-29', '2026-10-12'],
+ ['2026-10-13', '2026-10-17'],
+ ]);
+ });
+
+ it('skips a brand with no results', async () => {
+ resultBounds(null, null);
+ await expect(refreshMentionHistory('brand-1')).resolves.toBe(0);
+ expect(rpc).not.toHaveBeenCalled();
+ });
+
+ it('stops at a failed chunk so the backfill can be run again', async () => {
+ resultBounds('2026-09-01', '2026-10-17');
+ rpc.mockResolvedValueOnce({ error: null }).mockResolvedValueOnce({ error: { message: 'x' } });
+ await expect(refreshMentionHistory('brand-1')).rejects.toThrow(
+ 'mention rollup refresh failed for brand-1 2026-09-15..2026-09-28',
+ );
+ });
+});
diff --git a/server/src/scripts/backfill-mentions-daily.js b/server/src/scripts/backfill-mentions-daily.js
new file mode 100644
index 000000000..81d3fbcb4
--- /dev/null
+++ b/server/src/scripts/backfill-mentions-daily.js
@@ -0,0 +1,56 @@
+/**
+ * Backfill the Mentions daily rollups (00157) from historical prompt_results.
+ *
+ * Run: `node src/scripts/backfill-mentions-daily.js`
+ *
+ * Options via env:
+ * - MENTIONS_BACKFILL_PAUSE milliseconds between refresh calls
+ * (default 250)
+ * - MENTIONS_BACKFILL_BRAND limit the run to one brand id
+ *
+ * Covers every brand with results, cancelled orgs included, as the Insights
+ * and Citations backfills do: the page must not open empty on launch day, or
+ * for a reactivated account.
+ *
+ * Idempotent and restartable. `refresh_mentions_daily` is delete + insert per
+ * day range, so an interrupted run can be started again. Chunked by
+ * HISTORY_CHUNK_DAYS, with a pause between calls because this shares the
+ * instance with live dashboards.
+ */
+
+import 'dotenv/config';
+import supabaseAdmin from '../config/supabase.js';
+import { refreshMentionHistory } from '../lib/mentions-rollups.js';
+
+const PAUSE_MS = Number.parseInt(process.env.MENTIONS_BACKFILL_PAUSE ?? '250', 10);
+const ONLY_BRAND = process.env.MENTIONS_BACKFILL_BRAND ?? null;
+
+async function main() {
+ const query = supabaseAdmin.from('brands').select('id');
+ const { data: brands, error } = ONLY_BRAND ? await query.eq('id', ONLY_BRAND) : await query;
+ if (error) throw new Error(error.message);
+
+ let done = 0;
+ let failed = 0;
+ for (const brand of brands ?? []) {
+ try {
+ const chunks = await refreshMentionHistory(brand.id, { pauseMs: PAUSE_MS });
+ done++;
+ console.log(
+ chunks === 0
+ ? `[${done}/${brands.length}] ${brand.id} — no results, skipped`
+ : `[${done}/${brands.length}] ${brand.id} — ${chunks} chunk(s)`,
+ );
+ } catch (err) {
+ failed++;
+ console.error(`FAILED ${brand.id}: ${err.message}`);
+ }
+ }
+ console.log(`Backfill complete: ${done} brand(s), ${failed} failure(s).`);
+ if (failed > 0) process.exitCode = 1;
+}
+
+main().catch((err) => {
+ console.error(err);
+ process.exit(1);
+});
diff --git a/supabase/migrations/00157_mentions_daily.sql b/supabase/migrations/00157_mentions_daily.sql
new file mode 100644
index 000000000..c781f8492
--- /dev/null
+++ b/supabase/migrations/00157_mentions_daily.sql
@@ -0,0 +1,391 @@
+-- Mentions & Sentiment (MS-04): where AI names the brand, the tone of those
+-- answers, and the competitors named beside it, for any window, without
+-- re-reading every answer on each page load.
+--
+-- Tracking already stores what the page needs on each answer (prompt_results):
+-- mention_count (how often the brand is named), mention_position (where among
+-- the brands it is named, 00038), competitor_mentions (each competitor's
+-- count) and sentiment (the answer's tone toward the brand; set only when the
+-- brand is named). Opening the page or changing a filter therefore never
+-- calls an LLM: every number is an aggregation of those columns.
+--
+-- Two daily rollups, refreshed the way the Insights and Citations rollups are
+-- (server/src/lib/mentions-rollups.js): when a run's ledger row is stamped,
+-- by the nightly sweep for the trailing days, and once over each brand's
+-- history by server/src/scripts/backfill-mentions-daily.js.
+--
+-- * mentions_prompt_daily, one row per (UTC day, prompt, platform, region):
+-- the answers, the answers naming the brand ("mentions": an answer naming
+-- it twice is one mention), the occurrences, the positive and negative
+-- answers among the mentions (neutral is the rest, never dropped), and the
+-- brand's positions. The prompt grain lets the page filter by topic and
+-- search prompts, and count prompts with mentions, from the rollup.
+-- * mentions_competitor_daily, one row per (day, prompt, platform, region,
+-- competitor) where the competitor is named: the answers naming it, and
+-- those naming the brand too ("in the same answer as you"). Sparse.
+--
+-- A prompt keeps its history under the topic it is in now: the topic is read
+-- from prompts at query time, so a topic move needs no rebuild.
+-- chatgpt-shopping stays out, as in every rollup (#155).
+--
+-- mentions_overview reads a window. As topics_overview_window (00156) does,
+-- a window under two days (24 hours) reads its answers, and the previous
+-- window's, directly: today's run may not be in the rollups yet, and a day of
+-- answers is a small read. A longer window reads whole UTC days counted back
+-- from its end. Like 00147–00156 it is plpgsql with force_custom_plan, so
+-- each call is planned with its real window (and the branch it doesn't take
+-- is pruned), and security definer with the organization check made
+-- explicit, returning null to a caller outside the brand's organization.
+
+-- ─── Tables ─────────────────────────────────────────────────────────────────
+
+create table if not exists public.mentions_prompt_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ prompt_id uuid not null,
+ platform text,
+ region text,
+ answer_count integer not null,
+ -- Answers naming the brand at least once.
+ mention_answers integer not null,
+ -- Times the brand is named, over all answers.
+ mention_occurrences bigint not null,
+ -- Tone of the answers naming the brand; neutral is the rest.
+ positive_answers integer not null,
+ negative_answers integer not null,
+ -- The brand's position among the brands an answer names (1 = first).
+ position_sum bigint not null,
+ position_count integer not null,
+ last_answer_at timestamptz not null
+);
+
+create index if not exists idx_mentions_prompt_daily_brand_day
+ on public.mentions_prompt_daily (brand_id, day);
+
+create table if not exists public.mentions_competitor_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ prompt_id uuid not null,
+ platform text,
+ region text,
+ -- Text, as in the competitor_mentions payload and the Insights rollups.
+ competitor_id text not null,
+ -- Answers naming the competitor.
+ mention_answers integer not null,
+ -- Of those, the answers naming the brand too.
+ co_mention_answers integer not null
+);
+
+create index if not exists idx_mentions_competitor_daily_brand_day
+ on public.mentions_competitor_daily (brand_id, day);
+
+-- ─── RLS — same shape as prompt_results ─────────────────────────────────────
+
+alter table public.mentions_prompt_daily enable row level security;
+alter table public.mentions_competitor_daily enable row level security;
+
+create policy "Users can read own org mention rollups"
+ on public.mentions_prompt_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org competitor mention rollups"
+ on public.mentions_competitor_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+-- ─── Refresh ────────────────────────────────────────────────────────────────
+-- Recomputes a brand's mention rollups for an inclusive UTC day range from
+-- prompt_results: delete + insert in one transaction, so it is idempotent
+-- and readers never see a half-refreshed day. Service-role only.
+
+create or replace function public.refresh_mentions_daily(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+declare
+ -- The range's bounds as instants, so the answers are found by range.
+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';
+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';
+begin
+ delete from public.mentions_prompt_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.mentions_competitor_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+
+ insert into public.mentions_prompt_daily (
+ brand_id, day, prompt_id, platform, region,
+ answer_count, mention_answers, mention_occurrences,
+ positive_answers, negative_answers, position_sum, position_count, last_answer_at)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id, pr.platform, pr.region,
+ count(*),
+ count(*) filter (where pr.mention_count > 0),
+ coalesce(sum(pr.mention_count), 0),
+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'positive'),
+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'negative'),
+ coalesce(sum(pr.mention_position)
+ filter (where pr.mention_count > 0 and pr.mention_position is not null), 0),
+ count(*) filter (where pr.mention_count > 0 and pr.mention_position is not null),
+ max(pr.created_at)
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from
+ and pr.created_at < v_to
+ group by 2, pr.prompt_id, pr.platform, pr.region;
+
+ insert into public.mentions_competitor_daily (
+ brand_id, day, prompt_id, platform, region, competitor_id,
+ mention_answers, co_mention_answers)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id, pr.platform, pr.region,
+ cm.value->>'competitor_id',
+ count(*),
+ count(*) filter (where pr.mention_count > 0)
+ from public.prompt_results pr
+ cross join lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from
+ and pr.created_at < v_to
+ and cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0
+ group by 2, pr.prompt_id, pr.platform, pr.region, cm.value->>'competitor_id';
+end;
+$$;
+
+revoke execute on function public.refresh_mentions_daily(uuid, date, date)
+ from public, anon, authenticated;
+
+-- ─── Read ───────────────────────────────────────────────────────────────────
+-- The Overview's figures for a window and the window of the same length just
+-- before it, in one call:
+-- current / previous answers, mentions, occurrences, positive, negative,
+-- position_sum / position_count, prompts (answered),
+-- prompts_with_mentions, last_answer_at
+-- platforms the same per platform, current and prev_*
+-- daily per UTC day of the window: answers, mentions,
+-- positive, negative
+-- competitors every configured competitor: mentions (answers naming
+-- it), co_mentions (also naming the brand),
+-- prev_mentions
+-- Filters: platform, region, topic, and a case-insensitive search over the
+-- prompt's text.
+
+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(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(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),
+ 'platforms', coalesce((select jsonb_agg(to_jsonb(p) order by 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;
+$$;
+
+revoke execute on function public.mentions_overview(uuid, timestamptz, timestamptz, text, text, uuid, text)
+ from public, anon;
+grant execute on function public.mentions_overview(uuid, timestamptz, timestamptz, text, text, uuid, text)
+ to authenticated, service_role;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 96cba20c2..3973d1c81 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -19567,3 +19567,398 @@ revoke execute on function public.topics_overview_window(uuid, timestamptz, time
grant execute on function public.topics_overview_window(uuid, timestamptz, timestamptz)
to authenticated, service_role;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00157_mentions_daily.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Mentions & Sentiment (MS-04): where AI names the brand, the tone of those
+-- answers, and the competitors named beside it, for any window, without
+-- re-reading every answer on each page load.
+--
+-- Tracking already stores what the page needs on each answer (prompt_results):
+-- mention_count (how often the brand is named), mention_position (where among
+-- the brands it is named, 00038), competitor_mentions (each competitor's
+-- count) and sentiment (the answer's tone toward the brand; set only when the
+-- brand is named). Opening the page or changing a filter therefore never
+-- calls an LLM: every number is an aggregation of those columns.
+--
+-- Two daily rollups, refreshed the way the Insights and Citations rollups are
+-- (server/src/lib/mentions-rollups.js): when a run's ledger row is stamped,
+-- by the nightly sweep for the trailing days, and once over each brand's
+-- history by server/src/scripts/backfill-mentions-daily.js.
+--
+-- * mentions_prompt_daily, one row per (UTC day, prompt, platform, region):
+-- the answers, the answers naming the brand ("mentions": an answer naming
+-- it twice is one mention), the occurrences, the positive and negative
+-- answers among the mentions (neutral is the rest, never dropped), and the
+-- brand's positions. The prompt grain lets the page filter by topic and
+-- search prompts, and count prompts with mentions, from the rollup.
+-- * mentions_competitor_daily, one row per (day, prompt, platform, region,
+-- competitor) where the competitor is named: the answers naming it, and
+-- those naming the brand too ("in the same answer as you"). Sparse.
+--
+-- A prompt keeps its history under the topic it is in now: the topic is read
+-- from prompts at query time, so a topic move needs no rebuild.
+-- chatgpt-shopping stays out, as in every rollup (#155).
+--
+-- mentions_overview reads a window. As topics_overview_window (00156) does,
+-- a window under two days (24 hours) reads its answers, and the previous
+-- window's, directly: today's run may not be in the rollups yet, and a day of
+-- answers is a small read. A longer window reads whole UTC days counted back
+-- from its end. Like 00147–00156 it is plpgsql with force_custom_plan, so
+-- each call is planned with its real window (and the branch it doesn't take
+-- is pruned), and security definer with the organization check made
+-- explicit, returning null to a caller outside the brand's organization.
+
+-- ─── Tables ─────────────────────────────────────────────────────────────────
+
+create table if not exists public.mentions_prompt_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ prompt_id uuid not null,
+ platform text,
+ region text,
+ answer_count integer not null,
+ -- Answers naming the brand at least once.
+ mention_answers integer not null,
+ -- Times the brand is named, over all answers.
+ mention_occurrences bigint not null,
+ -- Tone of the answers naming the brand; neutral is the rest.
+ positive_answers integer not null,
+ negative_answers integer not null,
+ -- The brand's position among the brands an answer names (1 = first).
+ position_sum bigint not null,
+ position_count integer not null,
+ last_answer_at timestamptz not null
+);
+
+create index if not exists idx_mentions_prompt_daily_brand_day
+ on public.mentions_prompt_daily (brand_id, day);
+
+create table if not exists public.mentions_competitor_daily (
+ brand_id uuid not null references public.brands(id) on delete cascade,
+ day date not null,
+ prompt_id uuid not null,
+ platform text,
+ region text,
+ -- Text, as in the competitor_mentions payload and the Insights rollups.
+ competitor_id text not null,
+ -- Answers naming the competitor.
+ mention_answers integer not null,
+ -- Of those, the answers naming the brand too.
+ co_mention_answers integer not null
+);
+
+create index if not exists idx_mentions_competitor_daily_brand_day
+ on public.mentions_competitor_daily (brand_id, day);
+
+-- ─── RLS — same shape as prompt_results ─────────────────────────────────────
+
+alter table public.mentions_prompt_daily enable row level security;
+alter table public.mentions_competitor_daily enable row level security;
+
+create policy "Users can read own org mention rollups"
+ on public.mentions_prompt_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+create policy "Users can read own org competitor mention rollups"
+ on public.mentions_competitor_daily for select
+ using (brand_id in (
+ select b.id from public.brands b
+ join public.profiles p on p.organization_id = b.organization_id
+ where p.id = auth.uid()));
+
+-- ─── Refresh ────────────────────────────────────────────────────────────────
+-- Recomputes a brand's mention rollups for an inclusive UTC day range from
+-- prompt_results: delete + insert in one transaction, so it is idempotent
+-- and readers never see a half-refreshed day. Service-role only.
+
+create or replace function public.refresh_mentions_daily(
+ p_brand_id uuid,
+ p_day_from date,
+ p_day_to date
+) returns void
+language plpgsql
+set search_path to 'public'
+as $$
+declare
+ -- The range's bounds as instants, so the answers are found by range.
+ v_from timestamptz := p_day_from::timestamp at time zone 'utc';
+ v_to timestamptz := (p_day_to + 1)::timestamp at time zone 'utc';
+begin
+ delete from public.mentions_prompt_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+ delete from public.mentions_competitor_daily
+ where brand_id = p_brand_id and day between p_day_from and p_day_to;
+
+ insert into public.mentions_prompt_daily (
+ brand_id, day, prompt_id, platform, region,
+ answer_count, mention_answers, mention_occurrences,
+ positive_answers, negative_answers, position_sum, position_count, last_answer_at)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id, pr.platform, pr.region,
+ count(*),
+ count(*) filter (where pr.mention_count > 0),
+ coalesce(sum(pr.mention_count), 0),
+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'positive'),
+ count(*) filter (where pr.mention_count > 0 and pr.sentiment = 'negative'),
+ coalesce(sum(pr.mention_position)
+ filter (where pr.mention_count > 0 and pr.mention_position is not null), 0),
+ count(*) filter (where pr.mention_count > 0 and pr.mention_position is not null),
+ max(pr.created_at)
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from
+ and pr.created_at < v_to
+ group by 2, pr.prompt_id, pr.platform, pr.region;
+
+ insert into public.mentions_competitor_daily (
+ brand_id, day, prompt_id, platform, region, competitor_id,
+ mention_answers, co_mention_answers)
+ select
+ p_brand_id,
+ (pr.created_at at time zone 'utc')::date,
+ pr.prompt_id, pr.platform, pr.region,
+ cm.value->>'competitor_id',
+ count(*),
+ count(*) filter (where pr.mention_count > 0)
+ from public.prompt_results pr
+ cross join lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm
+ where pr.brand_id = p_brand_id
+ and pr.prompt_id is not null
+ and pr.platform <> 'chatgpt-shopping'
+ and pr.created_at >= v_from
+ and pr.created_at < v_to
+ and cm.value ? 'competitor_id'
+ and coalesce((cm.value->>'mention_count')::int, 0) > 0
+ group by 2, pr.prompt_id, pr.platform, pr.region, cm.value->>'competitor_id';
+end;
+$$;
+
+revoke execute on function public.refresh_mentions_daily(uuid, date, date)
+ from public, anon, authenticated;
+
+-- ─── Read ───────────────────────────────────────────────────────────────────
+-- The Overview's figures for a window and the window of the same length just
+-- before it, in one call:
+-- current / previous answers, mentions, occurrences, positive, negative,
+-- position_sum / position_count, prompts (answered),
+-- prompts_with_mentions, last_answer_at
+-- platforms the same per platform, current and prev_*
+-- daily per UTC day of the window: answers, mentions,
+-- positive, negative
+-- competitors every configured competitor: mentions (answers naming
+-- it), co_mentions (also naming the brand),
+-- prev_mentions
+-- Filters: platform, region, topic, and a case-insensitive search over the
+-- prompt's text.
+
+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(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(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),
+ 'platforms', coalesce((select jsonb_agg(to_jsonb(p) order by 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;
+$$;
+
+revoke execute on function public.mentions_overview(uuid, timestamptz, timestamptz, text, text, uuid, text)
+ from public, anon;
+grant execute on function public.mentions_overview(uuid, timestamptz, timestamptz, text, text, uuid, text)
+ to authenticated, service_role;
+
diff --git a/web/src/lib/actions/mentions.test.ts b/web/src/lib/actions/mentions.test.ts
new file mode 100644
index 000000000..b4ed20c01
--- /dev/null
+++ b/web/src/lib/actions/mentions.test.ts
@@ -0,0 +1,60 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+let result: { data: unknown; error: { code?: string; message: string } | null };
+const rpc = vi.fn(async () => result);
+vi.mock('@/lib/supabase/server', () => ({
+ createClient: vi.fn(async () => ({ rpc })),
+}));
+
+import { getMentionsOverview } from './mentions';
+
+beforeEach(() => {
+ rpc.mockClear();
+ result = { data: null, error: null };
+});
+
+describe('getMentionsOverview', () => {
+ it('reads the window and filters in one call', async () => {
+ result = {
+ data: {
+ window: { from: 'f', to: 't', days: 7, source: 'days' },
+ current: { answers: 8, mentions: 6 },
+ previous: null,
+ platforms: [],
+ daily: [],
+ competitors: [],
+ },
+ error: null,
+ };
+ const overview = await getMentionsOverview('b1', {
+ from: '2026-10-10T00:00:00.000Z',
+ platform: 'gemini-web',
+ topicId: 't1',
+ search: 'pricing',
+ });
+ expect(rpc).toHaveBeenCalledWith('mentions_overview', {
+ p_brand_id: 'b1',
+ p_date_from: '2026-10-10T00:00:00.000Z',
+ p_date_to: undefined,
+ p_platform: 'gemini-web',
+ p_region: undefined,
+ p_topic_id: 't1',
+ p_search: 'pricing',
+ });
+ expect(overview?.current).toMatchObject({ answers: 8, mentions: 6 });
+ });
+
+ it('is null before the migration has run', async () => {
+ result = { data: null, error: { code: 'PGRST202', message: 'not found' } };
+ await expect(getMentionsOverview('b1', { from: 'f' })).resolves.toBeNull();
+ });
+
+ it('is null for a caller outside the organization', async () => {
+ await expect(getMentionsOverview('b1', { from: 'f' })).resolves.toBeNull();
+ });
+
+ it('throws on any other error', async () => {
+ result = { data: null, error: { code: '57014', message: 'statement timeout' } };
+ await expect(getMentionsOverview('b1', { from: 'f' })).rejects.toThrow('statement timeout');
+ });
+});
diff --git a/web/src/lib/actions/mentions.ts b/web/src/lib/actions/mentions.ts
new file mode 100644
index 000000000..8380bbda5
--- /dev/null
+++ b/web/src/lib/actions/mentions.ts
@@ -0,0 +1,33 @@
+'use server';
+
+import { createClient } from '@/lib/supabase/server';
+import type { MentionsQuery } from '@/lib/mentions-filters';
+import { parseMentionsOverview, type MentionsOverview } from '@/lib/mentions-overview';
+
+/**
+ * The Mentions & Sentiment Overview's figures (MS-06) for a window and the
+ * window before it, from the mention rollups (00157). One database call, and
+ * no LLM: every figure aggregates what tracking stored.
+ *
+ * Null when there is nothing to read: the database doesn't have the function
+ * yet (PostgREST's PGRST202, a web build deployed before the migration), or
+ * the caller isn't in the brand's organization.
+ */
+export async function getMentionsOverview(
+ brandId: string,
+ query: MentionsQuery,
+): Promise<MentionsOverview | null> {
+ const supabase = await createClient();
+ const { data, error } = await supabase.rpc('mentions_overview', {
+ p_brand_id: brandId,
+ p_date_from: query.from,
+ p_date_to: query.to,
+ p_platform: query.platform,
+ p_region: query.region,
+ p_topic_id: query.topicId,
+ p_search: query.search,
+ });
+ if (error?.code === 'PGRST202') return null;
+ if (error) throw new Error(error.message);
+ return parseMentionsOverview(data);
+}
diff --git a/web/src/lib/mentions-filters.test.ts b/web/src/lib/mentions-filters.test.ts
index 7b5e5cf51..a8cce317c 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,
+ mentionsQuery,
mentionsStateParams,
readMentionsState,
type MentionsFilters,
@@ -85,3 +86,43 @@ describe('mentionsStateParams', () => {
).toMatchObject({ range: '7d', from: null, q: 'pricing' });
});
});
+
+describe('mentionsQuery', () => {
+ const at = (iso: string) => {
+ const real = Date.now;
+ return <T>(fn: () => T): T => {
+ Date.now = () => Date.parse(iso);
+ try {
+ return fn();
+ } finally {
+ Date.now = real;
+ }
+ };
+ };
+
+ it('turns a preset into its window and leaves empty filters out', () => {
+ const q = at('2026-10-17T12:00:00.000Z')(() =>
+ mentionsQuery({ ...DEFAULT_MENTIONS_FILTERS, range: '7d', platform: 'claude', q: ' faq ' }),
+ );
+ expect(q).toEqual({
+ from: '2026-10-10T12:00:00.000Z',
+ platform: 'claude',
+ search: 'faq',
+ });
+ });
+
+ 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');
+ });
+
+ it('is null for a custom range with no dates yet', () => {
+ expect(mentionsQuery({ ...DEFAULT_MENTIONS_FILTERS, range: 'custom' })).toBeNull();
+ });
+});
diff --git a/web/src/lib/mentions-filters.ts b/web/src/lib/mentions-filters.ts
index ba20a825c..5f6f5168e 100644
--- a/web/src/lib/mentions-filters.ts
+++ b/web/src/lib/mentions-filters.ts
@@ -1,4 +1,8 @@
-import { PROMPT_RANGE_PRESETS, type PromptRangePreset } from '@/config/prompt-options';
+import {
+ PROMPT_RANGE_PRESETS,
+ resolvePromptRange,
+ type PromptRangePreset,
+} from '@/config/prompt-options';
/**
* The Mentions & Sentiment page's tab and filters (MS-05). One filter shape is
@@ -81,3 +85,30 @@ export function mentionsStateParams(
q: orNull(filters.q.trim()),
};
}
+
+/** What the page's reads take: the window's bounds and the filters. */
+export interface MentionsQuery {
+ from: string;
+ to?: string;
+ platform?: string;
+ region?: string;
+ topicId?: string;
+ search?: string;
+}
+
+/**
+ * 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.
+ */
+export function mentionsQuery(filters: MentionsFilters, timeZone?: string): 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 query: MentionsQuery = { from: range.from };
+ if (range.to) query.to = range.to;
+ if (filters.platform) query.platform = filters.platform;
+ if (filters.region) query.region = filters.region;
+ if (filters.topic) query.topicId = filters.topic;
+ if (filters.q.trim()) query.search = filters.q.trim();
+ return query;
+}
diff --git a/web/src/lib/mentions-overview.test.ts b/web/src/lib/mentions-overview.test.ts
new file mode 100644
index 000000000..d1118c4ce
--- /dev/null
+++ b/web/src/lib/mentions-overview.test.ts
@@ -0,0 +1,132 @@
+import { describe, expect, it } from 'vitest';
+import {
+ averagePosition,
+ isLowSample,
+ mentionRate,
+ netSentiment,
+ parseMentionsOverview,
+ sentimentSplit,
+} from './mentions-overview';
+
+const raw = {
+ window: { from: '2026-09-17T06:00:00Z', to: '2026-10-17T06:00:00Z', days: 30, source: 'days' },
+ current: {
+ answers: 107,
+ mentions: 107,
+ occurrences: 320,
+ positive: 43,
+ negative: 21,
+ position_sum: 188,
+ position_count: 107,
+ prompts: 5,
+ prompts_with_mentions: 5,
+ last_answer_at: '2026-10-16T11:28:06Z',
+ },
+ previous: null,
+ platforms: [
+ {
+ platform: 'gemini-web',
+ answers: 7,
+ mentions: 7,
+ positive: 2,
+ negative: 2,
+ prev_answers: 7,
+ prev_mentions: 7,
+ prev_positive: 2,
+ prev_negative: 2,
+ },
+ ],
+ daily: [{ day: '2026-10-16', answers: 4, mentions: 4, positive: 2, negative: 1 }],
+ competitors: [
+ {
+ competitor_id: 'c1',
+ name: 'Crema Club',
+ mentions: 80,
+ co_mentions: 80,
+ prev_mentions: 27,
+ },
+ ],
+};
+
+describe('parseMentionsOverview', () => {
+ it("maps the function's jsonb to the page's shape", () => {
+ const o = parseMentionsOverview(raw)!;
+ expect(o.window).toEqual({
+ from: '2026-09-17T06:00:00Z',
+ to: '2026-10-17T06:00:00Z',
+ days: 30,
+ source: 'days',
+ });
+ expect(o.current).toMatchObject({
+ answers: 107,
+ mentions: 107,
+ occurrences: 320,
+ positionSum: 188,
+ promptsWithMentions: 5,
+ lastAnswerAt: '2026-10-16T11:28:06Z',
+ });
+ expect(o.platforms[0]).toEqual({
+ platform: 'gemini-web',
+ answers: 7,
+ mentions: 7,
+ 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 },
+ ]);
+ expect(o.competitors).toEqual([
+ {
+ competitorId: 'c1',
+ name: 'Crema Club',
+ mentions: 80,
+ coMentions: 80,
+ previousMentions: 27,
+ },
+ ]);
+ });
+
+ it('reads an empty window as zeros, not missing figures', () => {
+ const o = parseMentionsOverview(raw)!;
+ expect(o.previous).toMatchObject({ answers: 0, mentions: 0, prompts: 0, lastAnswerAt: null });
+ });
+
+ it('is null when there is nothing to read', () => {
+ expect(parseMentionsOverview(null)).toBeNull();
+ });
+});
+
+describe('the Overview metrics', () => {
+ // The spec's acceptance fixture (§16): one prompt over 2 days on 4
+ // platforms is 8 answers; 6 of them name the brand.
+ it('counts mentions per answer and the rate over the answers', () => {
+ const fixture = { answers: 8, mentions: 6 };
+ expect(fixture.mentions).toBe(6);
+ expect(mentionRate(fixture)).toBe(75);
+ expect(mentionRate({ answers: 0, mentions: 0 })).toBeNull();
+ });
+
+ it('splits the tone into shares that add up to 100, neutral kept', () => {
+ const split = sentimentSplit({ mentions: 50, positive: 24, negative: 7 })!;
+ expect(split).toEqual({ positive: 48, neutral: 38, negative: 14, n: 50 });
+ expect(split.positive + split.neutral + split.negative).toBeCloseTo(100, 10);
+ expect(sentimentSplit({ mentions: 0, positive: 0, negative: 0 })).toBeNull();
+ });
+
+ it('nets positive against negative, −100 to +100', () => {
+ expect(netSentiment({ mentions: 50, positive: 24, negative: 7 })).toBe(34);
+ expect(netSentiment({ mentions: 4, positive: 0, negative: 4 })).toBe(-100);
+ expect(netSentiment({ mentions: 0, positive: 0, negative: 0 })).toBeNull();
+ });
+
+ it('marks fewer than 20 mentions as a low sample', () => {
+ expect(isLowSample({ mentions: 19 })).toBe(true);
+ expect(isLowSample({ mentions: 20 })).toBe(false);
+ });
+
+ it('averages the position over the answers that placed the brand', () => {
+ expect(averagePosition({ positionSum: 188, positionCount: 107 })).toBeCloseTo(1.757, 3);
+ expect(averagePosition({ positionSum: 0, positionCount: 0 })).toBeNull();
+ });
+});
diff --git a/web/src/lib/mentions-overview.ts b/web/src/lib/mentions-overview.ts
new file mode 100644
index 000000000..d28585d29
--- /dev/null
+++ b/web/src/lib/mentions-overview.ts
@@ -0,0 +1,196 @@
+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';
+
+/**
+ * The Mentions & Sentiment Overview's figures (MS-06), as mentions_overview
+ * (00157) returns them for a window and the window of the same length before
+ * it, and the metrics the page derives from them. Definitions follow the spec
+ * (§5): a mention is an answer naming the brand at least once (naming it
+ * twice is still one mention; occurrences are counted apart), and sentiment is
+ * the tone of those answers toward the brand.
+ */
+
+export interface MentionTotals {
+ /** Answers tracked in the window. */
+ answers: number;
+ /** Answers naming the brand at least once. */
+ mentions: number;
+ /** Times the brand is named, over all answers. */
+ occurrences: number;
+ /** Mentions with a positive or negative tone; neutral is the rest. */
+ positive: number;
+ negative: number;
+ /** The brand's position among the brands an answer names (1 = first). */
+ positionSum: number;
+ positionCount: number;
+ /** Prompts answered, and prompts with at least one mention. */
+ prompts: number;
+ promptsWithMentions: number;
+ lastAnswerAt: string | null;
+}
+
+export interface MentionPlatformRow {
+ platform: string;
+ answers: number;
+ mentions: number;
+ positive: number;
+ negative: number;
+ previous: Pick<MentionTotals, 'answers' | 'mentions' | 'positive' | 'negative'>;
+}
+
+export interface MentionDay {
+ /** UTC day, `YYYY-MM-DD`. */
+ day: string;
+ answers: number;
+ mentions: number;
+ positive: number;
+ negative: number;
+}
+
+export interface MentionCompetitorRow {
+ competitorId: string;
+ name: string;
+ /** Answers naming the competitor. */
+ mentions: number;
+ /** Of those, the answers naming your brand too. */
+ coMentions: number;
+ previousMentions: number;
+}
+
+export interface MentionsOverview {
+ window: {
+ from: string;
+ to: string;
+ days: number;
+ /** Under two days the answers were read directly; longer windows read whole UTC days. */
+ source: 'answers' | 'days';
+ };
+ current: MentionTotals;
+ previous: MentionTotals;
+ platforms: MentionPlatformRow[];
+ daily: MentionDay[];
+ competitors: MentionCompetitorRow[];
+}
+
+const EMPTY_TOTALS: MentionTotals = {
+ answers: 0,
+ mentions: 0,
+ occurrences: 0,
+ positive: 0,
+ negative: 0,
+ positionSum: 0,
+ positionCount: 0,
+ prompts: 0,
+ promptsWithMentions: 0,
+ lastAnswerAt: null,
+};
+
+type Raw = Record<string, unknown>;
+const num = (r: Raw | undefined, key: string): number => Number(r?.[key] ?? 0) || 0;
+const rows = (value: unknown): Raw[] => (Array.isArray(value) ? (value as Raw[]) : []);
+
+function totals(r: Raw | null | undefined): MentionTotals {
+ if (!r) return EMPTY_TOTALS;
+ return {
+ answers: num(r, 'answers'),
+ mentions: num(r, 'mentions'),
+ occurrences: num(r, 'occurrences'),
+ positive: num(r, 'positive'),
+ negative: num(r, 'negative'),
+ positionSum: num(r, 'position_sum'),
+ positionCount: num(r, 'position_count'),
+ prompts: num(r, 'prompts'),
+ promptsWithMentions: num(r, 'prompts_with_mentions'),
+ lastAnswerAt: typeof r.last_answer_at === 'string' ? r.last_answer_at : 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).
+ */
+export function parseMentionsOverview(raw: unknown): MentionsOverview | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const r = raw as Raw;
+ const w = (r.window ?? {}) as Raw;
+ return {
+ window: {
+ from: String(w.from ?? ''),
+ to: String(w.to ?? ''),
+ days: num(w, 'days'),
+ source: w.source === 'answers' ? 'answers' : 'days',
+ },
+ current: totals(r.current as Raw | null),
+ previous: totals(r.previous as Raw | null),
+ platforms: rows(r.platforms).map((p) => ({
+ platform: String(p.platform ?? ''),
+ answers: num(p, 'answers'),
+ mentions: num(p, 'mentions'),
+ positive: num(p, 'positive'),
+ negative: num(p, 'negative'),
+ previous: {
+ answers: num(p, 'prev_answers'),
+ mentions: num(p, 'prev_mentions'),
+ positive: num(p, 'prev_positive'),
+ negative: num(p, 'prev_negative'),
+ },
+ })),
+ daily: rows(r.daily).map((d) => ({
+ day: String(d.day ?? ''),
+ answers: num(d, 'answers'),
+ mentions: num(d, 'mentions'),
+ positive: num(d, 'positive'),
+ negative: num(d, 'negative'),
+ })),
+ competitors: rows(r.competitors).map((c) => ({
+ competitorId: String(c.competitor_id ?? ''),
+ name: String(c.name ?? ''),
+ mentions: num(c, 'mentions'),
+ coMentions: num(c, 'co_mentions'),
+ previousMentions: num(c, 'prev_mentions'),
+ })),
+ };
+}
+
+type Counts = Pick<MentionTotals, 'answers' | 'mentions' | 'positive' | 'negative'>;
+
+/** Fewer mentions than this and sentiment is marked "Low sample" (spec §2). */
+export const LOW_SAMPLE_MENTIONS = LOW_SAMPLE_ANSWERS;
+
+/** Answers naming the brand, as a percentage of the answers; null with no answers. */
+export function mentionRate(t: Pick<Counts, 'answers' | 'mentions'>): number | null {
+ return t.answers > 0 ? (t.mentions * 100) / t.answers : null;
+}
+
+/**
+ * The tone of the mentions as percentages that add up to 100, neutral
+ * included (never folded into the others), with n, the mentions behind them.
+ * Null with no mentions.
+ */
+export function sentimentSplit(
+ t: Omit<Counts, 'answers'>,
+): { positive: number; neutral: number; negative: number; n: number } | null {
+ if (t.mentions <= 0) return null;
+ // Multiplied first, so whole percentages stay whole (7/50 → 14, not 14.000…2).
+ const share = (count: number) => (count * 100) / t.mentions;
+ return {
+ positive: share(t.positive),
+ neutral: share(t.mentions - t.positive - t.negative),
+ negative: share(t.negative),
+ n: t.mentions,
+ };
+}
+
+/** %positive − %negative of the mentions, −100…+100; null with no mentions. */
+export function netSentiment(t: Omit<Counts, 'answers'>): number | null {
+ const split = sentimentSplit(t);
+ return split ? split.positive - split.negative : null;
+}
+
+export function isLowSample(t: Pick<Counts, 'mentions'>): boolean {
+ return t.mentions < LOW_SAMPLE_MENTIONS;
+}
+
+/** The brand's average position when named (1 = first); null when never placed. */
+export function averagePosition(t: Pick<MentionTotals, 'positionSum' | 'positionCount'>) {
+ return t.positionCount > 0 ? t.positionSum / t.positionCount : null;
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 33fe9633a..0baa77342 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3260,6 +3260,18 @@ export type Database = {
}
Returns: Json
}
+ mentions_overview: {
+ Args: {
+ p_brand_id: string
+ p_date_from: string
+ p_date_to?: string
+ p_platform?: string
+ p_region?: string
+ p_search?: string
+ p_topic_id?: string
+ }
+ Returns: Json
+ }
normalize_page_path: { Args: { p_url: string }; Returns: string }
import_prompts: {
Args: {