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(insights): add the topics vs competitors heat map
Cihande6ec92489e1
diff --git a/supabase/migrations/00137_insights_topic_competitors.sql b/supabase/migrations/00137_insights_topic_competitors.sqlnew file mode 100644index 000000000..70cfc7fc7--- /dev/null+++ b/supabase/migrations/00137_insights_topic_competitors.sql@@ -0,0 +1,118 @@+-- Insights "Topics vs competitors" (VIS-010).+--+-- The v2 mockup's heat map has a row per topic and a column for you and each+-- competitor on the trend, each cell the Visibility score in that topic. The+-- score is the card's formula with the brand's answers as the shared+-- denominator (as the leaderboard scores competitors), so this returns, per+-- active topic, the brand's components over the topic's prompts and each+-- live competitor's components over the same answers. The app scores them+-- and picks the columns.+--+-- Prompts take their history to the topic they're in now (topic is read at+-- query time, like the other topic reads). Whole UTC days only, from the+-- prompt-grain rollups (00130): the heat map isn't shown on the 24h view.+-- `complete` is false while those rollups aren't backfilled.++create or replace function public.insights_topic_competitors_daily(+ p_brand_id uuid,+ p_day_from date default null,+ p_day_to date default null,+ p_models text[] default null,+ p_region text default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with topic_prompts as (+ select p.id as prompt_id, t.id as topic_id+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ join public.topics t on t.id = p.topic_id+ where ps.brand_id = p_brand_id+ and t.is_active+ ),+ brand_rows as (+ select tp.topic_id, d.prompt_id, d.answer_count, d.mention_answers, d.citation_answers,+ 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 (p_day_from is null or d.day >= p_day_from)+ and (p_day_to is null or d.day <= p_day_to)+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ ),+ competitor_rows as (+ select tp.topic_id, c.id as competitor_id, cpd.mention_answers, cpd.citation_answers,+ cpd.sum_inv_position, cpd.position_count+ from public.insights_competitor_prompt_daily cpd+ join topic_prompts tp on tp.prompt_id = cpd.prompt_id+ -- Live competitors only, like the leaderboard.+ 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 (p_day_from is null or cpd.day >= p_day_from)+ and (p_day_to is null or cpd.day <= p_day_to)+ and (p_models is null or cpd.model_used = any (p_models))+ and (p_region is null or cpd.region = p_region)+ ),+ brand as (+ select topic_id,+ count(distinct prompt_id) as prompts,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from brand_rows+ group by topic_id+ ),+ competitor as (+ select topic_id, competitor_id,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from competitor_rows+ group by topic_id, competitor_id+ )+ select jsonb_build_object(+ 'complete', not exists (select 1 from brand_rows where mention_answers is null)+ and not exists (select 1 from competitor_rows where mention_answers is null),+ 'topics', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'topic_id', b.topic_id,+ 'name', t.name,+ 'prompts', b.prompts,+ 'answers', b.answers,+ 'mention_answers', b.mention_answers,+ 'citation_answers', b.citation_answers,+ 'sum_inv_position', b.sum_inv_position,+ 'position_count', b.position_count,+ 'competitors', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', c.competitor_id,+ 'mention_answers', c.mention_answers,+ 'citation_answers', c.citation_answers,+ 'sum_inv_position', c.sum_inv_position,+ 'position_count', c.position_count))+ from competitor c+ where c.topic_id = b.topic_id),+ '[]'::jsonb)))+ from brand b+ join public.topics t on t.id = b.topic_id),+ '[]'::jsonb)+ );+$$;++revoke all on function public.insights_topic_competitors_daily(+ uuid, date, date, text[], text+) from public;+grant execute on function public.insights_topic_competitors_daily(+ uuid, date, date, text[], text+) to authenticated, service_role;++comment on function public.insights_topic_competitors_daily(uuid, date, date, text[], text) is+ 'Insights "Topics vs competitors" (VIS-010, 00137): per active topic, the brand''s Visibility components over the topic''s prompts and each live competitor''s components over the same answers, from the prompt-grain rollups. complete=false until they are backfilled (00130).';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 2eeed9b15..1b5e0e500 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -16614,3 +16614,125 @@ grant execute on function public.insights_trend_markers(uuid, timestamptz, timescomment on function public.insights_trend_markers(uuid, timestamptz, timestamptz, uuid) is'Insights trend markers (VIS-007, 00136): per UTC day, the prompts created for the brand (optionally in one topic) and the Action Center actions a person sent, between two optional bounds. Security invoker.';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00137_insights_topic_competitors.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Insights "Topics vs competitors" (VIS-010).+--+-- The v2 mockup's heat map has a row per topic and a column for you and each+-- competitor on the trend, each cell the Visibility score in that topic. The+-- score is the card's formula with the brand's answers as the shared+-- denominator (as the leaderboard scores competitors), so this returns, per+-- active topic, the brand's components over the topic's prompts and each+-- live competitor's components over the same answers. The app scores them+-- and picks the columns.+--+-- Prompts take their history to the topic they're in now (topic is read at+-- query time, like the other topic reads). Whole UTC days only, from the+-- prompt-grain rollups (00130): the heat map isn't shown on the 24h view.+-- `complete` is false while those rollups aren't backfilled.++create or replace function public.insights_topic_competitors_daily(+ p_brand_id uuid,+ p_day_from date default null,+ p_day_to date default null,+ p_models text[] default null,+ p_region text default null+)+returns jsonb+language sql+stable+security invoker+set search_path to 'public'+as $$+ with topic_prompts as (+ select p.id as prompt_id, t.id as topic_id+ from public.prompts p+ join public.prompt_sets ps on ps.id = p.prompt_set_id+ join public.topics t on t.id = p.topic_id+ where ps.brand_id = p_brand_id+ and t.is_active+ ),+ brand_rows as (+ select tp.topic_id, d.prompt_id, d.answer_count, d.mention_answers, d.citation_answers,+ 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 (p_day_from is null or d.day >= p_day_from)+ and (p_day_to is null or d.day <= p_day_to)+ and (p_models is null or d.model_used = any (p_models))+ and (p_region is null or d.region = p_region)+ ),+ competitor_rows as (+ select tp.topic_id, c.id as competitor_id, cpd.mention_answers, cpd.citation_answers,+ cpd.sum_inv_position, cpd.position_count+ from public.insights_competitor_prompt_daily cpd+ join topic_prompts tp on tp.prompt_id = cpd.prompt_id+ -- Live competitors only, like the leaderboard.+ 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 (p_day_from is null or cpd.day >= p_day_from)+ and (p_day_to is null or cpd.day <= p_day_to)+ and (p_models is null or cpd.model_used = any (p_models))+ and (p_region is null or cpd.region = p_region)+ ),+ brand as (+ select topic_id,+ count(distinct prompt_id) as prompts,+ sum(answer_count) as answers,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from brand_rows+ group by topic_id+ ),+ competitor as (+ select topic_id, competitor_id,+ sum(mention_answers) as mention_answers,+ sum(citation_answers) as citation_answers,+ sum(sum_inv_position) as sum_inv_position,+ sum(position_count) as position_count+ from competitor_rows+ group by topic_id, competitor_id+ )+ select jsonb_build_object(+ 'complete', not exists (select 1 from brand_rows where mention_answers is null)+ and not exists (select 1 from competitor_rows where mention_answers is null),+ 'topics', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'topic_id', b.topic_id,+ 'name', t.name,+ 'prompts', b.prompts,+ 'answers', b.answers,+ 'mention_answers', b.mention_answers,+ 'citation_answers', b.citation_answers,+ 'sum_inv_position', b.sum_inv_position,+ 'position_count', b.position_count,+ 'competitors', coalesce(+ (select jsonb_agg(jsonb_build_object(+ 'competitor_id', c.competitor_id,+ 'mention_answers', c.mention_answers,+ 'citation_answers', c.citation_answers,+ 'sum_inv_position', c.sum_inv_position,+ 'position_count', c.position_count))+ from competitor c+ where c.topic_id = b.topic_id),+ '[]'::jsonb)))+ from brand b+ join public.topics t on t.id = b.topic_id),+ '[]'::jsonb)+ );+$$;++revoke all on function public.insights_topic_competitors_daily(+ uuid, date, date, text[], text+) from public;+grant execute on function public.insights_topic_competitors_daily(+ uuid, date, date, text[], text+) to authenticated, service_role;++comment on function public.insights_topic_competitors_daily(uuid, date, date, text[], text) is+ 'Insights "Topics vs competitors" (VIS-010, 00137): per active topic, the brand''s Visibility components over the topic''s prompts and each live competitor''s components over the same answers, from the prompt-grain rollups. complete=false until they are backfilled (00130).';+diff --git a/web/messages/en.json b/web/messages/en.jsonindex 21e0092d3..fce04232f 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -1782,6 +1782,18 @@"moreActions": "{actions} +{count}","goal": "Goal {value}","goalLegend": "Action Center goal"+ },+ "topicMap": {+ "title": "Topics vs competitors",+ "tableLabel": "Visibility by topic and brand",+ "topic": "Topic",+ "you": "You",+ "gap": "Gap",+ "lead": "Lead",+ "lowSample": "Low sample",+ "openTopic": "Open {topic}",+ "showAll": "Show all {count}",+ "showLess": "Show less"}},"topics": {diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsxnew file mode 100644index 000000000..33ce40dcb--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_topic-heatmap.tsx@@ -0,0 +1,135 @@+'use client';++import { useState } from 'react';+import { useTranslations } from 'next-intl';+import { Link } from '@/i18n/navigation';+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';+import { cn } from '@/lib/utils';+import { heatShade, topicHeatmap, type TopicCompetitors } from '@/lib/insights-topics';+import { TONE_TEXT } from './kpi-format';++/** Rows shown before "Show all". */+const VISIBLE_ROWS = 6;++/** A gap with one decimal, so the column lines up: "−29.0", "−20.3". */+const gapText = (gap: number) => `−${Math.abs(gap).toFixed(1)}`;++/**+ * Cell shades, light to dark, as theme-relative tints so they read in both+ * themes; the darkest two flip the text color.+ */+const SHADES = [+ 'bg-muted/60 text-muted-foreground',+ 'bg-foreground/10 text-foreground',+ 'bg-foreground/20 text-foreground',+ 'bg-foreground/40 text-foreground',+ 'bg-foreground/75 text-background',+] as const;++/**+ * "Topics vs competitors" (VIS-010), as in the v2 mockup: a row per topic,+ * a column for you and each competitor on the trend (pinned, or the+ * strongest four), each cell the topic's Visibility score shaded light to+ * dark, and the gap to the topic's leader. A cell opens the topic.+ */+export function TopicHeatmap({+ topics,+ columns,+ className,+}: {+ topics: TopicCompetitors[];+ /** You first, then the competitors on the trend: `'you'` or a competitor id. */+ columns: { key: string; name: string }[];+ className?: string;+}) {+ const t = useTranslations('insights.topicMap');+ // Expanded for this data only: another brand or range starts folded.+ const [expandedFor, setExpandedFor] = useState<TopicCompetitors[] | null>(null);+ const expanded = expandedFor === topics;++ const rows = topicHeatmap(+ topics,+ columns.map((c) => c.key),+ );+ const shown = expanded ? rows : rows.slice(0, VISIBLE_ROWS);++ return (+ <Card className={className}>+ <CardHeader className="pb-2">+ <CardTitle className="text-sm font-medium">{t('title')}</CardTitle>+ </CardHeader>+ <CardContent className="overflow-x-auto">+ {/* Fixed layout: every brand column gets the same width, as in the mockup. */}+ <table className="w-full min-w-[520px] table-fixed text-sm" aria-label={t('tableLabel')}>+ <thead>+ <tr className="border-b text-[11px] uppercase tracking-wide text-muted-foreground">+ <th className="w-[30%] py-2 pr-3 text-left font-medium">{t('topic')}</th>+ {columns.map((c) => (+ <th key={c.key} className="px-1 py-2 text-center font-medium">+ <span className="block truncate" title={c.name}>+ {c.key === 'you' ? t('you') : c.name}+ </span>+ </th>+ ))}+ <th className="w-24 py-2 pl-2 text-right font-medium">{t('gap')}</th>+ </tr>+ </thead>+ <tbody>+ {shown.map((row) => (+ <tr key={row.topicId} className="border-b last:border-b-0">+ <td className="truncate py-1.5 pr-3 font-medium" title={row.name}>+ <Link href={`/dashboard/topics/${row.topicId}`} className="hover:underline">+ {row.name}+ </Link>+ </td>+ {row.scores.map((value, i) => (+ <td key={columns[i].key} className="px-1 py-1.5">+ {/* The topic name is the keyboard stop; cells are a mouse shortcut to it. */}+ <Link+ href={`/dashboard/topics/${row.topicId}`}+ tabIndex={-1}+ title={t('openTopic', { topic: row.name })}+ className={cn(+ 'block rounded-md px-1 py-1.5 text-center font-semibold tabular-nums transition-opacity hover:opacity-80',+ SHADES[heatShade(value)],+ // Too few answers to read much into: shown, but faded.+ row.status === 'lowSample' && 'opacity-50',+ )}+ >+ {value.toFixed(1)}+ </Link>+ </td>+ ))}+ <td+ className={cn(+ 'whitespace-nowrap py-1.5 pl-2 text-right font-semibold tabular-nums',+ row.status === 'lead'+ ? TONE_TEXT.good+ : row.status === 'behind'+ ? TONE_TEXT.bad+ : 'text-xs font-normal text-muted-foreground',+ )}+ >+ {row.status === 'lead'+ ? t('lead')+ : row.status === 'behind'+ ? gapText(row.gap!)+ : t('lowSample')}+ </td>+ </tr>+ ))}+ </tbody>+ </table>+ {rows.length > VISIBLE_ROWS && (+ <button+ type="button"+ onClick={() => setExpandedFor(expanded ? null : topics)}+ className="mt-1.5 w-full py-1 text-center text-xs font-medium text-muted-foreground transition-colors hover:text-foreground"+ >+ {expanded ? t('showLess') : t('showAll', { count: rows.length })}+ </button>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsxindex 3d7c5851c..64ad2bd3e 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx@@ -80,7 +80,9 @@ import { SummaryLine } from './_summary-line';import { PlatformTable } from './_platform-table';import { Leaderboard } from './_leaderboard';import { TrendCard } from './_trend-card';-import type { TrendMarkerData } from '@/lib/insights-trend';+import { trendLines, type TrendMarkerData } from '@/lib/insights-trend';+import { TopicHeatmap } from './_topic-heatmap';+import type { TopicCompetitors } from '@/lib/insights-topics';import { WhyChanged } from './_why-changed';import type { WhyChanged as WhyChangedData } from '@/lib/insights-drivers';@@ -856,6 +858,7 @@ export default function InsightsPage() {const [platforms, setPlatforms] = useState<PlatformTableRow[] | null>(null);const [whyChanged, setWhyChanged] = useState<WhyChangedData | null>(null);const [trendMarkers, setTrendMarkers] = useState<TrendMarkerData | null>(null);+ const [topicCompetitors, setTopicCompetitors] = useState<TopicCompetitors[] | null>(null);const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);const [breakdownTab, setBreakdownTab] = useState<BreakdownTab | undefined>(undefined);// The window and filters the cards were last loaded with (the 24h view@@ -949,6 +952,7 @@ export default function InsightsPage() {setPlatforms(insights.platforms);setWhyChanged(insights.whyChanged);setTrendMarkers(insights.trendMarkers);+ setTopicCompetitors(insights.topicCompetitors);setHasAnyData(insights.hasAnyData);// Group raw model slugs by their resolved display name so different@@ -1473,6 +1477,20 @@ export default function InsightsPage() {</div>)}+ {/* Topics vs competitors (VIS-010): the trend's brands, topic by topic. */}+ {/* Its columns are the trend's lines, so it needs the trend's points. */}+ {rateTrend &&+ rateTrend.points.length > 0 &&+ topicCompetitors &&+ topicCompetitors.length > 0 && (+ <TopicHeatmap+ topics={topicCompetitors}+ columns={trendLines(rateTrend.entities, rateTrend.points, rateTrend.pinned).map(+ (line) => ({ key: line.key, name: line.name }),+ )}+ />+ )}+{/* Recommendations (#459) — stored data, not period-scoped */}{recommendations && <RecommendationsSection data={recommendations} />}</>diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.tsindex e565ef08e..f71006aca 100644--- a/web/src/lib/actions/tracking.ts+++ b/web/src/lib/actions/tracking.ts@@ -47,6 +47,7 @@ import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';import { percentageChange } from '@/lib/metrics';import { parseChangeDrivers, whyChanged, type WhyChanged } from '@/lib/insights-drivers';import { parseTrendMarkers, type TrendMarkerData } from '@/lib/insights-trend';+import { parseTopicCompetitors, type TopicCompetitors } from '@/lib/insights-topics';import {parsePlatformRows,platformChanges,@@ -749,6 +750,12 @@ export interface InsightsData {* chart has no days to mark, or when the read failed.*/trendMarkers: TrendMarkerData | null;+ /**+ * "Topics vs competitors" (VIS-010): per topic, your and each competitor's+ * Visibility components. Null on the 24h view, with a topic selected,+ * before the backfill, or when the read failed.+ */+ topicCompetitors: TopicCompetitors[] | null;/** The run ledger, when the 24h window was anchored to it (`anchor24h`). */trackingWindow: TrackingWindow | null;}@@ -847,6 +854,7 @@ type WindowedInsights = Pick<| 'platforms'| 'whyChanged'| 'trendMarkers'+ | 'topicCompetitors'>;type InsightsFilterArgs = {@@ -900,6 +908,7 @@ async function loadWindowedInsights(platformData,drivers,trendMarkers,+ topicCompetitors,] = await Promise.all([getInsightsSummary(brandId, filterOpts),lenient(@@ -921,6 +930,7 @@ async function loadWindowedInsights(lenient(getPlatformData(brandId, filterOpts), null, 'platforms'),lenient(getChangeDrivers(brandId, filterOpts), null, 'why it changed'),lenient(getTrendMarkers(brandId, filterOpts), null, 'trend markers'),+ lenient(getTopicCompetitors(brandId, filterOpts), null, 'topics vs competitors'),]);const windowed = {...(comparisonWindows(filterOpts).prev ? { summary, sov } : withoutChanges(summary, sov)),@@ -942,6 +952,7 @@ async function loadWindowedInsights(drivers &&whyChanged(drivers, resolveProvider, { samePrompts: filterOpts.samePrompts !== false }),trendMarkers,+ topicCompetitors,};return withPromptComparison(windowed, same, filterOpts.samePrompts !== false);}@@ -1036,6 +1047,28 @@ async function getKpiSeries(return parseKpiSeries(data);}+/**+ * "Topics vs competitors" (VIS-010): per active topic, the brand's and each+ * competitor's Visibility components in the window, from the rollups. Null+ * on the 24h view and when a topic is selected (one row isn't a map).+ */+async function getTopicCompetitors(+ brandId: string,+ opts?: InsightsFilterArgs,+): Promise<TopicCompetitors[] | null> {+ if (!opts?.days || opts.topicId) return null;+ const supabase = await dbClient();+ const { data, error } = await supabase.rpc('insights_topic_competitors_daily', {+ p_brand_id: brandId,+ p_day_from: opts.days.dayFrom,+ p_day_to: opts.days.dayTo,+ p_models: modelFilterArray(opts.model),+ p_region: opts.region ?? undefined,+ });+ if (error) throw new Error(error.message);+ return parseTopicCompetitors(data);+}+/*** The trend's markers and goal (VIS-007): per UTC day in the charted range,* the prompts added and the actions people sent, and the target of thediff --git a/web/src/lib/insights-topics.test.ts b/web/src/lib/insights-topics.test.tsnew file mode 100644index 000000000..101a8466e--- /dev/null+++ b/web/src/lib/insights-topics.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it } from 'vitest';+import { computeAiVisibilityScore } from './visibility-score';+import {+ heatShade,+ parseTopicCompetitors,+ topicHeatmap,+ type TopicCompetitors,+} from './insights-topics';++const comps = (mentions: number) => ({+ mentionAnswers: mentions,+ citationAnswers: 0,+ sumInvPosition: 0,+ positionCount: 0,+});++const topic = (+ topicId: string,+ answers: number,+ you: number,+ competitors: Record<string, number>,+): TopicCompetitors => ({+ topicId,+ name: topicId.toUpperCase(),+ prompts: 3,+ answers,+ brand: comps(you),+ competitors: Object.fromEntries(Object.entries(competitors).map(([id, m]) => [id, comps(m)])),+});++const score = (answers: number, mentions: number) =>+ Math.round(+ computeAiVisibilityScore({+ answers,+ mentionAnswers: mentions,+ citationAnswers: 0,+ positionFactor: null,+ })! * 10,+ ) / 10;++describe('topicHeatmap', () => {+ it('scores every column over your answers in the topic', () => {+ const [row] = topicHeatmap([topic('crm', 100, 20, { a: 60 })], ['you', 'a', 'b']);++ // A competitor never named in the topic scores 0 there.+ expect(row.scores).toEqual([score(100, 20), score(100, 60), score(100, 0)]);+ expect(row).toMatchObject({+ status: 'behind',+ leader: 'a',+ gap: Math.round((score(100, 20) - score(100, 60)) * 10) / 10,+ });+ });++ it('puts the topics you lead first, then the biggest gaps, then low samples', () => {+ const rows = topicHeatmap(+ [+ topic('small-gap', 100, 40, { a: 50 }),+ topic('lead', 100, 80, { a: 50 }),+ topic('few', 10, 1, { a: 9 }),+ topic('big-gap', 100, 10, { a: 70 }),+ ],+ ['you', 'a'],+ );++ expect(rows.map((r) => [r.topicId, r.status])).toEqual([+ ['lead', 'lead'],+ ['big-gap', 'behind'],+ ['small-gap', 'behind'],+ ['few', 'lowSample'],+ ]);+ expect(rows[0]).toMatchObject({ gap: null, leader: 'you' });+ expect(rows[3].gap).toBeNull();+ });++ it('reads a tie at the top as a lead', () => {+ expect(topicHeatmap([topic('tie', 100, 50, { a: 50 })], ['you', 'a'])[0].status).toBe('lead');+ });+});++describe('heatShade', () => {+ it('darkens at the mockup’s steps', () => {+ expect([0, 14.9, 15, 25, 35, 45, 90].map(heatShade)).toEqual([0, 0, 1, 2, 3, 4, 4]);+ });+});++describe('parseTopicCompetitors', () => {+ it('reads the RPC payload and refuses rollups not yet backfilled', () => {+ const [parsed] = parseTopicCompetitors({+ complete: true,+ topics: [+ {+ topic_id: 't1',+ name: 'CRM',+ prompts: '3',+ answers: '59',+ mention_answers: 59,+ competitors: [{ competitor_id: 'c1', mention_answers: '39', position_count: 2 }],+ },+ ],+ })!;++ expect(parsed).toMatchObject({ topicId: 't1', name: 'CRM', prompts: 3, answers: 59 });+ expect(parsed.brand.mentionAnswers).toBe(59);+ expect(parsed.competitors.c1).toEqual({+ mentionAnswers: 39,+ citationAnswers: 0,+ sumInvPosition: 0,+ positionCount: 2,+ });+ expect(parseTopicCompetitors({ complete: false, topics: [] })).toBeNull();+ });+});diff --git a/web/src/lib/insights-topics.ts b/web/src/lib/insights-topics.tsnew file mode 100644index 000000000..2a4ce6554--- /dev/null+++ b/web/src/lib/insights-topics.ts@@ -0,0 +1,129 @@+import { computeAiVisibilityScore } from '@/lib/visibility-score';+import { LOW_SAMPLE_ANSWERS } from '@/lib/insights-summary';++/**+ * "Topics vs competitors" (VIS-010), as in the v2 mockup: a row per topic,+ * a column for you and each competitor on the trend, each cell the+ * Visibility score in that topic (the card's formula, over your answers in+ * the topic), and the gap to the topic's leader. Built from+ * insights_topic_competitors_daily (00137).+ */++interface Components {+ mentionAnswers: number;+ citationAnswers: number;+ sumInvPosition: number;+ positionCount: number;+}++export interface TopicCompetitors {+ topicId: string;+ name: string;+ prompts: number;+ /** Your answers in the topic: every score's denominator. */+ answers: number;+ brand: Components;+ /**+ * Live competitors named in the topic, by id; a missing one scored 0 there.+ * A plain object, as it crosses the server action boundary.+ */+ competitors: Record<string, Components>;+}++const num = (v: unknown): number => Number(v ?? 0);+const componentsOf = (r: Record<string, unknown>): Components => ({+ mentionAnswers: num(r.mention_answers),+ citationAnswers: num(r.citation_answers),+ sumInvPosition: num(r.sum_inv_position),+ positionCount: num(r.position_count),+});++/** The RPC payload, or null when the rollups behind it aren't backfilled. */+export function parseTopicCompetitors(raw: unknown): TopicCompetitors[] | null {+ const r = raw as { complete?: boolean; topics?: Record<string, unknown>[] } | null;+ if (!r || r.complete !== true) return null;+ return (r.topics ?? []).map((t) => ({+ topicId: String(t.topic_id),+ name: String(t.name ?? ''),+ prompts: num(t.prompts),+ answers: num(t.answers),+ brand: componentsOf(t),+ competitors: Object.fromEntries(+ (Array.isArray(t.competitors) ? (t.competitors as Record<string, unknown>[]) : []).map(+ (c) => [String(c.competitor_id), componentsOf(c)],+ ),+ ),+ }));+}++const score = (answers: number, c: Components | undefined) =>+ Math.round(+ (computeAiVisibilityScore({+ answers,+ mentionAnswers: c?.mentionAnswers ?? 0,+ citationAnswers: c?.citationAnswers ?? 0,+ positionFactor: c && c.positionCount > 0 ? c.sumInvPosition / c.positionCount : null,+ }) ?? 0) * 10,+ ) / 10;++export interface HeatmapRow {+ topicId: string;+ name: string;+ /** One score per column, in column order. */+ scores: number[];+ /**+ * 'lead': your score is the highest in the row; 'behind': `gap` is your+ * score minus the leader's; 'lowSample': too few answers for a gap.+ */+ status: 'lead' | 'behind' | 'lowSample';+ gap: number | null;+ /** The column leading the topic. */+ leader: string;+}++/**+ * The heat map's rows for the given columns (`'you'` and competitor ids):+ * the topics you lead first, then the ones you trail, biggest gap first,+ * then the ones with too few answers for a gap.+ */+export function topicHeatmap(topics: TopicCompetitors[], columns: string[]): HeatmapRow[] {+ const rows = topics.map((t): HeatmapRow => {+ const scores = columns.map((key) =>+ score(t.answers, key === 'you' ? t.brand : t.competitors[key]),+ );+ const you = scores[columns.indexOf('you')] ?? 0;+ const best = Math.max(...scores);+ const leader = columns[scores.indexOf(best)];+ if (t.answers < LOW_SAMPLE_ANSWERS) {+ return { topicId: t.topicId, name: t.name, scores, status: 'lowSample', gap: null, leader };+ }+ // A tie at the top is still a lead.+ return you >= best+ ? { topicId: t.topicId, name: t.name, scores, status: 'lead', gap: null, leader: 'you' }+ : {+ topicId: t.topicId,+ name: t.name,+ scores,+ status: 'behind',+ gap: Math.round((you - best) * 10) / 10,+ leader,+ };+ });++ const order = { lead: 0, behind: 1, lowSample: 2 };+ return rows.sort(+ (a, b) =>+ order[a.status] - order[b.status] ||+ (a.gap ?? 0) - (b.gap ?? 0) ||+ a.name.localeCompare(b.name),+ );+}++/** A cell's shade, light to dark, by score (the mockup's 15/25/35/45 steps). */+export function heatShade(score: number): 0 | 1 | 2 | 3 | 4 {+ if (score >= 45) return 4;+ if (score >= 35) return 3;+ if (score >= 25) return 2;+ if (score >= 15) return 1;+ return 0;+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 5098d158d..a08a27e60 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -3187,6 +3187,16 @@ export type Database = {}Returns: Json}+ insights_topic_competitors_daily: {+ Args: {+ p_brand_id: string+ p_day_from?: string+ p_day_to?: string+ p_models?: string[]+ p_region?: string+ }+ Returns: Json+ }insights_trend_markers: {Args: {p_brand_id: string