Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(mentions): correct an answer's sentiment from the response drawer (#1121)
Cihan66178c84a861
diff --git a/supabase/migrations/00160_mention_sentiment_override.sql b/supabase/migrations/00160_mention_sentiment_override.sqlnew file mode 100644index 000000000..5e1ee4fae--- /dev/null+++ b/supabase/migrations/00160_mention_sentiment_override.sql@@ -0,0 +1,172 @@+-- ============================================================================+-- 00160: "Sentiment is wrong" — correcting an answer's sentiment (MS-08)+-- ============================================================================+-- Tracking classifies each answer's tone toward the brand once, when it is+-- stored (prompt_results.sentiment, set only when the brand is named). A+-- person who knows better can now correct it from the Mentions tab's+-- response drawer. The spec asks that "a sentiment override changes the+-- metrics within one refresh and is logged":+--+-- * the answer's sentiment itself changes, so every figure that reads it+-- agrees: Insights' Net and Positive sentiment, the Mentions tab, the+-- Positions panel, reports written from now on, the MCP tools;+-- * its stored visibility_score follows, by the same sentiment bonus+-- tracking adds (server/src/lib/response-parser.js+-- computeVisibilityScore: +15 positive, +7 neutral when named, 0+-- negative; its parts add up to at most 100, so swapping the bonus is+-- exact);+-- * the answer's UTC day is refreshed in the Insights (refresh_insights_daily)+-- and Mentions (refresh_mentions_daily) rollups, so the change shows at+-- once instead of after the nightly sweep;+-- * every correction is kept in sentiment_overrides, with the tone it+-- replaced, who made it, when, and an optional note: the history the page+-- shows, and what a future classifier can learn from.+--+-- Only admins and managers correct, as with editing prompts. Members of the+-- brand's organization read the history.++create table if not exists public.sentiment_overrides (+ id uuid primary key default gen_random_uuid(),+ result_id uuid not null references public.prompt_results(id) on delete cascade,+ brand_id uuid not null references public.brands(id) on delete cascade,+ previous_sentiment text not null,+ sentiment text not null check (sentiment in ('positive', 'neutral', 'negative')),+ note text check (note is null or char_length(note) <= 500),+ user_id uuid references public.profiles(id) on delete set null,+ -- Kept as written: profiles are readable only by their owner, and the+ -- history should still name a person who later leaves the organization.+ user_name text,+ created_at timestamptz not null default now()+);++create index if not exists idx_sentiment_overrides_result+ on public.sentiment_overrides (result_id, created_at desc);+create index if not exists idx_sentiment_overrides_brand+ on public.sentiment_overrides (brand_id, created_at desc);++alter table public.sentiment_overrides enable row level security;++create policy "sentiment_overrides: member select" on public.sentiment_overrides+ 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()+ )+ );++-- Written only through override_mention_sentiment below, which checks the+-- role; the history is append-only.+create policy "sentiment_overrides: no client insert" on public.sentiment_overrides+ for insert with check (false);+create policy "sentiment_overrides: no client update" on public.sentiment_overrides+ for update using (false);+create policy "sentiment_overrides: no client delete" on public.sentiment_overrides+ for delete using (false);++-- Tracking's sentiment bonus in visibility_score, for an answer that names the brand.+create or replace function public.sentiment_visibility_bonus(p_sentiment text)+returns integer+language sql+immutable+set search_path to 'public'+as $$+ select case p_sentiment when 'positive' then 15 when 'neutral' then 7 else 0 end;+$$;++-- Returns jsonb { changed, previous, sentiment, override: { id, sentiment,+-- previous_sentiment, note, user_name, created_at } }. Raises:+-- 42501 the caller isn't an admin or manager of the answer's organization+-- P0002 no such answer+-- 22023 not a sentiment, or an answer that doesn't name the brand+create or replace function public.override_mention_sentiment(+ p_result_id uuid,+ p_sentiment text,+ p_note text default null+)+returns jsonb+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_row record;+ v_user record;+ v_day date;+ v_note text := nullif(btrim(coalesce(p_note, '')), '');+ v_override public.sentiment_overrides;+begin+ if p_sentiment is null or p_sentiment not in ('positive', 'neutral', 'negative') then+ raise exception 'Invalid sentiment' using errcode = '22023';+ end if;+ if v_note is not null and char_length(v_note) > 500 then+ raise exception 'The note is longer than 500 characters' using errcode = '22023';+ end if;++ select pr.id, pr.brand_id, pr.sentiment, pr.mention_count, pr.created_at, b.organization_id+ into v_row+ from public.prompt_results pr+ join public.brands b on b.id = pr.brand_id+ where pr.id = p_result_id+ for update of pr;+ if not found then+ raise exception 'Answer not found' using errcode = 'P0002';+ end if;++ select p.id, p.full_name, p.role+ into v_user+ from public.profiles p+ where p.id = auth.uid()+ and p.organization_id = v_row.organization_id+ and p.role = any (array['admin', 'manager']::public.user_role[]);+ if not found then+ raise exception 'Only admins and managers can correct a sentiment' using errcode = '42501';+ end if;++ -- Sentiment is only classified for answers that name the brand.+ if coalesce(v_row.mention_count, 0) <= 0 then+ raise exception 'This answer does not name the brand' using errcode = '22023';+ end if;++ if v_row.sentiment = p_sentiment then+ return jsonb_build_object('changed', false, 'previous', v_row.sentiment,+ 'sentiment', p_sentiment, 'override', null);+ end if;++ update public.prompt_results+ set sentiment = p_sentiment,+ visibility_score = greatest(0, least(100,+ coalesce(visibility_score, 0)+ - public.sentiment_visibility_bonus(v_row.sentiment)+ + public.sentiment_visibility_bonus(p_sentiment)))+ where id = p_result_id;++ insert into public.sentiment_overrides+ (result_id, brand_id, previous_sentiment, sentiment, note, user_id, user_name)+ values+ (p_result_id, v_row.brand_id, coalesce(v_row.sentiment, 'neutral'), p_sentiment, v_note,+ v_user.id, v_user.full_name)+ returning * into v_override;++ -- The answer's day in the rollups, now rather than at the nightly sweep.+ v_day := (v_row.created_at at time zone 'utc')::date;+ perform public.refresh_insights_daily(v_row.brand_id, v_day, v_day);+ perform public.refresh_mentions_daily(v_row.brand_id, v_day, v_day);++ return jsonb_build_object(+ 'changed', true,+ 'previous', v_override.previous_sentiment,+ 'sentiment', v_override.sentiment,+ 'override', jsonb_build_object(+ 'id', v_override.id,+ 'sentiment', v_override.sentiment,+ 'previous_sentiment', v_override.previous_sentiment,+ 'note', v_override.note,+ 'user_name', v_override.user_name,+ 'created_at', v_override.created_at));+end;+$$;++revoke execute on function public.override_mention_sentiment(uuid, text, text) from public, anon;+grant execute on function public.override_mention_sentiment(uuid, text, text)+ to authenticated, service_role;diff --git a/supabase/migrations/00162_refresh_insights_daily_range.sql b/supabase/migrations/00162_refresh_insights_daily_range.sqlnew file mode 100644index 000000000..8ed533044--- /dev/null+++ b/supabase/migrations/00162_refresh_insights_daily_range.sql@@ -0,0 +1,154 @@+-- refresh_insights_daily (00131) finds a day range's answers by range.+--+-- Its inserts picked the answers by (created_at at time zone 'utc')::date,+-- which no index serves, so refreshing one day read every answer the brand+-- has: about 1 s warm and 12 s cold for the largest brand's 222k answers.+-- That ran on every completed run and in the nightly sweep, and a+-- sentiment correction (00160) runs it inside the person's 8 s request,+-- where it timed out. The same answers are now found by created_at range+-- through (brand_id, created_at): 0.66 s for that day, the same rows.++create or replace function public.refresh_insights_daily(+ p_brand_id uuid,+ p_day_from date,+ p_day_to date+) returns void+language plpgsql+set search_path to 'public'+as $$+declare+ -- The range's bounds as instants, so the answers are found through+ -- (brand_id, created_at) rather than by reading all of the brand's.+ 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.insights_brand_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;++ insert into public.insights_brand_daily (+ brand_id, day, model_used, platform, region,+ answer_count, mention_answers, citation_answers, mentioning_answers,+ sum_visibility, sum_visibility_visible, total_mentions, total_citations,+ positive_count, sum_inv_position, position_count, max_created_at,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.model_used, pr.platform, pr.region,+ count(*),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ coalesce(sum(pr.visibility_score), 0),+ coalesce(sum(pr.visibility_score)+ filter (where pr.mention_count > 0 or pr.citation_count > 0), 0),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ count(*) filter (where pr.sentiment = 'positive'),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ max(pr.created_at),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ and pr.created_at >= v_from+ and pr.created_at < v_to+ group by 2, pr.model_used, pr.platform, pr.region;++ insert into public.insights_prompt_daily (+ brand_id, day, prompt_id, model_used, platform, region,+ answer_count, has_mention, has_citation,+ mention_answers, citation_answers, mentioning_answers, positive_count,+ total_mentions, total_citations, sum_inv_position, position_count,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ count(*),+ bool_or(pr.mention_count > 0),+ bool_or(pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ count(*) filter (where pr.sentiment = 'positive'),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ group by 2, pr.prompt_id, pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_daily (+ brand_id, day, competitor_id, model_used, platform, region,+ answer_count, sum_visibility, total_mentions, total_citations,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.model_used, pr.platform, pr.region,+ count(*),+ sum((cm.value->>'visibility_score')::numeric),+ coalesce(sum(coalesce((cm.value->>'mention_count')::int, 0)), 0),+ coalesce(sum(coalesce((cm.value->>'citation_count')::int, 0)), 0),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ and cm.value ? 'competitor_id'+ group by 2, cm.value->>'competitor_id', pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_prompt_daily (+ brand_id, day, competitor_id, prompt_id, model_used, platform, region, mention_count,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ sum(coalesce((cm.value->>'mention_count')::int, 0)),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ and cm.value ? 'competitor_id'+ and (coalesce((cm.value->>'mention_count')::int, 0) > 0+ or coalesce((cm.value->>'citation_count')::int, 0) > 0+ or coalesce((cm.value->>'visibility_score')::numeric, 0) > 0)+ group by 2, cm.value->>'competitor_id', pr.prompt_id, pr.model_used, pr.platform, pr.region;+end;+$$;++revoke execute on function public.refresh_insights_daily(uuid, date, date)+ from public, anon, authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 99978f31a..36303fe9f 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -20217,3 +20217,337 @@ grant execute on function public.mentions_list(uuid, timestamptz, timestamptz, text, text, uuid, text, text, text, text, text, integer, integer)to authenticated, service_role;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00160_mention_sentiment_override.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00160: "Sentiment is wrong" — correcting an answer's sentiment (MS-08)+-- ============================================================================+-- Tracking classifies each answer's tone toward the brand once, when it is+-- stored (prompt_results.sentiment, set only when the brand is named). A+-- person who knows better can now correct it from the Mentions tab's+-- response drawer. The spec asks that "a sentiment override changes the+-- metrics within one refresh and is logged":+--+-- * the answer's sentiment itself changes, so every figure that reads it+-- agrees: Insights' Net and Positive sentiment, the Mentions tab, the+-- Positions panel, reports written from now on, the MCP tools;+-- * its stored visibility_score follows, by the same sentiment bonus+-- tracking adds (server/src/lib/response-parser.js+-- computeVisibilityScore: +15 positive, +7 neutral when named, 0+-- negative; its parts add up to at most 100, so swapping the bonus is+-- exact);+-- * the answer's UTC day is refreshed in the Insights (refresh_insights_daily)+-- and Mentions (refresh_mentions_daily) rollups, so the change shows at+-- once instead of after the nightly sweep;+-- * every correction is kept in sentiment_overrides, with the tone it+-- replaced, who made it, when, and an optional note: the history the page+-- shows, and what a future classifier can learn from.+--+-- Only admins and managers correct, as with editing prompts. Members of the+-- brand's organization read the history.++create table if not exists public.sentiment_overrides (+ id uuid primary key default gen_random_uuid(),+ result_id uuid not null references public.prompt_results(id) on delete cascade,+ brand_id uuid not null references public.brands(id) on delete cascade,+ previous_sentiment text not null,+ sentiment text not null check (sentiment in ('positive', 'neutral', 'negative')),+ note text check (note is null or char_length(note) <= 500),+ user_id uuid references public.profiles(id) on delete set null,+ -- Kept as written: profiles are readable only by their owner, and the+ -- history should still name a person who later leaves the organization.+ user_name text,+ created_at timestamptz not null default now()+);++create index if not exists idx_sentiment_overrides_result+ on public.sentiment_overrides (result_id, created_at desc);+create index if not exists idx_sentiment_overrides_brand+ on public.sentiment_overrides (brand_id, created_at desc);++alter table public.sentiment_overrides enable row level security;++create policy "sentiment_overrides: member select" on public.sentiment_overrides+ 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()+ )+ );++-- Written only through override_mention_sentiment below, which checks the+-- role; the history is append-only.+create policy "sentiment_overrides: no client insert" on public.sentiment_overrides+ for insert with check (false);+create policy "sentiment_overrides: no client update" on public.sentiment_overrides+ for update using (false);+create policy "sentiment_overrides: no client delete" on public.sentiment_overrides+ for delete using (false);++-- Tracking's sentiment bonus in visibility_score, for an answer that names the brand.+create or replace function public.sentiment_visibility_bonus(p_sentiment text)+returns integer+language sql+immutable+set search_path to 'public'+as $$+ select case p_sentiment when 'positive' then 15 when 'neutral' then 7 else 0 end;+$$;++-- Returns jsonb { changed, previous, sentiment, override: { id, sentiment,+-- previous_sentiment, note, user_name, created_at } }. Raises:+-- 42501 the caller isn't an admin or manager of the answer's organization+-- P0002 no such answer+-- 22023 not a sentiment, or an answer that doesn't name the brand+create or replace function public.override_mention_sentiment(+ p_result_id uuid,+ p_sentiment text,+ p_note text default null+)+returns jsonb+language plpgsql+security definer+set search_path to 'public'+as $$+declare+ v_row record;+ v_user record;+ v_day date;+ v_note text := nullif(btrim(coalesce(p_note, '')), '');+ v_override public.sentiment_overrides;+begin+ if p_sentiment is null or p_sentiment not in ('positive', 'neutral', 'negative') then+ raise exception 'Invalid sentiment' using errcode = '22023';+ end if;+ if v_note is not null and char_length(v_note) > 500 then+ raise exception 'The note is longer than 500 characters' using errcode = '22023';+ end if;++ select pr.id, pr.brand_id, pr.sentiment, pr.mention_count, pr.created_at, b.organization_id+ into v_row+ from public.prompt_results pr+ join public.brands b on b.id = pr.brand_id+ where pr.id = p_result_id+ for update of pr;+ if not found then+ raise exception 'Answer not found' using errcode = 'P0002';+ end if;++ select p.id, p.full_name, p.role+ into v_user+ from public.profiles p+ where p.id = auth.uid()+ and p.organization_id = v_row.organization_id+ and p.role = any (array['admin', 'manager']::public.user_role[]);+ if not found then+ raise exception 'Only admins and managers can correct a sentiment' using errcode = '42501';+ end if;++ -- Sentiment is only classified for answers that name the brand.+ if coalesce(v_row.mention_count, 0) <= 0 then+ raise exception 'This answer does not name the brand' using errcode = '22023';+ end if;++ if v_row.sentiment = p_sentiment then+ return jsonb_build_object('changed', false, 'previous', v_row.sentiment,+ 'sentiment', p_sentiment, 'override', null);+ end if;++ update public.prompt_results+ set sentiment = p_sentiment,+ visibility_score = greatest(0, least(100,+ coalesce(visibility_score, 0)+ - public.sentiment_visibility_bonus(v_row.sentiment)+ + public.sentiment_visibility_bonus(p_sentiment)))+ where id = p_result_id;++ insert into public.sentiment_overrides+ (result_id, brand_id, previous_sentiment, sentiment, note, user_id, user_name)+ values+ (p_result_id, v_row.brand_id, coalesce(v_row.sentiment, 'neutral'), p_sentiment, v_note,+ v_user.id, v_user.full_name)+ returning * into v_override;++ -- The answer's day in the rollups, now rather than at the nightly sweep.+ v_day := (v_row.created_at at time zone 'utc')::date;+ perform public.refresh_insights_daily(v_row.brand_id, v_day, v_day);+ perform public.refresh_mentions_daily(v_row.brand_id, v_day, v_day);++ return jsonb_build_object(+ 'changed', true,+ 'previous', v_override.previous_sentiment,+ 'sentiment', v_override.sentiment,+ 'override', jsonb_build_object(+ 'id', v_override.id,+ 'sentiment', v_override.sentiment,+ 'previous_sentiment', v_override.previous_sentiment,+ 'note', v_override.note,+ 'user_name', v_override.user_name,+ 'created_at', v_override.created_at));+end;+$$;++revoke execute on function public.override_mention_sentiment(uuid, text, text) from public, anon;+grant execute on function public.override_mention_sentiment(uuid, text, text)+ to authenticated, service_role;++-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00162_refresh_insights_daily_range.sql+-- ─────────────────────────────────────────────────────────────────────────+-- refresh_insights_daily (00131) finds a day range's answers by range.+--+-- Its inserts picked the answers by (created_at at time zone 'utc')::date,+-- which no index serves, so refreshing one day read every answer the brand+-- has: about 1 s warm and 12 s cold for the largest brand's 222k answers.+-- That ran on every completed run and in the nightly sweep, and a+-- sentiment correction (00160) runs it inside the person's 8 s request,+-- where it timed out. The same answers are now found by created_at range+-- through (brand_id, created_at): 0.66 s for that day, the same rows.++create or replace function public.refresh_insights_daily(+ p_brand_id uuid,+ p_day_from date,+ p_day_to date+) returns void+language plpgsql+set search_path to 'public'+as $$+declare+ -- The range's bounds as instants, so the answers are found through+ -- (brand_id, created_at) rather than by reading all of the brand's.+ 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.insights_brand_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;+ delete from public.insights_competitor_prompt_daily+ where brand_id = p_brand_id and day between p_day_from and p_day_to;++ insert into public.insights_brand_daily (+ brand_id, day, model_used, platform, region,+ answer_count, mention_answers, citation_answers, mentioning_answers,+ sum_visibility, sum_visibility_visible, total_mentions, total_citations,+ positive_count, sum_inv_position, position_count, max_created_at,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.model_used, pr.platform, pr.region,+ count(*),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ coalesce(sum(pr.visibility_score), 0),+ coalesce(sum(pr.visibility_score)+ filter (where pr.mention_count > 0 or pr.citation_count > 0), 0),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ count(*) filter (where pr.sentiment = 'positive'),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ max(pr.created_at),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping' -- #155 — isolate from Insights+ and pr.created_at >= v_from+ and pr.created_at < v_to+ group by 2, pr.model_used, pr.platform, pr.region;++ insert into public.insights_prompt_daily (+ brand_id, day, prompt_id, model_used, platform, region,+ answer_count, has_mention, has_citation,+ mention_answers, citation_answers, mentioning_answers, positive_count,+ total_mentions, total_citations, sum_inv_position, position_count,+ negative_count, sum_position)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ count(*),+ bool_or(pr.mention_count > 0),+ bool_or(pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0),+ count(*) filter (where pr.citation_count > 0),+ count(*) filter (where pr.mention_count > 0 or pr.citation_count > 0),+ count(*) filter (where pr.sentiment = 'positive'),+ coalesce(sum(pr.mention_count), 0),+ coalesce(sum(pr.citation_count), 0),+ sum(1.0 / pr.mention_position) filter (where pr.mention_position is not null),+ count(*) filter (where pr.mention_position is not null),+ count(*) filter (where pr.sentiment = 'negative'),+ sum(pr.mention_position) filter (where pr.mention_position is not null)+ from public.prompt_results pr+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ group by 2, pr.prompt_id, pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_daily (+ brand_id, day, competitor_id, model_used, platform, region,+ answer_count, sum_visibility, total_mentions, total_citations,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.model_used, pr.platform, pr.region,+ count(*),+ sum((cm.value->>'visibility_score')::numeric),+ coalesce(sum(coalesce((cm.value->>'mention_count')::int, 0)), 0),+ coalesce(sum(coalesce((cm.value->>'citation_count')::int, 0)), 0),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ and cm.value ? 'competitor_id'+ group by 2, cm.value->>'competitor_id', pr.model_used, pr.platform, pr.region;++ insert into public.insights_competitor_prompt_daily (+ brand_id, day, competitor_id, prompt_id, model_used, platform, region, mention_count,+ mention_answers, citation_answers, sum_inv_position, position_count)+ select+ p_brand_id,+ (pr.created_at at time zone 'utc')::date,+ cm.value->>'competitor_id',+ pr.prompt_id, pr.model_used, pr.platform, pr.region,+ sum(coalesce((cm.value->>'mention_count')::int, 0)),+ count(*) filter (where coalesce((cm.value->>'mention_count')::int, 0) > 0),+ count(*) filter (where coalesce((cm.value->>'citation_count')::int, 0) > 0),+ sum(1.0 / (cm.value->>'mention_position')::numeric)+ filter (where (cm.value->>'mention_position') is not null),+ count(*) filter (where (cm.value->>'mention_position') is not null)+ from public.prompt_results pr,+ lateral jsonb_array_elements(coalesce(pr.competitor_mentions, '[]'::jsonb)) cm+ where pr.brand_id = p_brand_id+ and pr.prompt_id is not null+ and pr.platform <> 'chatgpt-shopping'+ and pr.created_at >= v_from+ and pr.created_at < v_to+ and cm.value ? 'competitor_id'+ and (coalesce((cm.value->>'mention_count')::int, 0) > 0+ or coalesce((cm.value->>'citation_count')::int, 0) > 0+ or coalesce((cm.value->>'visibility_score')::numeric, 0) > 0)+ group by 2, cm.value->>'competitor_id', pr.prompt_id, pr.model_used, pr.platform, pr.region;+end;+$$;++revoke execute on function public.refresh_insights_daily(uuid, date, date)+ from public, anon, authenticated;+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 3163ce121..81f1da5f5 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -3179,7 +3179,24 @@"copyFailed": "Couldn't copy the response. Select the text and copy it instead.","close": "Close","legendBrand": "Your brand",- "legendCompetitor": "Competitors"+ "legendCompetitor": "Competitors",+ "correction": {+ "open": "Sentiment is wrong?",+ "title": "Correct the sentiment toward your brand",+ "hint": "Every figure counts the new sentiment from now on; the original stays in the history.",+ "options": "New sentiment",+ "note": "Note (optional)",+ "notePlaceholder": "Why is it wrong? It helps improve the classification.",+ "save": "Save correction",+ "cancel": "Cancel",+ "saved": "Sentiment corrected",+ "savedDescription": "This answer now counts as {sentiment} everywhere.",+ "unchanged": "The answer already has this sentiment.",+ "failed": "Couldn't correct the sentiment",+ "forbidden": "Only admins and managers can correct a sentiment.",+ "correctedBy": "Corrected by {name} on {date} · was {previous}",+ "correctedOn": "Corrected on {date} · was {previous}"+ }},"actions": {"sendToActionCenter": "Send to Action Center",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsxindex 752ec68a8..05ed0f0af 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.test.tsx@@ -11,10 +11,16 @@ import { MentionsListTab } from './_mentions-tab';const listMentions = vi.fn();const getMentionResponse = vi.fn();const sendMentionsToActionCenter = vi.fn();+const overrideMentionSentiment = vi.fn();vi.mock('@/lib/actions/mentions', () => ({listMentions: (...args: unknown[]) => listMentions(...args),getMentionResponse: (...args: unknown[]) => getMentionResponse(...args),sendMentionsToActionCenter: (...args: unknown[]) => sendMentionsToActionCenter(...args),+ overrideMentionSentiment: (...args: unknown[]) => overrideMentionSentiment(...args),+}));+let canManage = true;+vi.mock('@/hooks/use-user-role', () => ({+ useUserRole: () => ({ role: canManage ? 'admin' : 'analyst', canManage, canAdmin: canManage }),}));const suggestContentForPrompt = vi.fn();vi.mock('@/lib/actions/content', () => ({@@ -121,6 +127,8 @@ afterEach(() => {listMentions.mockReset();getMentionResponse.mockReset();sendMentionsToActionCenter.mockReset();+ overrideMentionSentiment.mockReset();+ canManage = true;suggestContentForPrompt.mockReset();push.mockReset();Object.values(toast).forEach((fn) => fn.mockClear());@@ -301,6 +309,119 @@ describe('MentionsListTab', () => {);});+ it("shows an answer's last correction, and lets a manager correct it", async () => {+ listMentions.mockResolvedValue(list());+ getMentionResponse.mockResolvedValue({+ response: 'Acme Coffee.',+ citations: [],+ override: {+ sentiment: 'negative',+ previousSentiment: 'neutral',+ note: 'Calls us pricey',+ userName: 'Demo User',+ createdAt: '2026-10-16T10:00:00Z',+ },+ });+ overrideMentionSentiment.mockResolvedValue({+ changed: true,+ sentiment: 'positive',+ override: {+ sentiment: 'positive',+ previousSentiment: 'negative',+ note: 'Praises the roast',+ userName: 'Demo User',+ createdAt: '2026-10-17T10:00:00Z',+ },+ });+ render(tab());+ await settle();+ await act(async () => {+ (container.querySelector('tbody tr[tabindex]') as HTMLElement).click();+ await vi.advanceTimersByTimeAsync(0);+ });+ const drawer = () => document.body.querySelector('[role="dialog"]') as HTMLElement;+ expect(drawer().textContent).toContain('Corrected by Demo User on Oct 16, 2026 · was Neutral');+ expect(drawer().textContent).toContain('“Calls us pricey”');++ const button = (label: string) =>+ [...drawer().querySelectorAll('button')].find((b) => b.textContent === label) as HTMLElement;+ act(() => button('Sentiment is wrong?').click());+ // The current sentiment is chosen, so there is nothing to save yet.+ expect(button('Save correction').hasAttribute('disabled')).toBe(true);+ act(() => button('Positive').click());+ const note = drawer().querySelector('textarea') as HTMLTextAreaElement;+ act(() => {+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!;+ setter.call(note, 'Praises the roast');+ note.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => {+ button('Save correction').click();+ await vi.advanceTimersByTimeAsync(0);+ });+ expect(overrideMentionSentiment).toHaveBeenCalledWith('r1', 'positive', 'Praises the roast');+ expect(toast.success).toHaveBeenCalledWith(+ 'Sentiment corrected',+ expect.objectContaining({ description: 'This answer now counts as Positive everywhere.' }),+ );+ // The drawer and the row show the new sentiment at once, with the new history.+ expect(drawer().textContent).toContain('Corrected by Demo User on Oct 17, 2026 · was Negative');+ const firstRow = container.querySelector('tbody tr[tabindex]') as HTMLElement;+ expect(firstRow.textContent).toContain('Positive');+ expect(firstRow.textContent).not.toContain('Negative');+ });++ it('reads the page again when a correction takes a row out of the sentiment filter', async () => {+ window.history.replaceState(null, '', '/dashboard/mentions?tab=mentions&sentiment=negative');+ listMentions.mockResolvedValue(list());+ getMentionResponse.mockResolvedValue({+ response: 'Acme Coffee.',+ citations: [],+ override: null,+ });+ overrideMentionSentiment.mockResolvedValue({+ changed: true,+ sentiment: 'neutral',+ override: null,+ });+ render(tab());+ await settle();+ expect(listMentions).toHaveBeenCalledTimes(1);+ await act(async () => {+ (container.querySelector('tbody tr[tabindex]') as HTMLElement).click();+ await vi.advanceTimersByTimeAsync(0);+ });+ const drawer = document.body.querySelector('[role="dialog"]') as HTMLElement;+ const button = (label: string) =>+ [...drawer.querySelectorAll('button')].find((b) => b.textContent === label) as HTMLElement;+ act(() => button('Sentiment is wrong?').click());+ act(() => button('Neutral').click());+ await act(async () => {+ button('Save correction').click();+ await vi.advanceTimersByTimeAsync(0);+ });+ await settle();+ expect(listMentions).toHaveBeenCalledTimes(2);+ });++ it('offers no correction to analysts', async () => {+ canManage = false;+ listMentions.mockResolvedValue(list());+ getMentionResponse.mockResolvedValue({+ response: 'Acme Coffee.',+ citations: [],+ override: null,+ });+ render(tab());+ await settle();+ await act(async () => {+ (container.querySelector('tbody tr[tabindex]') as HTMLElement).click();+ await vi.advanceTimersByTimeAsync(0);+ });+ const drawer = document.body.querySelector('[role="dialog"]') as HTMLElement;+ expect(drawer.textContent).not.toContain('Sentiment is wrong?');+ });+it('keeps its page when a read fails, and says so', async () => {listMentions.mockResolvedValueOnce(list({ total: 250 }));render(tab());diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsxindex df6f18237..0ac83377c 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_mentions-tab.tsx@@ -7,6 +7,7 @@ import { Send } from 'lucide-react';import { Button } from '@/components/ui/button';import { Card, CardContent } from '@/components/ui/card';import { Skeleton } from '@/components/ui/skeleton';+import { useUserRole } from '@/hooks/use-user-role';import { listMentions } from '@/lib/actions/mentions';import { mentionsQuery, type MentionsFilters } from '@/lib/mentions-filters';import {@@ -16,6 +17,7 @@ import {mentionsTableParams,readMentionsTable,type MentionRow,+ type MentionSentiment,type MentionsList,type MentionsTableState,} from '@/lib/mentions-list';@@ -89,7 +91,11 @@ export function MentionsListTab({const [total, setTotal] = useState(0);// Back to the first page whenever the filters or the controls change.const pager = usePagination(total, JSON.stringify([brandId, query, table]), MENTIONS_PAGE_SIZE);- const key = query && urlRead ? JSON.stringify([brandId, query, table, pager.page]) : null;+ // Bumped to read the page again, e.g. after a correction moves a row out of+ // a sentiment filter.+ const [version, setVersion] = useState(0);+ const key =+ query && urlRead ? JSON.stringify([brandId, query, table, pager.page, version]) : null;useEffect(() => {if (!key || !query) return;@@ -113,6 +119,25 @@ export function MentionsListTab({const [open, setOpen] = useState<MentionRow | null>(null);const actions = useMentionActions(brandId);+ const { canManage } = useUserRole();++ // A corrected sentiment shows in the drawer and its row at once.+ const correctSentiment = (id: string, sentiment: MentionSentiment) => {+ setOpen((row) => (row && row.id === id ? { ...row, sentiment } : row));+ // Filtered by another sentiment, the row no longer belongs: read the page again.+ if (table.sentiment && table.sentiment !== sentiment) setVersion((v) => v + 1);+ setLoaded((prev) =>+ prev?.status === 'ok' && prev.list+ ? {+ ...prev,+ list: {+ ...prev.list,+ rows: prev.list.rows.map((r) => (r.id === id ? { ...r, sentiment } : r)),+ },+ }+ : prev,+ );+ };// Answers ticked for a bulk action, on the page shown; a new page or// filter starts with none.@@ -286,6 +311,8 @@ export function MentionsListTab({competitors: competitors.map((c) => c.domain).filter(Boolean),}}actions={actions}+ canCorrect={canManage}+ onSentimentChanged={correctSentiment}onClose={() => setOpen(null)}/></section>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsxindex 974cdcade..2100b47ab 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_response-drawer.tsx@@ -23,7 +23,7 @@ import { getMentionResponse } from '@/lib/actions/mentions';import { classifyDomain, extractHostname, SOURCE_CATEGORY_LABELS } from '@/lib/citations/classify';import { stripEntityMarkup } from '@/lib/entity-markup';import { mentionPlatformLabel } from '@/lib/mentions-headline';-import type { MentionRow } from '@/lib/mentions-list';+import type { MentionRow, MentionSentiment, SentimentOverride } from '@/lib/mentions-list';import { formatRegionDisplay } from '@/lib/region';import { cn } from '@/lib/utils';import type { Citation } from '@/types';@@ -34,10 +34,17 @@ import {SentimentPill,type MentionNames,} from './_mention-parts';+import { SentimentCorrection } from './_sentiment-correction';import type { useMentionActions } from './_use-mention-actions';type Loaded =- | { id: string; status: 'ok'; response: string; citations: Citation[] }+ | {+ id: string;+ status: 'ok';+ response: string;+ citations: Citation[];+ override: SentimentOverride | null;+ }| { id: string; status: 'missing' | 'error' };function Section({@@ -75,6 +82,8 @@ export function ResponseDrawer({names,domains,actions,+ canCorrect,+ onSentimentChanged,onClose,}: {brandId: string;@@ -87,6 +96,9 @@ export function ResponseDrawer({ReturnType<typeof useMentionActions>,'send' | 'sending' | 'suggest' | 'suggesting'>;+ /** Admins and managers may correct the sentiment ("Sentiment is wrong"). */+ canCorrect: boolean;+ onSentimentChanged: (id: string, sentiment: MentionSentiment) => void;onClose: () => void;}) {const t = useTranslations('mentions.drawer');@@ -114,6 +126,17 @@ export function ResponseDrawer({// A previous answer's text never shows under this one's header.const answer = loaded && loaded.id === id ? loaded : null;+ // A correction made here shows at once, before the answer is read again.+ const [corrected, setCorrected] = useState<{+ id: string;+ override: SentimentOverride | null;+ } | null>(null);+ const override =+ corrected && corrected.id === id+ ? corrected.override+ : answer?.status === 'ok'+ ? answer.override+ : null;const response = answer?.status === 'ok' ? stripEntityMarkup(answer.response) : '';// The marks inside the rendered answer; keyed below so new names re-render it.@@ -210,6 +233,17 @@ export function ResponseDrawer({</SheetHeader><div className="flex-1 space-y-6 overflow-y-auto px-5 py-4">+ <SentimentCorrection+ key={row.id}+ row={row}+ override={override}+ canCorrect={canCorrect}+ onCorrected={(sentiment, next) => {+ setCorrected({ id: row.id, override: next });+ onSentimentChanged(row.id, sentiment);+ }}+ />+<Section title={t('mention')}><blockquote className="rounded-md border-l-2 border-violet-400 bg-muted/40 px-3 py-2 text-sm leading-relaxed"><Highlighted text={row.excerpt} names={names} />diff --git a/web/src/app/[locale]/(dashboard)/dashboard/mentions/_sentiment-correction.tsx b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_sentiment-correction.tsxnew file mode 100644index 000000000..3fed849f3--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/mentions/_sentiment-correction.tsx@@ -0,0 +1,161 @@+'use client';++import { useState } from 'react';+import { useLocale, useTranslations } from 'next-intl';+import { toast } from 'sonner';+import { Button } from '@/components/ui/button';+import { Textarea } from '@/components/ui/textarea';+import { overrideMentionSentiment } from '@/lib/actions/mentions';+import {+ MENTION_SENTIMENTS,+ type MentionRow,+ type MentionSentiment,+ type SentimentOverride,+} from '@/lib/mentions-list';+import { cn } from '@/lib/utils';++const NOTE_MAX = 500;++/**+ * "Sentiment is wrong" (MS-08): the answer's last correction, if any, and+ * for admins and managers a form to correct it with an optional note. The+ * database changes the answer everywhere its sentiment counts and keeps the+ * history (00160); the drawer and the table show the new tone at once.+ */+export function SentimentCorrection({+ row,+ override,+ canCorrect,+ onCorrected,+}: {+ row: MentionRow;+ /** The latest correction, once the answer has loaded. */+ override: SentimentOverride | null;+ canCorrect: boolean;+ onCorrected: (sentiment: MentionSentiment, override: SentimentOverride | null) => void;+}) {+ const t = useTranslations('mentions.drawer.correction');+ const tSentiment = useTranslations('mentions.overview.sentiment');+ const locale = useLocale();+ const [open, setOpen] = useState(false);+ const [choice, setChoice] = useState<MentionSentiment | null>(row.sentiment);+ const [note, setNote] = useState('');+ const [saving, setSaving] = useState(false);++ const save = async () => {+ if (!choice) return;+ setSaving(true);+ const result = await overrideMentionSentiment(row.id, choice, note);+ setSaving(false);+ if ('error' in result) {+ toast.error(t('failed'), {+ description: result.error === 'forbidden' ? t('forbidden') : result.message,+ });+ return;+ }+ if (!result.changed) {+ toast.info(t('unchanged'));+ } else {+ toast.success(t('saved'), {+ description: t('savedDescription', { sentiment: tSentiment(result.sentiment) }),+ });+ onCorrected(result.sentiment, result.override);+ }+ setOpen(false);+ setNote('');+ };++ const date = override+ ? new Date(override.createdAt).toLocaleDateString(locale, {+ month: 'short',+ day: 'numeric',+ year: 'numeric',+ })+ : '';+ const history = override+ ? override.userName+ ? t('correctedBy', {+ name: override.userName,+ date,+ previous: tSentiment(override.previousSentiment),+ })+ : t('correctedOn', { date, previous: tSentiment(override.previousSentiment) })+ : null;++ if (!history && !canCorrect) return null;++ return (+ <div className="space-y-2">+ {history && (+ <p className="text-xs text-muted-foreground">+ {history}+ {override?.note && <span className="block italic">“{override.note}”</span>}+ </p>+ )}+ {canCorrect && !open && (+ <Button+ variant="link"+ size="sm"+ className="h-auto px-0 text-xs"+ onClick={() => {+ setChoice(row.sentiment);+ setOpen(true);+ }}+ >+ {t('open')}+ </Button>+ )}+ {canCorrect && open && (+ <div className="space-y-3 rounded-md border bg-muted/30 p-3">+ <div>+ <p className="text-sm font-medium">{t('title')}</p>+ <p className="text-xs text-muted-foreground">{t('hint')}</p>+ </div>+ <div className="flex flex-wrap gap-1.5" role="group" aria-label={t('options')}>+ {MENTION_SENTIMENTS.map((s) => (+ <button+ key={s}+ type="button"+ aria-pressed={choice === s}+ onClick={() => setChoice(s)}+ className={cn(+ 'rounded-md border px-2.5 py-1 text-xs font-medium transition-colors',+ choice === s+ ? 'border-primary bg-primary text-primary-foreground'+ : 'bg-background hover:bg-muted',+ )}+ >+ {tSentiment(s)}+ </button>+ ))}+ </div>+ <div>+ <label htmlFor={`correction-note-${row.id}`} className="text-xs font-medium">+ {t('note')}+ </label>+ <Textarea+ id={`correction-note-${row.id}`}+ value={note}+ maxLength={NOTE_MAX}+ onChange={(e) => setNote(e.target.value)}+ placeholder={t('notePlaceholder')}+ className="mt-1 min-h-16 text-sm"+ />+ </div>+ <div className="flex items-center gap-2">+ <Button+ size="sm"+ onClick={save}+ disabled={saving || !choice || choice === row.sentiment}+ >+ {t('save')}+ </Button>+ <Button variant="ghost" size="sm" onClick={() => setOpen(false)} disabled={saving}>+ {t('cancel')}+ </Button>+ </div>+ </div>+ )}+ </div>+ );+}diff --git a/web/src/lib/actions/mentions.test.ts b/web/src/lib/actions/mentions.test.tsindex 8924f6d56..82f5b6705 100644--- a/web/src/lib/actions/mentions.test.ts+++ b/web/src/lib/actions/mentions.test.ts@@ -2,15 +2,22 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';let result: { data: unknown; error: { code?: string; message: string } | null };const rpc = vi.fn(async () => result);-// A table read: every filter call is recorded, and the read ends in maybeSingle.+// A table read: every filter call is recorded, and the read ends in maybeSingle+// with the result set for that table (tableResult for any other).let tableResult: { data: unknown; error: { message: string } | null };+let tableResults: Record<string, { data: unknown; error: { message: string } | null }> = {};const tableCalls: unknown[][] = [];-const query = {- select: (...args: unknown[]) => (tableCalls.push(['select', ...args]), query),- eq: (...args: unknown[]) => (tableCalls.push(['eq', ...args]), query),- maybeSingle: async () => tableResult,-};-const from = vi.fn((table: string) => (tableCalls.push(['from', table]), query));+function query(table: string) {+ const q = {+ select: (...args: unknown[]) => (tableCalls.push(['select', ...args]), q),+ eq: (...args: unknown[]) => (tableCalls.push(['eq', ...args]), q),+ order: (...args: unknown[]) => (tableCalls.push(['order', ...args]), q),+ limit: (...args: unknown[]) => (tableCalls.push(['limit', ...args]), q),+ maybeSingle: async () => tableResults[table] ?? tableResult,+ };+ return q;+}+const from = vi.fn((table: string) => (tableCalls.push(['from', table]), query(table)));let session: { access_token: string } | null = { access_token: 'tok' };vi.mock('@/lib/supabase/server', () => ({createClient: vi.fn(async () => ({@@ -25,6 +32,7 @@ import {getMentionResponse,getMentionsOverview,listMentions,+ overrideMentionSentiment,sendMentionsToActionCenter,} from './mentions';import { DEFAULT_MENTIONS_TABLE } from '@/lib/mentions-list';@@ -35,6 +43,7 @@ beforeEach(() => {tableCalls.length = 0;result = { data: null, error: null };tableResult = { data: null, error: null };+ tableResults = {};});describe('getMentionsOverview', () => {@@ -177,21 +186,53 @@ describe('listMentions', () => {});describe('getMentionResponse', () => {- it("reads the answer's text and citations within the brand", async () => {- tableResult = {+ it("reads the answer's text, citations and latest correction within the brand", async () => {+ tableResults.prompt_results = {data: { response: 'Hello', citations: [{ url: 'https://a.com', title: 'A' }] },error: null,};+ tableResults.sentiment_overrides = {+ data: {+ sentiment: 'positive',+ previous_sentiment: 'negative',+ note: 'Praises the roast',+ user_name: 'Demo User',+ created_at: '2026-10-17T10:00:00Z',+ },+ error: null,+ };await expect(getMentionResponse('b1', 'r1')).resolves.toEqual({response: 'Hello',citations: [{ url: 'https://a.com', title: 'A' }],+ override: {+ sentiment: 'positive',+ previousSentiment: 'negative',+ note: 'Praises the roast',+ userName: 'Demo User',+ createdAt: '2026-10-17T10:00:00Z',+ },});- expect(tableCalls).toEqual([- ['from', 'prompt_results'],- ['select', 'response, citations'],- ['eq', 'id', 'r1'],- ['eq', 'brand_id', 'b1'],- ]);+ expect(tableCalls).toEqual(+ expect.arrayContaining([+ ['from', 'prompt_results'],+ ['eq', 'id', 'r1'],+ ['eq', 'brand_id', 'b1'],+ ['from', 'sentiment_overrides'],+ ['eq', 'result_id', 'r1'],+ ['order', 'created_at', { ascending: false }],+ ['limit', 1],+ ]),+ );+ });++ it('has no correction when there is none, or the table is not there yet', async () => {+ tableResults.prompt_results = { data: { response: 'Hi', citations: [] }, error: null };+ await expect(getMentionResponse('b1', 'r1')).resolves.toMatchObject({ override: null });+ tableResults.sentiment_overrides = {+ data: null,+ error: { message: 'relation does not exist' },+ };+ await expect(getMentionResponse('b1', 'r1')).resolves.toMatchObject({ override: null });});it("is null when the answer isn't readable", async () => {@@ -199,6 +240,65 @@ describe('getMentionResponse', () => {});});+describe('overrideMentionSentiment', () => {+ it('corrects the sentiment with a note and returns the correction', async () => {+ result = {+ data: {+ changed: true,+ previous: 'negative',+ sentiment: 'positive',+ override: {+ sentiment: 'positive',+ previous_sentiment: 'negative',+ note: 'Praises the roast',+ user_name: 'Demo User',+ created_at: '2026-10-17T10:00:00Z',+ },+ },+ error: null,+ };+ await expect(+ overrideMentionSentiment('r1', 'positive', ' Praises the roast '),+ ).resolves.toEqual({+ changed: true,+ sentiment: 'positive',+ override: expect.objectContaining({ previousSentiment: 'negative', userName: 'Demo User' }),+ });+ expect(rpc).toHaveBeenCalledWith('override_mention_sentiment', {+ p_result_id: 'r1',+ p_sentiment: 'positive',+ p_note: 'Praises the roast',+ });+ });++ it('sends no note when it is blank, and says when nothing changed', async () => {+ result = { data: { changed: false, override: null }, error: null };+ await expect(overrideMentionSentiment('r1', 'neutral', ' ')).resolves.toEqual({+ changed: false,+ sentiment: 'neutral',+ override: null,+ });+ expect(rpc).toHaveBeenCalledWith('override_mention_sentiment', {+ p_result_id: 'r1',+ p_sentiment: 'neutral',+ p_note: undefined,+ });+ });++ it.each([+ ['42501', 'forbidden'],+ ['22023', 'invalid'],+ ['P0002', 'missing'],+ ['57014', 'unknown'],+ ])('reads error %s as %s', async (code, kind) => {+ result = { data: null, error: { code, message: 'nope' } };+ await expect(overrideMentionSentiment('r1', 'negative')).resolves.toEqual({+ error: kind,+ message: 'nope',+ });+ });+});+describe('sendMentionsToActionCenter', () => {const fetchMock = vi.fn();beforeEach(() => {diff --git a/web/src/lib/actions/mentions.ts b/web/src/lib/actions/mentions.tsindex 1bbfe20fa..fd490f874 100644--- a/web/src/lib/actions/mentions.ts+++ b/web/src/lib/actions/mentions.ts@@ -7,8 +7,11 @@ import type { MentionsQuery } from '@/lib/mentions-filters';import {MENTIONS_PAGE_SIZE,parseMentionsList,+ parseSentimentOverride,+ type MentionSentiment,type MentionsList,type MentionsTableState,+ type SentimentOverride,} from '@/lib/mentions-list';import { parseMentionsOverview, type MentionsOverview } from '@/lib/mentions-overview';import type { Citation } from '@/types';@@ -88,26 +91,79 @@ export async function listMentions(}/**- * One answer's stored text and citations, for the response drawer. Read as- * the caller, so row-level security limits it to their organization's- * answers; null when it isn't theirs or no longer exists.+ * One answer's stored text and citations, and its latest sentiment+ * correction, for the response drawer. Read as the caller, so row-level+ * security limits it to their organization's answers; null when it isn't+ * theirs or no longer exists.*/export async function getMentionResponse(brandId: string,resultId: string,-): Promise<{ response: string; citations: Citation[] } | null> {+): Promise<{ response: string; citations: Citation[]; override: SentimentOverride | null } | null> {const supabase = await createClient();- const { data, error } = await supabase- .from('prompt_results')- .select('response, citations')- .eq('id', resultId)- .eq('brand_id', brandId)- .maybeSingle();- if (error) throw new Error(error.message);+ const [answer, correction] = await Promise.all([+ supabase+ .from('prompt_results')+ .select('response, citations')+ .eq('id', resultId)+ .eq('brand_id', brandId)+ .maybeSingle(),+ supabase+ .from('sentiment_overrides')+ .select('sentiment, previous_sentiment, note, user_name, created_at')+ .eq('result_id', resultId)+ .order('created_at', { ascending: false })+ .limit(1)+ .maybeSingle(),+ ]);+ if (answer.error) throw new Error(answer.error.message);+ const data = answer.data;if (!data) return null;return {response: typeof data.response === 'string' ? data.response : '',citations: Array.isArray(data.citations) ? (data.citations as unknown as Citation[]) : [],+ // A missing table (a build before 00160) reads as no correction.+ override: correction.error ? null : parseSentimentOverride(correction.data),+ };+}++/**+ * "Sentiment is wrong" in the response drawer (MS-08): sets an answer's+ * sentiment toward the brand, with an optional note. The database checks+ * that the caller is an admin or manager of the answer's organization,+ * changes the answer everywhere its sentiment counts, refreshes that day's+ * rollups and keeps the correction's history (00160).+ */+export async function overrideMentionSentiment(+ resultId: string,+ sentiment: MentionSentiment,+ note?: string,+): Promise<+ | { changed: boolean; sentiment: MentionSentiment; override: SentimentOverride | null }+ | { error: 'forbidden' | 'invalid' | 'missing' | 'unknown'; message: string }+> {+ const supabase = await createClient();+ const { data, error } = await supabase.rpc('override_mention_sentiment', {+ p_result_id: resultId,+ p_sentiment: sentiment,+ p_note: note?.trim() || undefined,+ });+ if (error) {+ const kind =+ error.code === '42501'+ ? 'forbidden'+ : error.code === '22023'+ ? 'invalid'+ : error.code === 'P0002'+ ? 'missing'+ : 'unknown';+ return { error: kind, message: error.message };+ }+ const r = (data ?? {}) as Record<string, unknown>;+ return {+ changed: r.changed === true,+ sentiment,+ override: parseSentimentOverride(r.override),};}diff --git a/web/src/lib/mentions-list.ts b/web/src/lib/mentions-list.tsindex 513c9d148..e9af7cbae 100644--- a/web/src/lib/mentions-list.ts+++ b/web/src/lib/mentions-list.ts@@ -145,3 +145,28 @@ export function parseMentionsList(})),};}++/** A correction of an answer's sentiment ("Sentiment is wrong", 00160). */+export interface SentimentOverride {+ sentiment: MentionSentiment;+ previousSentiment: MentionSentiment;+ note: string | null;+ /** As written when the correction was made. */+ userName: string | null;+ createdAt: string;+}++/** A sentiment_overrides row (or the function's `override`) as the page's shape. */+export function parseSentimentOverride(raw: unknown): SentimentOverride | null {+ if (!raw || typeof raw !== 'object') return null;+ const r = raw as Raw;+ const tone = (v: unknown): MentionSentiment =>+ SENTIMENTS.includes(String(v)) ? (v as MentionSentiment) : 'neutral';+ return {+ sentiment: tone(r.sentiment),+ previousSentiment: tone(r.previous_sentiment),+ note: str(r.note),+ userName: str(r.user_name),+ createdAt: String(r.created_at ?? ''),+ };+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 1f3ff4291..e7a9cc3d6 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -2374,6 +2374,64 @@ export type Database = {},]}+ sentiment_overrides: {+ Row: {+ brand_id: string+ created_at: string+ id: string+ note: string | null+ previous_sentiment: string+ result_id: string+ sentiment: string+ user_id: string | null+ user_name: string | null+ }+ Insert: {+ brand_id: string+ created_at?: string+ id?: string+ note?: string | null+ previous_sentiment: string+ result_id: string+ sentiment: string+ user_id?: string | null+ user_name?: string | null+ }+ Update: {+ brand_id?: string+ created_at?: string+ id?: string+ note?: string | null+ previous_sentiment?: string+ result_id?: string+ sentiment?: string+ user_id?: string | null+ user_name?: string | null+ }+ Relationships: [+ {+ foreignKeyName: "sentiment_overrides_brand_id_fkey"+ columns: ["brand_id"]+ isOneToOne: false+ referencedRelation: "brands"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "sentiment_overrides_result_id_fkey"+ columns: ["result_id"]+ isOneToOne: false+ referencedRelation: "prompt_results"+ referencedColumns: ["id"]+ },+ {+ foreignKeyName: "sentiment_overrides_user_id_fkey"+ columns: ["user_id"]+ isOneToOne: false+ referencedRelation: "profiles"+ referencedColumns: ["id"]+ },+ ]+ }signals: {Row: {action_id: string | null@@ -3290,6 +3348,10 @@ export type Database = {}Returns: Json}+ override_mention_sentiment: {+ Args: { p_note?: string; p_result_id: string; p_sentiment: string }+ Returns: Json+ }normalize_page_path: { Args: { p_url: string }; Returns: string }import_prompts: {Args: {