Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(insights): add the one-line summary above the KPI cards (#1038)

Cihand8df32ff16e2
diff --git a/supabase/migrations/00132_insights_platform_compare.sql b/supabase/migrations/00132_insights_platform_compare.sql
new file mode 100644
index 000000000..871cf2daa
--- /dev/null
+++ b/supabase/migrations/00132_insights_platform_compare.sql
@@ -0,0 +1,177 @@
+-- Insights summary line (VIS-006): which platform moved Visibility most.
+--
+-- The v2 mockup's summary line names the platform whose Visibility rose most
+-- and the one that fell most ("Up most: Google AI Mode +16.1 · Down most:
+-- ChatGPT −3.2"). That needs each platform's score components in both
+-- comparison windows, and with "Compare: Same prompts" (00130) only over the
+-- prompts answered in both, like every other change on the page.
+--
+-- These return one row per (model_used, platform, window) with the
+-- Visibility components; the app folds model slugs into providers and scores
+-- them with the card's formula. Same windows and filters as
+-- insights_same_prompt_compare[_daily]: the rollups for whole days, the raw
+-- rows for the 24h and topic views. `complete` is false while the
+-- prompt-grain rollups behind the window are not backfilled (00130).
+
+create or replace function public.insights_platform_compare_daily(
+ p_brand_id uuid,
+ p_cur_from date,
+ p_cur_to date,
+ p_prev_from date,
+ p_prev_to date,
+ p_models text[] default null,
+ p_region text default null,
+ p_same_prompts boolean default true
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with prompt_rows as (
+ select d.*,
+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win
+ from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)
+ ),
+ shared as (
+ select prompt_id
+ from prompt_rows
+ group by prompt_id
+ having bool_or(win = 'cur') and bool_or(win = 'prev')
+ ),
+ scoped as (
+ select * from prompt_rows
+ where not p_same_prompts or prompt_id in (select prompt_id from shared)
+ ),
+ platforms as (
+ select model_used, platform, win,
+ 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 scoped
+ group by model_used, platform, win
+ )
+ select jsonb_build_object(
+ 'complete', not exists (select 1 from prompt_rows where mention_answers is null),
+ 'platforms', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', p.model_used,
+ 'platform', p.platform,
+ 'win', p.win,
+ 'answers', p.answers,
+ 'mention_answers', p.mention_answers,
+ 'citation_answers', p.citation_answers,
+ 'sum_inv_position', p.sum_inv_position,
+ 'position_count', p.position_count))
+ from platforms p),
+ '[]'::jsonb)
+ );
+$$;
+
+create or replace function public.insights_platform_compare(
+ p_brand_id uuid,
+ p_cur_from timestamptz,
+ p_cur_to timestamptz,
+ p_prev_from timestamptz,
+ p_prev_to timestamptz,
+ p_models text[] default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_same_prompts boolean default true
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with filtered as (
+ select pr.prompt_id, pr.model_used, pr.platform, pr.created_at,
+ pr.mention_count, pr.citation_count, pr.mention_position
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (p_models is null or pr.model_used = any (p_models))
+ and (p_region is null or pr.region = p_region)
+ and pr.created_at >= p_prev_from
+ and pr.created_at <= p_cur_to
+ and (p_topic_id is null or exists (
+ select 1 from public.prompts p
+ where p.id = pr.prompt_id and p.topic_id = p_topic_id))
+ ),
+ -- Each window selected on its own, inclusive at both ends like the card.
+ windowed as (
+ select 'cur' as win, f.* from filtered f
+ where f.created_at >= p_cur_from and f.created_at <= p_cur_to
+ union all
+ select 'prev' as win, f.* from filtered f
+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to
+ ),
+ shared as (
+ select prompt_id
+ from windowed
+ group by prompt_id
+ having bool_or(win = 'cur') and bool_or(win = 'prev')
+ ),
+ scoped as (
+ select * from windowed
+ where not p_same_prompts or prompt_id in (select prompt_id from shared)
+ ),
+ platforms as (
+ select model_used, platform, win,
+ count(*) as answers,
+ count(*) filter (where mention_count > 0) as mention_answers,
+ count(*) filter (where citation_count > 0) as citation_answers,
+ sum(1.0 / mention_position) filter (where mention_position is not null)
+ as sum_inv_position,
+ count(*) filter (where mention_position is not null) as position_count
+ from scoped
+ group by model_used, platform, win
+ )
+ select jsonb_build_object(
+ 'complete', true,
+ 'platforms', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', p.model_used,
+ 'platform', p.platform,
+ 'win', p.win,
+ 'answers', p.answers,
+ 'mention_answers', p.mention_answers,
+ 'citation_answers', p.citation_answers,
+ 'sum_inv_position', p.sum_inv_position,
+ 'position_count', p.position_count))
+ from platforms p),
+ '[]'::jsonb)
+ );
+$$;
+
+revoke all on function public.insights_platform_compare_daily(
+ uuid, date, date, date, date, text[], text, boolean
+) from public;
+grant execute on function public.insights_platform_compare_daily(
+ uuid, date, date, date, date, text[], text, boolean
+) to authenticated, service_role;
+
+revoke all on function public.insights_platform_compare(
+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean
+) from public;
+grant execute on function public.insights_platform_compare(
+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean
+) to authenticated, service_role;
+
+comment on function public.insights_platform_compare_daily(
+ uuid, date, date, date, date, text[], text, boolean
+) is
+ 'Insights summary line (VIS-006, 00132): Visibility components per (model, platform) in both comparison windows, over the prompts answered in both when p_same_prompts, from the prompt-grain rollups. complete=false until they are backfilled (00130).';
+
+comment on function public.insights_platform_compare(
+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean
+) is
+ 'Insights summary line (VIS-006, 00132) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_platform_compare_daily.';
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 4b60df96c..88f062eed 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -16116,6 +16116,187 @@ grant execute on function public.insights_kpi_series(uuid, date, date, text[], t
comment on function public.insights_kpi_series(uuid, date, date, text[], text, uuid) is
'Insights KPI sparklines (VIS-003, 00131): the cards'' components per day from the prompt-grain rollups, topic filter included. complete=false until the rows are rewritten by refresh_insights_daily.';
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00132_insights_platform_compare.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- Insights summary line (VIS-006): which platform moved Visibility most.
+--
+-- The v2 mockup's summary line names the platform whose Visibility rose most
+-- and the one that fell most ("Up most: Google AI Mode +16.1 · Down most:
+-- ChatGPT −3.2"). That needs each platform's score components in both
+-- comparison windows, and with "Compare: Same prompts" (00130) only over the
+-- prompts answered in both, like every other change on the page.
+--
+-- These return one row per (model_used, platform, window) with the
+-- Visibility components; the app folds model slugs into providers and scores
+-- them with the card's formula. Same windows and filters as
+-- insights_same_prompt_compare[_daily]: the rollups for whole days, the raw
+-- rows for the 24h and topic views. `complete` is false while the
+-- prompt-grain rollups behind the window are not backfilled (00130).
+
+create or replace function public.insights_platform_compare_daily(
+ p_brand_id uuid,
+ p_cur_from date,
+ p_cur_to date,
+ p_prev_from date,
+ p_prev_to date,
+ p_models text[] default null,
+ p_region text default null,
+ p_same_prompts boolean default true
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with prompt_rows as (
+ select d.*,
+ case when d.day between p_cur_from and p_cur_to then 'cur' else 'prev' end as win
+ from public.insights_prompt_daily d
+ where d.brand_id = p_brand_id
+ and (p_models is null or d.model_used = any (p_models))
+ and (p_region is null or d.region = p_region)
+ and (d.day between p_cur_from and p_cur_to or d.day between p_prev_from and p_prev_to)
+ ),
+ shared as (
+ select prompt_id
+ from prompt_rows
+ group by prompt_id
+ having bool_or(win = 'cur') and bool_or(win = 'prev')
+ ),
+ scoped as (
+ select * from prompt_rows
+ where not p_same_prompts or prompt_id in (select prompt_id from shared)
+ ),
+ platforms as (
+ select model_used, platform, win,
+ 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 scoped
+ group by model_used, platform, win
+ )
+ select jsonb_build_object(
+ 'complete', not exists (select 1 from prompt_rows where mention_answers is null),
+ 'platforms', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', p.model_used,
+ 'platform', p.platform,
+ 'win', p.win,
+ 'answers', p.answers,
+ 'mention_answers', p.mention_answers,
+ 'citation_answers', p.citation_answers,
+ 'sum_inv_position', p.sum_inv_position,
+ 'position_count', p.position_count))
+ from platforms p),
+ '[]'::jsonb)
+ );
+$$;
+
+create or replace function public.insights_platform_compare(
+ p_brand_id uuid,
+ p_cur_from timestamptz,
+ p_cur_to timestamptz,
+ p_prev_from timestamptz,
+ p_prev_to timestamptz,
+ p_models text[] default null,
+ p_region text default null,
+ p_topic_id uuid default null,
+ p_same_prompts boolean default true
+)
+returns jsonb
+language sql
+stable
+security invoker
+set search_path to 'public'
+as $$
+ with filtered as (
+ select pr.prompt_id, pr.model_used, pr.platform, pr.created_at,
+ pr.mention_count, pr.citation_count, pr.mention_position
+ from public.prompt_results pr
+ where pr.brand_id = p_brand_id
+ and pr.platform <> 'chatgpt-shopping'
+ and (p_models is null or pr.model_used = any (p_models))
+ and (p_region is null or pr.region = p_region)
+ and pr.created_at >= p_prev_from
+ and pr.created_at <= p_cur_to
+ and (p_topic_id is null or exists (
+ select 1 from public.prompts p
+ where p.id = pr.prompt_id and p.topic_id = p_topic_id))
+ ),
+ -- Each window selected on its own, inclusive at both ends like the card.
+ windowed as (
+ select 'cur' as win, f.* from filtered f
+ where f.created_at >= p_cur_from and f.created_at <= p_cur_to
+ union all
+ select 'prev' as win, f.* from filtered f
+ where f.created_at >= p_prev_from and f.created_at <= p_prev_to
+ ),
+ shared as (
+ select prompt_id
+ from windowed
+ group by prompt_id
+ having bool_or(win = 'cur') and bool_or(win = 'prev')
+ ),
+ scoped as (
+ select * from windowed
+ where not p_same_prompts or prompt_id in (select prompt_id from shared)
+ ),
+ platforms as (
+ select model_used, platform, win,
+ count(*) as answers,
+ count(*) filter (where mention_count > 0) as mention_answers,
+ count(*) filter (where citation_count > 0) as citation_answers,
+ sum(1.0 / mention_position) filter (where mention_position is not null)
+ as sum_inv_position,
+ count(*) filter (where mention_position is not null) as position_count
+ from scoped
+ group by model_used, platform, win
+ )
+ select jsonb_build_object(
+ 'complete', true,
+ 'platforms', coalesce(
+ (select jsonb_agg(jsonb_build_object(
+ 'model_used', p.model_used,
+ 'platform', p.platform,
+ 'win', p.win,
+ 'answers', p.answers,
+ 'mention_answers', p.mention_answers,
+ 'citation_answers', p.citation_answers,
+ 'sum_inv_position', p.sum_inv_position,
+ 'position_count', p.position_count))
+ from platforms p),
+ '[]'::jsonb)
+ );
+$$;
+
+revoke all on function public.insights_platform_compare_daily(
+ uuid, date, date, date, date, text[], text, boolean
+) from public;
+grant execute on function public.insights_platform_compare_daily(
+ uuid, date, date, date, date, text[], text, boolean
+) to authenticated, service_role;
+
+revoke all on function public.insights_platform_compare(
+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean
+) from public;
+grant execute on function public.insights_platform_compare(
+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean
+) to authenticated, service_role;
+
+comment on function public.insights_platform_compare_daily(
+ uuid, date, date, date, date, text[], text, boolean
+) is
+ 'Insights summary line (VIS-006, 00132): Visibility components per (model, platform) in both comparison windows, over the prompts answered in both when p_same_prompts, from the prompt-grain rollups. complete=false until they are backfilled (00130).';
+
+comment on function public.insights_platform_compare(
+ uuid, timestamptz, timestamptz, timestamptz, timestamptz, text[], text, uuid, boolean
+) is
+ 'Insights summary line (VIS-006, 00132) for timestamp windows (24h, topic views), from prompt_results. Same output as insights_platform_compare_daily.';
+
-- ─────────────────────────────────────────────────────────────────────────
-- migrations/00147_insights_same_prompts_definer.sql
-- ─────────────────────────────────────────────────────────────────────────
diff --git a/web/messages/en.json b/web/messages/en.json
index e883bebeb..5f1d3d591 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -1724,6 +1724,22 @@
"citationRate": "Citation rate",
"citationRateTip": "Share of answers that cite your domain.",
"citationRateSub": "of answers cite you"
+ },
+ "summary": {
+ "label": "Summary",
+ "visibility": "visibility",
+ "rank": "#{rank}",
+ "ofCount": "of {count}",
+ "pts": "{value} pts",
+ "behind": "behind {name}",
+ "ahead": "ahead of {name}",
+ "tied": "tied with {name}",
+ "upMost": "Up most:",
+ "downMost": "Down most:",
+ "vs": "vs {from} – {to}",
+ "copy": "Copy summary",
+ "copied": "Summary copied",
+ "copyFailed": "Couldn't copy the summary. Select the text and copy it instead."
}
},
"topics": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
index 2b476330c..00f4ce2f7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_kpi-cards.tsx
@@ -34,9 +34,9 @@ import {
lowerIsGood,
signedChange,
signedValue,
+ TONE_TEXT,
upIsGood,
type Change,
- type Tone,
} from './kpi-format';
// ─── Info tooltip ─────────────────────────────────────────────────────────────
@@ -91,12 +91,6 @@ export function InfoTip({ content }: { content: string }) {
// ─── Card parts ───────────────────────────────────────────────────────────────
-const TONE_TEXT: Record<Tone, string> = {
- good: 'text-emerald-600 dark:text-emerald-400',
- bad: 'text-red-600 dark:text-red-400',
- neutral: 'text-muted-foreground',
-};
-
/**
* A daily sparkline. Days without a value are skipped; fewer than two
* points draw nothing. Grey normally, red when the card's change is bad.
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsx
new file mode 100644
index 000000000..6bf1123c3
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/_summary-line.tsx
@@ -0,0 +1,85 @@
+'use client';
+
+import { Fragment } from 'react';
+import { useTranslations } from 'next-intl';
+import { Copy, Sparkles } from 'lucide-react';
+import { toast } from 'sonner';
+import { cn } from '@/lib/utils';
+import { TONE_TEXT } from './kpi-format';
+import { summaryContext, summaryFacts, summaryText, type SummaryInput } from './summary-format';
+
+/**
+ * The summary line above the KPI cards (VIS-006), as in the v2 mockup: the
+ * Visibility score and change, the rank and the gap to the neighbouring
+ * brand, the platforms that moved most, and what the change compares. A fixed
+ * template over numbers the page already shows; Copy puts the same line on
+ * the clipboard as text.
+ */
+export function SummaryLine(props: SummaryInput) {
+ const t = useTranslations('insights.summary');
+ const tCompare = useTranslations('insights.compare');
+
+ const facts = summaryFacts(props, t);
+ const context = summaryContext(props, t, tCompare);
+ if (facts.length === 0 && !context) return null;
+
+ const copy = async () => {
+ try {
+ // Missing outside a secure context (e.g. a self-hosted install over http).
+ if (!navigator.clipboard) throw new Error('Clipboard unavailable');
+ await navigator.clipboard.writeText(summaryText(facts, context));
+ toast.success(t('copied'));
+ } catch {
+ toast.error(t('copyFailed'));
+ }
+ };
+
+ return (
+ <section
+ aria-label={t('label')}
+ className="flex flex-wrap items-center gap-x-2.5 gap-y-1.5 rounded-xl border bg-card px-3.5 py-2.5 text-[13.5px]"
+ >
+ <Sparkles className="h-4 w-4 shrink-0 text-muted-foreground" aria-hidden />
+ {facts.map((fact, i) => (
+ <Fragment key={fact.key}>
+ {i > 0 && (
+ <span className="text-muted-foreground/40" aria-hidden>
+ •
+ </span>
+ )}
+ <span>
+ {fact.parts.map((part, j) => (
+ <Fragment key={j}>
+ {j > 0 && ' '}
+ <span
+ className={cn(
+ 'tabular-nums',
+ part.bold && 'font-semibold',
+ part.tone && ['font-medium', TONE_TEXT[part.tone]],
+ )}
+ >
+ {part.text}
+ </span>
+ </Fragment>
+ ))}
+ </span>
+ </Fragment>
+ ))}
+ <span className="flex-1" />
+ {context && (
+ <span className="text-xs text-muted-foreground" title={tCompare('hint')}>
+ {context}
+ </span>
+ )}
+ <button
+ type="button"
+ onClick={copy}
+ aria-label={t('copy')}
+ title={t('copy')}
+ className="inline-flex h-7 w-7 items-center justify-center rounded-md border bg-background text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <Copy className="h-3.5 w-3.5" />
+ </button>
+ </section>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
index c12bdbfe1..3cd1ade63 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest';
-import { lowerIsGood, signedChange, signedValue, upIsGood } from './kpi-format';
+import { formatWindowBound, lowerIsGood, signedChange, signedValue, upIsGood } from './kpi-format';
describe('KPI card formatting', () => {
it('writes changes with a sign, and no change as ±0', () => {
@@ -26,4 +26,9 @@ describe('KPI card formatting', () => {
expect(lowerIsGood(0.5)).toEqual({ text: '↓0.5', tone: 'bad' });
expect(lowerIsGood(0)).toEqual({ text: '±0', tone: 'neutral' });
});
+
+ it('labels whole-day windows by their UTC days', () => {
+ // A day-only bound is the UTC day itself, whatever the viewer's zone.
+ expect(formatWindowBound('2026-08-16')).toBe('Aug 16, 2026');
+ });
});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
index 139591635..d033672bf 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/kpi-format.ts
@@ -7,6 +7,13 @@
/** Whether a change is good news, bad news, or neither (counts like tracked prompts). */
export type Tone = 'good' | 'bad' | 'neutral';
+/** Text colour for each tone, in both themes. */
+export const TONE_TEXT: Record<Tone, string> = {
+ good: 'text-emerald-600 dark:text-emerald-400',
+ bad: 'text-red-600 dark:text-red-400',
+ neutral: 'text-muted-foreground',
+};
+
export interface Change {
text: string;
tone: Tone;
@@ -43,3 +50,18 @@ export function lowerIsGood(change: number | null): Change | null {
tone: change < 0 ? 'good' : 'bad',
};
}
+
+/**
+ * A comparison-window bound for the "vs <range>" label. Whole-day windows
+ * come as 'YYYY-MM-DD' UTC days and are shown as those days; the 24h and
+ * topic views come as timestamps and are shown in local time.
+ */
+export function formatWindowBound(value: string): string {
+ const dayOnly = /^\d{4}-\d{2}-\d{2}$/.test(value);
+ return new Date(dayOnly ? `${value}T00:00:00Z` : value).toLocaleDateString('en-US', {
+ month: 'short',
+ day: '2-digit',
+ year: 'numeric',
+ ...(dayOnly ? { timeZone: 'UTC' } : {}),
+ });
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 12ab4035f..ec25d630c 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -107,7 +107,9 @@ import { toast } from 'sonner';
import { readUrlChoice, readUrlParam, writeUrlParams } from '@/lib/url-state';
import type { PromptComparison } from '@/lib/insights-same-prompts';
import type { KpiSeriesDay } from '@/lib/insights-kpis';
+import type { PlatformChange } from '@/lib/insights-summary';
import { KpiRows } from './_kpi-cards';
+import { SummaryLine } from './_summary-line';
// ─── Filter Types ─────────────────────────────────────────────────────────────
@@ -229,21 +231,6 @@ function getDateRange(
return { dateFrom: `${dayFrom}T00:00:00.000Z`, dateTo: undefined, days: { dayFrom, dayTo } };
}
-/**
- * A comparison-window bound for the "vs <range>" label. Whole-day windows
- * come as 'YYYY-MM-DD' UTC days and are shown as those days; the 24h and
- * topic views come as timestamps and are shown in local time.
- */
-function formatWindowBound(value: string): string {
- const dayOnly = /^\d{4}-\d{2}-\d{2}$/.test(value);
- return new Date(dayOnly ? `${value}T00:00:00Z` : value).toLocaleDateString('en-US', {
- month: 'short',
- day: '2-digit',
- year: 'numeric',
- ...(dayOnly ? { timeZone: 'UTC' } : {}),
- });
-}
-
// ─── Sub-components ───────────────────────────────────────────────────────────
// ─── Delta Badge ──────────────────────────────────────────────────────────────
@@ -912,6 +899,7 @@ export default function InsightsPage() {
const [comparison, setComparison] = useState<PromptComparison | null>(null);
const [coverage, setCoverage] = useState<CoverageKpi | null>(null);
const [kpiSeries, setKpiSeries] = useState<KpiSeriesDay[] | null>(null);
+ const [platformChanges, setPlatformChanges] = useState<PlatformChange[] | null>(null);
const [breakdownMetric, setBreakdownMetric] = useState<BreakdownMetric | null>(null);
// The window and filters the cards were last loaded with (the 24h view
// anchored to its tracking run): the breakdown panel explains those exact
@@ -1000,6 +988,7 @@ export default function InsightsPage() {
setComparison(insights.comparison);
setCoverage(insights.coverage);
setKpiSeries(insights.kpiSeries);
+ setPlatformChanges(insights.platformChanges);
setHasAnyData(insights.hasAnyData);
// Group raw model slugs by their resolved display name so different
@@ -1446,6 +1435,14 @@ export default function InsightsPage() {
<NoDataForPeriod datePreset={filters.datePreset} onReset={handleResetFilters} />
) : (
<>
+ {/* Summary line (VIS-006): the page's story in one line. */}
+ <SummaryLine
+ trend={rateTrend}
+ competitors={competitorData}
+ comparison={comparison}
+ platformChanges={platformChanges}
+ />
+
{/* KPI cards (VIS-003): today's five, then the new rates. */}
<KpiRows
summary={summary!}
@@ -1489,24 +1486,6 @@ export default function InsightsPage() {
{rateTrend.summary.change} pts
</span>
)}
- {rateTrend.summary.change !== null && rateTrend.summary.prevFrom && (
- <span className="text-muted-foreground">
- vs {formatWindowBound(rateTrend.summary.prevFrom)} –{' '}
- {formatWindowBound(rateTrend.summary.prevTo)}
- </span>
- )}
- {/* Shown even without a change: when every prompt is new,
- this is why there is nothing to compare. */}
- {comparison && comparison.newPrompts > 0 && (
- <span className="text-muted-foreground" title={t('compare.hint')}>
- {rateTrend.summary.change !== null &&
- rateTrend.summary.prevFrom &&
- '· '}
- {comparison.basis === 'same'
- ? t('compare.newExcluded', { count: comparison.newPrompts })
- : t('compare.newIncluded', { count: comparison.newPrompts })}
- </span>
- )}
</div>
</div>
) : (
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.ts
new file mode 100644
index 000000000..8e662d82b
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.test.ts
@@ -0,0 +1,95 @@
+import { describe, expect, it } from 'vitest';
+import type { CompetitorComparisonData, VisibilityRateTrendData } from '@/lib/actions/tracking';
+import { summaryContext, summaryFacts, summaryText, type SummaryInput } from './summary-format';
+
+// en.json's insights.summary / insights.compare, enough to read the output.
+const messages: Record<string, string> = {
+ visibility: 'visibility',
+ rank: '#{rank}',
+ ofCount: 'of {count}',
+ pts: '{value} pts',
+ behind: 'behind {name}',
+ ahead: 'ahead of {name}',
+ tied: 'tied with {name}',
+ upMost: 'Up most:',
+ downMost: 'Down most:',
+ vs: 'vs {from} – {to}',
+ newExcluded: '{count} new prompts excluded',
+ newIncluded: 'includes {count} new prompts',
+};
+const t = (key: string, values: Record<string, string | number> = {}) =>
+ messages[key].replace(/\{(\w+)\}/g, (_, k) => String(values[k]));
+
+const trend = (rate: number, change: number | null) =>
+ ({
+ entities: [],
+ points: [],
+ summary: { rate, prevRate: null, change, prevFrom: '2026-08-14', prevTo: '2026-09-12' },
+ }) as VisibilityRateTrendData;
+
+const leaderboard = (...brands: [string, number, boolean?][]) =>
+ ({
+ providerRows: [],
+ brands: brands.map(([name, score, own]) => ({ name, score, isOwnBrand: !!own })),
+ }) as unknown as CompetitorComparisonData;
+
+const input = (over: Partial<SummaryInput> = {}): SummaryInput => ({
+ trend: trend(17.4, 1.5),
+ competitors: leaderboard(['Semrush', 36.3], ['Peec AI', 18.3], ['Ansvisor', 17.4, true]),
+ comparison: { basis: 'same', samePrompts: 200, newPrompts: 509, droppedPrompts: 0 },
+ platformChanges: [
+ { name: 'Google AI Mode', cur: 21, prev: 4.9, change: 16.1 },
+ { name: 'Gemini', cur: 24.8, prev: 22.4, change: 2.4 },
+ { name: 'ChatGPT', cur: 8.1, prev: 11.3, change: -3.2 },
+ ],
+ ...over,
+});
+
+describe('summary line', () => {
+ it('reads like the mockup, on screen and when copied', () => {
+ const facts = summaryFacts(input(), t);
+ const context = summaryContext(input(), t, t);
+
+ expect(summaryText(facts, context)).toBe(
+ '17.4 visibility +1.5 · #3 of 3 · 0.9 pts behind Peec AI · Up most: Google AI Mode +16.1 · ' +
+ 'Down most: ChatGPT −3.2 · vs Aug 14, 2026 – Sep 12, 2026 · 509 new prompts excluded',
+ );
+ // The change and the movers carry their tone for the screen.
+ expect(facts[0].parts[2]).toEqual({ text: '+1.5', tone: 'good' });
+ expect(facts[3].parts[2]).toEqual({ text: '−3.2', tone: 'bad' });
+ });
+
+ it('says ahead when first and tied when level', () => {
+ const first = summaryFacts(
+ input({ competitors: leaderboard(['Ansvisor', 20, true], ['B', 18.5]) }),
+ t,
+ );
+ const tied = summaryFacts(
+ input({ competitors: leaderboard(['Ansvisor', 20, true], ['B', 20]) }),
+ t,
+ );
+
+ expect(summaryText([first[1]], null)).toBe('#1 of 2 · 1.5 pts ahead of B');
+ expect(summaryText([tied[1]], null)).toBe('#1 of 2 · tied with B');
+ });
+
+ it('leaves out what it has no data for, never showing a made-up 0', () => {
+ const facts = summaryFacts(
+ input({ trend: null, competitors: null, platformChanges: null, comparison: null }),
+ t,
+ );
+
+ expect(facts).toEqual([]);
+ expect(summaryContext(input({ trend: trend(17.4, null), comparison: null }), t, t)).toBeNull();
+ });
+
+ it('says the change includes new prompts when Same prompts is off', () => {
+ const context = summaryContext(
+ input({ comparison: { basis: 'all', samePrompts: 200, newPrompts: 509, droppedPrompts: 0 } }),
+ t,
+ t,
+ );
+
+ expect(context).toBe('vs Aug 14, 2026 – Sep 12, 2026 · includes 509 new prompts');
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.ts b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.ts
new file mode 100644
index 000000000..c3f9bf850
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/summary-format.ts
@@ -0,0 +1,121 @@
+import type { CompetitorComparisonData, VisibilityRateTrendData } from '@/lib/actions/tracking';
+import type { PromptComparison } from '@/lib/insights-same-prompts';
+import { platformMovers, rankSummary, type PlatformChange } from '@/lib/insights-summary';
+import { formatWindowBound, upIsGood, type Tone } from './kpi-format';
+
+/**
+ * What the summary line says (VIS-006), built once for both the screen and
+ * Copy, so the two can't drift apart. Each fact is a run of parts; a part
+ * is bold (the number or name to read first) or toned (a change).
+ */
+
+export interface SummaryPart {
+ text: string;
+ bold?: boolean;
+ tone?: Tone;
+}
+
+export interface SummaryFact {
+ key: string;
+ parts: SummaryPart[];
+}
+
+/** The message lookup, as next-intl's `t` for `insights.summary`. */
+type Translate = (key: string, values?: Record<string, string | number>) => string;
+
+export interface SummaryInput {
+ trend: VisibilityRateTrendData | null;
+ competitors: CompetitorComparisonData | null;
+ comparison: PromptComparison | null;
+ platformChanges: PlatformChange[] | null;
+}
+
+/** The line's facts, left to right; a fact without its data is left out. */
+export function summaryFacts(input: SummaryInput, t: Translate): SummaryFact[] {
+ const facts: SummaryFact[] = [];
+
+ // No score without the trend: a missing read must not read as 0.
+ if (input.trend) {
+ const change = upIsGood(input.trend.summary.change);
+ facts.push({
+ key: 'visibility',
+ parts: [
+ { text: String(input.trend.summary.rate), bold: true },
+ { text: t('visibility') },
+ ...(change ? [{ text: change.text, tone: change.tone }] : []),
+ ],
+ });
+ }
+
+ const rank = input.competitors ? rankSummary(input.competitors.brands) : null;
+ if (rank) {
+ const { neighbour } = rank;
+ facts.push({
+ key: 'rank',
+ parts: [
+ { text: t('rank', { rank: rank.rank }), bold: true },
+ { text: `${t('ofCount', { count: rank.count })} ·` },
+ ...(neighbour.side === 'tied'
+ ? [{ text: t('tied', { name: neighbour.name }) }]
+ : [
+ { text: t('pts', { value: neighbour.gap }), bold: true },
+ {
+ text:
+ neighbour.side === 'behind'
+ ? t('behind', { name: neighbour.name })
+ : t('ahead', { name: neighbour.name }),
+ },
+ ]),
+ ],
+ });
+ }
+
+ const { up, down } = platformMovers(input.platformChanges ?? []);
+ for (const [key, label, mover] of [
+ ['up', t('upMost'), up],
+ ['down', t('downMost'), down],
+ ] as const) {
+ if (!mover) continue;
+ const moved = upIsGood(mover.change)!;
+ facts.push({
+ key,
+ parts: [
+ { text: label },
+ { text: mover.name, bold: true },
+ { text: moved.text, tone: moved.tone },
+ ],
+ });
+ }
+
+ return facts;
+}
+
+/** What the change compares: the previous window and the prompts left out or in. */
+export function summaryContext(
+ input: SummaryInput,
+ t: Translate,
+ tCompare: Translate,
+): string | null {
+ const { trend, comparison } = input;
+ const parts = [
+ trend && trend.summary.change !== null && trend.summary.prevFrom
+ ? t('vs', {
+ from: formatWindowBound(trend.summary.prevFrom),
+ to: formatWindowBound(trend.summary.prevTo),
+ })
+ : null,
+ comparison && comparison.newPrompts > 0
+ ? tCompare(comparison.basis === 'same' ? 'newExcluded' : 'newIncluded', {
+ count: comparison.newPrompts,
+ })
+ : null,
+ ].filter((p): p is string => p !== null);
+ return parts.length > 0 ? parts.join(' · ') : null;
+}
+
+/** The whole line as one line of text, for Copy. */
+export function summaryText(facts: SummaryFact[], context: string | null): string {
+ return [...facts.map((f) => f.parts.map((p) => p.text).join(' ')), context]
+ .filter(Boolean)
+ .join(' · ');
+}
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index f4c3084dd..eb88207c7 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -45,6 +45,7 @@ import { getPromptVolumes } from '@/lib/actions/volumes';
import { getPromptSuggestions } from '@/lib/actions/prompt-suggestions';
import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
import { percentageChange } from '@/lib/metrics';
+import { parsePlatformRows, platformChanges, type PlatformChange } from '@/lib/insights-summary';
import {
coverage as coverageRate,
kpiRates,
@@ -720,6 +721,12 @@ export interface InsightsData {
* view (a single day), when the read failed, or before the backfill.
*/
kpiSeries: KpiSeriesDay[] | null;
+ /**
+ * Each platform's Visibility change for the summary line (VIS-006),
+ * following Same prompts; biggest rise first. Null without a previous
+ * window, before the backfill, or when the read failed.
+ */
+ platformChanges: PlatformChange[] | null;
/** The run ledger, when the 24h window was anchored to it (`anchor24h`). */
trackingWindow: TrackingWindow | null;
}
@@ -814,6 +821,7 @@ type WindowedInsights = Pick<
| 'comparison'
| 'coverage'
| 'kpiSeries'
+ | 'platformChanges'
>;
type InsightsFilterArgs = {
@@ -855,26 +863,36 @@ async function loadWindowedInsights(
return fallback;
});
- const [summary, competitors, sov, filterOptions, trend, same, coverage, kpiSeries] =
- await Promise.all([
- getInsightsSummary(brandId, filterOpts),
- lenient(
- getCompetitorComparison(brandId, filterOpts),
- EMPTY_COMPETITORS,
- 'competitor comparison',
- ),
- lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),
- getInsightsFilterOptions(brandId),
- // The chart follows the same window as every other number on the page.
- lenient<VisibilityRateTrendData | null>(
- getVisibilityRateTrend(brandId, filterOpts),
- null,
- 'visibility trend',
- ),
- lenient(getSamePromptComparison(brandId, filterOpts), null, 'same-prompt comparison'),
- lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),
- lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),
- ]);
+ const [
+ summary,
+ competitors,
+ sov,
+ filterOptions,
+ trend,
+ same,
+ coverage,
+ kpiSeries,
+ platformChangesData,
+ ] = await Promise.all([
+ getInsightsSummary(brandId, filterOpts),
+ lenient(
+ getCompetitorComparison(brandId, filterOpts),
+ EMPTY_COMPETITORS,
+ 'competitor comparison',
+ ),
+ lenient(getShareOfVoiceData(brandId, filterOpts), EMPTY_SOV, 'share of voice'),
+ getInsightsFilterOptions(brandId),
+ // The chart follows the same window as every other number on the page.
+ lenient<VisibilityRateTrendData | null>(
+ getVisibilityRateTrend(brandId, filterOpts),
+ null,
+ 'visibility trend',
+ ),
+ lenient(getSamePromptComparison(brandId, filterOpts), null, 'same-prompt comparison'),
+ lenient(getCoverageKpi(brandId, filterOpts), null, 'coverage'),
+ lenient(getKpiSeries(brandId, filterOpts), null, 'KPI sparklines'),
+ lenient(getPlatformChanges(brandId, filterOpts), null, 'platform changes'),
+ ]);
const windowed = {
...(comparisonWindows(filterOpts).prev ? { summary, sov } : withoutChanges(summary, sov)),
competitors,
@@ -882,6 +900,7 @@ async function loadWindowedInsights(
trend,
coverage,
kpiSeries,
+ platformChanges: platformChangesData,
};
return withPromptComparison(windowed, same, filterOpts.samePrompts !== false);
}
@@ -976,6 +995,52 @@ async function getKpiSeries(
return parseKpiSeries(data);
}
+/**
+ * Each platform's Visibility change over the card's windows, for the summary
+ * line's "Up most / Down most" (VIS-006). With Same prompts on (the default)
+ * only the prompts answered in both windows count, like every other change.
+ */
+async function getPlatformChanges(
+ brandId: string,
+ opts?: InsightsFilterArgs,
+): Promise<PlatformChange[] | null> {
+ const windows = comparisonWindows(opts);
+ if (!windows.prev) return null;
+ const supabase = await dbClient();
+ const base = {
+ p_brand_id: brandId,
+ p_models: modelFilterArray(opts?.model),
+ p_region: opts?.region ?? undefined,
+ p_same_prompts: opts?.samePrompts !== false,
+ };
+
+ let res;
+ if (windows.cur.kind === 'days') {
+ const { cur, prev } = deltaDayWindows(windows.cur.days);
+ res = await supabase.rpc('insights_platform_compare_daily', {
+ ...base,
+ p_cur_from: cur.dayFrom,
+ p_cur_to: cur.dayTo,
+ p_prev_from: prev.dayFrom,
+ p_prev_to: prev.dayTo,
+ });
+ } else {
+ const cur = windowBounds(windows.cur);
+ const prev = windowBounds(windows.prev);
+ res = await supabase.rpc('insights_platform_compare', {
+ ...base,
+ p_cur_from: cur.from,
+ p_cur_to: cur.to,
+ p_prev_from: prev.from,
+ p_prev_to: prev.to,
+ p_topic_id: opts?.topicId ?? undefined,
+ });
+ }
+ if (res.error) throw new Error(res.error.message);
+ const rows = parsePlatformRows(res.data);
+ return rows && platformChanges(rows, (model, platform) => resolveProvider(model, platform));
+}
+
/**
* The comparison windows' totals over the prompts answered in both
* (VIS-002): the daily rollups for whole days, the raw rows for the 24h and
diff --git a/web/src/lib/insights-summary.test.ts b/web/src/lib/insights-summary.test.ts
new file mode 100644
index 000000000..0d501300b
--- /dev/null
+++ b/web/src/lib/insights-summary.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+import { computeAiVisibilityScore } from './visibility-score';
+import {
+ parsePlatformRows,
+ platformChanges,
+ platformMovers,
+ rankSummary,
+ type PlatformRow,
+} from './insights-summary';
+
+const row = (
+ model_used: string | null,
+ platform: string | null,
+ win: 'cur' | 'prev',
+ answers: number,
+ mentions: number,
+): PlatformRow => ({
+ model_used,
+ platform,
+ win,
+ answers,
+ mention_answers: mentions,
+ citation_answers: 0,
+ sum_inv_position: null,
+ position_count: 0,
+});
+
+// Model slugs fold into the platform names "Share of Voice by Platform" uses.
+const platformOf = (model: string | null, platform: string | null) =>
+ platform === 'google-aimode' ? 'Google AI Mode' : model?.startsWith('gpt-') ? 'ChatGPT' : 'Other';
+
+const score = (answers: number, mentions: number) =>
+ computeAiVisibilityScore({
+ answers,
+ mentionAnswers: mentions,
+ citationAnswers: 0,
+ positionFactor: null,
+ })!;
+
+describe('platformChanges', () => {
+ it('scores each platform in both windows, folding model slugs together', () => {
+ const changes = platformChanges(
+ [
+ row('gpt-5-mini', null, 'cur', 50, 10),
+ row('gpt-4o', null, 'cur', 50, 10),
+ row('gpt-5-mini', null, 'prev', 100, 40),
+ row(null, 'google-aimode', 'cur', 100, 60),
+ row(null, 'google-aimode', 'prev', 100, 20),
+ ],
+ platformOf,
+ );
+
+ expect(changes.map((c) => c.name)).toEqual(['Google AI Mode', 'ChatGPT']);
+ const chatgpt = changes[1];
+ expect(chatgpt.cur).toBe(score(100, 20));
+ expect(chatgpt.change).toBe(Math.round((score(100, 20) - score(100, 40)) * 10) / 10);
+ });
+
+ it('leaves out platforms not answered in both windows', () => {
+ expect(platformChanges([row('gpt-5-mini', null, 'cur', 10, 5)], platformOf)).toEqual([]);
+ });
+});
+
+describe('platformMovers', () => {
+ const change = (name: string, c: number) => ({ name, cur: 0, prev: 0, change: c });
+
+ it('names the biggest rise and the biggest drop', () => {
+ const sorted = [change('A', 16.1), change('B', 2), change('C', -1), change('D', -3.2)];
+
+ expect(platformMovers(sorted)).toEqual({ up: sorted[0], down: sorted[3] });
+ });
+
+ it('names nothing when nothing moved that way', () => {
+ expect(platformMovers([change('A', 0), change('B', -1)])).toEqual({
+ up: null,
+ down: change('B', -1),
+ });
+ expect(platformMovers([])).toEqual({ up: null, down: null });
+ });
+});
+
+describe('rankSummary', () => {
+ const brand = (name: string, score: number, isOwnBrand = false) => ({ name, score, isOwnBrand });
+
+ it('gives the gap to the brand directly ahead', () => {
+ expect(
+ rankSummary([brand('Semrush', 36.3), brand('Peec AI', 18.3), brand('Ansvisor', 17.4, true)]),
+ ).toEqual({
+ rank: 3,
+ count: 3,
+ neighbour: { name: 'Peec AI', gap: 0.9, side: 'behind' },
+ });
+ });
+
+ it('gives the lead over the runner-up when first', () => {
+ expect(rankSummary([brand('Ansvisor', 78.8, true), brand('Demo Coffee Co', 61.9)])).toEqual({
+ rank: 1,
+ count: 2,
+ neighbour: { name: 'Demo Coffee Co', gap: 16.9, side: 'ahead' },
+ });
+ });
+
+ it('has no rank alone on the leaderboard', () => {
+ expect(rankSummary([brand('Ansvisor', 78.8, true)])).toBeNull();
+ });
+});
+
+describe('parsePlatformRows', () => {
+ it('reads the RPC payload and refuses rollups not yet backfilled', () => {
+ expect(
+ parsePlatformRows({
+ complete: true,
+ platforms: [{ model_used: 'gpt-4o', platform: null, win: 'prev', answers: '3' }],
+ }),
+ ).toEqual([
+ {
+ model_used: 'gpt-4o',
+ platform: null,
+ win: 'prev',
+ answers: 3,
+ mention_answers: 0,
+ citation_answers: 0,
+ sum_inv_position: null,
+ position_count: 0,
+ },
+ ]);
+ expect(parsePlatformRows({ complete: false, platforms: [] })).toBeNull();
+ });
+});
diff --git a/web/src/lib/insights-summary.ts b/web/src/lib/insights-summary.ts
new file mode 100644
index 000000000..4cfe1743d
--- /dev/null
+++ b/web/src/lib/insights-summary.ts
@@ -0,0 +1,142 @@
+import { computeAiVisibilityScore } from '@/lib/visibility-score';
+
+/**
+ * The Insights summary line (VIS-006): the brand's rank and the gap to its
+ * neighbour, and the platforms that moved Visibility most. A fixed template
+ * over numbers the page already shows, no AI call.
+ */
+
+const round1 = (n: number) => Math.round(n * 10) / 10;
+
+/** One row of insights_platform_compare[_daily] (00132). */
+export interface PlatformRow {
+ model_used: string | null;
+ platform: string | null;
+ win: 'cur' | 'prev';
+ answers: number;
+ mention_answers: number;
+ citation_answers: number;
+ sum_inv_position: number | null;
+ position_count: number;
+}
+
+/** A platform's Visibility in both windows. */
+export interface PlatformChange {
+ name: string;
+ cur: number;
+ prev: number;
+ change: number;
+}
+
+const num = (v: unknown): number => Number(v ?? 0);
+
+/**
+ * The RPC payload, or null when it can't be used: missing, or read from
+ * rollup rows not yet backfilled (00130) — the summary then names no
+ * platform rather than one picked from partial data.
+ */
+export function parsePlatformRows(raw: unknown): PlatformRow[] | null {
+ const r = raw as { complete?: boolean; platforms?: Record<string, unknown>[] } | null;
+ if (!r || r.complete !== true) return null;
+ return (r.platforms ?? []).map((p) => ({
+ model_used: (p.model_used as string | null) ?? null,
+ platform: (p.platform as string | null) ?? null,
+ win: p.win === 'prev' ? 'prev' : 'cur',
+ answers: num(p.answers),
+ mention_answers: num(p.mention_answers),
+ citation_answers: num(p.citation_answers),
+ sum_inv_position:
+ p.sum_inv_position === null || p.sum_inv_position === undefined
+ ? null
+ : num(p.sum_inv_position),
+ position_count: num(p.position_count),
+ }));
+}
+
+interface Sums {
+ answers: number;
+ mentions: number;
+ citations: number;
+ invPosition: number;
+ positions: number;
+}
+
+const score = (s: Sums) =>
+ computeAiVisibilityScore({
+ answers: s.answers,
+ mentionAnswers: s.mentions,
+ citationAnswers: s.citations,
+ positionFactor: s.positions > 0 ? s.invPosition / s.positions : null,
+ });
+
+/**
+ * Each platform's Visibility change, with model slugs folded into their
+ * platform the way "Share of Voice by Platform" names them. Only platforms
+ * answered in both windows; biggest rise first.
+ */
+export function platformChanges(
+ rows: PlatformRow[],
+ platformOf: (modelUsed: string | null, platform: string | null) => string,
+): PlatformChange[] {
+ const sums = new Map<string, { cur: Sums; prev: Sums }>();
+ const empty = (): Sums => ({
+ answers: 0,
+ mentions: 0,
+ citations: 0,
+ invPosition: 0,
+ positions: 0,
+ });
+ for (const r of rows) {
+ const name = platformOf(r.model_used, r.platform);
+ const entry = sums.get(name) ?? { cur: empty(), prev: empty() };
+ const s = entry[r.win];
+ s.answers += r.answers;
+ s.mentions += r.mention_answers;
+ s.citations += r.citation_answers;
+ s.invPosition += r.sum_inv_position ?? 0;
+ s.positions += r.position_count;
+ sums.set(name, entry);
+ }
+
+ const out: PlatformChange[] = [];
+ for (const [name, { cur, prev }] of sums) {
+ const c = score(cur);
+ const p = score(prev);
+ if (c === null || p === null) continue;
+ out.push({ name, cur: c, prev: p, change: round1(c - p) });
+ }
+ return out.sort((a, b) => b.change - a.change || a.name.localeCompare(b.name));
+}
+
+/** The platform that rose most and the one that fell most; null when none moved that way. */
+export function platformMovers(changes: PlatformChange[]): {
+ up: PlatformChange | null;
+ down: PlatformChange | null;
+} {
+ const up = changes.find((c) => c.change > 0) ?? null;
+ const falling = changes.filter((c) => c.change < 0);
+ return { up, down: falling.length > 0 ? falling[falling.length - 1] : null };
+}
+
+export interface RankSummary {
+ rank: number;
+ count: number;
+ /** The brand directly ahead, or, when first, the runner-up. */
+ neighbour: { name: string; gap: number; side: 'behind' | 'ahead' | 'tied' };
+}
+
+/** The brand's place on the leaderboard (brands sorted by score, as shown). */
+export function rankSummary(
+ brands: { name: string; score: number | null; isOwnBrand: boolean }[],
+): RankSummary | null {
+ const i = brands.findIndex((b) => b.isOwnBrand);
+ if (i < 0 || brands.length < 2) return null;
+ const own = brands[i].score ?? 0;
+ const other = i > 0 ? brands[i - 1] : brands[1];
+ const gap = round1(Math.abs((other.score ?? 0) - own));
+ return {
+ rank: i + 1,
+ count: brands.length,
+ neighbour: { name: other.name, gap, side: gap === 0 ? 'tied' : i > 0 ? 'behind' : 'ahead' },
+ };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 37abb04dc..7e680250d 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -3108,6 +3108,33 @@ export type Database = {
}
Returns: Json
}
+ insights_platform_compare: {
+ Args: {
+ p_brand_id: string
+ p_cur_from: string
+ p_cur_to: string
+ p_models?: string[]
+ p_prev_from: string
+ p_prev_to: string
+ p_region?: string
+ p_same_prompts?: boolean
+ p_topic_id?: string
+ }
+ Returns: Json
+ }
+ insights_platform_compare_daily: {
+ Args: {
+ p_brand_id: string
+ p_cur_from: string
+ p_cur_to: string
+ p_models?: string[]
+ p_prev_from: string
+ p_prev_to: string
+ p_region?: string
+ p_same_prompts?: boolean
+ }
+ Returns: Json
+ }
insights_same_prompt_compare: {
Args: {
p_brand_id: string