Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(topics): read the overview over a date range, fast enough not to time out (#1106)
Cihan7dc99d16cf57
diff --git a/supabase/migrations/00156_topics_overview_window.sql b/supabase/migrations/00156_topics_overview_window.sqlnew file mode 100644index 000000000..a2e2965c0--- /dev/null+++ b/supabase/migrations/00156_topics_overview_window.sql@@ -0,0 +1,302 @@+-- The Topics overview for any window, for its date range (24h, 7d, 30d, 90d,+-- custom), fast enough not to fail.+--+-- topics_overview_aggregates (00057, 00098) reads fixed windows from the raw+-- answers: 30 days for the table, the last 7 days against the 7 before for+-- the change, 14 days for the trend. On the largest brand it now runs past the+-- authenticated role's 8 s statement timeout, so the page fails to load+-- ("Failed to load topics"; the request ends in a 500 after ~9 s).+--+-- This takes the window instead: the table's figures cover it, the change+-- compares it with the window of the same length just before, and the trend+-- has a point per UTC day of it. It reads in two ways:+--+-- * A window under two days (24 hours, the page's default) reads its+-- answers, and the previous window's, directly: two days of answers are a+-- small read, and today's run may not be in the rollups yet. Its+-- competitor share comes from those answers' competitor_mentions. It has+-- no trend: one day has no line to draw.+-- * A longer window reads whole UTC days from the daily rollups the Insights+-- page reads (insights_prompt_daily, 00130; insights_competitor_prompt_daily,+-- 00098), counted back from the window's end, the rule 00098 used for the+-- competitor share over 30 days: a rolling 7 days is today and the 6 days+-- before. A day enters the rollups when its run completes, and a sweep+-- re-refreshes the last days every morning (server/src/lib/insights-rollups.js).+-- Only each topic's last answer time is read from the answers, as an+-- index-only scan of idx_prompt_results_brand_created_cover.+--+-- Prompts take their history to the topic they are in now, as before.+-- chatgpt-shopping stays out (#155); the rollups leave it out too.+--+-- As 00147, 00148, 00152 and 00153 do, it is plpgsql with force_custom_plan,+-- so every call is planned with its real window, and work_mem; and security+-- definer with the organization check made explicit (the same rule as+-- prompt_results' RLS), returning nothing for a caller outside the brand's+-- organization. topics_overview_aggregates stays for a web build deployed+-- before this migration, which falls back to it.++create or replace function public.topics_overview_window(+ p_brand_id uuid,+ p_date_from timestamptz,+ p_date_to timestamptz default null+)+returns table (+ topic_id uuid,+ answers bigint,+ mention_answers bigint,+ citation_answers bigint,+ pos_sum double precision,+ pos_n bigint,+ prev_answers bigint,+ prev_mention_answers bigint,+ prev_citation_answers bigint,+ prev_pos_sum double precision,+ prev_pos_n bigint,+ total_mentions bigint,+ total_citations bigint,+ comp_mentions bigint,+ active_prompts bigint,+ visible_prompts bigint,+ last_run_at timestamptz,+ competitors jsonb,+ daily 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 $$+#variable_conflict use_column+declare+ v_to timestamptz := coalesce(p_date_to, now());+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));+ -- Whole days the window spans, at least one, with an hour of slack: a+ -- rolling 7 days starts where the browser put it and ends at now(), a+ -- moment later, which must not make it 8 (lib/topic-trend.ts counts alike).+ v_days integer;+ -- The rollup days of a longer window, and of the window before it.+ v_day_to date;+ v_day_from date;+ v_prev_from date;+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;+ end if;++ v_days := greatest(1, ceil(extract(epoch from (v_to - v_from)) / 86400.0 - 1.0 / 24)::integer);++ if v_days < 2 then+ return query+ with+ rows as (+ select p.topic_id,+ pr.prompt_id,+ pr.created_at,+ pr.competitor_mentions,+ (pr.created_at >= v_from) as in_window,+ coalesce(pr.mention_count, 0) as mentions,+ coalesce(pr.citation_count, 0) as citations,+ pr.mention_position,+ (coalesce(pr.mention_count, 0) > 0+ or coalesce(pr.citation_count, 0) > 0) as visible+ from public.prompt_results pr+ join public.prompts p on p.id = pr.prompt_id+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where pr.brand_id = p_brand_id+ and ps.brand_id = p_brand_id+ and p.topic_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from - (v_to - v_from)+ and pr.created_at <= v_to+ ),+ comps as (+ select r.topic_id,+ cm.value->>'competitor_id' as competitor_id,+ min(c.name) as name,+ sum(coalesce((cm.value->>'mention_count')::int, 0))::bigint as mentions+ from rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ join public.competitors c on c.id::text = cm.value->>'competitor_id' and c.brand_id = p_brand_id+ where r.in_window+ group by r.topic_id, cm.value->>'competitor_id'+ having sum(coalesce((cm.value->>'mention_count')::int, 0)) > 0+ ),+ comp_totals as (+ select topic_id,+ sum(mentions)::bigint as comp_mentions,+ jsonb_object_agg(competitor_id, jsonb_build_object('name', name, 'sov', mentions))+ as competitors+ from comps+ group by topic_id+ ),+ main as (+ select r.topic_id,+ count(*) filter (where r.in_window)::bigint as answers,+ count(*) filter (where r.in_window and r.mentions > 0)::bigint as mention_answers,+ count(*) filter (where r.in_window and r.citations > 0)::bigint as citation_answers,+ coalesce(sum(1.0 / r.mention_position)+ filter (where r.in_window and r.mention_position > 0), 0)::double precision+ as pos_sum,+ count(*) filter (where r.in_window and r.mention_position > 0)::bigint+ as pos_n,+ count(*) filter (where not r.in_window)::bigint as prev_answers,+ count(*) filter (where not r.in_window and r.mentions > 0)::bigint as prev_mention_answers,+ count(*) filter (where not r.in_window and r.citations > 0)::bigint as prev_citation_answers,+ coalesce(sum(1.0 / r.mention_position)+ filter (where not r.in_window and r.mention_position > 0), 0)::double precision+ as prev_pos_sum,+ count(*) filter (where not r.in_window and r.mention_position > 0)::bigint+ as prev_pos_n,+ coalesce(sum(r.mentions) filter (where r.in_window), 0)::bigint as total_mentions,+ coalesce(sum(r.citations) filter (where r.in_window), 0)::bigint as total_citations,+ count(distinct r.prompt_id) filter (where r.in_window)::bigint as active_prompts,+ count(distinct r.prompt_id) filter (where r.in_window and r.visible)::bigint+ as visible_prompts,+ max(r.created_at) filter (where r.in_window) as last_run_at+ from rows r+ group by r.topic_id+ )+ select m.topic_id,+ m.answers, m.mention_answers, m.citation_answers, m.pos_sum, m.pos_n,+ m.prev_answers, m.prev_mention_answers, m.prev_citation_answers, m.prev_pos_sum, m.prev_pos_n,+ m.total_mentions, m.total_citations,+ coalesce(ct.comp_mentions, 0)::bigint,+ m.active_prompts, m.visible_prompts, m.last_run_at,+ coalesce(ct.competitors, '{}'::jsonb),+ '{}'::jsonb+ from main m+ left join comp_totals ct on ct.topic_id = m.topic_id+ where m.answers > 0;+ return;+ end if;++ 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;++ return query+ with+ topic_prompts as (+ select p.id as prompt_id, p.topic_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 not null+ ),+ days as (+ select tp.topic_id,+ d.prompt_id,+ d.day,+ (d.day >= v_day_from) as in_window,+ d.answer_count,+ d.mention_answers,+ d.citation_answers,+ d.mentioning_answers,+ d.total_mentions,+ d.total_citations,+ d.sum_inv_position,+ d.position_count+ from public.insights_prompt_daily d+ join topic_prompts tp on tp.prompt_id = d.prompt_id+ where d.brand_id = p_brand_id+ and d.day between v_prev_from and v_day_to+ ),+ comps as (+ select tp.topic_id,+ cpd.competitor_id,+ min(c.name) as name,+ sum(cpd.mention_count)::bigint as mentions+ from public.insights_competitor_prompt_daily cpd+ join topic_prompts tp on tp.prompt_id = cpd.prompt_id+ join public.competitors c on c.id::text = cpd.competitor_id and c.brand_id = p_brand_id+ where cpd.brand_id = p_brand_id+ and cpd.day between v_day_from and v_day_to+ group by tp.topic_id, cpd.competitor_id+ having sum(cpd.mention_count) > 0+ ),+ comp_totals as (+ select topic_id,+ sum(mentions)::bigint as comp_mentions,+ jsonb_object_agg(competitor_id, jsonb_build_object('name', name, 'sov', mentions))+ as competitors+ from comps+ group by topic_id+ ),+ -- A point per UTC day, keyed as the client builds its keys+ -- (Date.toISOString()).+ daily as (+ select x.topic_id,+ jsonb_object_agg(x.day, jsonb_build_object('visible', x.visible, 'count', x.count))+ as daily+ from (+ select topic_id,+ to_char(day, 'YYYY-MM-DD') as day,+ sum(mentioning_answers)::bigint as visible,+ sum(answer_count)::bigint as count+ from days+ where in_window+ group by topic_id, day+ ) x+ group by x.topic_id+ ),+ -- Each topic's last answer in the window: the covering index holds+ -- (brand_id, created_at) with the prompt, so this never reads the rows.+ last_runs as (+ select tp.topic_id, max(pr.created_at) as last_run_at+ from public.prompt_results pr+ join topic_prompts tp on tp.prompt_id = pr.prompt_id+ where pr.brand_id = p_brand_id+ and pr.created_at >= v_from+ and pr.created_at <= v_to+ and pr.platform <> 'chatgpt-shopping'+ group by tp.topic_id+ ),+ main as (+ select topic_id,+ coalesce(sum(answer_count) filter (where in_window), 0)::bigint as answers,+ coalesce(sum(mention_answers) filter (where in_window), 0)::bigint as mention_answers,+ coalesce(sum(citation_answers) filter (where in_window), 0)::bigint as citation_answers,+ coalesce(sum(sum_inv_position) filter (where in_window), 0)::double precision+ as pos_sum,+ coalesce(sum(position_count) filter (where in_window), 0)::bigint as pos_n,+ coalesce(sum(answer_count) filter (where not in_window), 0)::bigint as prev_answers,+ coalesce(sum(mention_answers) filter (where not in_window), 0)::bigint as prev_mention_answers,+ coalesce(sum(citation_answers) filter (where not in_window), 0)::bigint as prev_citation_answers,+ coalesce(sum(sum_inv_position) filter (where not in_window), 0)::double precision+ as prev_pos_sum,+ coalesce(sum(position_count) filter (where not in_window), 0)::bigint as prev_pos_n,+ coalesce(sum(total_mentions) filter (where in_window), 0)::bigint as total_mentions,+ coalesce(sum(total_citations) filter (where in_window), 0)::bigint as total_citations,+ count(distinct prompt_id) filter (where in_window and answer_count > 0)::bigint+ as active_prompts,+ count(distinct prompt_id) filter (where in_window and mentioning_answers > 0)::bigint+ as visible_prompts+ from days+ group by topic_id+ )+ select m.topic_id,+ m.answers, m.mention_answers, m.citation_answers, m.pos_sum, m.pos_n,+ m.prev_answers, m.prev_mention_answers, m.prev_citation_answers, m.prev_pos_sum, m.prev_pos_n,+ m.total_mentions, m.total_citations,+ coalesce(ct.comp_mentions, 0)::bigint,+ m.active_prompts, m.visible_prompts, lr.last_run_at,+ coalesce(ct.competitors, '{}'::jsonb),+ coalesce(dl.daily, '{}'::jsonb)+ from main m+ left join comp_totals ct on ct.topic_id = m.topic_id+ left join daily dl on dl.topic_id = m.topic_id+ left join last_runs lr on lr.topic_id = m.topic_id+ where m.answers > 0;+end;+$$;++revoke execute on function public.topics_overview_window(uuid, timestamptz, timestamptz)+ from public, anon;+grant execute on function public.topics_overview_window(uuid, timestamptz, timestamptz)+ to authenticated, service_role;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 3c5fcc2c0..96cba20c2 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -19261,3 +19261,309 @@ set ai_volume_multiplier = 0.450,est_ai_volume = round(total_google_volume * 0.450)::integerwhere ai_volume_multiplier = 0.150;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00156_topics_overview_window.sql+-- ─────────────────────────────────────────────────────────────────────────+-- The Topics overview for any window, for its date range (24h, 7d, 30d, 90d,+-- custom), fast enough not to fail.+--+-- topics_overview_aggregates (00057, 00098) reads fixed windows from the raw+-- answers: 30 days for the table, the last 7 days against the 7 before for+-- the change, 14 days for the trend. On the largest brand it now runs past the+-- authenticated role's 8 s statement timeout, so the page fails to load+-- ("Failed to load topics"; the request ends in a 500 after ~9 s).+--+-- This takes the window instead: the table's figures cover it, the change+-- compares it with the window of the same length just before, and the trend+-- has a point per UTC day of it. It reads in two ways:+--+-- * A window under two days (24 hours, the page's default) reads its+-- answers, and the previous window's, directly: two days of answers are a+-- small read, and today's run may not be in the rollups yet. Its+-- competitor share comes from those answers' competitor_mentions. It has+-- no trend: one day has no line to draw.+-- * A longer window reads whole UTC days from the daily rollups the Insights+-- page reads (insights_prompt_daily, 00130; insights_competitor_prompt_daily,+-- 00098), counted back from the window's end, the rule 00098 used for the+-- competitor share over 30 days: a rolling 7 days is today and the 6 days+-- before. A day enters the rollups when its run completes, and a sweep+-- re-refreshes the last days every morning (server/src/lib/insights-rollups.js).+-- Only each topic's last answer time is read from the answers, as an+-- index-only scan of idx_prompt_results_brand_created_cover.+--+-- Prompts take their history to the topic they are in now, as before.+-- chatgpt-shopping stays out (#155); the rollups leave it out too.+--+-- As 00147, 00148, 00152 and 00153 do, it is plpgsql with force_custom_plan,+-- so every call is planned with its real window, and work_mem; and security+-- definer with the organization check made explicit (the same rule as+-- prompt_results' RLS), returning nothing for a caller outside the brand's+-- organization. topics_overview_aggregates stays for a web build deployed+-- before this migration, which falls back to it.++create or replace function public.topics_overview_window(+ p_brand_id uuid,+ p_date_from timestamptz,+ p_date_to timestamptz default null+)+returns table (+ topic_id uuid,+ answers bigint,+ mention_answers bigint,+ citation_answers bigint,+ pos_sum double precision,+ pos_n bigint,+ prev_answers bigint,+ prev_mention_answers bigint,+ prev_citation_answers bigint,+ prev_pos_sum double precision,+ prev_pos_n bigint,+ total_mentions bigint,+ total_citations bigint,+ comp_mentions bigint,+ active_prompts bigint,+ visible_prompts bigint,+ last_run_at timestamptz,+ competitors jsonb,+ daily 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 $$+#variable_conflict use_column+declare+ v_to timestamptz := coalesce(p_date_to, now());+ v_from timestamptz := least(p_date_from, coalesce(p_date_to, now()));+ -- Whole days the window spans, at least one, with an hour of slack: a+ -- rolling 7 days starts where the browser put it and ends at now(), a+ -- moment later, which must not make it 8 (lib/topic-trend.ts counts alike).+ v_days integer;+ -- The rollup days of a longer window, and of the window before it.+ v_day_to date;+ v_day_from date;+ v_prev_from date;+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;+ end if;++ v_days := greatest(1, ceil(extract(epoch from (v_to - v_from)) / 86400.0 - 1.0 / 24)::integer);++ if v_days < 2 then+ return query+ with+ rows as (+ select p.topic_id,+ pr.prompt_id,+ pr.created_at,+ pr.competitor_mentions,+ (pr.created_at >= v_from) as in_window,+ coalesce(pr.mention_count, 0) as mentions,+ coalesce(pr.citation_count, 0) as citations,+ pr.mention_position,+ (coalesce(pr.mention_count, 0) > 0+ or coalesce(pr.citation_count, 0) > 0) as visible+ from public.prompt_results pr+ join public.prompts p on p.id = pr.prompt_id+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ where pr.brand_id = p_brand_id+ and ps.brand_id = p_brand_id+ and p.topic_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from - (v_to - v_from)+ and pr.created_at <= v_to+ ),+ comps as (+ select r.topic_id,+ cm.value->>'competitor_id' as competitor_id,+ min(c.name) as name,+ sum(coalesce((cm.value->>'mention_count')::int, 0))::bigint as mentions+ from rows r+ cross join lateral jsonb_array_elements(coalesce(r.competitor_mentions, '[]'::jsonb)) cm+ join public.competitors c on c.id::text = cm.value->>'competitor_id' and c.brand_id = p_brand_id+ where r.in_window+ group by r.topic_id, cm.value->>'competitor_id'+ having sum(coalesce((cm.value->>'mention_count')::int, 0)) > 0+ ),+ comp_totals as (+ select topic_id,+ sum(mentions)::bigint as comp_mentions,+ jsonb_object_agg(competitor_id, jsonb_build_object('name', name, 'sov', mentions))+ as competitors+ from comps+ group by topic_id+ ),+ main as (+ select r.topic_id,+ count(*) filter (where r.in_window)::bigint as answers,+ count(*) filter (where r.in_window and r.mentions > 0)::bigint as mention_answers,+ count(*) filter (where r.in_window and r.citations > 0)::bigint as citation_answers,+ coalesce(sum(1.0 / r.mention_position)+ filter (where r.in_window and r.mention_position > 0), 0)::double precision+ as pos_sum,+ count(*) filter (where r.in_window and r.mention_position > 0)::bigint+ as pos_n,+ count(*) filter (where not r.in_window)::bigint as prev_answers,+ count(*) filter (where not r.in_window and r.mentions > 0)::bigint as prev_mention_answers,+ count(*) filter (where not r.in_window and r.citations > 0)::bigint as prev_citation_answers,+ coalesce(sum(1.0 / r.mention_position)+ filter (where not r.in_window and r.mention_position > 0), 0)::double precision+ as prev_pos_sum,+ count(*) filter (where not r.in_window and r.mention_position > 0)::bigint+ as prev_pos_n,+ coalesce(sum(r.mentions) filter (where r.in_window), 0)::bigint as total_mentions,+ coalesce(sum(r.citations) filter (where r.in_window), 0)::bigint as total_citations,+ count(distinct r.prompt_id) filter (where r.in_window)::bigint as active_prompts,+ count(distinct r.prompt_id) filter (where r.in_window and r.visible)::bigint+ as visible_prompts,+ max(r.created_at) filter (where r.in_window) as last_run_at+ from rows r+ group by r.topic_id+ )+ select m.topic_id,+ m.answers, m.mention_answers, m.citation_answers, m.pos_sum, m.pos_n,+ m.prev_answers, m.prev_mention_answers, m.prev_citation_answers, m.prev_pos_sum, m.prev_pos_n,+ m.total_mentions, m.total_citations,+ coalesce(ct.comp_mentions, 0)::bigint,+ m.active_prompts, m.visible_prompts, m.last_run_at,+ coalesce(ct.competitors, '{}'::jsonb),+ '{}'::jsonb+ from main m+ left join comp_totals ct on ct.topic_id = m.topic_id+ where m.answers > 0;+ return;+ end if;++ 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;++ return query+ with+ topic_prompts as (+ select p.id as prompt_id, p.topic_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 not null+ ),+ days as (+ select tp.topic_id,+ d.prompt_id,+ d.day,+ (d.day >= v_day_from) as in_window,+ d.answer_count,+ d.mention_answers,+ d.citation_answers,+ d.mentioning_answers,+ d.total_mentions,+ d.total_citations,+ d.sum_inv_position,+ d.position_count+ from public.insights_prompt_daily d+ join topic_prompts tp on tp.prompt_id = d.prompt_id+ where d.brand_id = p_brand_id+ and d.day between v_prev_from and v_day_to+ ),+ comps as (+ select tp.topic_id,+ cpd.competitor_id,+ min(c.name) as name,+ sum(cpd.mention_count)::bigint as mentions+ from public.insights_competitor_prompt_daily cpd+ join topic_prompts tp on tp.prompt_id = cpd.prompt_id+ join public.competitors c on c.id::text = cpd.competitor_id and c.brand_id = p_brand_id+ where cpd.brand_id = p_brand_id+ and cpd.day between v_day_from and v_day_to+ group by tp.topic_id, cpd.competitor_id+ having sum(cpd.mention_count) > 0+ ),+ comp_totals as (+ select topic_id,+ sum(mentions)::bigint as comp_mentions,+ jsonb_object_agg(competitor_id, jsonb_build_object('name', name, 'sov', mentions))+ as competitors+ from comps+ group by topic_id+ ),+ -- A point per UTC day, keyed as the client builds its keys+ -- (Date.toISOString()).+ daily as (+ select x.topic_id,+ jsonb_object_agg(x.day, jsonb_build_object('visible', x.visible, 'count', x.count))+ as daily+ from (+ select topic_id,+ to_char(day, 'YYYY-MM-DD') as day,+ sum(mentioning_answers)::bigint as visible,+ sum(answer_count)::bigint as count+ from days+ where in_window+ group by topic_id, day+ ) x+ group by x.topic_id+ ),+ -- Each topic's last answer in the window: the covering index holds+ -- (brand_id, created_at) with the prompt, so this never reads the rows.+ last_runs as (+ select tp.topic_id, max(pr.created_at) as last_run_at+ from public.prompt_results pr+ join topic_prompts tp on tp.prompt_id = pr.prompt_id+ where pr.brand_id = p_brand_id+ and pr.created_at >= v_from+ and pr.created_at <= v_to+ and pr.platform <> 'chatgpt-shopping'+ group by tp.topic_id+ ),+ main as (+ select topic_id,+ coalesce(sum(answer_count) filter (where in_window), 0)::bigint as answers,+ coalesce(sum(mention_answers) filter (where in_window), 0)::bigint as mention_answers,+ coalesce(sum(citation_answers) filter (where in_window), 0)::bigint as citation_answers,+ coalesce(sum(sum_inv_position) filter (where in_window), 0)::double precision+ as pos_sum,+ coalesce(sum(position_count) filter (where in_window), 0)::bigint as pos_n,+ coalesce(sum(answer_count) filter (where not in_window), 0)::bigint as prev_answers,+ coalesce(sum(mention_answers) filter (where not in_window), 0)::bigint as prev_mention_answers,+ coalesce(sum(citation_answers) filter (where not in_window), 0)::bigint as prev_citation_answers,+ coalesce(sum(sum_inv_position) filter (where not in_window), 0)::double precision+ as prev_pos_sum,+ coalesce(sum(position_count) filter (where not in_window), 0)::bigint as prev_pos_n,+ coalesce(sum(total_mentions) filter (where in_window), 0)::bigint as total_mentions,+ coalesce(sum(total_citations) filter (where in_window), 0)::bigint as total_citations,+ count(distinct prompt_id) filter (where in_window and answer_count > 0)::bigint+ as active_prompts,+ count(distinct prompt_id) filter (where in_window and mentioning_answers > 0)::bigint+ as visible_prompts+ from days+ group by topic_id+ )+ select m.topic_id,+ m.answers, m.mention_answers, m.citation_answers, m.pos_sum, m.pos_n,+ m.prev_answers, m.prev_mention_answers, m.prev_citation_answers, m.prev_pos_sum, m.prev_pos_n,+ m.total_mentions, m.total_citations,+ coalesce(ct.comp_mentions, 0)::bigint,+ m.active_prompts, m.visible_prompts, lr.last_run_at,+ coalesce(ct.competitors, '{}'::jsonb),+ coalesce(dl.daily, '{}'::jsonb)+ from main m+ left join comp_totals ct on ct.topic_id = m.topic_id+ left join daily dl on dl.topic_id = m.topic_id+ left join last_runs lr on lr.topic_id = m.topic_id+ where m.answers > 0;+end;+$$;++revoke execute on function public.topics_overview_window(uuid, timestamptz, timestamptz)+ from public, anon;+grant execute on function public.topics_overview_window(uuid, timestamptz, timestamptz)+ to authenticated, service_role;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex c8a2a5a39..e00fc61cf 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2444,7 +2444,7 @@"noBrandTitle": "No brand selected","noBrandBody": "Select a brand from the top switcher to view topic analytics.","title": "Topics",- "description": "Topic-level analytics across all tracked prompts (last 30 days)",+ "description": "Topic-level analytics across all tracked prompts","exportHint": "No topics yet - add topics or run a tracking job first.","manageTopics": "Manage topics","kpi": {@@ -2453,7 +2453,7 @@"allCategorised": "All prompts categorised","bestPerformer": "Best performer","biggestGap": "Biggest gap",- "topMover": "Top mover (7d)",+ "topMover": "Top mover","noDataYet": "No data yet","notEnoughData": "Not enough data"},@@ -2466,7 +2466,7 @@"columns": {"topic": "Topic","prompts": "Prompts",- "visibility": "Visibility (30d)",+ "visibility": "Visibility","sov": "SoV","mentions": "Mentions","citations": "Citations",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsxindex ca74b64fd..bcccf8273 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/topics/page.tsx@@ -1,11 +1,19 @@'use client';-import { useCallback, useEffect, useMemo, useState } from 'react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { Link } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';import { useUserRole } from '@/hooks/use-user-role';import { getTopicsOverview, type TopicOverviewRow } from '@/lib/actions/topic';+import { customUtcWindow } from '@/lib/topic-trend';+import { DateRangeFilter } from '@/components/filters/date-range-filter';+import {+ DEFAULT_PROMPT_RANGE_PRESET,+ PROMPT_RANGE_PRESETS,+ resolvePromptRange,+ type PromptRangePreset,+} from '@/config/prompt-options';import { TopicSuggestionsCard } from './_suggestions-card';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { createTopic } from '@/lib/actions/topic';@@ -224,6 +232,21 @@ export default function TopicsPage() {// Default matches the previous hard-coded order (#597): visibility descending.const [sortKey, setSortKey] = useState<TopicSortKey>('visibility');const [sortDir, setSortDir] = useState<SortDir>('desc');+ // The window the table covers, as on the Prompts page; opens on 24 hours.+ const [rangePreset, setRangePreset] = useState<PromptRangePreset>(DEFAULT_PROMPT_RANGE_PRESET);+ const [customFrom, setCustomFrom] = useState('');+ const [customTo, setCustomTo] = useState('');+ // A custom range is a window only once a bound is entered.+ const range = useMemo(+ () =>+ rangePreset === 'custom' && !customFrom && !customTo+ ? null+ : resolvePromptRange(rangePreset, { from: customFrom, to: customTo }),+ [rangePreset, customFrom, customTo],+ );+ // Only the latest request may fill the table: a slow 90-day read must not+ // land after the 24-hour one picked since.+ const requestRef = useRef(0);const handleSort = useCallback((key: TopicSortKey) => {@@ -239,20 +262,28 @@ export default function TopicsPage() {setLoading(false);return;}+ if (!range) return;+ const request = ++requestRef.current;setLoading(true);setError(null);try {- const data = await getTopicsOverview(activeBrandId);+ const window =+ rangePreset === 'custom'+ ? customUtcWindow(customFrom, customTo, range)+ : { from: range.from, to: range.to };+ const data = await getTopicsOverview(activeBrandId, window);+ if (request !== requestRef.current) return;setTopics(data.topics);setUnassignedPromptCount(data.unassignedPromptCount);} catch (err) {+ if (request !== requestRef.current) return;console.error('Failed to load topics overview', err);setError(err instanceof Error ? err.message : t('loadError'));toast.error(t('loadError'));} finally {- setLoading(false);+ if (request === requestRef.current) setLoading(false);}- }, [activeBrandId, t]);+ }, [activeBrandId, range, rangePreset, customFrom, customTo, t]);useEffect(() => {loadData();@@ -332,11 +363,11 @@ export default function TopicsPage() {const slug = activeBrand?.slug ?? 'brand';link.href = url;- link.download = `ansvisor_${slug}_topics_${date}.csv`;+ link.download = `ansvisor_${slug}_topics_${rangePreset}_${date}.csv`;link.click();URL.revokeObjectURL(url);- }, [activeBrand?.slug, canExport, topics]);+ }, [activeBrand?.slug, canExport, rangePreset, topics]);if (!activeBrandId) {return (@@ -457,6 +488,16 @@ export default function TopicsPage() {</div></div>+ <DateRangeFilter+ value={rangePreset}+ presets={PROMPT_RANGE_PRESETS}+ onChange={setRangePreset}+ from={customFrom}+ to={customTo}+ onFromChange={setCustomFrom}+ onToChange={setCustomTo}+ />+{/* KPIs */}{loading ? (<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">@@ -670,10 +711,13 @@ export default function TopicsPage() {{topic.totalCitations.toLocaleString()}</TableCell><TableCell>- {topic.trendSparkline.length > 0 &&- topic.trendSparkline.some((v) => v > 0) ? (+ {/* Under two days there is no line, only the change. */}+ {topic.trendSparkline.some((v) => v > 0) ||+ topic.visibilityChange !== null ? (<div className="flex items-center gap-2">- <Sparkline points={topic.trendSparkline} />+ {topic.trendSparkline.some((v) => v > 0) && (+ <Sparkline points={topic.trendSparkline} />+ )}{topic.visibilityChange !== null && topic.visibilityChange !== 0 && (<spanclassName={cn(diff --git a/web/src/lib/actions/topic.test.ts b/web/src/lib/actions/topic.test.tsnew file mode 100644index 000000000..50ba1342b--- /dev/null+++ b/web/src/lib/actions/topic.test.ts@@ -0,0 +1,141 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The Topics overview over the page's date range (00156): the window's+ * figures, the change against the window just before, and a trend point per+ * whole day; the fixed 30-day overview without a window, or where the+ * database doesn't have the windowed function yet.+ */++const DAY = 24 * 60 * 60 * 1000;+let calls: { fn: string; args: Record<string, unknown> }[] = [];+let windowRows: Record<string, unknown>[] | 'missing' = [];+let fixedRows: Record<string, unknown>[] = [];++const tables: Record<string, unknown[]> = {+ topics: [{ id: 't1', name: 'Espresso', created_at: '2026-01-01T00:00:00Z' }],+ prompt_sets: [{ id: 's1' }],+ prompts: [+ { id: 'p1', topic_id: 't1' },+ { id: 'p2', topic_id: 't1' },+ ],+};++/** A query builder whose every call chains, resolving to the table's rows. */+function query(table: string): unknown {+ const result = { data: tables[table] ?? [], error: null };+ const builder: unknown = new Proxy(+ {},+ {+ get: (_, prop) =>+ prop === 'then' ? (resolve: (value: unknown) => void) => resolve(result) : () => builder,+ },+ );+ return builder;+}++vi.mock('@/lib/supabase/server', () => ({+ createClient: vi.fn(async () => ({+ from: (table: string) => query(table),+ rpc: async (fn: string, args: Record<string, unknown>) => {+ calls.push({ fn, args });+ if (fn === 'topics_overview_window') {+ return windowRows === 'missing'+ ? { data: null, error: { code: 'PGRST202', message: 'not found' } }+ : { data: windowRows, error: null };+ }+ return { data: fixedRows, error: null };+ },+ })),+}));++const { getTopicsOverview } = await import('./topic');++const counts = (prefix: string, answers: number, mentions: number) => ({+ [`${prefix}answers`]: answers,+ [`${prefix}mention_answers`]: mentions,+ [`${prefix}citation_answers`]: 0,+ [`${prefix}pos_sum`]: 0,+ [`${prefix}pos_n`]: 0,+});++const shared = {+ topic_id: 't1',+ total_mentions: 6,+ total_citations: 2,+ comp_mentions: 4,+ active_prompts: 2,+ visible_prompts: 1,+ last_run_at: '2026-10-16T14:28:00Z',+ competitors: { c1: { name: 'Crema Club', sov: 4 } },+};++beforeEach(() => {+ calls = [];+ const today = new Date().toISOString().slice(0, 10);+ windowRows = [+ {+ ...shared,+ ...counts('', 10, 6),+ ...counts('prev_', 10, 2),+ daily: { [today]: { visible: 3, count: 4 } },+ },+ ];+ fixedRows = [+ {+ ...shared,+ ...counts('', 30, 9),+ ...counts('cur_', 10, 6),+ ...counts('prev_', 10, 2),+ daily: {},+ },+ ];+});++describe('getTopicsOverview', () => {+ it('reads the window and compares it with the window of the same length before it', async () => {+ const from = new Date(Date.now() - 7 * DAY).toISOString();+ const summary = await getTopicsOverview('b1', { from });++ expect(calls.map((c) => c.fn)).toEqual(['topics_overview_window']);+ expect(calls[0].args).toMatchObject({ p_brand_id: 'b1', p_date_from: from });+ const [row] = summary.topics;+ expect(row.promptCount).toBe(2);+ expect(row.totalMentions).toBe(6);+ // 6 mentions of 10 against 2 of 10: up.+ expect(row.visibilityChange).toBeGreaterThan(0);+ expect(row.shareOfVoice).toBe(60);+ // Seven whole days, today last, today's share drawn.+ expect(summary.trendDays).toHaveLength(7);+ expect(row.trendSparkline).toHaveLength(7);+ expect(row.trendSparkline.at(-1)).toBe(75);+ });++ it('draws no trend for a 24-hour window, only the change', async () => {+ const summary = await getTopicsOverview('b1', {+ from: new Date(Date.now() - DAY).toISOString(),+ });+ expect(summary.trendDays).toEqual([]);+ expect(summary.topics[0].trendSparkline).toEqual([]);+ expect(summary.topics[0].visibilityChange).not.toBeNull();+ });++ it('falls back to the fixed overview where the database has no windowed function yet', async () => {+ windowRows = 'missing';+ const summary = await getTopicsOverview('b1', {+ from: new Date(Date.now() - DAY).toISOString(),+ });+ expect(calls.map((c) => c.fn)).toEqual([+ 'topics_overview_window',+ 'topics_overview_aggregates',+ ]);+ expect(summary.trendDays).toHaveLength(14);+ expect(summary.topics[0].totalMentions).toBe(6);+ });++ it('reads the fixed 30-day overview without a window', async () => {+ const summary = await getTopicsOverview('b1');+ expect(calls.map((c) => c.fn)).toEqual(['topics_overview_aggregates']);+ expect(summary.trendDays).toHaveLength(14);+ });+});diff --git a/web/src/lib/actions/topic.ts b/web/src/lib/actions/topic.tsindex 579ea44d5..a870019d0 100644--- a/web/src/lib/actions/topic.ts+++ b/web/src/lib/actions/topic.ts@@ -4,6 +4,9 @@ import { createClient } from '@/lib/supabase/server';import { computeAiVisibilityScore } from '@/lib/visibility-score';import { API_BASE_URL } from '@/config/api';import type { Topic } from '@/types';+import { DAY_MS, topicTrendDays, type TopicsWindow } from '@/lib/topic-trend';++export type { TopicsWindow } from '@/lib/topic-trend';function mapTopicRow(row: Record<string, unknown>): Topic {return {@@ -126,31 +129,129 @@ export interface TopicOverviewRow {visiblePrompts: number;/** Distinct prompts that produced results in the window (rate denominator). */activePrompts: number;- /** Rate difference in points: (current 7d) − (previous 7d). */+ /**+ * Score difference in points: the window against the window of the same+ * length just before it. Without a window, the last 7 days against the 7+ * before.+ */visibilityChange: number | null;totalMentions: number;totalCitations: number;shareOfVoice: number;topCompetitor: { name: string; sov: number } | null;lastRunAt: string | null;+ /** A point per day of `TopicOverviewSummary.trendDays`; empty when it is. */trendSparkline: number[];}export interface TopicOverviewSummary {topics: TopicOverviewRow[];unassignedPromptCount: number;+ /**+ * The UTC days the trend covers, oldest first: the window's whole days+ * counted back from its end, none for a window under two days (one day has+ * no line to draw). Without a window, the last 14 days.+ */+ trendDays: string[];+}++interface AnswerCounts {+ answers: number;+ mentionAnswers: number;+ citationAnswers: number;+ posSum: number;+ posN: number;+}++/** One topic's figures, whichever function read them. */+interface TopicAgg {+ /** The table's window. */+ window: AnswerCounts;+ /** The change compares these two. */+ current: AnswerCounts;+ previous: AnswerCounts;+ totalMentions: number;+ totalCitations: number;+ compMentions: number;+ activePrompts: number;+ visiblePrompts: number;+ lastRunAt: string | null;+ competitors: Record<string, { name: string; sov: number }>;+ daily: Record<string, { visible: number; count: number }>;+}++const num = (v: unknown) => Number(v ?? 0);+const counts = (r: Record<string, unknown>, prefix: string): AnswerCounts => ({+ answers: num(r[`${prefix}answers`]),+ mentionAnswers: num(r[`${prefix}mention_answers`]),+ citationAnswers: num(r[`${prefix}citation_answers`]),+ posSum: num(r[`${prefix}pos_sum`]),+ posN: num(r[`${prefix}pos_n`]),+});+const shared = (r: Record<string, unknown>) => ({+ totalMentions: num(r.total_mentions),+ totalCitations: num(r.total_citations),+ compMentions: num(r.comp_mentions),+ activePrompts: num(r.active_prompts),+ visiblePrompts: num(r.visible_prompts),+ lastRunAt: (r.last_run_at as string | null) ?? null,+ competitors: (r.competitors as TopicAgg['competitors'] | null) ?? {},+ daily: (r.daily as TopicAgg['daily'] | null) ?? {},+});++/**+ * The window's figures from topics_overview_window (00156); null when the+ * database doesn't have it yet (PostgREST's PGRST202), for a web build+ * deployed before the migration, which then reads the fixed overview.+ */+async function readWindowAggregates(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+ window: TopicsWindow,+): Promise<Map<string, TopicAgg> | null> {+ const { data, error } = await supabase.rpc('topics_overview_window', {+ p_brand_id: brandId,+ p_date_from: window.from,+ p_date_to: window.to ?? undefined,+ });+ if (error?.code === 'PGRST202') return null;+ if (error) throw new Error(error.message);+ return new Map(+ ((data ?? []) as unknown as Record<string, unknown>[]).map((r) => [+ r.topic_id as string,+ { window: counts(r, ''), current: counts(r, ''), previous: counts(r, 'prev_'), ...shared(r) },+ ]),+ );+}++/** The fixed overview (00057, 00098): 30 days, and 7 days against the 7 before. */+async function readFixedAggregates(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+): Promise<Map<string, TopicAgg>> {+ const { data, error } = await supabase.rpc('topics_overview_aggregates', {+ p_brand_id: brandId,+ });+ if (error) throw new Error(error.message);+ return new Map(+ ((data ?? []) as unknown as Record<string, unknown>[]).map((r) => [+ r.topic_id as string,+ {+ window: counts(r, ''),+ current: counts(r, 'cur_'),+ previous: counts(r, 'prev_'),+ ...shared(r),+ },+ ]),+ );}/**- * Aggregate per-topic analytics for a brand.- * Looks at last 30 days of prompt_results and derives visibility rate,- * mentions, citations, SoV, top competitor and a short sparkline per topic.- * Visibility uses the prompt-level rate from #490 (prompts appeared in ÷- * prompts with results), NOT the raw score average — the Topics page must- * read on the same scale as the Insights headline (#493). Change is- * (current 7d rate) − (previous 7d rate) in points. Like every analytical- * surface, chatgpt-shopping rows are excluded (#155) — totals here must- * agree with the Insights KPIs on the same 30d window (#464).+ * Aggregate per-topic analytics for a brand over a window (the page's date+ * range), or the last 30 days without one: visibility, mentions, citations,+ * SoV, top competitor and a trend per topic. Visibility is the AI Visibility+ * Score over the topic's answers, the Insights headline's blend (#493).+ * chatgpt-shopping rows are excluded (#155).*//*** The roster read still pages: PostgREST silently caps an un-paginated select@@ -164,13 +265,27 @@ export interface TopicOverviewSummary {const TOPIC_RESULTS_PAGE_SIZE = 1000;const TOPIC_PROMPTS_MAX_ROWS = 10_000;-export async function getTopicsOverview(brandId: string): Promise<TopicOverviewSummary> {+export async function getTopicsOverview(+ brandId: string,+ window?: TopicsWindow,+): Promise<TopicOverviewSummary> {const supabase = await createClient();// Only the sparkline's day keys are built here now; every window boundary// is resolved inside the aggregate, from the database's clock.const now = Date.now();+ // The aggregate needs only the brand, so it runs while the roster pages in.+ // One aggregate per brand instead of downloading the window (#721); only the+ // AI Visibility Score is computed here, over ~20 rows, so this page and the+ // Insights headline keep one implementation.+ const aggregates = (async () => {+ const windowed = window ? await readWindowAggregates(supabase, brandId, window) : null;+ return { windowed, aggByTopic: windowed ?? (await readFixedAggregates(supabase, brandId)) };+ })();+ // Settled here so a roster failure doesn't leave it rejecting unobserved.+ aggregates.catch(() => {});+const [topicsRes, setsRes] = await Promise.all([supabase.from('topics')@@ -221,59 +336,20 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewSpromptCountByTopic.set(p.topic_id, (promptCountByTopic.get(p.topic_id) ?? 0) + 1);}- // One aggregate per brand instead of downloading the window (#721). The page- // used to page through every result row — 33 requests and 73 MB on the- // largest brand — to compute twenty table rows in JavaScript. The arithmetic- // now runs where the data is; only the AI Visibility Score stays here, over- // ~20 rows, so this page and the Insights headline keep one implementation.- const { data: aggRows, error: aggError } = await supabase.rpc('topics_overview_aggregates', {- p_brand_id: brandId,- });- if (aggError) throw new Error(aggError.message);-- interface TopicAggRow {- topic_id: string;- answers: number;- mention_answers: number;- citation_answers: number;- pos_sum: number;- pos_n: number;- cur_answers: number;- cur_mention_answers: number;- cur_citation_answers: number;- cur_pos_sum: number;- cur_pos_n: number;- prev_answers: number;- prev_mention_answers: number;- prev_citation_answers: number;- prev_pos_sum: number;- prev_pos_n: number;- total_mentions: number;- total_citations: number;- comp_mentions: number;- active_prompts: number;- visible_prompts: number;- last_run_at: string | null;- competitors: Record<string, { name: string; sov: number }>;- daily: Record<string, { visible: number; count: number }>;- }-- const aggByTopic = new Map<string, TopicAggRow>(- ((aggRows ?? []) as unknown as TopicAggRow[]).map((row) => [row.topic_id, row]),- );+ const { windowed, aggByTopic } = await aggregates;+ const trendDays =+ window && windowed+ ? topicTrendDays(window, now)+ : Array.from({ length: 14 }, (_, i) =>+ new Date(now - (13 - i) * DAY_MS).toISOString().slice(0, 10),+ );- const scoreOf = (- answers: number,- mention: number,- citation: number,- posSum: number,- posN: number,- ) =>+ const scoreOf = (c: AnswerCounts) =>computeAiVisibilityScore({- answers,- mentionAnswers: mention,- citationAnswers: citation,- positionFactor: posN > 0 ? posSum / posN : null,+ answers: c.answers,+ mentionAnswers: c.mentionAnswers,+ citationAnswers: c.citationAnswers,+ positionFactor: c.posN > 0 ? c.posSum / c.posN : null,}) ?? 0;const rows: TopicOverviewRow[] = topics.map((t) => {@@ -296,49 +372,27 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewSshareOfVoice: 0,topCompetitor: null,lastRunAt: null,- trendSparkline: Array.from({ length: 14 }, () => 0),+ trendSparkline: trendDays.map(() => 0),};}// Visibility Rate IS the AI Visibility Score over the topic's answers —// same blend as the Insights headline (see lib/visibility-score).- const visibilityRate = scoreOf(- agg.answers,- agg.mention_answers,- agg.citation_answers,- agg.pos_sum,- agg.pos_n,- );+ const visibilityRate = scoreOf(agg.window);const change =- agg.cur_answers > 0 && agg.prev_answers > 0- ? Math.round(- (scoreOf(- agg.cur_answers,- agg.cur_mention_answers,- agg.cur_citation_answers,- agg.cur_pos_sum,- agg.cur_pos_n,- ) -- scoreOf(- agg.prev_answers,- agg.prev_mention_answers,- agg.prev_citation_answers,- agg.prev_pos_sum,- agg.prev_pos_n,- )) *- 10,- ) / 10+ agg.current.answers > 0 && agg.previous.answers > 0+ ? Math.round((scoreOf(agg.current) - scoreOf(agg.previous)) * 10) / 10: null;// The brand's own mentions are the same total the table shows.- const totalForSov = agg.total_mentions + agg.comp_mentions;+ const totalForSov = agg.totalMentions + agg.compMentions;const shareOfVoice =- totalForSov > 0 ? Math.round((agg.total_mentions / totalForSov) * 1000) / 10 : 0;+ totalForSov > 0 ? Math.round((agg.totalMentions / totalForSov) * 1000) / 10 : 0;let topCompetitor: TopicOverviewRow['topCompetitor'] = null;if (totalForSov > 0) {let best: { name: string; sov: number } | null = null;- for (const c of Object.values(agg.competitors ?? {})) {+ for (const c of Object.values(agg.competitors)) {const pct = Math.round((c.sov / totalForSov) * 1000) / 10;if (!best || pct > best.sov) best = { name: c.name, sov: pct };}@@ -347,33 +401,29 @@ export async function getTopicsOverview(brandId: string): Promise<TopicOverviewS// Daily visible-answer share (result-level) — a trend proxy for the// headline rate; sparklines have no axis, only shape matters.- const sparklineDays: number[] = [];- for (let i = 13; i >= 0; i--) {- const key = new Date(now - i * 24 * 60 * 60 * 1000).toISOString().slice(0, 10);- const bucket = agg.daily?.[key];- sparklineDays.push(- bucket && bucket.count > 0 ? Math.round((bucket.visible / bucket.count) * 100) : 0,- );- }+ const sparklineDays = trendDays.map((key) => {+ const bucket = agg.daily[key];+ return bucket && bucket.count > 0 ? Math.round((bucket.visible / bucket.count) * 100) : 0;+ });return {id: t.id,name: t.name,promptCount,visibilityRate,- visiblePrompts: agg.visible_prompts,- activePrompts: agg.active_prompts,+ visiblePrompts: agg.visiblePrompts,+ activePrompts: agg.activePrompts,visibilityChange: change,- totalMentions: agg.total_mentions,- totalCitations: agg.total_citations,+ totalMentions: agg.totalMentions,+ totalCitations: agg.totalCitations,shareOfVoice,topCompetitor,- lastRunAt: agg.last_run_at,+ lastRunAt: agg.lastRunAt,trendSparkline: sparklineDays,};});- return { topics: rows, unassignedPromptCount };+ return { topics: rows, unassignedPromptCount, trendDays };}export async function deleteTopic(topicId: string): Promise<void> {diff --git a/web/src/lib/topic-trend.test.ts b/web/src/lib/topic-trend.test.tsnew file mode 100644index 000000000..a399af00a--- /dev/null+++ b/web/src/lib/topic-trend.test.ts@@ -0,0 +1,50 @@+import { describe, expect, it } from 'vitest';+import { customUtcWindow, topicTrendDays, windowDayCount } from './topic-trend';++const NOW = Date.parse('2026-10-17T09:30:00Z');+const hoursAgo = (h: number) => new Date(NOW - h * 3_600_000).toISOString();++describe('topicTrendDays', () => {+ it('has no days for a window under two days', () => {+ expect(topicTrendDays({ from: hoursAgo(24) }, NOW)).toEqual([]);+ });++ it("counts a rolling week's whole days back from today, not a clipped eighth", () => {+ expect(topicTrendDays({ from: hoursAgo(7 * 24) }, NOW)).toEqual([+ '2026-10-11',+ '2026-10-12',+ '2026-10-13',+ '2026-10-14',+ '2026-10-15',+ '2026-10-16',+ '2026-10-17',+ ]);+ });++ it('keeps a rolling week at 7 days when the server reads it a moment later', () => {+ expect(windowDayCount(NOW - 7 * 86_400_000, NOW + 2_000)).toBe(7);+ expect(topicTrendDays({ from: hoursAgo(7 * 24) }, NOW + 2_000)).toHaveLength(7);+ });++ it('ends a custom range on its own last day', () => {+ expect(+ topicTrendDays({ from: '2026-10-01T00:00:00Z', to: '2026-10-03T23:59:59Z' }, NOW),+ ).toEqual(['2026-10-01', '2026-10-02', '2026-10-03']);+ });++ it("reads a custom range's dates as whole UTC days, wherever the viewer is", () => {+ const window = customUtcWindow('2026-10-10', '2026-10-14', {+ // New York's day edges, as the date inputs resolve them there.+ from: '2026-10-10T04:00:00.000Z',+ to: '2026-10-15T03:59:59.999Z',+ });+ expect(window).toEqual({ from: '2026-10-10T00:00:00.000Z', to: '2026-10-14T23:59:59.999Z' });+ expect(topicTrendDays(window, NOW)).toEqual([+ '2026-10-10',+ '2026-10-11',+ '2026-10-12',+ '2026-10-13',+ '2026-10-14',+ ]);+ });+});diff --git a/web/src/lib/topic-trend.ts b/web/src/lib/topic-trend.tsnew file mode 100644index 000000000..6ca585fa5--- /dev/null+++ b/web/src/lib/topic-trend.ts@@ -0,0 +1,55 @@+/**+ * The Topics overview's window and trend days (00156), apart from the server+ * action that reads them: a 'use server' module may only export async+ * functions.+ */++/** The window the overview covers, as the page's date range resolves it. */+export interface TopicsWindow {+ from: string;+ /** Omitted: up to now. */+ to?: string;+}++export const DAY_MS = 24 * 60 * 60 * 1000;++/**+ * Whole days a window spans, at least one. An hour of slack: a rolling 7 days+ * starts where the browser put it and ends when the server reads it, a moment+ * later, which must not make it 8. topics_overview_window counts the same way.+ */+export function windowDayCount(from: number, to: number): number {+ return Math.max(1, Math.ceil((to - from) / DAY_MS - 1 / 24));+}++/**+ * A window's trend days, oldest first: its whole days counted back from the+ * end, as topics_overview_window (00156) reads the competitor rollup, so a+ * rolling 7 days draws today and the 6 days before, not a clipped eighth.+ * None for a window under two days: one day has no line to draw.+ */+export function topicTrendDays(window: TopicsWindow, now = Date.now()): string[] {+ const to = window.to ? Date.parse(window.to) : now;+ const days = windowDayCount(Date.parse(window.from), to);+ if (days < 2) return [];+ return Array.from({ length: days }, (_, i) =>+ new Date(to - (days - 1 - i) * DAY_MS).toISOString().slice(0, 10),+ );+}++/**+ * A custom range's window as whole UTC days, the days the rollups hold+ * (00156). The date inputs name calendar days; read in the viewer's zone, a+ * range picked west of UTC would end on the next UTC day and every rollup day+ * would shift one later. A missing bound falls back to the resolved range's.+ */+export function customUtcWindow(+ from: string,+ to: string,+ resolved: { from: string; to?: string },+): TopicsWindow {+ return {+ from: from ? `${from}T00:00:00.000Z` : resolved.from,+ to: to ? `${to}T23:59:59.999Z` : resolved.to,+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex d2e2e869e..33fe9633a 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3500,6 +3500,30 @@ export type Database = {visible_prompts: number}[]}+ topics_overview_window: {+ Args: { p_brand_id: string; p_date_from: string; p_date_to?: string }+ Returns: {+ active_prompts: number+ answers: number+ citation_answers: number+ comp_mentions: number+ competitors: Json+ daily: Json+ last_run_at: string+ mention_answers: number+ pos_n: number+ pos_sum: number+ prev_answers: number+ prev_citation_answers: number+ prev_mention_answers: number+ prev_pos_n: number+ prev_pos_sum: number+ topic_id: string+ total_citations: number+ total_mentions: number+ visible_prompts: number+ }[]+ }tracked_prompt_count: {Args: {p_brand_id: string